How to Use avformat_write_header in FFmpeg C API
Writing a media container header is a crucial step when muxing audio
or video streams into a file using the FFmpeg C API. This article
provides a concise, step-by-step guide on how to properly initialize,
configure, and call the avformat_write_header function to
write the necessary metadata and stream headers to an output
container.
Prerequisites Before Writing the Header
Before you can call avformat_write_header, you must set
up the output format context, add the necessary streams, and open the
output file.
- Allocate the Output Format Context: Initialize the
AVFormatContextfor your output file format (e.g., MP4, MKV, or FLV). - Create Streams: Add video or audio streams to the
context using
avformat_new_stream. - Configure Codec Parameters: Copy the codec
parameters from your encoder context to the stream’s
codecparfield usingavcodec_parameters_from_context. - Open the Output File: Open the target file for
writing using the
avio_openoravio_open2function.
Step-by-Step Implementation
Once the prerequisites are met, you can write the container header. Here is a practical C code example demonstrating how to configure and execute this process:
#include <libavformat/avformat.h>
#include <libavutil/dict.h>
int write_container_header(AVFormatContext *out_ctx) {
int ret;
AVDictionary *options = NULL;
// 1. (Optional) Set format-specific options
// For example, optimize MP4 files for web streaming (faststart)
av_dict_set(&options, "movflags", "faststart", 0);
// 2. Write the container header
ret = avformat_write_header(out_ctx, &options);
if (ret < 0) {
fprintf(stderr, "Error occurred when writing header: %s\n", av_err2str(ret));
av_dict_free(&options);
return ret;
}
// 3. Free the options dictionary
// Note: avformat_write_header consumes recognized options; free any remaining ones
av_dict_free(&options);
return 0;
}Key Considerations
- The Options Dictionary: The second argument of
avformat_write_headeraccepts a pointer to anAVDictionary. This allows you to pass muxer-specific options (such asmovflagsfor MP4/MOV, orflvflagsfor FLV). If you do not need to pass any custom options, you can simply passNULL. - Value Modification: If options are passed,
avformat_write_headerwill modify the dictionary pointer, leaving only the options that were not recognized or successfully applied. You must free this dictionary afterward usingav_dict_freeto avoid memory leaks. - Stream Validation: The function validates the streams added to the format context. If your stream parameters (such as sample rate, time base, or resolution) are invalid or unsupported by the selected muxer, the function will fail and return a negative error code.
- Time Base Initialization: During this call, FFmpeg
may update the
time_baseof the output streams to match the container’s specifications. Always use the updated streamtime_basewhen rescaling packet timestamps later during the muxing process.