diff --git a/libavformat/mux.c b/libavformat/mux.c
index f29d731..da63070 100644
--- a/libavformat/mux.c
+++ b/libavformat/mux.c
@@ -932,10 +932,14 @@ int av_write_trailer(AVFormatContext *s)
             goto fail;
     }
 
+fail:
     if (s->oformat->write_trailer)
+        if (ret == 0) {
         ret = s->oformat->write_trailer(s);
+        } else {
+            s->oformat->write_trailer(s);
+        }
 
-fail:
     if (s->pb)
        avio_flush(s->pb);
     if (ret == 0)
