How to Close Output Files with av_write_trailer

When working with the FFmpeg C API, properly finalizing a media container is crucial to ensure the output file is valid and playable. This article provides a direct, step-by-step guide on how to use av_write_trailer to write necessary container metadata, flush remaining packets, and cleanly close your output file structure to prevent data corruption.

What is av_write_trailer?

The av_write_trailer function is the final writing step in the FFmpeg multiplexing process. It writes the stream trailer to an output media file and finalizes the container format. For many formats (like MP4 or MKV), this function performs critical tasks such as: * Writing index tables (moov atom in MP4). * Updating duration headers. * Flushing any remaining delayed packets in the muxer.

Without calling this function, your output file will likely be corrupted, unindexed, or unplayable by standard media players.

Step-by-Step Implementation

To close your output file correctly, you must call av_write_trailer after all media packets have been written with av_interleaved_write_frame or av_write_frame.

Here is the standard code sequence to finalize and free your resources:

// 1. Write the trailer to the output file
int ret = av_write_trailer(format_context);
if (ret < 0) {
    fprintf(stderr, "Error occurred when writing output file trailer\n");
    // Handle error accordingly
}

// 2. Close the output file context if it was opened
if (format_context && !(format_context->oformat->flags & AVFMT_NOFILE)) {
    avio_closep(&format_context->pb);
}

// 3. Free the format context and associated streams
avformat_free_context(format_context);
format_context = NULL;

Key Considerations