Skip to content
systemcoding.dev
Media

Open an input with avformat_open_input

Open a media file in C with avformat_open_input from libavformat 61 (FFmpeg 7.1), check the negative error code, and release it with avformat_close_input.

2 min read
Summarize in AI

Every libav program starts the same way: ask libavformat to open the file and detect the container. avformat_open_input allocates the AVFormatContext for you when you pass a pointer to a NULL pointer, and it reports failure as a negative AVERROR code.

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

int main(int argc, char **argv) {
    AVFormatContext *fmt = NULL;
    char err[AV_ERROR_MAX_STRING_SIZE];

    int ret = avformat_open_input(&fmt, argv[1], NULL, NULL);
    if (ret < 0) {
        av_strerror(ret, err, sizeof err);
        fprintf(stderr, "open %s: %s\n", argv[1], err);
        return 1;
    }
    printf("container: %s\n", fmt->iformat->name);
    avformat_close_input(&fmt);
    return 0;
}
Text
container: mov,mp4,m4a,3gp,3g2,mj2

The container name is a comma-separated list because one demuxer, mov, serves MP4, M4A, 3GP and their relatives. Compile with cc open.c $(pkg-config --cflags --libs libavformat libavutil) against FFmpeg 7.1.

Two details save debugging time. On failure the function frees the context and sets your pointer back to NULL, so you must not call avformat_close_input afterwards. On success, use avformat_close_input and never avformat_free_context, because only the first one also closes the I/O handle and sets the pointer to NULL. Opening reads the container header only: for formats without one the stream list is still empty, which is the next snippet. See avformat_open_input in the API reference.

Taggedclibav
Share

More snippets

Media

List ALSA devices with aplay -l

List the playback cards and devices ALSA sees with aplay -l from alsa-utils 1.2, and turn the output into a hw:card,device name.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.