主頁 >  其他 > Qt-FFmpeg開發-實作錄屏功能(10)

Qt-FFmpeg開發-實作錄屏功能(10)

2023-04-09 09:22:22 其他

音視頻/FFmpeg #Qt

Qt-FFmpeg開發-實作錄屏功能??

目錄
  • 音視頻/FFmpeg #Qt
  • Qt-FFmpeg開發-實作錄屏功能??
    • 1、概述??
    • 2、實作效果??
    • 3、FFmpeg錄屏代碼流程???????
    • 4、主要代碼??
    • 5、完整源代碼??

更多精彩內容
??個人內容分類匯總 ??
??音視頻開發 ??

1、概述??

  • 最近研究了一下FFmpeg開發,功能實在是太強大了,網上ffmpeg3、4的文章還是很多的,但是學習嘛,最新的還是不能放過,就選了一個最新的ffmpeg n5.1.2版本,和3、4版本api變化還是挺大的;
  • 在這個Demo里主要使用Qt + FFmpeg開發一個【簡易錄屏軟體】,這里主要使用的是【軟解碼】,需要使用硬解碼的可以看之前的文章;
  • 為了便于學習,這里只是錄制視頻影像,沒有引入音頻等資訊;
  • 由于錄制的視頻影像格式和保存的影像格式不一定相同,所以中間需要進行影像格式轉換,這里使用的是FFmpeg自帶的sws_scale(),聽說libyuv性能更強,后續在研究研究,

開發環境說明

  • 系統:Windows10、Ubuntu20.04
  • Qt版本:V5.12.5
  • 編譯器:MSVC2017-64、GCC/G++64
  • FFmpeg版本:n5.1.2
    • 注意:如果使用了較低版本的庫,程式中部分功能可能會存在問題,不會兼容,
    • 官方下載
    • 我使用的庫

2、實作效果??

  1. 抓取桌面影像轉碼后保存到本地視頻檔案中;
  2. 支持各種常見視頻檔案型別;
  3. 支持Windows、Linux錄屏功能;
  4. 支持全屏錄制功能、錄制指定區域功能;
  5. 默認將錄制視頻保存到系統的視頻檔案夾下;
  6. 主要功能分為錄屏執行緒、錄屏解碼、影像像素轉換、編碼保存4部分,

img

3、FFmpeg錄屏代碼流程???????

  • 白色部分: 主要為抓取桌面影像解碼流程;
  • 綠色部分: 將桌面影像轉碼/編碼保存到視頻檔案,

img

4、主要代碼??

  • 啥也不說了,直接上代碼,一切有注釋

  • videodecode.h檔案

    /******************************************************************************
     * @檔案名     videodecode.h
     * @功能       視頻解碼類,在這個類中呼叫ffmpeg打開捕獲桌面影像進行解碼
     *
     * @開發者     mhf
     * @郵箱       [email protected]
     * @時間       2022/09/15
     * @備注
     *****************************************************************************/
    #ifndef VIDEODECODE_H
    #define VIDEODECODE_H
    
    #include <QString>
    #include <QSize>
    #include <qfile.h>
    #include <QPoint>
    
    struct AVFormatContext;
    struct AVCodecContext;
    struct AVRational;
    struct AVPacket;
    struct AVFrame;
    struct SwsContext;
    struct AVBufferRef;
    struct AVInputFormat;
    struct AVStream;
    class QImage;
    
    class VideoDecode
    {
    public:
        VideoDecode();
        ~VideoDecode();
    
        bool open(const QString& url = QString());    // 打開媒體檔案,或者流媒體rtmp、strp、http
        AVFrame* read();                               // 讀取視頻影像
        void close();                                 // 關閉
        bool isEnd();                                 // 是否讀取完成
        AVCodecContext* getCodecContext(){return m_codecContext;}
        QPoint avgFrameRate(){return m_avgFrameRate;}
    
    private:
        void initFFmpeg();                            // 初始化ffmpeg庫(整個程式中只需加載一次)
        void showError(int err);                      // 顯示ffmpeg執行錯誤時的錯誤資訊
        qreal rationalToDouble(AVRational* rational); // 將AVRational轉換為double
        void clear();                                 // 清空讀取緩沖
        void free();                                  // 釋放
    
    private:
        const AVInputFormat* m_inputFormat = nullptr;
        AVFormatContext* m_formatContext = nullptr;   // 解封裝背景關系
        AVCodecContext*  m_codecContext  = nullptr;   // 解碼器背景關系
        AVPacket* m_packet = nullptr;                 // 資料包
        AVFrame*  m_frame  = nullptr;                 // 解碼后的視頻幀
        int    m_videoIndex   = 0;                    // 視頻流索引
        qint64 m_totalTime    = 0;                    // 視頻總時長
        qint64 m_totalFrames  = 0;                    // 視頻總幀數
        qint64 m_obtainFrames = 0;                    // 視頻當前獲取到的幀數
        qreal  m_frameRate    = 0;                    // 視頻幀率
        QSize  m_size;                                // 視頻解析度大小
        char*  m_error = nullptr;                     // 保存例外資訊
        bool   m_end = false;                         // 視頻讀取完成
        QPoint m_avgFrameRate;
    
    };
    
    #endif // VIDEODECODE_H
    
    
  • videodecode.cpp檔案

    #include "videodecode.h"
    #include <QDebug>
    #include <QImage>
    #include <QMutex>
    #include <qdatetime.h>
    
    
    extern "C" {        // 用C規則編譯指定的代碼
    #include "libavcodec/avcodec.h"
    #include "libavformat/avformat.h"
    #include "libavutil/avutil.h"
    #include "libswscale/swscale.h"
    #include "libavutil/imgutils.h"
    #include "libavdevice/avdevice.h"    // 呼叫輸入設備需要的頭檔案
    }
    
    #define ERROR_LEN 1024  // 例外資訊陣列長度
    #define PRINT_LOG 1
    
    VideoDecode::VideoDecode()
    {
        initFFmpeg();
    
        m_error = new char[ERROR_LEN];
    
        /**
         * dshow:  Windows 媒體輸入設備,目前僅支持音頻和視頻設備,
         * gdigrab:基于 Win32 GDI 的螢屏捕獲設備
         * video4linux2:Linux輸入視頻設備
         * x11grab:x11螢屏捕獲設備
         */
    #if defined(Q_OS_WIN)
        m_inputFormat = av_find_input_format("gdigrab");            // Windows下如果沒有則不能打開設備
    #elif defined(Q_OS_LINUX)
        m_inputFormat = av_find_input_format("x11grab");
    #elif defined(Q_OS_MAC)
    //    m_inputFormat = av_find_input_format("avfoundation");
    #endif
    
        if(!m_inputFormat)
        {
            qWarning() << "查詢AVInputFormat失敗!";
        }
    }
    
    VideoDecode::~VideoDecode()
    {
        close();
    }
    
    /**
     * @brief 初始化ffmpeg庫(整個程式中只需加載一次)
     *        舊版本的ffmpeg需要注冊各種檔案格式、解復用器、對網路庫進行全域初始化,
     *        在新版本的ffmpeg中紛紛棄用了,不需要注冊了
     */
    void VideoDecode::initFFmpeg()
    {
        static bool isFirst = true;
        static QMutex mutex;
        QMutexLocker locker(&mutex);
        if(isFirst)
        {
            //        av_register_all();         // 已經從原始碼中洗掉
            /**
             * 初始化網路庫,用于打開網路流媒體,此函式僅用于解決舊GnuTLS或OpenSSL庫的執行緒安全問題,
             * 一旦洗掉對舊GnuTLS和OpenSSL庫的支持,此函式將被棄用,并且此函式不再有任何用途,
             */
            avformat_network_init();
            // 初始化libavdevice并注冊所有輸入和輸出設備,
            avdevice_register_all();
            isFirst = false;
        }
    }
    
    /**
     * @brief      打開媒體檔案,或者流媒體,例如rtmp、strp、http
     * @param url  視頻地址
     * @return     true:成功  false:失敗
     */
    bool VideoDecode::open(const QString &url)
    {
        if(url.isNull()) return false;
    
        AVDictionary* dict = nullptr;
    
        // 所有引數:https://ffmpeg.org/ffmpeg-devices.html
        av_dict_set(&dict, "framerate", "20", 0);          // 設定幀率,默認的是30000/1001,但是實際可能達不到30的幀率,所以最好手動設定
        av_dict_set(&dict, "draw_mouse", "1", 0);          // 指定是否繪制滑鼠指標,0:不包含滑鼠,1:包含滑鼠
        av_dict_set(&dict, "video_size", "500x400", 0);    // 錄制視頻的大小(寬高),默認為全屏
    #if defined(Q_OS_WIN)
    //    av_dict_set(&dict, "offset_x", "100", 0);          // 錄制視頻的起點X坐標
    //    av_dict_set(&dict, "offset_y", "500", 0);          // 錄制視頻的起點Y坐標
    #elif defined(Q_OS_LINUX)
    //    av_dict_set(&dict, "select_region", "1", 0);          // 1:指定是否使用指標以圖形方式選擇抓取區域 0:不使用
    
        // 當video_size設定,并且video_size加上grab_x、grab_y后不超出桌面區域時,可以通過grab_x、grab_y設定錄屏的起始坐標,如果超出桌面區域則會設定失敗
    //       av_dict_set(&dict, "grab_x", "300", 0);          // 錄制視頻的起點X坐標
    //       av_dict_set(&dict, "grab_y", "500", 0);          // 錄制視頻的起點Y坐標
    #endif
    
        // 打開輸入流并回傳解封裝背景關系
        int ret = avformat_open_input(&m_formatContext,          // 回傳解封裝背景關系
                                      url.toStdString().data(),  // 打開視頻地址
                                      m_inputFormat,             // 如果非null,此引數強制使用特定的輸入格式,自動選擇解封裝器(檔案格式)
                                      &dict);                    // 引數設定
    
        // 釋放引數字典
        if(dict)
        {
            av_dict_free(&dict);
        }
        // 打開視頻失敗
        if(ret < 0)
        {
            showError(ret);
            free();
            return false;
        }
    
        // 讀取媒體檔案的資料包以獲取流資訊,
        ret = avformat_find_stream_info(m_formatContext, nullptr);
        if(ret < 0)
        {
            showError(ret);
            free();
            return false;
        }
        m_totalTime = m_formatContext->duration / (AV_TIME_BASE / 1000); // 計算視頻總時長(毫秒)
    #if PRINT_LOG
        qDebug() << QString("視頻總時長:%1 ms,[%2]").arg(m_totalTime).arg(QTime::fromMSecsSinceStartOfDay(int(m_totalTime)).toString("HH:mm:ss zzz"));
    #endif
    
        // 通過AVMediaType列舉查詢視頻流ID(也可以通過遍歷查找),最后一個引數無用
        m_videoIndex = av_find_best_stream(m_formatContext, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
        if(m_videoIndex < 0)
        {
            showError(m_videoIndex);
            free();
            return false;
        }
    
        AVStream* videoStream = m_formatContext->streams[m_videoIndex];  // 通過查詢到的索引獲取視頻流
    
        // 獲取視頻影像解析度(AVStream中的AVCodecContext在新版本中棄用,改為使用AVCodecParameters)
        m_size.setWidth(videoStream->codecpar->width);
        m_size.setHeight(videoStream->codecpar->height);
        m_frameRate = rationalToDouble(&videoStream->avg_frame_rate);  // 視頻幀率
        m_avgFrameRate.setX(videoStream->avg_frame_rate.num);
        m_avgFrameRate.setY(videoStream->avg_frame_rate.den);
    
        // 通過解碼器ID獲取視頻解碼器(新版本回傳值必須使用const)
        const AVCodec* codec = avcodec_find_decoder(videoStream->codecpar->codec_id);
        m_totalFrames = videoStream->nb_frames;
    
    #if PRINT_LOG
        qDebug() << QString("解析度:[w:%1,h:%2] 幀率:%3  總幀數:%4  解碼器:%5")
                    .arg(m_size.width()).arg(m_size.height()).arg(m_frameRate).arg(m_totalFrames).arg(codec->name);
    #endif
    
        // 分配AVCodecContext并將其欄位設定為默認值,
        m_codecContext = avcodec_alloc_context3(codec);
        if(!m_codecContext)
        {
    #if PRINT_LOG
            qWarning() << "創建視頻解碼器背景關系失敗!";
    #endif
            free();
            return false;
        }
    
        // 使用視頻流的codecpar為解碼器背景關系賦值
        ret = avcodec_parameters_to_context(m_codecContext, videoStream->codecpar);
        if(ret < 0)
        {
            showError(ret);
            free();
            return false;
        }
    
        m_codecContext->flags2 |= AV_CODEC_FLAG2_FAST;    // 允許不符合規范的加速技巧,
        m_codecContext->thread_count = 8;                 // 使用8執行緒解碼
    
        // 初始化解碼器背景關系,如果之前avcodec_alloc_context3傳入了解碼器,這里設定NULL就可以
        ret = avcodec_open2(m_codecContext, nullptr, nullptr);
        if(ret < 0)
        {
            showError(ret);
            free();
            return false;
        }
    
        // 分配AVPacket并將其欄位設定為默認值,
        m_packet = av_packet_alloc();
        if(!m_packet)
        {
    #if PRINT_LOG
            qWarning() << "av_packet_alloc() Error!";
    #endif
            free();
            return false;
        }
        // 分配AVFrame并將其欄位設定為默認值,
        m_frame = av_frame_alloc();
        if(!m_frame)
        {
    #if PRINT_LOG
            qWarning() << "av_frame_alloc() Error!";
    #endif
            free();
            return false;
        }
    
        m_end = false;
        return true;
    }
    
    /**
     * @brief   讀取影像并將影像轉換為YUV420P格式
     * @return
     */
    AVFrame* VideoDecode::read()
    {
        // 如果沒有打開則回傳
        if(!m_formatContext)
        {
            return nullptr;
        }
    
        // 讀取下一幀資料
        int readRet = av_read_frame(m_formatContext, m_packet);
        if(readRet < 0)
        {
            avcodec_send_packet(m_codecContext, m_packet); // 讀取完成后向解碼器中傳如空AVPacket,否則無法讀取出最后幾幀
        }
        else
        {
    
            if(m_packet->stream_index == m_videoIndex)     // 如果是影像資料則進行解碼
            {
                // 將讀取到的原始資料包傳入解碼器
                int ret = avcodec_send_packet(m_codecContext, m_packet);
                if(ret < 0)
                {
                    showError(ret);
                }
            }
        }
        av_packet_unref(m_packet);  // 釋放資料包,參考計數-1,為0時釋放空間
    
        av_frame_unref(m_frame);
        int ret = avcodec_receive_frame(m_codecContext, m_frame);
        if(ret < 0)
        {
            av_frame_unref(m_frame);
            if(readRet < 0)
            {
                m_end = true;     // 當無法讀取到AVPacket并且解碼器中也沒有資料時表示讀取完成
            }
            return nullptr;
        }
    
        return m_frame;
    }
    
    /**
     * @brief 關閉視頻播放并釋放記憶體
     */
    void VideoDecode::close()
    {
        clear();
        free();
    
        m_totalTime     = 0;
        m_videoIndex    = 0;
        m_totalFrames   = 0;
        m_obtainFrames  = 0;
        m_frameRate     = 0;
        m_size          = QSize(0, 0);
    }
    
    /**
     * @brief  視頻是否讀取完成
     * @return
     */
    bool VideoDecode::isEnd()
    {
        return m_end;
    }
    
    
    /**
     * @brief        顯示ffmpeg函式呼叫例外資訊
     * @param err
     */
    void VideoDecode::showError(int err)
    {
    #if PRINT_LOG
        memset(m_error, 0, ERROR_LEN);        // 將陣列置零
        av_strerror(err, m_error, ERROR_LEN);
        qWarning() << "DecodeVideo Error:" << m_error;
    #else
        Q_UNUSED(err)
    #endif
    }
    
    /**
     * @brief          將AVRational轉換為double,用于計算幀率
     * @param rational
     * @return
     */
    qreal VideoDecode::rationalToDouble(AVRational* rational)
    {
        qreal frameRate = (rational->den == 0) ? 0 : (qreal(rational->num) / rational->den);
        return frameRate;
    }
    
    /**
     * @brief 清空讀取緩沖
     */
    void VideoDecode::clear()
    {
        // 因為avformat_flush不會重繪AVIOContext (s->pb),如果有必要,在呼叫此函式之前呼叫avio_flush(s->pb),
        if(m_formatContext && m_formatContext->pb)
        {
            avio_flush(m_formatContext->pb);
        }
        if(m_formatContext)
        {
            avformat_flush(m_formatContext);   // 清理讀取緩沖
        }
    }
    
    void VideoDecode::free()
    {
        // 釋放編解碼器背景關系和與之相關的所有內容,并將NULL寫入提供的指標
        if(m_codecContext)
        {
            avcodec_free_context(&m_codecContext);
        }
        // 關閉并失敗m_formatContext,并將指標置為null
        if(m_formatContext)
        {
            avformat_close_input(&m_formatContext);
        }
        if(m_packet)
        {
            av_packet_free(&m_packet);
        }
        if(m_frame)
        {
            av_frame_free(&m_frame);
        }
    }
    
    
  • videocodec.h檔案

    /******************************************************************************
     * @檔案名     videocodec.h
     * @功能       視頻編碼保存類,將AVFrame影像進行格式轉換后編碼保存到視頻檔案中
     *
     * @開發者     mhf
     * @郵箱       [email protected]
     * @時間       2022/12/26
     * @備注
     *****************************************************************************/
    #ifndef VIDEOCODEC_H
    #define VIDEOCODEC_H
    
    #include <QPoint>
    #include <qmutex.h>
    #include <qstring.h>
    
    
    struct AVCodecParameters;
    struct AVFormatContext;
    struct AVCodecContext;
    struct AVStream;
    struct AVFrame;
    struct AVPacket;
    struct AVOutputFormat;
    struct SwsContext;
    
    class VideoCodec
    {
    public:
        VideoCodec();
        ~VideoCodec();
    
        bool open(AVCodecContext *codecContext, QPoint point, const QString& fileName);
        void write(AVFrame* frame);
        void close();
    
    private:
        void showError(int err);
        bool swsFormat(AVFrame* frame);
    
    private:
        AVFormatContext* m_formatContext = nullptr;
        AVCodecContext * m_codecContext  = nullptr;    // 編碼器背景關系
        SwsContext     * m_swsContext    = nullptr;    // 影像轉換背景關系
        AVStream       * m_videoStream   = nullptr;
        AVPacket       * m_packet        = nullptr;    // 資料包
        AVFrame        * m_frame         = nullptr;    // 解碼后的視頻幀
        int m_index = 0;
        bool             m_writeHeader   = false;      // 是否寫入頭
        QMutex           m_mutex;
    };
    
    #endif // VIDEOCODEC_H
    
    
  • videocodec.cpp檔案

    #include "videocodec.h"
    #include <QDebug>
    
    extern "C" {        // 用C規則編譯指定的代碼
    #include "libavcodec/avcodec.h"
    #include "libavformat/avformat.h"
    #include "libavutil/avutil.h"
    #include "libswscale/swscale.h"
    #include "libavutil/imgutils.h"
    #include "libavdevice/avdevice.h"
    }
    
    #define ERROR_LEN 1024  // 例外資訊陣列長度
    #define PRINT_LOG 1
    
    VideoCodec::VideoCodec()
    {
    
    }
    
    VideoCodec::~VideoCodec()
    {
        close();
    }
    
    bool VideoCodec::open(AVCodecContext *codecContext, QPoint point, const QString &fileName)
    {
        if(!codecContext || fileName.isEmpty()) return false;
    
        // 通過輸出檔案名為輸出格式分配AVFormatContext,引數3編碼器設定為空,由引數4檔案名后綴推測合適的編碼器
        int ret = avformat_alloc_output_context2(&m_formatContext, nullptr, nullptr, fileName.toStdString().data());
    
        if(ret < 0)
        {
            close();
            showError(ret);
            return false;
        }
        // 創建并初始化AVIOContext以訪問url所指示的資源,
        ret = avio_open(&m_formatContext->pb, fileName.toStdString().data(), AVIO_FLAG_WRITE);
        if(ret < 0)
        {
            close();
            showError(ret);
            return false;
        }
    
        // 查詢編碼器
        const AVCodec* codec = avcodec_find_encoder(m_formatContext->oformat->video_codec);
        if(!codec)
        {
            close();
            showError(AVERROR(ENOMEM));
            return false;
        }
        qDebug() << codec->id <<" " << codec->name;
    
        // 分配AVCodecContext并將其欄位設定為默認值,
        m_codecContext = avcodec_alloc_context3(codec);
        if(!m_codecContext)
        {
            close();
            showError(AVERROR(ENOMEM));
            return false;
        }
    
        // 設定編碼器背景關系引數
        m_codecContext->width = codecContext->width;                          // 圖片寬度/高度
        m_codecContext->height = codecContext->height;
        m_codecContext->pix_fmt = codec->pix_fmts[0];                         // 像素格式(這里通過編碼器賦值,不需要自己指定)
        m_codecContext->time_base = {point.y(), point.x()};                   //設定時間基,20為分母,1為分子,表示以1/20秒時間間隔播放一幀影像
        m_codecContext->framerate = {point.x(), point.y()};
        m_codecContext->bit_rate = 1000000;                                   // 目標的碼率,即采樣的碼率;顯然,采樣碼率越大,視頻大小越大,畫質越高
        m_codecContext->gop_size = 12;                                        // I幀間隔(值越大,視頻檔案越小,編解碼延時越長)
        m_codecContext->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
    
        // 打開編碼器
        ret = avcodec_open2(m_codecContext, nullptr, nullptr);
        if(ret < 0)
        {
            close();
            showError(ret);
            return false;
        }
    
        // 向媒體檔案添加新流
        m_videoStream = avformat_new_stream(m_formatContext, nullptr);
        if(!m_videoStream)
        {
            close();
            showError(AVERROR(ENOMEM));
            return false;
        }
    
        //拷貝一些引數,給codecpar賦值
        ret = avcodec_parameters_from_context(m_videoStream->codecpar,m_codecContext);
        if(ret < 0)
        {
            close();
            showError(ret);
            return false;
        }
    
        // 寫入檔案頭
        ret = avformat_write_header(m_formatContext, nullptr);
        if(ret < 0)
        {
            close();
            showError(ret);
            return false;
        }
        m_writeHeader = true;
    
        // 分配一個AVPacket
        m_packet = av_packet_alloc();
        if(!m_packet)
        {
            close();
            showError(AVERROR(ENOMEM));
            return false;
        }
    
        m_frame = av_frame_alloc();
        if(!m_frame)
        {
            close();
            showError(AVERROR(ENOMEM));
            return false;
        }
        m_frame->format = codec->pix_fmts[0];
    
        qDebug() << "開始錄制視頻!";
        return true;
    }
    
    /**
     * @brief          將影像幀編碼寫入視頻檔案
     * @param frame
     */
    void VideoCodec::write(AVFrame *frame)
    {
        QMutexLocker locker(&m_mutex);
        if(!m_packet)
        {
            return;
        }
    
        if(!swsFormat(frame))              // 由于解碼的影像格式和編碼需要的影像格式不一定相同,所以需要轉換一下格式
        {
            return;
        }
        if(m_frame)
        {
            m_frame->pts = m_index;         // pts從0開始增加,保存的視頻才會時間從0開始增加
            m_index++;
        }
    
    
        avcodec_send_frame(m_codecContext, m_frame); // 將影像傳入編碼器
    
        // 回圈讀取所有編碼完的幀
        while (true)
        {
            // 從編碼器中讀取影像幀
            int ret = avcodec_receive_packet(m_codecContext, m_packet);
            if(ret < 0)
            {
                break;
            }
    
            // 將資料包中的有效時間欄位(時間戳/持續時間)從一個時基轉換為 輸出流的時間
            av_packet_rescale_ts(m_packet, m_codecContext->time_base, m_videoStream->time_base);
            av_write_frame(m_formatContext, m_packet);   // 將資料包寫入輸出媒體檔案
            av_packet_unref(m_packet);
        }
    }
    
    void VideoCodec::close()
    {
        write(nullptr);   // 傳入空幀,讀取所有編碼資料
        QMutexLocker locker(&m_mutex);    // 如果不加鎖可能在點擊關閉時,write函式正在寫入資料,導致崩潰
        if(m_formatContext)
        {
            // 寫入檔案尾
            if(m_writeHeader)
            {
                m_writeHeader = false;
                int ret = av_write_trailer(m_formatContext);
                if(ret < 0)
                {
                    showError(ret);
                    return;
                }
            }
            int ret = avio_close(m_formatContext->pb);
            if(ret < 0)
            {
                showError(ret);
                return;
            }
            avformat_free_context(m_formatContext);
            m_formatContext = nullptr;
            m_videoStream = nullptr;
        }
        // 釋放編解碼器背景關系并置空
        if(m_codecContext)
        {
            avcodec_free_context(&m_codecContext);
        }
        if(m_packet)
        {
            av_packet_free(&m_packet);
        }
        // 釋放背景關系swsContext,
        if(m_swsContext)
        {
            sws_freeContext(m_swsContext);
            m_swsContext = nullptr;             // sws_freeContext不會把背景關系置NULL
        }
        if(m_frame)
        {
            av_frame_free(&m_frame);
        }
        m_index = 0;
    }
    
    void VideoCodec::showError(int err)
    {
    #if PRINT_LOG
        static char  m_error[ERROR_LEN];         // 保存例外資訊
        memset(m_error, 0, ERROR_LEN);           // 將陣列置零
        av_strerror(err, m_error, ERROR_LEN);
        qWarning() << "VideoSave Error:" << m_error;
    #else
        Q_UNUSED(err)
    #endif
    }
    
    /**
     * @brief        將解碼影像幀的像素格式轉換未編碼影像幀的像素格式
     * @param frame
     * @return       true:轉換成功  false:轉換失敗
     */
    bool VideoCodec::swsFormat(AVFrame *frame)
    {
        if(!frame || frame->width <= 0 || frame->height <= 0)
        {
            return false;
        }
        // 為什么影像轉換背景關系要放在這里初始化呢,是因為m_frame->format,如果使用硬體解碼,解碼出來的影像格式和m_codecContext->pix_fmt的影像格式不一樣,就會導致無法轉換為QImage
        // 由于解碼后的影像格式不一定支持保存裸流,或者不支持直接編碼為H264,所以需要轉換格式
        if(!m_swsContext)
        {
            // 獲取快取的影像轉換背景關系,首先校驗引數是否一致,如果校驗不通過就釋放資源;然后判斷背景關系是否存在,如果存在直接復用,如不存在進行分配、初始化操作
            m_swsContext = sws_getCachedContext(m_swsContext,
                                                frame->width,                     // 輸入影像的寬度
                                                frame->height,                    // 輸入影像的高度
                                                (AVPixelFormat)frame->format,     // 輸入影像的像素格式
                                                frame->width,                     // 輸出影像的寬度
                                                frame->height,                    // 輸出影像的高度
                                                (AVPixelFormat)m_frame->format,   // 輸出影像的像素格式
                                                SWS_BILINEAR,                     // 選擇縮放演算法(只有當輸入輸出影像大小不同時有效),一般選擇SWS_FAST_BILINEAR
                                                nullptr,                          // 輸入影像的濾波器資訊, 若不需要傳NULL
                                                nullptr,                          // 輸出影像的濾波器資訊, 若不需要傳NULL
                                                nullptr);                         // 特定縮放演算法需要的引數(?),默認為NULL
            if(!m_swsContext)
            {
    #if PRINT_LOG
                qWarning() << "sws_getCachedContext() Error!";
    #endif
    
                av_frame_unref(frame);
                return false;
            }
    
            if(m_frame)
            {
                // 創建一個影像幀用于保存YUV420P影像
                m_frame->width = frame->width;
                m_frame->height = frame->height;
                av_frame_get_buffer(m_frame, 3 * 8);
            }
        }
    
        if(m_frame->width <= 0 || m_frame->height <= 0)      // 如果m_frame沒有分配空間則回傳
        {
            return false;
        }
    
        // 開始轉換格式
        bool ret = sws_scale(m_swsContext,             // 縮放背景關系
                        frame->data,                   // 原影像陣列
                        frame->linesize,               // 包含源影像每個平面步幅的陣列
                        0,                             // 開始位置
                        frame->height,                 // 行數
                        m_frame->data,                 // 目標影像陣列
                        m_frame->linesize);            // 包含目標影像每個平面的步幅的陣列
        av_frame_unref(frame);
        return ret;
    }
    
    

5、完整源代碼??

  • github
  • gitee

∧__∧
( `Д′ )
(っ▄︻▇〓┳═????
/   )
( / ̄∪

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/549531.html

標籤:其他

上一篇:Qt-FFmpeg開發-打開本地攝像頭錄制視頻(7)

下一篇:Qt-FFmpeg開發-保存視頻流裸流(11)

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more