Skip to content
systemcoding.dev
Media

Pick the main video stream with av_find_best_stream

Pick the main video or audio stream with av_find_best_stream, which returns an index and can hand back the decoder, instead of looping over streams yourself.

2 min read
Summarize in AI

A file can hold several video tracks, such as a cover image stored as a stream, or a second audio language. Looping over fmt->streams and taking the first of a type picks the wrong one often enough to matter. av_find_best_stream applies the library's own ranking.

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

int main(int argc, char **argv) {
    AVFormatContext *fmt = NULL;
    if (avformat_open_input(&fmt, argv[1], NULL, NULL) < 0) return 1;
    if (avformat_find_stream_info(fmt, NULL) < 0) return 1;

    const AVCodec *dec = NULL;
    int v = av_find_best_stream(fmt, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
    int a = av_find_best_stream(fmt, AVMEDIA_TYPE_AUDIO, -1, v, NULL, 0);

    printf("video stream: %d (%s)\n", v, dec ? dec->name : "no decoder");
    printf("audio stream: %d\n", a);
    avformat_close_input(&fmt);
    return 0;
}
Text
video stream: 0 (h264)
audio stream: 1

The result is a stream index, or a negative error: AVERROR_STREAM_NOT_FOUND when there is no stream of that type, and AVERROR_DECODER_NOT_FOUND when there is one but no decoder was compiled in. The fifth argument returns the decoder as a const AVCodec * since FFmpeg 5.0, so the pointer must be const.

The third and fourth arguments let you ask for a stream related to another one. Passing the video index as related_stream makes the audio choice prefer a track in the same program, which matters in MPEG-TS. The function also skips streams flagged as attached pictures, so an MP3 with cover art does not report it as the video. The function is in the libavformat API.

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.