diff --git a/libavformat/4xm.c b/libavformat/4xm.c
index 39b30413cf..e93095cb09 100644
--- a/libavformat/4xm.c
+++ b/libavformat/4xm.c
@@ -218,6 +218,7 @@ static int fourxm_read_header(AVFormatContext *s)
     fourxm->track_count = 0;
     fourxm->tracks      = NULL;
     fourxm->fps         = (AVRational){1,1};
+    fourxm->video_stream_index = -1;
 
     /* skip the first 3 32-bit numbers */
     avio_skip(pb, 12);
@@ -323,6 +324,8 @@ static int fourxm_read_packet(AVFormatContext *s,
         case cfr2_TAG:
             /* allocate 8 more bytes than 'size' to account for fourcc
              * and size */
+            if (fourxm->video_stream_index < 0)
+                return AVERROR_INVALIDDATA;
             if (size + 8 < size || av_new_packet(pkt, size + 8))
                 return AVERROR(EIO);
             pkt->stream_index = fourxm->video_stream_index;