diff --git a/libavcodec/avpacket.c b/libavcodec/avpacket.c
index 87454d5647b6acc346516a10a9cedf5ab5fde834..3f8e16346726d2380e61907024863110ccfc0b7f 100644
--- a/libavcodec/avpacket.c
+++ b/libavcodec/avpacket.c
@@ -69,7 +69,7 @@ void av_packet_free(AVPacket **pkt)
 static int packet_alloc(AVBufferRef **buf, int size)
 {
     int ret;
-    if ((unsigned)size >= (unsigned)size + AV_INPUT_BUFFER_PADDING_SIZE)
+    if (size < 0 || size >= INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
         return AVERROR(EINVAL);
 
     ret = av_buffer_realloc(buf, size + AV_INPUT_BUFFER_PADDING_SIZE);