用Qt调用ffmpeg接口的简单例子
时间: 2023-07-19 20:22:22 浏览: 137
下面是一个简单的使用Qt调用FFmpeg接口的例子:
```cpp
#include <QCoreApplication>
#include <QDebug>
#include <QString>
#include <QByteArray>
#include <QFile>
#include <QDir>
#include <QProcess>
#include <iostream>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 注册所有FFmpeg组件
av_register_all();
// 打开输入文件
AVFormatContext *pFormatCtx = NULL;
if (avformat_open_input(&pFormatCtx, "input.mp4", NULL, NULL) != 0) {
qCritical() << "Could not open input file" << endl;
return -1;
}
// 获取流信息
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
qCritical() << "Could not find stream information" << endl;
return -1;
}
// 找到视频流
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) {
qCritical() << "Could not find video stream" << endl;
return -1;
}
// 获取视频解码器
AVCodecParameters *pCodecParams = pFormatCtx->streams[videoStream]->codecpar;
AVCodec *pCodec = avcodec_find_decoder(pCodecParams->codec_id);
if (pCodec == NULL) {
qCritical() << "Could not find codec" << endl;
return -1;
}
// 打开解码器
AVCodecContext *pCodecCtx = avcodec_alloc_context3(pCodec);
if (avcodec_parameters_to_context(pCodecCtx, pCodecParams) < 0) {
qCritical() << "Could not copy codec parameters to decoder context" << endl;
return -1;
}
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
qCritical() << "Could not open codec" << endl;
return -1;
}
// 获取帧缓冲
AVFrame *pFrame = av_frame_alloc();
if (pFrame == NULL) {
qCritical() << "Could not allocate frame" << endl;
return -1;
}
// 读取视频帧
AVPacket packet;
int frameCount = 0;
while (av_read_frame(pFormatCtx, &packet) >= 0) {
if (packet.stream_index == videoStream) {
// 解码视频帧
int ret = avcodec_send_packet(pCodecCtx, &packet);
if (ret < 0) {
qCritical() << "Error sending packet to decoder" << endl;
return -1;
}
while (ret >= 0) {
ret = avcodec_receive_frame(pCodecCtx, pFrame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
break;
} else if (ret < 0) {
qCritical() << "Error during decoding" << endl;
return -1;
}
// 处理视频帧
std::cout << "Frame " << frameCount << " (type=" << pFrame->pict_type << ", size=" << pFrame->pkt_size << ")" << std::endl;
frameCount++;
}
}
av_packet_unref(&packet);
}
// 释放资源
avcodec_free_context(&pCodecCtx);
avformat_close_input(&pFormatCtx);
avformat_free_context(pFormatCtx);
av_frame_free(&pFrame);
return a.exec();
}
```
这个例子演示了如何使用FFmpeg解码视频帧。请注意,此代码仅为示例,实际使用时可能需要进行更多的错误处理和资源管理。
阅读全文