How to Use avformat_alloc_output_context2

This article explains how to allocate an output format context using the avformat_alloc_output_context2 function in the FFmpeg C API. You will learn the purpose of the function, its parameter requirements, how FFmpeg deduces the output format, and how to implement it in your C code to prepare for media muxing.

Function Signature and Parameters

The avformat_alloc_output_context2 function is the standard way to initialize an AVFormatContext for writing media files. It allocates the context and automatically selects the appropriate output container format based on the arguments you provide.

Its prototype is defined in <libavformat/avformat.h> as follows:

int avformat_alloc_output_context2(AVFormatContext **ctx,
                                   const AVOutputFormat *oformat,
                                   const char *format_name,
                                   const char *filename);

The function returns 0 on success, or a negative AVERROR code on failure.

Code Example

Below is a complete, minimal C example demonstrating how to allocate an output format context using a target filename.

#include <stdio.h>
#include <libavformat/avformat.h>

int main() {
    AVFormatContext *output_context = NULL;
    const char *filename = "output_video.mp4";

    // Allocate the output context based on the file extension
    int ret = avformat_alloc_output_context2(&output_context, NULL, NULL, filename);
    
    if (ret < 0) {
        char err_buf[AV_ERROR_MAX_STRING_SIZE];
        av_strerror(ret, err_buf, sizeof(err_buf));
        fprintf(stderr, "Could not allocate output context: %s\n", err_buf);
        return ret;
    }

    printf("Successfully allocated output context for format: %s\n", 
           output_context->oformat->name);

    // Perform further operations like adding streams and writing headers here

    // Always free the context when finished to prevent memory leaks
    avformat_free_context(output_context);

    return 0;
}

Format Selection Priority

When calling avformat_alloc_output_context2, FFmpeg determines the output container format using a strict priority queue based on your inputs:

  1. Explicit Format Object: If oformat is not NULL, FFmpeg uses that specific format.
  2. Explicit Format Name: If oformat is NULL but format_name is provided (e.g., "mpegts"), FFmpeg searches for a matching format.
  3. Filename Extension: If both oformat and format_name are NULL, FFmpeg parses the extension of the filename (e.g., .mkv) and assigns the corresponding format.

If FFmpeg cannot match a format using any of these methods, the function returns a negative error code (usually AVERROR_MUXER_NOT_FOUND).