FFmpeg 是一个强大的多媒体处理库,下面我将介绍其基本 API 并结合网络流/本地文件解码示例说明每个 API 的功能和用法。
一、核心 API 分类
1. 格式处理 API (libavformat)
2. 编解码 API (libavcodec)
3. 实用工具 API (libavutil)
4. 图像缩放/像素格式转换 API (libswscale)
二、基本 API 详解及示例
1. 初始化相关 API
// 注册所有编解码器和格式 (4.0+已废弃,但许多示例仍保留) av_register_all(); // 初始化网络库 (用于网络流) avformat_network_init();
2. 打开输入流 API
AVFormatContext *pFormatCtx = NULL;
// 本地文件打开
const char *url = "input.mp4";
if (avformat_open_input(&pFormatCtx, url, NULL, NULL) != 0) {
printf("无法打开输入文件\n");
return -1;
}
// 网络流打开 (如RTMP)
const char *rtmp_url = "rtmp://live.example.com/app/stream";
AVDictionary *options = NULL;
av_dict_set(&options, "rtsp_transport", "tcp", 0); // 设置RTSP over TCP
av_dict_set(&options, "stimeout", "5000000", 0); // 设置超时5秒
if (avformat_open_input(&pFormatCtx, rtmp_url, NULL, &options) != 0) {
printf("无法打开网络流\n");
return -1;
}
3. 获取流信息 API
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
printf("无法获取流信息\n");
return -1;
}
// 打印流信息
av_dump_format(pFormatCtx, 0, url, 0);
4. 查找视频流 API
int videoStream = -1;
for (int i = 0; i < pFormatCtx->nb_streams; i++) {
if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
videoStream = i;
break;
}
}
if (videoStream == -1) {
printf("未找到视频流\n");
return -1;
}
5. 编解码器设置 API
// 获取编解码器参数
AVCodecParameters *pCodecParams = pFormatCtx->streams[videoStream]->codecpar;
// 查找解码器
const AVCodec *pCodec = avcodec_find_decoder(pCodecParams->codec_id);
if (!pCodec) {

最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



