diff --git a/libavcodec/msrledec.c b/libavcodec/msrledec.c
index 7f9adcdce65497413263fbd21124918289af1300..b8f5e6246b7d59950dd09f9e4dc97b9d769b090b 100644
--- a/libavcodec/msrledec.c
+++ b/libavcodec/msrledec.c
@@ -167,7 +167,8 @@ static int msrle_decode_8_16_24_32(AVCodecContext *avctx, AVPicture *pic, int de
                 continue;
             }
             // Copy data
-            if (output + p2 * (depth >> 3) > output_end) {
+            if ((pic->linesize[0] > 0 && output + p2 * (depth >> 3) > output_end)
+              ||(pic->linesize[0] < 0 && output + p2 * (depth >> 3) < output_end)) {
                 src += p2 * (depth >> 3);
                 continue;
             }
@@ -211,7 +212,8 @@ static int msrle_decode_8_16_24_32(AVCodecContext *avctx, AVPicture *pic, int de
                      src += 4;
                      break;
             }
-            if (output + p1 * (depth >> 3) > output_end)
+            if ((pic->linesize[0] > 0 && output + p1 * (depth >> 3) > output_end)
+              ||(pic->linesize[0] < 0 && output + p1 * (depth >> 3) < output_end))
                 continue;
             for(i = 0; i < p1; i++) {
                 switch(depth){