diff --git a/libavformat/utils.c b/libavformat/utils.c
index 5cf3d9cd47c226fdaddd0b54e1e724ff41959b4e..a43238bd2080651e0d1702b88000dd1ffb29b282 100644
--- a/libavformat/utils.c
+++ b/libavformat/utils.c
@@ -2137,6 +2137,8 @@ int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int
 {
     if(min_ts > ts || max_ts < ts)
         return -1;
+    if (stream_index < -1 || stream_index >= (int)s->nb_streams)
+        return AVERROR(EINVAL);
 
     if(s->seek2any>0)
         flags |= AVSEEK_FLAG_ANY;