diff --git a/libavcodec/utils.c b/libavcodec/utils.c
index 4ab0c350ee4438bfa3184790da0b84a528a556c8..c3df903f1e161c2e3829aa84c3780778747e5817 100644
--- a/libavcodec/utils.c
+++ b/libavcodec/utils.c
@@ -480,6 +480,11 @@ int attribute_align_arg avcodec_open(AVCodecContext *avctx, AVCodec *codec)
     }
 
     avctx->codec = codec;
+    if ((avctx->codec_type == CODEC_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
+        avctx->codec_id == CODEC_ID_NONE) {
+        avctx->codec_type = codec->type;
+        avctx->codec_id   = codec->id;
+    }
     if(avctx->codec_id != codec->id || avctx->codec_type != codec->type){
         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
         goto free_and_end;