Commit e0c94b2d1c for ffmpeg

commit e0c94b2d1c96c2548645d00690f26dc5178d4855
Author: Michael Niedermayer <michael@niedermayer.cc>
Date:   Tue Sep 29 21:14:23 2026 +0000

    avcodec/nvenc: avoid invalid surface destruction after init error

    A partially initialized surface array contains null handles, and the input handle for the surface whose bitstream allocation failed has already been destroyed. Avoid passing the null handles to NVENC and clear the input handle after its early destruction so it cannot be destroyed twice during close.

    Fixes issue #24019.

    Reported-by: hmaarrfk
    Assisted-by: Fairy

diff --git a/libavcodec/nvenc.c b/libavcodec/nvenc.c
index 5ea094e095..6e7331405f 100644
--- a/libavcodec/nvenc.c
+++ b/libavcodec/nvenc.c
@@ -1937,8 +1937,10 @@ static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
     nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
     if (nv_status != NV_ENC_SUCCESS) {
         int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
-        if (!IS_HWACCEL(avctx->pix_fmt))
+        if (!IS_HWACCEL(avctx->pix_fmt)) {
             p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
+            ctx->surfaces[idx].input_surface = NULL;
+        }
         av_frame_free(&ctx->surfaces[idx].in_ref);
         return err;
     }
@@ -2072,10 +2074,11 @@ av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)

     if (ctx->surfaces) {
         for (i = 0; i < ctx->nb_surfaces; ++i) {
-            if (!IS_HWACCEL(avctx->pix_fmt))
+            if (!IS_HWACCEL(avctx->pix_fmt) && ctx->surfaces[i].input_surface)
                 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
             av_frame_free(&ctx->surfaces[i].in_ref);
-            p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
+            if (ctx->surfaces[i].output_surface)
+                p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
         }
     }
     av_freep(&ctx->surfaces);