背景
上篇文章我們詳細闡述了windows環境下使用ffmpeg進行軟解碼的步驟,并給出了完整代碼,
FFmpeg 4.x 從入門到精通(一)—— QT 中如何用 FFmpeg 實作軟體解碼
接下來這篇文章繼續進行深入,帶大家學習使用FFmpeg實作windows下的硬解碼,
FFmpeg下載地址(粉絲免費下載):
https://download.csdn.net/download/u012534831/14045436
本文的語言環境基于C++,界面部分是 QT,
流程分析
老規矩,在開始看代碼之前,我們必須先了解下ffmpeg硬解的常規流程:

紅色的部分是和軟解的區別,
雖然有些函式在第一篇文章已經解釋了,但是為了使文章顯得完整,因為本文也會再講一遍,
1、avformat_open_input
為 AVFormatContext 分配空間,打開輸入的視頻資料并且探測視頻的格式,這個函式里面包含了復雜的格式決議與探測演算法,可決議的內容包括:視頻流、音頻流、視頻流引數、音頻流引數、視頻幀索引等,用雷神的話說就是 可以算作FFmpeg的“靈魂”,
2、avformat_find_stream_info
獲取多媒體流的資訊,包括碼流、幀率、時長等資訊,但是有些早期格式或者裸流資料它的索引并沒有放到頭當中,因此需要在后面進行探測,注意一個視頻檔案中可能會同時包括視頻檔案、音頻檔案、字幕檔案等多個媒體流,
3、av_find_best_stream
當視頻被解封裝出來后,需要分開處理音頻和視頻,需要找到對應的音頻流和視頻流,獲取音視頻對應的stream_index,
*4、enum AVHWDeviceType av_hwdevice_find_type_by_name(const char name)
對于硬解碼來說就不能使用avcodec_find_decoder方法來查找解碼器了,而是使用av_hwdevice_find_type_by_name方法,要知道avcodec_find_decoder根據 AVCodecID 查找,比如我們要解碼H264,那入參就是AV_CODEC_ID_H264,找到先注冊的decoder就退出了,可能得到的這個解碼器不能去解碼AV_CODEC_ID_VP6檔案,最主要的是:同一個 AVCodecID 可能對應多個不同的解碼器 (AVCodec),他們有不同的 AVCodec.name,
但是比如說你想在windows下使用dxva解碼,不管視頻源是h264、H265,使用av_hwdevice_find_type_by_name函式,入參是dxva就行,得到的解碼器就可以解H264和H265(當然前提是你的解碼器支持解碼這兩種編碼),
所以說這是兩個完全不同的方法,可能看起來類似,但千萬不要被它迷惑,
**5、const AVCodecHWConfig avcodec_get_hw_config(const AVCodec codec, int index);
獲取到該解碼器codec的硬體屬性,比如可以支持的目標像素格式等,
6、avcodec_alloc_context3
創建AVCodecContext并分配空間,
7、avcodec_parameters_to_context
該函式用于將流里面的引數,也就是AVStream里面的引數直接復制到AVCodecContext的背景關系當中,執行真正的內容拷貝,avcodec_parameters_to_context()是新的API,替換了舊版本的avcodec_copy_context(),
8、av_hwdevice_ctx_create
初始化硬體,打開硬體,創建硬體設備相關的背景關系資訊AVHWDeviceContext,包括分配記憶體資源、對硬體設備進行初始化,
初始化硬體設備完成后,還有個必須的操作是將獲取到的硬體資訊系結到AVCodecContext的hw_device_ctx指標上,
如果使用軟解碼則默認有一個軟解碼的緩沖區(獲取AVFrame的),而硬解碼則需要額外創建硬體解碼的緩沖區,這個緩沖區變數為hw_frames_ctx,不手動創建,則在呼叫avcodec_send_packet()函式內部自動創建一個,但是必須手動賦值硬體解碼緩沖區參考hw_device_ctx(它是一個AVBufferRef變數),不然的話呼叫avcodec_send_packet的時候會回傳錯誤,
9、avcodec_open2
用給定的 AVCodec 去初始化 AVCodecContext,
到這兒,解碼器的初始化作業已經完成,下面就可以開始真正的解碼操作了,
10、av_read_frame
讀取碼流中的音頻若干幀或者視頻一幀,av_read_frame()函式是新型ffmpeg的用法,對 av_read_packet 進行了封裝,舊用法之所以被拋棄,就是因為以前獲取的資料可能不是完整的,而av_read_frame()保證了視頻資料一幀的完整性,使讀出的資料總是完整的一幀,
11、avcodec_send_packet
發送資料到后臺解碼佇列,
It can be NULL (or an AVPacket with data set to NULL and
size set to 0); in this case, it is considered a flush
packet, which signals the end of the stream. Sending the
first flush packet will return success. Subsequent ones are
unnecessary and will return AVERROR_EOF. If the decoder
still has frames buffered, it will return them after sending
原始碼中關于發送一包空資料的解釋:
由于ffmpeg內部會快取幀,在av_read_frame讀不到資料的時候,需要通過packet.data = NULL;packet.size = 0;給ffmpeg發送一包空資料,即再avcodec_send_packet一次,將ffmpeg里面快取的幀全部刷出來,解決最后幾幀沒有解碼出來的問題,
12、avcodec_receive_frame
從解碼器讀取幀資料,這個函式執行完后,就已經能拿到我們的幀資料了,它被存盤在 AVFrame 中,
此處需要注意的是:
一般而言,一次avcodec_send_packet()對應一次avcodec_receive_frame(),但是也會有一次對應多次的情況,這個得看具體的流,并常見于音頻流,會存在一個AVPacket對應多個AVFrame的情況,因此可以看我上面的流程圖有兩個while回圈,
13、av_hwframe_transfer_data
- 這個函式是硬解碼后將資料從 GPU 拷貝到 CPU,當然前提是你需要在CPU進行資料的操作,比如保存資料或者轉為RGB、YUV等,然后通過Opengl渲染出來,但是由于
TexImage2D技術效率很低,因此此方法并不是最優的方案, - 因此若你不需要拷貝到CPU想要直接把資料渲染出來,有幾種方案,比如D3D11解碼出的資料格式
AV_PIX_FMT_D3D11VA_VLD,可以直接轉換為D3D紋理,然后通過IDirect3DTexture貼圖,還有一種方案是使用EGL+OpenglES,或者直接使用 ANGLE(開源的EGL+OpenglES實作) 這個開源專案, - 此函式會將硬解碼出的資料格式進行轉換,也就是說會將GPU映射的資料格式轉換成CPU方式映射的資料格式,比如將DXVA2解碼出來的
AV_PIX_FMT_DXVA2_VLD轉換為AV_PIX_FMT_NV12,
代碼示例
//頭檔案
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include<thread>
extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/pixfmt.h"
#include "libswscale/swscale.h"
#include "libavdevice/avdevice.h"
#include <libavutil/pixdesc.h>
#include <libavutil/hwcontext.h>
#include <libavutil/opt.h>
#include <libavutil/avassert.h>
#include <libavutil/imgutils.h>
}
typedef struct DecodeContext {
AVBufferRef *hw_device_ref;
} DecodeContext;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
void init();
void play();
private:
AVBufferRef *hw_device_ctx = NULL;
static enum AVPixelFormat hw_pix_fmt;
int ret;
enum AVHWDeviceType type;
std::thread m_decodecThread;
Ui::MainWindow *ui;
AVFormatContext *pAVFormatCtx;
AVCodecContext *pAVCodecCtx;
SwsContext *pSwsCtx = nullptr;
uint8_t *pRgbBuffer = nullptr;
AVPacket packet;
AVFrame *pAVFrameRGB = nullptr;
int iVideoIndex = -1;
QImage m_image;
bool isFinish =false;
void decodec();
signals:
void signalDraw();
public slots:
void slotDraw();
protected:
void paintEvent(QPaintEvent *event) override;
private:
int hw_decoder_init(AVCodecContext *ctx, const enum AVHWDeviceType type);
static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,const enum AVPixelFormat *pix_fmts);
};
#endif // MAINWINDOW_H
//CPP檔案
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QPainter>
#include<thread>
#include <QDateTime>
enum AVPixelFormat MainWindow::hw_pix_fmt = AV_PIX_FMT_NONE;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(this,&MainWindow::signalDraw,this,&MainWindow::slotDraw);
}
MainWindow::~MainWindow()
{
delete ui;
}
int MainWindow::hw_decoder_init(AVCodecContext *ctx, const enum AVHWDeviceType type)
{
int err = 0;
//初始化硬體,打開硬體,系結到具體硬體的指標函式上
//創建硬體設備相關的背景關系資訊AVHWDeviceContext,包括分配記憶體資源、對硬體設備進行初始化
if ((err = av_hwdevice_ctx_create(&hw_device_ctx, type,
NULL, NULL, 0)) < 0) {
fprintf(stderr, "Failed to create specified HW device.\n");
return err;
}
/* 需要把這個資訊系結到AVCodecContext
* 如果使用軟解碼則默認有一個軟解碼的緩沖區(獲取AVFrame的),而硬解碼則需要額外創建硬體解碼的緩沖區
* 這個緩沖區變數為hw_frames_ctx,不手動創建,則在呼叫avcodec_send_packet()函式內部自動創建一個
* 但是必須手動賦值硬體解碼緩沖區參考hw_device_ctx(它是一個AVBufferRef變數)
*/
ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
return err;
}
enum AVPixelFormat MainWindow::get_hw_format(AVCodecContext *ctx,
const enum AVPixelFormat *pix_fmts)
{
const enum AVPixelFormat *p;
for (p = pix_fmts; *p != -1; p++) {
if (*p == hw_pix_fmt)
return *p;
}
fprintf(stderr, "Failed to get HW surface format.\n");
return AV_PIX_FMT_NONE;
}
void MainWindow::init()
{
std::string file = "E:/Video/bb.mp4";
//描述多媒體檔案的構成及其基本資訊
if (avformat_open_input(&pAVFormatCtx, file.data(), NULL, NULL) != 0)
{
qDebug() <<"open file fail";
avformat_free_context(pAVFormatCtx);
return;
}
//讀取一部分視音頻資料并且獲得一些相關的資訊
if (avformat_find_stream_info(pAVFormatCtx, NULL) < 0)
{
qDebug() <<"vformat find stream fail";
avformat_close_input(&pAVFormatCtx);
return;
}
// 根據解碼器列舉型別找到解碼器
AVCodec *pAVCodec;
int ret = av_find_best_stream(pAVFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &pAVCodec, 0);
if (ret < 0) {
qDebug()<< "av_find_best_stream faliture";
avformat_close_input(&pAVFormatCtx);
return;
}
iVideoIndex = ret;
type = av_hwdevice_find_type_by_name("dxva2");
// type = av_hwdevice_find_type_by_name("d3d11va");
if (type == AV_HWDEVICE_TYPE_NONE) {
fprintf(stderr, "Device type %s is not supported.\n", "dxva2");
fprintf(stderr, "Available device types:");
while((type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE)
fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
fprintf(stderr, "\n");
}
// 所有支持的硬體解碼器保存在AVCodec的hw_configs變數中,對于硬體編碼器來說又是單獨的AVCodec
for (int i = 0;; i++) {
//獲取到該解碼器codec的硬體屬性,比如可以支持的目標像素格式等
const AVCodecHWConfig *config = avcodec_get_hw_config(pAVCodec, i);
if (!config) {
fprintf(stderr, "Decoder %s does not support device type %s.\n",
pAVCodec->name, av_hwdevice_get_type_name(type));
}
if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&config->device_type == type) {
hw_pix_fmt = config->pix_fmt;
break;
}
}
pAVCodecCtx = avcodec_alloc_context3(pAVCodec);
if (pAVCodecCtx == NULL)
{
qDebug() <<"get pAVCodecCtx fail";
avformat_close_input(&pAVFormatCtx);
return;
}
ret = avcodec_parameters_to_context(pAVCodecCtx,pAVFormatCtx->streams[iVideoIndex]->codecpar);
if (ret < 0)
{
qDebug() <<"avcodec_parameters_to_context fail";
avformat_close_input(&pAVFormatCtx);
return;
}
// 配置獲取硬體加速器像素格式的函式;該函式實際上就是將AVCodec中AVHWCodecConfig中的pix_fmt回傳
pAVCodecCtx->get_format = get_hw_format;
if (hw_decoder_init(pAVCodecCtx, type) < 0)
return ;
if (avcodec_open2(pAVCodecCtx, pAVCodec, NULL) < 0)
{
qDebug()<<"avcodec_open2 fail";
return;
}
//為解碼幀分配記憶體
pAVFrameRGB = av_frame_alloc();
qDebug()<<"pAVCodecCtx->width:" << pAVCodecCtx->width<<"pAVCodecCtx->height:" << pAVCodecCtx->height;
int size = av_image_get_buffer_size(AVPixelFormat(AV_PIX_FMT_RGB32), pAVCodecCtx->width, pAVCodecCtx->height, 1);
pRgbBuffer = (uint8_t *)(av_malloc(size));
//舊版本avpicture_fill
av_image_fill_arrays(pAVFrameRGB->data, pAVFrameRGB->linesize, pRgbBuffer, AV_PIX_FMT_RGB32,
pAVCodecCtx->width, pAVCodecCtx->height, 1);
// //AVpacket 用來存放解碼資料
av_new_packet(&packet, pAVCodecCtx->width * pAVCodecCtx->height);
qDebug()<<"pAVCodecCtx->pix_fmt:" << pAVCodecCtx->pix_fmt;
}
void MainWindow::play()
{
m_decodecThread = std::thread([this]()
{
decodec();
});
m_decodecThread.detach();
}
void MainWindow::decodec()
{
//讀取碼流中視頻幀
while (true)
{
AVFrame *frame = NULL, *sw_frame = NULL;
AVFrame *tmp_frame = NULL;
int ret = av_read_frame(pAVFormatCtx, &packet);
if(ret != 0)
{
qDebug()<<"file end";
isFinish = !isFinish;
return;
}
if (packet.stream_index != iVideoIndex)
{
av_packet_unref(&packet);
continue;
}
int iGotPic = AVERROR(EAGAIN);
// //解碼一幀視頻資料
iGotPic = avcodec_send_packet(pAVCodecCtx, &packet);
if(iGotPic!=0){
qDebug()<<"avcodec_send_packet error";
continue;
}
if (!(frame = av_frame_alloc()) || !(sw_frame = av_frame_alloc())) {
fprintf(stderr, "Can not alloc frame\n");
ret = AVERROR(ENOMEM);
continue;
}
while (0 == avcodec_receive_frame(pAVCodecCtx, frame))
{
qDebug()<<"frame->format:" << frame->format;//53 AV_PIX_FMT_DXVA2_VLD
if (frame->format == hw_pix_fmt) {
int64_t time = QDateTime::currentDateTime().toMSecsSinceEpoch();
qDebug() << "qhttime1:" << time;
/* retrieve data from GPU to CPU */
if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0) {
fprintf(stderr, "Error transferring the data to system memory\n");
break;
}
tmp_frame = sw_frame;
} else
{
tmp_frame = frame;
qDebug()<<"frame img";
}
if(!pSwsCtx)
{
pSwsCtx = sws_getContext(pAVCodecCtx->width, pAVCodecCtx->height, (AVPixelFormat)tmp_frame->format,
pAVCodecCtx->width, pAVCodecCtx->height, AV_PIX_FMT_RGB32,
SWS_BILINEAR, NULL, NULL, NULL);
}
int ret = sws_scale(pSwsCtx, (uint8_t const * const *) tmp_frame->data, tmp_frame->linesize, 0,
tmp_frame->height, pAVFrameRGB->data, pAVFrameRGB->linesize);
qDebug()<<"ret:" << ret;
QImage img((uint8_t *)pAVFrameRGB->data[0], tmp_frame->width, tmp_frame->height, QImage::Format_RGB32);
qDebug()<<"decode img";
m_image = img;
emit signalDraw();
std::this_thread::sleep_for(std::chrono::milliseconds(25));
}
//資源回收
av_free(pAVFrameRGB);
sws_freeContext(pSwsCtx);
avcodec_close(pAVCodecCtx);
avformat_close_input(&pAVFormatCtx);
}
void MainWindow::slotDraw()
{
update();
}
void MainWindow::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setBrush(Qt::black);
painter.drawRect(0, 0, this->width(), this->height());
if (m_image.size().width() <= 0)
return;
//比例縮放
QImage img = m_image.scaled(this->size(),Qt::KeepAspectRatio);
int x = this->width() - img.width();
int y = this->height() - img.height();
x /= 2;
y /= 2;
//QPoint(x,y)為中心繪制影像
painter.drawImage(QPoint(x,y),img);
}
如有興趣,歡迎加入我的QQ群,QT/Android/音視頻 問題在線解答,資源分享,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/266746.html
標籤:其他
