Qt使用FFmpeg播放视频
liuian 2025-01-18 21:55 33 浏览
一、使用场景
因为项目中需要加载MP4播放开机视频,而我们的设备所使用的架构为arm架构,其中缺乏一些多媒体库。安装这些插件库比较麻烦,所以最终决定使用FFmpeg播放视频。
二、下载编译ffmpeg库
2.1 下载源码
源码下载路径:https://www.ffmpeg.org/download.html#build-windows
2.2 编译源码
1) 解压:将源码放到指定目录,并运行"tar -jxvf ffmpeg-snapshot.tar.bz2"。若是xxx.tar.gz源文件,则用"tar -zxvf ffmpeg-xxx.tar.gz"。
2) 创建构建目录,"cd ffmpeg", "mkdir build";
3)编译:
a) ubuntu编译: "./configure --enable-static --prefix=./build"
b)arm交叉编译: "./configure --cc=xxx/aarch64-linux-gnu-gcc(QT指定的gcc路径) --cxx=xxx/aarch64-linux-gnu-g++ --enable-staticc(QT指定的g++路径) --prefix=./build --enable-cross-compile --arch=arm64 --target-os=linux"。
4) make安装: "make && make install"。
5) 运行:若需要运行ffmpeg则需要增加--enable-shared参数,并且添加环境变量"export LD_LIBRARY_PATH=xxx/build/lib/"。
6)使用帮助: 在xxx/build/bin路径下运行"./ffmpeg --help"。
2.3 常见报错
1) 交叉编译需要指定对应的gcc和g++编译器和其它的如平台参数,Linux的QTCreator可以通过如下选项查看对应的编译器路径,工程-》管理构建-》编译器-》指南(Manual)-》双击gcc或g++。注意在操作之前需要先选择工程当前的运行和构建平台为arrch64。
2) make install 报错:"strip: Unable to recognise the format of the input file":将config.mak中的"Trip=strip"改为"Trip=arm -linux-strip"。
三、使用源码
1.在工程中导入头文件和库,注意库顺序。eg:
INCLUDEPATH += xxx/build/include
LIBS += -Lxxx/xxx -lavformat\
-lavdevice \
-lavcodec \
-lswresample \
-lavfilter \
-lavutil \
-lswscale2.头文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDebug>
#include <QTimer>
#include <QTime>
#include <QAudioOutput>
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavdevice/avdevice.h>
#include <libavformat/version.h>
#include <libavutil/time.h>
#include <libavutil/mathematics.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavutil/avutil.h>
#include <libavutil/imgutils.h>
#include <libavutil/pixfmt.h>
#include <libswresample/swresample.h>
}
#define MAX_AUDIO_FRAME_SIZE 192000
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
public slots:
void timeCallback(void);
void on_play_clicked();
void resizeEvent(QResizeEvent* );
private:
Ui::MainWindow *ui;
int playVedio(void);
QTimer *timer; // 定时播放,根据帧率来
int vedioW,vedioH; // 图像宽高
QList<QPixmap> vedioBuff; // 图像缓存区
QString myUrl = QString("E:/workspace/Qt_workspace/ffmpeg/三国之战神无双.mp4"); // 视频地址
AVFormatContext *pFormatCtx;
AVCodecContext *pCodecCtx;
AVCodec *pCodec;
AVFrame *pFrame, *pFrameRGB;
int ret, got_picture,got_audio; // 视频解码标志
int videoindex; // 视频序号
// 音频
int audioindex; // 音频序号
AVCodecParameters *aCodecParameters;
AVCodec *aCodec;
AVCodecContext *aCodecCtx;
QByteArray byteBuf;//音频缓冲
QAudioOutput *audioOutput;
QIODevice *streamOut;
};
#endif // MAINWINDOW_H3.源文件:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// qDebug(avcodec_configuration());
// unsigned version = avcodec_version();
// QString ch = QString::number(version,10);
// qDebug()<<"version:"<<version;
timer = new QTimer(this);
timer->setTimerType(Qt::PreciseTimer); // 精准定时设置
connect(timer,SIGNAL(timeout()),this,SLOT(timeCallback()));
}
void MainWindow::timeCallback(void)
{
// 视频缓存播放
if(!vedioBuff.isEmpty())
{
ui->label->setPixmap(vedioBuff.at(0));
vedioBuff.removeAt(0);
}
else {
timer->stop();
}
// 音频缓存播放
if(audioOutput && audioOutput->state() != QAudio::StoppedState && audioOutput->state() != QAudio::SuspendedState)
{
int writeBytes = qMin(byteBuf.length(), audioOutput->bytesFree());
streamOut->write(byteBuf.data(), writeBytes);
byteBuf = byteBuf.right(byteBuf.length() - writeBytes);
}
}
void Delay_MSec(unsigned int msec)
{
QTime _Timer = QTime::currentTime().addMSecs(msec);
while( QTime::currentTime() < _Timer )
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
int MainWindow::playVedio(void)
{
QAudioFormat fmt;
fmt.setSampleRate(44100);
fmt.setSampleSize(16);
fmt.setChannelCount(2);
fmt.setCodec("audio/pcm");
fmt.setByteOrder(QAudioFormat::LittleEndian);
fmt.setSampleType(QAudioFormat::SignedInt);
audioOutput = new QAudioOutput(fmt);
streamOut = audioOutput->start();
char *filepath = myUrl.toUtf8().data();
av_register_all();
avformat_network_init();
pFormatCtx = avformat_alloc_context();
// 打开视频文件,初始化pFormatCtx结构
if(avformat_open_input(&pFormatCtx,filepath,NULL,NULL)!=0){
qDebug("视频文件打开失败.\n");
return -1;
}
// 获取音视频流
if(avformat_find_stream_info(pFormatCtx,NULL)<0){
qDebug("媒体流获取失败.\n");
return -1;
}
videoindex = -1;
audioindex = -1;
//nb_streams视音频流的个数,这里当查找到视频流时就中断了。
for(int i=0; i<pFormatCtx->nb_streams; i++)
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){
videoindex=i;
break;
}
if(videoindex==-1){
qDebug("找不到视频流.\n");
return -1;
}
//nb_streams视音频流的个数,这里当查找到音频流时就中断了。
for(int i=0; i<pFormatCtx->nb_streams; i++)
if(pFormatCtx->streams[i]->codecpar->codec_type==AVMEDIA_TYPE_AUDIO){
audioindex=i;
break;
}
if(audioindex==-1){
qDebug("找不到音频流.\n");
return -1;
}
//获取视频流编码结构
pCodecCtx=pFormatCtx->streams[videoindex]->codec;
float frameNum = pCodecCtx->framerate.num; // 每秒帧数
if(frameNum>100) frameNum = frameNum/1001;
int frameRate = 1000/frameNum; //
qDebug("帧/秒 = %f 播放间隔是时间=%d\n",frameNum,frameRate);
//查找解码器
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL)
{
qDebug("找不到解码器.\n");
return -1;
}
//使用解码器读取pCodecCtx结构
if(avcodec_open2(pCodecCtx, pCodec,NULL)<0)
{
qDebug("打开视频码流失败.\n");
return -1;
}
//获取音频流编码结构-------------------------------------------------------------
aCodecParameters = pFormatCtx->streams[audioindex]->codecpar;
aCodec = avcodec_find_decoder(aCodecParameters->codec_id);
if (aCodec == 0) {
qDebug("找不到解码器.\n");
return -1;
}
aCodecCtx = avcodec_alloc_context3(aCodec);
avcodec_parameters_to_context(aCodecCtx, aCodecParameters);
//使用解码器读取aCodecCtx结构
if (avcodec_open2(aCodecCtx, aCodec, 0) < 0) {
qDebug("打开视频码流失败.\n");
return 0;
}
// 清空缓存区
byteBuf.clear();
vedioBuff.clear();
//创建帧结构,此函数仅分配基本结构空间,图像数据空间需通过av_malloc分配
pFrame = av_frame_alloc();
pFrameRGB = av_frame_alloc();
// 获取音频参数
uint64_t out_channel_layout = aCodecCtx->channel_layout;
AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
int out_sample_rate = aCodecCtx->sample_rate;
int out_channels = av_get_channel_layout_nb_channels(out_channel_layout);
uint8_t *audio_out_buffer = (uint8_t *)av_malloc(MAX_AUDIO_FRAME_SIZE*2);
SwrContext *swr_ctx = swr_alloc_set_opts(NULL, out_channel_layout, out_sample_fmt,out_sample_rate, aCodecCtx->channel_layout, aCodecCtx->sample_fmt, aCodecCtx->sample_rate, 0, 0);
swr_init(swr_ctx);
//创建动态内存,创建存储图像数据的空间
unsigned char *out_buffer = (unsigned char *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_RGB32, pCodecCtx->width, pCodecCtx->height, 1));
av_image_fill_arrays(pFrameRGB->data, pFrameRGB->linesize, out_buffer, AV_PIX_FMT_RGB32, pCodecCtx->width, pCodecCtx->height, 1);
AVPacket *packet = (AVPacket *)av_malloc(sizeof(AVPacket));
//初始化img_convert_ctx结构
struct SwsContext *img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_RGB32, SWS_BICUBIC, NULL, NULL, NULL);
timer->start(frameRate); //定时间隔播放
while (av_read_frame(pFormatCtx, packet) >= 0){
if (packet->stream_index == audioindex){
int ret = avcodec_decode_audio4(aCodecCtx, pFrame, &got_audio, packet);
if ( ret < 0)
{
qDebug("解码失败.\n");
return 0;
}
if (got_audio)
{
int len = swr_convert(swr_ctx, &audio_out_buffer, MAX_AUDIO_FRAME_SIZE, (const uint8_t **)pFrame->data, pFrame->nb_samples);
if (len <= 0)
{
continue;
}
int dst_bufsize = av_samples_get_buffer_size(0, out_channels, len, out_sample_fmt, 1);
QByteArray atemp = QByteArray((const char *)audio_out_buffer, dst_bufsize);
byteBuf.append(atemp);
}
}
//如果是视频数据
else if (packet->stream_index == videoindex){
//解码一帧视频数据
ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
if (ret < 0){
qDebug("解码失败.\n");
return 0;
}
if (got_picture){
sws_scale(img_convert_ctx, (const unsigned char* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
pFrameRGB->data, pFrameRGB->linesize);
QImage img((uchar*)pFrameRGB->data[0],pCodecCtx->width,pCodecCtx->height,QImage::Format_RGB32);
img = img.scaled(vedioW, vedioH);
QPixmap temp = QPixmap::fromImage(img);
vedioBuff.append(temp);
Delay_MSec(frameRate-5); // 这里需要流出时间来显示,如果不要这个延时界面回卡死到整个视频解码完成才能播放显示
//ui->label->setPixmap(temp);
}
}
av_free_packet(packet);
}
sws_freeContext(img_convert_ctx);
av_frame_free(&pFrameRGB);
av_frame_free(&pFrame);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
}
void MainWindow::resizeEvent(QResizeEvent* )
{
vedioW = ui->label->width();
vedioH = ui->label->height();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_play_clicked()
{
vedioW = ui->label->width();
vedioH = ui->label->height();
if(timer->isActive()) timer->stop();
playVedio();
}相关推荐
- MySQL慢查询优化:从explain到索引,DBA手把手教你提升10倍性能
-
数据库性能是应用系统的生命线,而慢查询就像隐藏在系统中的定时炸弹。某电商平台曾因一条未优化的SQL导致订单系统响应时间从200ms飙升至8秒,最终引发用户投诉和订单流失。今天我们就来系统学习MySQL...
- 一文读懂SQL五大操作类别(DDL/DML/DQL/DCL/TCL)的基础语法
-
在SQL中,DDL、DML、DQL、DCL、TCL是按操作类型划分的五大核心语言类别,缩写及简介如下:DDL(DataDefinitionLanguage,数据定义语言):用于定义和管理数据库结构...
- 闲来无事,学学Mysql增、删,改,查
-
Mysql增、删,改,查1“增”——添加数据1.1为表中所有字段添加数据1.1.1INSERT语句中指定所有字段名语法:INSERTINTO表名(字段名1,字段名2,…)VALUES(值1...
- 数据库:MySQL 高性能优化规范建议
-
数据库命令规范所有数据库对象名称必须使用小写字母并用下划线分割所有数据库对象名称禁止使用MySQL保留关键字(如果表名中包含关键字查询时,需要将其用单引号括起来)数据库对象的命名要能做到见名识意,...
- 下载工具合集_下载工具手机版
-
迅雷,在国内的下载地位还是很难撼动的,所需要用到的地方还挺多。缺点就是不开会员,软件会限速。EagleGet,全能下载管理器,支持HTTP(S)FTPMMSRTSP协议,也可以使用浏览器扩展检测...
- mediamtx v1.15.2 更新详解:功能优化与问题修复
-
mediamtxv1.15.2已于2025年10月14日发布,本次更新在功能、性能优化以及问题修复方面带来了多项改进,同时也更新了部分依赖库并提升了安全性。以下为本次更新的详细内容:...
- 声学成像仪:泄露监测 “雷达” 方案开启精准防控
-
声学成像仪背景将声像图与阵列上配装的摄像实所拍的视频图像以透明的方式叠合在一起,就形成了可直观分析被测物产生状态。这种利用声学、电子学和信息处理等技术,变换成人眼可见的图像的技术可以帮助人们直观地认识...
- 最稳存储方案:两种方法将摄像头接入威联通Qu405,录像不再丢失
-
今年我家至少被4位邻居敲门,就是为了查监控!!!原因是小区内部监控很早就停止维护了,半夜老有小黄毛掰车门偷东西,还有闲的没事划车的,车主损失不小,我家很早就配备监控了,人来亮灯有一定威慑力,不过监控设...
- 离岗检测算法_离岗检查内容
-
一、研发背景如今社会许多岗位是严禁随意脱离岗位的,如塔台、保安室、监狱狱警监控室等等,因为此类行为可能会引起重大事故,而此类岗位监督管理又有一定困难,因此促生了智能视频识别系统的出现。二、产品概述及工...
- 消防安全通道占用检测报警系统_消防安全通道占用检测报警系统的作用
-
一、产品概述科缔欧消防安全通道占用检测报警系统,是创新行业智能监督管理方式、完善监管部门动态监控及预警预报体系的信息化手段,是实现平台远程监控由“人为监控”向“智能监控”转变的必要手段。产品致力于设...
- 外出住酒店、民宿如何使用手机检测隐藏的监控摄像头
-
最近,一个家庭在他们的民宿收到了一个大惊喜:客厅里有一个伪装成烟雾探测器的隐藏摄像头,监视着他们的一举一动。隐藏摄像头的存在如果您住在酒店或民宿,隐藏摄像头不应再是您的担忧。对于民宿,房东应报告所有可...
- 基于Tilera众核平台的流媒体流量发生系统的设计
-
曾帅,高宗彬,赵国锋(重庆邮电大学通信与信息工程学院,重庆400065)摘要:设计了一种基于Tilera众核平台高强度的流媒体流量发生系统架构,其主要包括:系统界面管理模块、服务承载模块和流媒体...
- 使用ffmpeg将rtsp流转流实现h5端播放
-
1.主要实现rtsp转tcp协议视频流播放ffmpeg下载安装(公认业界视频处理大佬)a、官网地址:www.ffmpeg.org/b、gitHub:github.com/FFmpeg/FFmp…c、推...
- 将摄像头视频流从Rtsp协议转为websocket协议
-
写在前面很多通过摄像头拿到的视频流格式都是Rtsp协议的,比如:海康威视摄像头。在现代的浏览器中,已经不支持直接播放Rtsp视频流,而且,海康威视提供的本身的webSdk3.3.0视频插件有很多...
- 华芸科技推出安全监控中心2.1 Beta测试版
-
全球独家支持hdmi在线实时监看摄像机画面,具单一、循环或同时监看四频道视频影像,可透过华芸专用红外线遥控器、airemote或是键盘鼠标进行操作,提供摄像机频道增购服务,满足用户弹性扩增频道需...
- 一周热门
- 最近发表
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- vscode切换git分支 (35)
- python bytes转16进制 (35)
- grep前后几行 (34)
- hashmap转list (35)
- c++ 字符串查找 (35)
- mysql刷新权限 (34)
