栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

ffmpeg--拉流RTSP,解码后使用QT显示

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ffmpeg--拉流RTSP,解码后使用QT显示

单独开线程拉流解码,用到的ffmpeg中的函数在代码中基本都有注释。

mdecode.h

#ifndef MDECODE_H
#define MDECODE_H

#include 
#include 
#include 
#include 
extern "C"
{
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
}
class mdecode : public QThread
{
    Q_OBJECT

public:
    mdecode(QString url,AVPixelFormat pix_fmt,AVDictionary* options=nullptr);
    ~mdecode();
    void run();
private:
    AVFormatContext *pAVFormatContext=nullptr;
    AVCodecContext  *pAVCodecContext=nullptr;
    AVCodec         *pAVCodec=nullptr;
    AVPacket        *pAVpacket=nullptr;
    AVframe         *pAVframe=nullptr;
    AVframe         *pAVframeRgb=nullptr;
    struct SwsContext *pSwsContext=nullptr;
    AVPixelFormat   mpix_fmt;

    int videoIndex = -1;
    int numBytes =0;            // 解码后的数据长度
    uint8_t * outbuffer=nullptr;
    QString filename;
public :
    bool init_mdecode();
    void test_mdecode(QString out_dir);

signals:
    DrawImg(QImage img,QByteArray msg);

};

class mffmpg
{
public:
    mffmpg();
static void init_ffmpeg();
};
#endif // MDECODE_H

mdecode.cpp

#include "mdecode.h"

mdecode::mdecode(QString url,AVPixelFormat pix_fmt,AVDictionary* options)
{
    filename = url;
    mpix_fmt = pix_fmt;

}

bool mdecode::init_mdecode()
{
    int ret=0;
    pAVFormatContext = avformat_alloc_context();//分配全局上下文空间
    pAVpacket = av_packet_alloc();              //分配数据包空间
    pAVframe  = av_frame_alloc();               //分配单帧空间
    pAVframeRgb  = av_frame_alloc();           //分配rgb单帧空间
    if(!pAVFormatContext || !pAVpacket || !pAVframe || !pAVframeRgb)
    {
        qDebug()<< "init_mdecode failed";
        return false;
    }
    AVDictionary *optionsDict = NULL;
    av_dict_set(&optionsDict, "buffer_size", "1024000", 0); //设置缓存大小,1080p可将值调大
    av_dict_set(&optionsDict, "rtsp_transport", "tcp", 0); //以udp方式打开,如果以tcp方式打开将udp替换为tcp
    av_dict_set(&optionsDict, "stimeout", "20000000", 0); //设置超时断开连接时间,单位微秒
    av_dict_set(&optionsDict, "max_delay", "30000000", 0);

    ret = avformat_open_input(&pAVFormatContext, filename.toUtf8().data(), 0, 0);
    if(ret)
    {
        qDebug() << "Failed to avformat_open_input(&pAVFormatContext, filename.toUtf8().data(), 0, 0)";
        return false;
    }
    
    ret = avformat_find_stream_info(pAVFormatContext, 0);
    if(ret < 0)
    {
        qDebug() << "Failed to avformat_find_stream_info(pAVCodecContext, 0)";
        return false;
    }

    av_dump_format(pAVFormatContext, 0, filename.toUtf8().data(), 0);//打印文件中包含的格式信息

    for(int index = 0; index < pAVFormatContext->nb_streams; index++) //遍历寻找视频流
    {
        pAVCodecContext = pAVFormatContext->streams[index]->codec;
        if(pAVCodecContext->codec_type==AVMEDIA_TYPE_VIDEO)
        {
            videoIndex = index;//此处只找视频流,不找音频和其他
            break;
        }
    }
    if(videoIndex == -1 || !pAVCodecContext)
    {
        qDebug() << "Failed to find video stream";
        return false;
    }
    
    pAVCodec = avcodec_find_decoder(pAVCodecContext->codec_id);
    if(!pAVCodec)
    {
        qDebug() << "Fialed to avcodec_find_decoder(pAVCodecContext->codec_id):"<< pAVCodecContext->codec_id;
        return false;
    }
    QString url_type=filename.mid(0,4);

    if(url_type=="rtsp")
    {
        if(avcodec_open2(pAVCodecContext, pAVCodec, &optionsDict))
        {
            qDebug() <<"Failed to avcodec_open2(pAVCodecContext, pAVCodec, pAVDictionary)";
            return false;
        }
    }
    else
    {
        if(avcodec_open2(pAVCodecContext, pAVCodec, NULL))
        {
            qDebug() <<"Failed to avcodec_open2(pAVCodecContext, pAVCodec, pAVDictionary)";
            return false;
        }
    }
    qDebug()<<"video W x H:"<< pAVCodecContext->width << "x" << pAVCodecContext->height<pix_fmt;
    numBytes = avpicture_get_size(mpix_fmt,pAVCodecContext->width,pAVCodecContext->height);       //计算转换后的内存大小
    outbuffer=(uchar*)av_malloc(numBytes);//申请转换后图片存放的内存

    
    avpicture_fill((AVPicture *)pAVframeRgb,outbuffer,mpix_fmt,pAVCodecContext->width,pAVCodecContext->height);

    
    pSwsContext = sws_getContext(pAVCodecContext->width,pAVCodecContext->height,pAVCodecContext->pix_fmt,//转换前的长、宽、像素格式
                                 pAVCodecContext->width,pAVCodecContext->height,mpix_fmt,         //转换后的长、宽、像素格式
                                 SWS_BICUBIC,                                                      //转换方法  libswscale/swscale.h
                                 0,0,0                                                                   //其他参数默认为空
                                 );
    return true;
}


void mdecode::test_mdecode(QString out_dir)
{
    int frameIndex=0;
    while(av_read_frame(pAVFormatContext,pAVpacket)>=0) //av_read_frame()读取一帧数据
    {
        if(pAVpacket->stream_index==videoIndex)
        {
            if(avcodec_send_packet(pAVCodecContext, pAVpacket)) //将数据包放入解码器
            {
                qDebug() << "Failed to avcodec_send_packet(pAVCodecContext, pAVPacket)";
                break;
            }
            while(!avcodec_receive_frame(pAVCodecContext, pAVframe))//获取解码后的数据到AVframe中,因为解码后的数据可能不止一包,所以使用while判断
            {
                sws_scale(pSwsContext,                              //上面使用sws_getContext得到的结构体
                          pAVframe->data, //解码后的数据
                          pAVframe->linesize,                      //每个通道的行字节数,linesize和width不同。
                          0,                                        //起始位置
                          pAVCodecContext->height,                         //处理行数
                          pAVframeRgb->data,                       //目的buffer
                          pAVframeRgb->linesize
                        );
                QImage image(  outbuffer,
                               pAVCodecContext->width,
                               pAVCodecContext->height,
                               pAVframeRgb->linesize[0],
                               QImage::Format_RGBA8888);
                qDebug()<<"numbytes"<=0) //av_read_frame()读取一帧数据
    {
        if(pAVpacket->stream_index==videoIndex)
        {
            if(avcodec_send_packet(pAVCodecContext, pAVpacket)) //将数据包放入解码器
            {
                qDebug() << "Failed to avcodec_send_packet(pAVCodecContext, pAVPacket)";
                break;
            }
            while(!avcodec_receive_frame(pAVCodecContext, pAVframe))//获取解码后的数据到AVframe中,因为解码后的数据可能不止一包,所以使用while判断
            {
                sws_scale(pSwsContext,                              //上面使用sws_getContext得到的结构体
                          pAVframe->data, //解码后的数据
                          pAVframe->linesize,                      //每个通道的行字节数,linesize和width不同。
                          0,                                        //起始位置
                          pAVCodecContext->height,                         //处理行数
                          pAVframeRgb->data,                       //目的buffer
                          pAVframeRgb->linesize
                        );
                QImage image(  outbuffer,
                               pAVCodecContext->width,
                               pAVCodecContext->height,
                               pAVframeRgb->linesize[0],
                               QImage::Format_RGBA8888);

                //emit DrawImg(img_queue.dequeue(),temp);  //实际项目中应该使用队列控制显示速度,temp是画框的位置,
                emit DrawImg(image,NULL);   //这里只解码显示。
            }
        }
        //QThread::msleep(30);
        av_free_packet(pAVpacket);
    }
}


mdecode::~mdecode()
{
    if(outbuffer) av_free(outbuffer);
    if(pSwsContext) sws_freeContext(pSwsContext);
    if(pAVframeRgb) av_frame_free(&pAVframeRgb);
    if(pAVframe) av_frame_free(&pAVframe);
    if(pAVpacket) av_packet_free(&pAVpacket);
    if(pAVCodecContext) avcodec_close(pAVCodecContext);
    if(pAVFormatContext) avformat_free_context(pAVFormatContext);
}

mffmpg::mffmpg()
{

}
void mffmpg::init_ffmpeg()
{
    av_register_all();
}

具体用法:mplayer.cpp

#include "mplayer.h"
#include "ui_mplayer.h"

mplayer::mplayer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::mplayer)
{
    ui->setupUi(this);

    mffmpg::init_ffmpeg();
    avformat_network_init();
    edecode = new mdecode("rtsp://easen:xxxxxx@192.168.1.165",AV_PIX_FMT_RGB32);
    connect(edecode,&mdecode::DrawImg,this,Show_img,Qt::QueuedConnection);
    if(edecode->init_mdecode())
    {
        //edecode.test_mdecode("E:/avcode/video_out/3_decode_rtsp_h264/");
        edecode->start();
    }
    else
    {
        qDebug()<<"cant open edecode";
    }
}
void mplayer::Show_img(QImage image, QByteArray res)
{
    QImage mimage = image.scaled(ui->VideoLabel->width(),ui->VideoLabel->height());
    ui->VideoLabel->setScaledContents(true);
    ui->VideoLabel->setPixmap(QPixmap::fromImage(mimage));
}
mplayer::~mplayer()
{
    delete ui;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/769346.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号