FFmpeg - 基本 API大全(视频编解码相关的)

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) {
  
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值