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.

  1. Allocate the Output Format Context: Initialize the AVFormatContext for your output file format (e.g., MP4, MKV, or FLV).
  2. Create Streams: Add video or audio streams to the context using avformat_new_stream.
  3. Configure Codec Parameters: Copy the codec parameters from your encoder context to the stream’s codecpar field using avcodec_parameters_from_context.
  4. Open the Output File: Open the target file for writing using the avio_open or avio_open2 function.

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