diff --git a/libavcodec/xan.c b/libavcodec/xan.c
index c71a7185374aef934d87054c3dc45bd7a356f1e1..3965617838e80c547d9ea22ae60e26aa9b1038f5 100644
--- a/libavcodec/xan.c
+++ b/libavcodec/xan.c
@@ -112,7 +112,10 @@ static int xan_huffman_decode(unsigned char *dest, int dest_len,
     init_get_bits(&gb, ptr, ptr_len * 8);
 
     while ( val != 0x16 ) {
-        val = src[val - 0x17 + get_bits1(&gb) * byte];
+        unsigned idx = val - 0x17 + get_bits1(&gb) * byte;
+        if (idx >= 2 * byte)
+            return -1;
+        val = src[idx];
 
         if ( val < 0x16 ) {
             if (dest >= dest_end)