diff --git a/libavcodec/vaapi_encode.c b/libavcodec/vaapi_encode.c
index c02b633b4679d1f95eac9346a709d2eeeb16cbbb..411d8790919dcce249abe99b4dfaad69facbd300 100644
--- a/libavcodec/vaapi_encode.c
+++ b/libavcodec/vaapi_encode.c
@@ -428,6 +428,8 @@ fail:
 fail_at_end:
     av_freep(&pic->codec_picture_params);
     av_frame_free(&pic->recon_image);
+    av_buffer_unref(&pic->output_buffer_ref);
+    pic->output_buffer = VA_INVALID_ID;
     return err;
 }