diff --git a/libavcodec/utils.c b/libavcodec/utils.c
index 97e75c87828765dec349c2b44c44b309c31edb1a..5c7885ac0769c6ebf3245107e1f3fc4f412f0c7b 100644
--- a/libavcodec/utils.c
+++ b/libavcodec/utils.c
@@ -1210,6 +1210,11 @@ int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
     memcpy(choices, fmt, (n + 1) * sizeof(*choices));
 
     for (;;) {
+        if (avctx->hwaccel && avctx->hwaccel->uninit)
+            avctx->hwaccel->uninit(avctx);
+        av_freep(&avctx->internal->hwaccel_priv_data);
+        avctx->hwaccel = NULL;
+
         ret = avctx->get_format(avctx, choices);
 
         desc = av_pix_fmt_desc_get(ret);
@@ -1218,11 +1223,6 @@ int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
             break;
         }
 
-        if (avctx->hwaccel && avctx->hwaccel->uninit)
-            avctx->hwaccel->uninit(avctx);
-        av_freep(&avctx->internal->hwaccel_priv_data);
-        avctx->hwaccel = NULL;
-
         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
             break;
         if (avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)