背景
这段时间突发奇想,想要给 Godot 引擎的视频组件做一个 ffmpeg 的兼容层,整完这个就做 CS61B 的 lab 去了。今天晚上上完离散数学已经差不多九点了,以为配个环境应该要不了半小时,结果中间出各种问题,一直折腾到现在。现在把配置工作差不多做完了,顺便把踩的坑记录一下。
几个关键问题
下载版本的选择
说实话 Windows 系统在这种时候就极其拉垮,开始下了全部源文件准备自己编译,结果 Windows 这边就出各种奇异搞笑问题。所以我的建议是,如果用 Windows 系统,最好还是去下预编译的版本吧……省事又省心。
一个预编译版本可在 ffmpeg 官网 找到。

进入 Release 中下载 Windows 的包,解压缩。
CMake 项目架构
首先把 lib include 目录都放到正确的地方。例如我这里:
1 2 3 4 5 6 7 8 9 10 11 12 13
| Project/ thirdparty/ libavx/ include/ libavcodec/ ... libavdevice/ ... lib/ ...
src/ main.cpp
|
然后 CMakeList.txt 文件我是这么写的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| cmake_minimum_required(VERSION 3.29) project(godot_ffmpeg)
set(CMAKE_CXX_STANDARD 17)
include_directories(thirdparty/libavx/include) link_directories(thirdparty/libavx/lib)
add_executable(godot_ffmpeg src/main.cpp)
target_link_libraries( godot_ffmpeg avcodec avdevice avfilter avformat avutil postproc swresample swscale )
|
这样 CMakeList 算是勉强配置好了。
使用 C++ 调用 ffmpeg 函数
我这里创建的是一个 C++ 项目(因为 GDExtension 提供的是 C++ API)开始编译的时候报 undefined reference to xxx
,这个解决起来简单,加个 extern "C"
的事情。
1 2 3 4
| extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> }
|
动态链接库
现在可以正常过编译了,但是运行时直接退出,返回 -1073741515 (0xC0000135)
。这个是因为没有找到动态链接库导致的。把刚才下载的预编译包的 bin 里的 dll 复制到输出目录下面即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include <iostream> extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> }
int main() { AVFormatContext* avFormatContext = avformat_alloc_context(); if (avFormatContext == nullptr) { std::cout << "avFormatContext is nullptr" << std::endl; } else { std::cout << "avFormatContext is not nullptr" << std::endl; } avformat_free_context(avFormatContext); return 0; }
|
运行正常输出:
1
| avcodec_alloc_context success
|
以上。