diff --git a/libavformat/mux.c b/libavformat/mux.c
index be72d91867..dbb9b55f39 100644
--- a/libavformat/mux.c
+++ b/libavformat/mux.c
@@ -421,6 +421,8 @@ int avformat_write_header(AVFormatContext *s, AVDictionary **options)
             ret = s->pb->error;
         if (ret < 0)
             return ret;
+        if (s->flush_packets && s->pb && s->pb->error >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
+            avio_flush(s->pb);
     }
 
     if ((ret = init_pts(s)) < 0)