diff --git a/libavcodec/utils.c b/libavcodec/utils.c
index 9fe3a16db73131faaaa1fa7ba8696ac1a4a832dc..e0819f45150d4e7ff9e10100a61da675528f9a72 100644
--- a/libavcodec/utils.c
+++ b/libavcodec/utils.c
@@ -1920,6 +1920,8 @@ int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *pi
     // copy to ensure we do not change avpkt
     AVPacket tmp = *avpkt;
 
+    if (!avctx->codec)
+        return AVERROR(EINVAL);
     if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {
         av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");
         return AVERROR(EINVAL);