百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

Qt使用FFmpeg播放视频

liuian 2025-01-18 21:55 14 浏览

一、使用场景

  因为项目中需要加载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 \
    -lswscale

  2.头文件

#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_H

  3.源文件:

#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();
}

相关推荐

【开源推荐】给大家推荐个基于ChatGPT的PHP开发库 openai-php-api

有了这个库大家就可以愉快的使用PHP对接chatGPT的官方接口了,至于对接了官方接口想要做什么就看你自己的啦环境要求PHP7.4或以上composer1.6.5以上支持框架Laravel、Sym...

3个最流行的大模型应用开发框架【LLM】

随着人工智能的能力,特别是大型语言模型(LLM)的不断发展和演变,开发人员正在寻求将AI功能整合到他们的应用程序中。虽然文本完成和摘要等简单任务可以通过直接调用OpenAI或Coher...

都说PHP性能差,但PHP性能真的差吗?

今天本能是想测试一个PDO持久化,会不会带来会话混乱的问题先贴一下PHP代码,代码丑了点,但是坚持能run就行,反正就是做个测试。<?php$dsn='mysql:host=l...

saas介绍和原理 · laravel-独立站-商城SaaS – 湾区梁工

SaaS就是多租户,一个应用可以分给很多用户使用,而应用只需要维护一个。那么应用就需要做好各种资源的隔离(数据库,文件,缓存,队列,后台,命令行等等)。有两种类型的多租户SaaS形式:1,单数据库Sa...

3分钟短文 | Laravel SQL筛选两个日期之间的记录,怎么写?

引言今天说一个细分的需求,在模型中,或者使用laravel提供的EloquentORM功能,构造查询语句时,返回位于两个指定的日期之间的条目。应该怎么写?本文通过几个例子,为大家梳理一下。学习时...

pip 2(根细胞吸收水借助pip2)

pip-h#-helppipdownload#下载.whl文件,然后是可以安装的UV:Python包管理神器-比pip快100倍安装方法Windows:1powershe...

想买《辐射4》的Pip-Boy特别版?那你可得抓紧点

今年秋天玩家就能够玩到《辐射4(Fallout4)》,而且还可以边玩这款游戏边把真实的Pip-Boy穿戴装置套在手上。最近,这款游戏的Pip-Boy特殊版本已经开放玩家在百思买、沃尔玛以及GameS...

PaddleOCR 介绍及部署(paddleocr 安装)

PaddleOCR是由百度飞桨(PaddlePaddle)团队开发的开源OCR工具包,凭借其高精度、多场景适应性和易用性,成为目前最受欢迎的光学字符识别工具之一。以下是其核心特点与技术亮点:一、...

从需求到技术落地:AI产品经理的技术同理心修炼

在当今快速发展的AI时代,产品经理的角色不再局限于需求收集与规划,还需要深入理解技术实现的边界与成本。本文以UnityML-Agents环境配置与寻路Demo实战为例,探讨AI产品经理如何通过亲身体...

在windows上设置python的环境(windows配置python环境)

上文安装好了python,再具体说下python语言的相关环境。#01关于PythonPython是一个高级别的、边运行边解释的、动态类型的编程语言,以简洁的语法、强大的功能和丰富的资源库而闻名。...

uv——Python开发栈中的高效全能小工具

每天写Python代码的同学,肯定都离不开pip、virtualenv、Poetry等基础工具,但是对这些工具可能是又恨又离不开。那么有什么好的替代呢,虫虫今天就给大家介绍一个替代他们的小工具uv,一...

数据驱动型Python应用开发框架:Taipy

1.介绍Taipy是一个用于构建数据驱动应用的Python框架。它允许开发者快速创建交互式数据应用,支持数据可视化、数据处理和自动化工作流。1.1Taipy核心特性低代码/无代码GUI开发数据...

推荐这几个Python实战项目,瞬间读懂Python!

推荐这几个Python实战项目,瞬间读懂Python!Python这玩意儿,说难不难,说简单吧也不是那么容易。我琢磨着,光看书学理论可不行,得动手写点东西才能真正掌握。今儿个我就给大伙儿推荐几个实战项...

Python项目源码加密部署方案(python源码加密工具)

保护Python代码的几种方式对代码进行混淆以降低源码可读性将py文件编译为二进制pyc文件使用Pyinstaller打包源码为二进制可执行文件使用PyArmor加密脚本将py/py...

史上最全!近万字梳理Python 开发必备的 os 模块(建议收藏)

点赞、收藏、加关注,下次找我不迷路一、开篇本文将带你深入探索os模块的核心功能,通过大量实际案例和代码示例,助你彻底掌握这个Python开发的必备神器。全文近万字,建议收藏后慢慢消化,用的时...