How to Write a C Application Using FFmpeg libavcodec
This guide provides a straightforward walkthrough on how to create a
custom C application that integrates and links with FFmpeg’s
libavcodec library. You will learn how to set up your C
development environment, write a basic program to initialize an H.264
video decoder, and compile your project using command-line tools like
gcc and pkg-config.
Prerequisites
Before writing your application, you must install the development headers and libraries for FFmpeg.
On Ubuntu or Debian-based systems, run:
sudo apt update
sudo apt install build-essential pkg-config libavcodec-dev libavutil-devOn macOS using Homebrew, run:
brew install ffmpeg pkg-configWriting the C Code
Create a file named main.c. This program will initialize
the libavcodec library, locate the H.264 decoder, allocate
a codec context, and safely open and close the codec.
#include <stdio.h>
#include <libavcodec/avcodec.h>
int main() {
// 1. Find the H.264 decoder
const AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_H264);
if (!codec) {
fprintf(stderr, "Error: H.264 codec not found.\n");
return 1;
}
// 2. Allocate a codec context
AVCodecContext *codec_context = avcodec_alloc_context3(codec);
if (!codec_context) {
fprintf(stderr, "Error: Could not allocate codec context.\n");
return 1;
}
// 3. Open the codec
if (avcodec_open2(codec_context, codec, NULL) < 0) {
fprintf(stderr, "Error: Could not open codec.\n");
avcodec_free_context(&codec_context);
return 1;
}
// 4. Print success message and details
printf("Success: Initialized the '%s' (%s) decoder.\n",
codec->name, codec->long_name);
// 5. Clean up allocated resources
avcodec_free_context(&codec_context);
return 0;
}Compiling and Linking the Application
To compile the application, you must instruct your compiler
(gcc) where to find the FFmpeg headers and how to link
against the shared libraries (libavcodec and
libavutil). The easiest way to handle these flags
automatically is by using pkg-config.
Run the following compilation command in your terminal:
gcc main.c -o my_codec_app $(pkg-config --cflags --libs libavcodec libavutil)Understanding the Compilation Flags:
gcc main.c -o my_codec_app: Compilesmain.cand outputs an executable namedmy_codec_app.pkg-config --cflags libavcodec libavutil: Automatically locates the directory containing the header files (e.g.,-I/usr/include/x86_64-linux-gnu).pkg-config --libs libavcodec libavutil: Automatically adds the necessary linker flags (e.g.,-lavcodec -lavutil).
Running the Application
Execute the compiled binary from your terminal:
./my_codec_appUpon successful execution, the output will display:
Success: Initialized the 'h264' (H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10) decoder.