diff --git a/libavcodec/mjpegdec.c b/libavcodec/mjpegdec.c
index 058b08fa83cf8971f66d261a536d51e20f470005..7a85c16d95476a9542260d650ef71458fd9556d2 100644
--- a/libavcodec/mjpegdec.c
+++ b/libavcodec/mjpegdec.c
@@ -881,14 +881,22 @@ static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, i
                 }
             }
 
-            if (s->restart_interval && show_bits(&s->gb, 8) == 0xFF){ /* skip RSTn */
-                --s->restart_count;
-                align_get_bits(&s->gb);
-                while(show_bits(&s->gb, 8) == 0xFF)
-                    skip_bits(&s->gb, 8);
-                skip_bits(&s->gb, 8);
-                for (i=0; i<nb_components; i++) /* reset dc */
-                    s->last_dc[i] = 1024;
+            if (s->restart_interval) {
+                s->restart_count--;
+                i = 8 + ((-get_bits_count(&s->gb)) & 7);
+                /* skip RSTn */
+                if (show_bits(&s->gb, i) == (1 << i) - 1) {
+                    int pos = get_bits_count(&s->gb);
+                    align_get_bits(&s->gb);
+                    while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
+                        skip_bits(&s->gb, 8);
+                    if ((get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
+                        for (i = 0; i < nb_components; i++) /* reset dc */
+                            s->last_dc[i] = 1024;
+                    } else {
+                        skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
+                    }
+                }
             }
         }
     }