diff --git a/ffmpeg.c b/ffmpeg.c
index 86fbf3d5b47d68f83635eb69105ce9db66de8030..bbb6fabe47a964a5833e3f04f609cfeec0c96605 100644
--- a/ffmpeg.c
+++ b/ffmpeg.c
@@ -1510,6 +1510,12 @@ static int av_encode(AVFormatContext **output_files,
     /* dump report by using the first video and audio streams */
     print_report(output_files, ost_table, nb_ostreams, 1);
 
+    /* write the trailer if needed and close file */
+    for(i=0;i<nb_output_files;i++) {
+        os = output_files[i];
+        av_write_trailer(os);
+    }
+
     /* close each encoder */
     for(i=0;i<nb_ostreams;i++) {
         ost = ost_table[i];
@@ -1526,13 +1532,7 @@ static int av_encode(AVFormatContext **output_files,
             avcodec_close(&ist->st->codec);
         }
     }
-    
 
-    /* write the trailer if needed and close file */
-    for(i=0;i<nb_output_files;i++) {
-        os = output_files[i];
-        av_write_trailer(os);
-    }
     /* finished ! */
     
     ret = 0;