diff --git a/libavformat/mpeg.c b/libavformat/mpeg.c
index 6618d5f46955460cce0ece3ee0883f9658d8e8a5..e0060584c6d9d10094655e8ae5208cdf9f1f9ece 100644
--- a/libavformat/mpeg.c
+++ b/libavformat/mpeg.c
@@ -730,6 +730,15 @@ static void flush_packet(AVFormatContext *ctx, int stream_index,
             }
         }
 
+        if (s->is_mpeg2) {
+            /* special stuffing byte that is always written
+               to prevent accidental generation of start codes. */
+            put_byte(&ctx->pb, 0xff);
+
+            for(i=0;i<stuffing_size;i++)
+                put_byte(&ctx->pb, 0xff);
+        }
+
         if (startcode == PRIVATE_STREAM_1) {
             put_byte(&ctx->pb, id);
             if (id >= 0xa0) {
@@ -746,15 +755,6 @@ static void flush_packet(AVFormatContext *ctx, int stream_index,
             }
         }
 
-        if (s->is_mpeg2) {
-            /* special stuffing byte that is always written
-               to prevent accidental generation of start codes. */
-            put_byte(&ctx->pb, 0xff);
-
-            for(i=0;i<stuffing_size;i++)
-                put_byte(&ctx->pb, 0xff);
-        }
-
         /* output data */
         put_buffer(&ctx->pb, stream->buffer, payload_size - stuffing_size);
     }