PR #25984 opened by t-boiko
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/25984
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/25984.patch

VP9 inter frames can change resolution without resetting probability contexts. 
Reinitializing the Vulkan hwaccel on each size change recreates the video 
session and loses those contexts, causing incorrect decoding.

Reuse existing frame pools while pictures fit, and retain a compatible video 
session when pools grow. Keep old frame pools and DPB images alive until 
submitted GPU work completes.

Allocate layered DPBs at the current pool extent rather than the session 
maximum. Grow them on keyframes or full-refresh intra-only frames, deactivating 
old DPB slots without resetting probability state. Layered growth on dependent 
frames remains unsupported when separate reference images are unavailable.

Validation: compared per-frame Vulkan and software decoding hashes on VP9 
resolution-change streams.


>From 4e35c692599e0f510f6eb52ffe5b1add9a7e8283 Mon Sep 17 00:00:00 2001
From: Tymur Boiko <[email protected]>
Date: Thu, 5 Nov 2026 18:58:05 +0100
Subject: [PATCH] avcodec/vulkan_vp9: preserve decode state across resolution
 changes

VP9 inter frames can change resolution without resetting probability
contexts. Reinitializing the hwaccel on each size change recreates the
Vulkan video session and loses those contexts.

Reuse frame pools while pictures fit and retain a compatible video
session when output or DPB pools grow. Keep old frame contexts and DPB
images alive until submitted GPU work completes.

Allocate layered DPBs at the current frame-pool extent and grow them on
keyframes or full-refresh intra-only frames. Deactivate old DPB slots
without resetting probability state. Layered growth on dependent frames
remains unsupported when references must share one image.

Signed-off-by: Tymur Boiko <[email protected]>
---
 libavcodec/vp9.c           |   8 +-
 libavcodec/vp9dec.h        |   3 +
 libavcodec/vulkan_decode.c |  41 ++++++-
 libavcodec/vulkan_decode.h |   8 +-
 libavcodec/vulkan_vp9.c    | 226 +++++++++++++++++++++++++++++++++----
 5 files changed, 255 insertions(+), 31 deletions(-)

diff --git a/libavcodec/vp9.c b/libavcodec/vp9.c
index 3a52b8444ff..4a47e9ebb75 100644
--- a/libavcodec/vp9.c
+++ b/libavcodec/vp9.c
@@ -267,7 +267,13 @@ static int update_size(AVCodecContext *avctx, int w, int h)
         *fmtp++ = s->pix_fmt;
         *fmtp = AV_PIX_FMT_NONE;
 
-        ret = ff_get_format(avctx, pix_fmts);
+        ret = 0;
+#if CONFIG_VP9_VULKAN_HWACCEL
+        if (s->pix_fmt == s->gf_fmt && avctx->pix_fmt == AV_PIX_FMT_VULKAN)
+            ret = ff_vp9_vulkan_resize_can_reuse_pool(avctx, w, h);
+#endif
+        if (ret >= 0)
+            ret = ret ? avctx->pix_fmt : ff_get_format(avctx, pix_fmts);
         if (ret < 0) {
             ff_set_dimensions(avctx, s->w, s->h);
             return ret;
diff --git a/libavcodec/vp9dec.h b/libavcodec/vp9dec.h
index fd33d03c2b4..1eb5fe54813 100644
--- a/libavcodec/vp9dec.h
+++ b/libavcodec/vp9dec.h
@@ -249,6 +249,9 @@ void ff_vp9_fill_mv(VP9TileData *td, VP9mv *mv, int mode, 
int sb);
 
 void ff_vp9_adapt_probs(VP9Context *s);
 
+/* Returns 1 for reuse, 0 for reinitialization, or a negative error code. */
+int ff_vp9_vulkan_resize_can_reuse_pool(struct AVCodecContext *avctx, int 
width, int height);
+
 void ff_vp9_decode_block(VP9TileData *td, int row, int col,
                          VP9Filter *lflvl, ptrdiff_t yoff, ptrdiff_t uvoff,
                          enum BlockLevel bl, enum BlockPartition bp);
diff --git a/libavcodec/vulkan_decode.c b/libavcodec/vulkan_decode.c
index 55c34d92f91..b144d360e73 100644
--- a/libavcodec/vulkan_decode.c
+++ b/libavcodec/vulkan_decode.c
@@ -199,8 +199,16 @@ int ff_vk_decode_prepare_frame(FFVulkanDecodeContext *dec, 
AVFrame *pic,
         return AVERROR(ENOMEM);
 
     if (ctx->common.layered_dpb && alloc_dpb) {
-        vkpic->view.ref = ctx->common.layered_view;
-        vkpic->view.aspect_ref = ctx->common.layered_aspect;
+        if (!ctx->common.layered_img) {
+            ctx->common.layered_img = 
av_refstruct_pool_get(ctx->common.dpb->img_pool);
+            if (!ctx->common.layered_img)
+                return AVERROR(ENOMEM);
+            ctx->common.layered_view   = ctx->common.layered_img->view;
+            ctx->common.layered_aspect = ctx->common.layered_img->aspect;
+        }
+        vkpic->dpb_img = av_refstruct_ref(ctx->common.layered_img);
+        vkpic->view.ref        = vkpic->dpb_img->view;
+        vkpic->view.aspect_ref = vkpic->dpb_img->aspect;
     } else if (alloc_dpb) {
         vkpic->dpb_img = av_refstruct_pool_get(ctx->common.dpb->img_pool);
         if (!vkpic->dpb_img)
@@ -475,6 +483,11 @@ int ff_vk_decode_frame(AVCodecContext *avctx,
         decode_start.referenceSlotCount++;
     }
 
+#if CONFIG_VP9_VULKAN_HWACCEL
+    if (avctx->codec_id == AV_CODEC_ID_VP9)
+        ff_vk_vp9_invalidate_dpb_slots(vp, &decode_start);
+#endif
+
     sd_buf = vp->slices_buf;
 
     /* Flush if needed */
@@ -505,6 +518,25 @@ int ff_vk_decode_frame(AVCodecContext *avctx,
         return err;
     cmd_buf = exec->buf;
 
+    /* Keep VP9 DPB images and frame pools alive until GPU execution 
completes. */
+    if (avctx->codec_id == AV_CODEC_ID_VP9) {
+        for (int i = 0; i <= vp->decode_info.referenceSlotCount; i++) {
+            AVFrame *dep = i ? rpic[i - 1] : pic;
+            FFVulkanDecodePicture *dp = i ? rvkp[i - 1] : vp;
+
+            if (dp->dpb_img)
+                ff_vk_exec_add_dep_refstruct(&ctx->s, exec, dp->dpb_img);
+            if ((i && dec->dedicated_dpb) ||
+                dep->hw_frames_ctx->data == ctx->s.frames_ref->data)
+                continue;
+            err = ff_vk_exec_add_dep_sw_frame(&ctx->s, exec, dep);
+            if (err < 0) {
+                ff_vk_exec_discard(&ctx->s, exec);
+                return err;
+            }
+        }
+    }
+
     /* Slices; owned by the execution from now on */
     ff_vk_exec_move_dep_refstruct(&ctx->s, exec, &vp->slices_buf);
 
@@ -548,7 +580,8 @@ int ff_vk_decode_frame(AVCodecContext *avctx,
     ff_vk_exec_update_frame(&ctx->s, exec, pic,
                             &img_bar[nb_img_bar], &nb_img_bar);
 
-    /* Current picture's DISTINCT-mode DPB image: transition on first use */
+    /* Current picture's DISTINCT-mode DPB image: transition on first use,
+     * including after layered DPB growth. */
     if (vp->dpb_img) {
         FFVkVideoDPBImage *di = vp->dpb_img;
 
@@ -567,7 +600,7 @@ int ff_vk_decode_frame(AVCodecContext *avctx,
                 .image = di->img,
                 .subresourceRange = (VkImageSubresourceRange) {
                     .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
-                    .layerCount = 1,
+                    .layerCount = layered_dpb ? VK_REMAINING_ARRAY_LAYERS : 1,
                     .levelCount = 1,
                 },
             };
diff --git a/libavcodec/vulkan_decode.h b/libavcodec/vulkan_decode.h
index 2f8a2b714c1..961bc6d7f15 100644
--- a/libavcodec/vulkan_decode.h
+++ b/libavcodec/vulkan_decode.h
@@ -46,6 +46,8 @@ typedef struct FFVulkanDecodeShared {
     VkVideoCapabilitiesKHR caps;
     VkVideoDecodeCapabilitiesKHR dec_caps;
 
+    uint32_t active_dpb_slots; /* VP9 slots activated by submitted decodes */
+
     /* Software-defined decoder context */
     void *sd_ctx;
     void (*sd_ctx_free)(struct FFVulkanDecodeShared *ctx);
@@ -72,7 +74,7 @@ typedef struct FFVulkanDecodeContext {
 
 typedef struct FFVulkanDecodePicture {
     AVFrame                        *dpb_frame;      /* Software-defined 
decoders only. */
-    FFVkVideoDPBImage              *dpb_img;        /* DISTINCT-mode reference 
image */
+    FFVkVideoDPBImage              *dpb_img;        /* DISTINCT-mode reference 
image; shared for layered DPBs */
 
     struct {
         VkImageView                     ref;        /* Image representation 
view (reference) */
@@ -151,6 +153,10 @@ int ff_vk_decode_frame(AVCodecContext *avctx,
                        AVFrame *pic,    FFVulkanDecodePicture *vp,
                        AVFrame *rpic[], FFVulkanDecodePicture *rvkp[]);
 
+/* Append VP9 DPB slot invalidations to the begin-coding reference list. */
+void ff_vk_vp9_invalidate_dpb_slots(FFVulkanDecodePicture *vp,
+                                  VkVideoBeginCodingInfoKHR *decode_start);
+
 /**
  * Free a frame and its state.
  */
diff --git a/libavcodec/vulkan_vp9.c b/libavcodec/vulkan_vp9.c
index 26379571e12..8e6a795443b 100644
--- a/libavcodec/vulkan_vp9.c
+++ b/libavcodec/vulkan_vp9.c
@@ -38,6 +38,8 @@ typedef struct VP9VulkanDecodePicture {
      * independent. */
     FFVulkanDecodeContext          *dec;
 
+    FFVulkanDecodeShared           *shared_ctx;
+
     /* Current picture */
     StdVideoVP9ColorConfig color_config;
     StdVideoVP9Segmentation segmentation;
@@ -50,8 +52,29 @@ typedef struct VP9VulkanDecodePicture {
     uint8_t frame_id_set;
     uint8_t frame_id;
     uint8_t ref_frame_sign_bias_mask;
+    uint8_t frame_resize; /* Layered DPB grew for this frame */
+    uint32_t invalidate_dpb_slots; /* Deactivate at begin coding */
 } VP9VulkanDecodePicture;
 
+void ff_vk_vp9_invalidate_dpb_slots(FFVulkanDecodePicture *vp,
+                                  VkVideoBeginCodingInfoKHR *decode_start)
+{
+    VP9VulkanDecodePicture *ap = (VP9VulkanDecodePicture *)vp;
+    uint32_t slots = ap->invalidate_dpb_slots;
+
+    /* Deactivate references without resetting codec probability state. */
+    for (uint32_t i = 0; i < ap->shared_ctx->caps.maxDpbSlots; i++, slots >>= 
1) {
+        if (slots & 1) {
+            VkVideoReferenceSlotInfoKHR *slot =
+                (void 
*)&decode_start->pReferenceSlots[decode_start->referenceSlotCount++];
+            *slot = (VkVideoReferenceSlotInfoKHR) {
+                .sType = VK_STRUCTURE_TYPE_VIDEO_REFERENCE_SLOT_INFO_KHR,
+                .slotIndex = i,
+            };
+        }
+    }
+}
+
 static int vk_vp9_fill_pict(AVCodecContext *avctx, const VP9Frame **ref_src,
                             VkVideoReferenceSlotInfoKHR *ref_slot,      /* 
Main structure */
                             VkVideoPictureResourceInfoKHR *ref,         /* 
Goes in ^ */
@@ -121,6 +144,38 @@ static int vk_vp9_start_frame(AVCodecContext          
*avctx,
 
     VP9VulkanDecodePicture *ap = pic->hwaccel_picture_private;
     FFVulkanDecodePicture *vp = &ap->vp;
+    FFVulkanDecodeShared *ctx = dec->shared_ctx;
+    FFVkVideoDPB *dpb = ctx->common.dpb;
+    const AVHWFramesContext *frames = (AVHWFramesContext 
*)pic->tf.f->hw_frames_ctx->data;
+
+    if (dpb && (frames->width > dpb->width || frames->height > dpb->height)) {
+        FFVkVideoCommon next = { 0 };
+
+        if (ctx->common.layered_dpb && !s->h.keyframe &&
+            !(s->h.intraonly && s->h.refreshrefmask == 0xff)) {
+            av_log(avctx, AV_LOG_ERROR, "Layered VP9 DPB growth requires "
+                   "a keyframe or a full-refresh intra-only frame.\n");
+            return AVERROR(ENOSYS);
+        }
+
+        err = ff_vk_video_dpb_init(&ctx->s, &next, dpb->format,
+                                   dpb->usage, dpb->tiling, dpb->create_pnext,
+                                   FFMAX(frames->width, dpb->width),
+                                   FFMAX(frames->height, dpb->height), 
dpb->nb_layers);
+        if (err < 0)
+            return err;
+
+        if (ctx->common.layered_dpb) {
+            ap->frame_resize = 1;
+            ap->invalidate_dpb_slots = ctx->active_dpb_slots;
+        }
+
+        /* Pictures and submissions retain images from the old pool. */
+        av_refstruct_unref(&ctx->common.layered_img);
+        ctx->common.layered_view = VK_NULL_HANDLE;
+        av_refstruct_pool_uninit(&dpb->img_pool);
+        ctx->common.dpb = next.dpb;
+    }
 
     /* Use the current frame_ids in ref_frames[] to decide occupied frame_ids 
*/
     for (int i = 0; i < STD_VIDEO_VP9_NUM_REF_FRAMES; i++) {
@@ -142,31 +197,33 @@ static int vk_vp9_start_frame(AVCodecContext          
*avctx,
         frame_id_alloc_mask |= (1 << slot_idx);
     }
 
-    for (int i = 0; i < STD_VIDEO_VP9_REFS_PER_FRAME; i++) {
-        const int idx = pic->frame_header->ref_frame_idx[i];
-        const VP9Frame *ref_frame = &s->ref_frames[idx];
-        VP9VulkanDecodePicture *hp = ref_frame->hwaccel_picture_private;
-        int found = 0;
+    if (!ap->frame_resize) {
+        for (int i = 0; i < STD_VIDEO_VP9_REFS_PER_FRAME; i++) {
+            const int idx = pic->frame_header->ref_frame_idx[i];
+            const VP9Frame *ref_frame = &s->ref_frames[idx];
+            VP9VulkanDecodePicture *hp = ref_frame->hwaccel_picture_private;
+            int found = 0;
 
-        if (!ref_frame->tf.f)
-            continue;
+            if (!ref_frame->tf.f)
+                continue;
 
-        for (int j = 0; j < ref_count; j++) {
-            if (vp->ref_slots[j].slotIndex == hp->frame_id) {
-                found = 1;
-                break;
+            for (int j = 0; j < ref_count; j++) {
+                if (vp->ref_slots[j].slotIndex == hp->frame_id) {
+                    found = 1;
+                    break;
+                }
             }
+            if (found)
+                continue;
+
+            err = vk_vp9_fill_pict(avctx, &ap->ref_src[ref_count],
+                                   &vp->ref_slots[ref_count], 
&vp->refs[ref_count],
+                                   ref_frame, 0);
+            if (err < 0)
+                return err;
+
+            ref_count++;
         }
-        if (found)
-            continue;
-
-        err = vk_vp9_fill_pict(avctx, &ap->ref_src[ref_count],
-                               &vp->ref_slots[ref_count], &vp->refs[ref_count],
-                               ref_frame, 0);
-        if (err < 0)
-            return err;
-
-        ref_count++;
     }
 
     err = vk_vp9_fill_pict(avctx, NULL, &vp->ref_slot, &vp->ref,
@@ -277,7 +334,7 @@ static int vk_vp9_start_frame(AVCodecContext          
*avctx,
         const VP9Frame *ref_frame = &s->ref_frames[idx];
         VP9VulkanDecodePicture *hp = ref_frame->hwaccel_picture_private;
 
-        if (!ref_frame->tf.f)
+        if (ap->frame_resize || !ref_frame->tf.f)
             ap->vp9_pic_info.referenceNameSlotIndices[i] = -1;
         else
             ap->vp9_pic_info.referenceNameSlotIndices[i] = hp->frame_id;
@@ -300,6 +357,7 @@ static int vk_vp9_start_frame(AVCodecContext          
*avctx,
     };
 
     ap->dec = dec;
+    av_refstruct_replace(&ap->shared_ctx, dec->shared_ctx);
 
     return 0;
 }
@@ -322,6 +380,7 @@ static int vk_vp9_decode_slice(AVCodecContext *avctx,
 
 static int vk_vp9_end_frame(AVCodecContext *avctx)
 {
+    int err;
     const VP9SharedContext *s = avctx->priv_data;
 
     const VP9Frame *pic = &s->frames[CUR_FRAME];
@@ -341,7 +400,15 @@ static int vk_vp9_end_frame(AVCodecContext *avctx)
     av_log(avctx, AV_LOG_VERBOSE, "Decoding frame, %zu bytes\n",
            vp->slices_size);
 
-    return ff_vk_decode_frame(avctx, pic->tf.f, vp, rav, rvp);
+    err = ff_vk_decode_frame(avctx, pic->tf.f, vp, rav, rvp);
+    if (err >= 0) {
+        ap->shared_ctx->active_dpb_slots &= ~ap->invalidate_dpb_slots;
+        if (s->h.refreshrefmask)
+            ap->shared_ctx->active_dpb_slots |= 1U << ap->frame_id;
+        else
+            ap->shared_ctx->active_dpb_slots &= ~(1U << ap->frame_id);
+    }
+    return err;
 }
 
 static void vk_vp9_free_frame_priv(AVRefStructOpaque _hwctx, void *data)
@@ -351,6 +418,115 @@ static void vk_vp9_free_frame_priv(AVRefStructOpaque 
_hwctx, void *data)
 
     /* Free frame resources, this also destroys the session parameters. */
     ff_vk_decode_free_frame(hwctx, &ap->vp);
+    av_refstruct_unref(&ap->shared_ctx);
+}
+
+int ff_vp9_vulkan_resize_can_reuse_pool(AVCodecContext *avctx, int width, int 
height)
+{
+    const VP9SharedContext *s = avctx->priv_data;
+    const VP9Frame *prev = &s->frames[CUR_FRAME];
+    const FFVulkanDecodeContext *dec = avctx->internal->hwaccel_priv_data;
+    const FFVulkanDecodeShared *ctx;
+    const AVHWFramesContext *frames;
+    const VP9VulkanDecodePicture *hp;
+
+    if (!dec || !dec->shared_ctx || !avctx->hw_frames_ctx ||
+        !prev->tf.f || prev->tf.f->format != AV_PIX_FMT_VULKAN ||
+        prev->tf.f->hw_frames_ctx->data != avctx->hw_frames_ctx->data)
+        return 0;
+
+    ctx = dec->shared_ctx;
+    frames = (AVHWFramesContext *)avctx->hw_frames_ctx->data;
+    hp = prev->hwaccel_picture_private;
+    if (!hp || hp->shared_ctx != ctx || hp->std_pic_info.profile != 
avctx->profile)
+        return 0;
+
+    if (width  < ctx->caps.minCodedExtent.width  ||
+        height < ctx->caps.minCodedExtent.height ||
+        width  > ctx->caps.maxCodedExtent.width  ||
+        height > ctx->caps.maxCodedExtent.height)
+        return 0;
+
+    return width <= frames->width && height <= frames->height;
+}
+
+static int vk_vp9_frame_params(AVCodecContext *avctx, AVBufferRef 
*hw_frames_ctx)
+{
+    const VP9SharedContext *s = avctx->priv_data;
+    const VP9Frame *prev = &s->frames[CUR_FRAME];
+    FFVulkanDecodeContext *dec = avctx->internal->hwaccel_priv_data;
+    AVHWFramesContext *frames = (AVHWFramesContext *)hw_frames_ctx->data;
+    const AVHWFramesContext *old;
+    const VP9VulkanDecodePicture *hp;
+    int err;
+
+    err = ff_vk_frame_params(avctx, hw_frames_ctx);
+    if (err < 0)
+        return err;
+
+    if (!prev->tf.f || prev->tf.f->format != AV_PIX_FMT_VULKAN)
+        return 0;
+    hp = prev->hwaccel_picture_private;
+    if (!hp || !hp->shared_ctx || hp->std_pic_info.profile != avctx->profile)
+        return 0;
+
+    old = (AVHWFramesContext *)prev->tf.f->hw_frames_ctx->data;
+    if (old->device_ctx == frames->device_ctx && old->sw_format == 
frames->sw_format &&
+        ((AVVulkanFramesContext *)old->hwctx)->format[0] ==
+        ((AVVulkanFramesContext *)frames->hwctx)->format[0] &&
+        old->width <= dec->shared_ctx->caps.maxCodedExtent.width &&
+        old->height <= dec->shared_ctx->caps.maxCodedExtent.height) {
+        /* Grow either dimension without shrinking the other one. */
+        frames->width  = FFMAX(frames->width,  old->width);
+        frames->height = FFMAX(frames->height, old->height);
+    }
+
+    return 0;
+}
+
+static int vk_vp9_decode_init(AVCodecContext *avctx)
+{
+    const VP9SharedContext *s = avctx->priv_data;
+    FFVulkanDecodeContext *dec = avctx->internal->hwaccel_priv_data;
+    AVHWFramesContext *frames = NULL;
+    AVVulkanFramesContext *hwfc = NULL;
+    int err;
+
+    /* Resizing does not reset VP9 probability contexts. Keep a compatible
+     * session when only the image pools need to grow. */
+    for (int i = 0; i < STD_VIDEO_VP9_NUM_REF_FRAMES; i++) {
+        const VP9Frame *ref = &s->ref_frames[i];
+        const VP9VulkanDecodePicture *hp;
+        FFVulkanDecodeShared *ctx;
+
+        if (!ref->tf.f || ref->tf.f->format != AV_PIX_FMT_VULKAN)
+            continue;
+        hp = ref->hwaccel_picture_private;
+        if (!hp || !hp->shared_ctx || hp->std_pic_info.profile != 
avctx->profile)
+            continue;
+
+        if (!frames) {
+            err = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_VULKAN);
+            if (err < 0)
+                return err;
+            frames = (AVHWFramesContext *)avctx->hw_frames_ctx->data;
+            hwfc = frames->hwctx;
+        }
+
+        ctx = hp->shared_ctx;
+        if (!!ctx->common.dpb == dec->dedicated_dpb &&
+            ctx->common.layered_dpb == dec->shared_ctx->common.layered_dpb &&
+            ctx->s.device == frames->device_ctx &&
+            ctx->s.frames->sw_format == frames->sw_format &&
+            ctx->s.hwfc->format[0] == hwfc->format[0] &&
+            avctx->coded_width <= ctx->caps.maxCodedExtent.width &&
+            avctx->coded_height <= ctx->caps.maxCodedExtent.height) {
+            av_refstruct_replace(&dec->shared_ctx, ctx);
+            return 0;
+        }
+    }
+
+    return ff_vk_decode_init(avctx);
 }
 
 const FFHWAccel ff_vp9_vulkan_hwaccel = {
@@ -363,10 +539,10 @@ const FFHWAccel ff_vp9_vulkan_hwaccel = {
     .end_frame             = &vk_vp9_end_frame,
     .free_frame_priv       = &vk_vp9_free_frame_priv,
     .frame_priv_data_size  = sizeof(VP9VulkanDecodePicture),
-    .init                  = &ff_vk_decode_init,
+    .init                  = &vk_vp9_decode_init,
     .update_thread_context = &ff_vk_update_thread_context,
     .uninit                = &ff_vk_decode_uninit,
-    .frame_params          = &ff_vk_frame_params,
+    .frame_params          = &vk_vp9_frame_params,
     .priv_data_size        = sizeof(FFVulkanDecodeContext),
     .caps_internal         = HWACCEL_CAP_ASYNC_SAFE,
 };
-- 
2.54.0

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

Reply via email to