diff --git a/libavformat/apetag.c b/libavformat/apetag.c
index 7d2f0b3222dfc1418bb1d0fefc349da7835a5754..c8d1bdca5ad063350620b821fd6aaf846aa7ce65 100644
--- a/libavformat/apetag.c
+++ b/libavformat/apetag.c
@@ -55,8 +55,10 @@ static int ape_tag_read_field(AVFormatContext *s)
         av_log(s, AV_LOG_WARNING, "Invalid APE tag key '%s'.\n", key);
         return -1;
     }
-    if (size >= UINT_MAX)
-        return -1;
+    if (size > INT32_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
+        av_log(s, AV_LOG_ERROR, "APE tag size too large.\n");
+        return AVERROR_INVALIDDATA;
+    }
     if (flags & APE_TAG_FLAG_IS_BINARY) {
         uint8_t filename[1024];
         enum AVCodecID id;