ffmpeg实现dxva2硬件加速

╰+哭是因爲堅強的太久メ 2022-01-31 13:21 617阅读 0赞

https://www.cnblogs.com/betterwgo/p/6125507.html

这几天在做dxva2硬件加速,找不到什么资料,翻译了一下微软的两篇相关文档。这是第二篇,记录用ffmpeg实现dxva2。

第一篇翻译的Direct3D device manager,链接:http://www.cnblogs.com/betterwgo/p/6124588.html

  第二篇翻译的在DirectShow中支持DXVA 2.0,链接:http://www.cnblogs.com/betterwgo/p/6125351.html
  在做dxva2的过程中,参考了许多网上的代码,这些代码又多参考VLC和ffmpeg的例子。

1.ffmpeg支持dxva2硬件加速的格式
  当前我所使用的ffmpeg的版本是3.2,支持dxva2硬件加速的有以下几种文件格式: AV_CODEC_ID_MPEG2VIDEO、AV_CODEC_ID_H264、AV_CODEC_ID_VC1、AV_CODEC_ID_WMV3、AV_CODEC_ID_HEVC、AV_CODEC_ID_VP9。ffmpeg识别为这几种格式的文件都可以尝试使用dxva2做硬件加速。但这并不代表是这几种格式的文件就一定支持dxva2硬件加速,因为我就遇到了一个AV_CODEC_ID_HEVC文件在初始化配置dxva2的过程中会失败,PotPlayer在播放这个文件时也不能用dxva2硬件加速。
2.一些要注意的地方
  (1)ffmpeg只实现了dxva2硬件解码的内容。我所翻译的第一篇、第二篇文章的那部分内容除了解码部分,都要由用户自己去实现。这一块颇有一点复杂,不过不用担心,VLC和ffmpeg都有例子可以参考。这一部分的内容需要对以上两篇翻译的内容有所了解才能比较好的理解代码的逻辑。
  (2)要想真正看到硬件加速的效果,解码后的数据不建议再copy到内存中用CPU进行处理。我一开始就是因为拷贝到吧解码后的数据又copy回内存导致不仅gpu的使用率看不到明显变化,而且CPU的使用率相对于不使用dxva2反而提高了。后来我修改为把解码后的数据直接显示出来,GPU使用率一下子就上去了,CPU使用率也降下来了。
3.关键代码
  由于网上已经有从ffmpeg的例子中分离出来的配置dxva2解码器的代码,所以具体实现起来也相当简单。
(1)头文件ffmpeg_dxva2.h

复制代码

  1. /*
  2. * This file is part of FFmpeg.
  3. *
  4. * FFmpeg is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * FFmpeg is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with FFmpeg; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #ifndef FFMPEG_DXVA2_H
  19. #define FFMPEG_DXVA2_H
  20. //#include "windows.h"
  21. extern "C"{
  22. #include "libavcodec/avcodec.h"
  23. #include "libavutil/pixfmt.h"
  24. #include "libavutil/rational.h"
  25. }
  26. enum HWAccelID {
  27. HWACCEL_NONE = 0,
  28. HWACCEL_AUTO,
  29. HWACCEL_VDPAU,
  30. HWACCEL_DXVA2,
  31. HWACCEL_VDA,
  32. HWACCEL_VIDEOTOOLBOX,
  33. HWACCEL_QSV,
  34. };
  35. typedef struct AVStream AVStream;
  36. typedef struct AVCodecContext AVCodecContext;
  37. typedef struct AVCodec AVCodec;
  38. typedef struct AVFrame AVFrame;
  39. typedef struct AVDictionary AVDictionary;
  40. typedef struct InputStream {
  41. int file_index;
  42. AVStream *st;
  43. int discard; /* true if stream data should be discarded */
  44. int user_set_discard;
  45. int decoding_needed; /* non zero if the packets must be decoded in 'raw_fifo', see DECODING_FOR_* */
  46. #define DECODING_FOR_OST 1
  47. #define DECODING_FOR_FILTER 2
  48. AVCodecContext *dec_ctx;
  49. AVCodec *dec;
  50. AVFrame *decoded_frame;
  51. AVFrame *filter_frame; /* a ref of decoded_frame, to be sent to filters */
  52. int64_t start; /* time when read started */
  53. /* predicted dts of the next packet read for this stream or (when there are
  54. * several frames in a packet) of the next frame in current packet (in AV_TIME_BASE units) */
  55. int64_t next_dts;
  56. int64_t dts; ///< dts of the last packet read for this stream (in AV_TIME_BASE units)
  57. int64_t next_pts; ///< synthetic pts for the next decode frame (in AV_TIME_BASE units)
  58. int64_t pts; ///< current pts of the decoded frame (in AV_TIME_BASE units)
  59. int wrap_correction_done;
  60. int64_t filter_in_rescale_delta_last;
  61. int64_t min_pts; /* pts with the smallest value in a current stream */
  62. int64_t max_pts; /* pts with the higher value in a current stream */
  63. int64_t nb_samples; /* number of samples in the last decoded audio frame before looping */
  64. double ts_scale;
  65. int saw_first_ts;
  66. int showed_multi_packet_warning;
  67. AVDictionary *decoder_opts;
  68. AVRational framerate; /* framerate forced with -r */
  69. int top_field_first;
  70. int guess_layout_max;
  71. int autorotate;
  72. int resample_height;
  73. int resample_width;
  74. int resample_pix_fmt;
  75. int resample_sample_fmt;
  76. int resample_sample_rate;
  77. int resample_channels;
  78. uint64_t resample_channel_layout;
  79. int fix_sub_duration;
  80. struct { /* previous decoded subtitle and related variables */
  81. int got_output;
  82. int ret;
  83. AVSubtitle subtitle;
  84. } prev_sub;
  85. struct sub2video {
  86. int64_t last_pts;
  87. int64_t end_pts;
  88. AVFrame *frame;
  89. int w, h;
  90. } sub2video;
  91. int dr1;
  92. /* decoded data from this stream goes into all those filters
  93. * currently video and audio only */
  94. //InputFilter **filters;
  95. //int nb_filters;
  96. //int reinit_filters;
  97. /* hwaccel options */
  98. enum HWAccelID hwaccel_id;
  99. char *hwaccel_device;
  100. /* hwaccel context */
  101. enum HWAccelID active_hwaccel_id;
  102. void *hwaccel_ctx;
  103. void(*hwaccel_uninit)(AVCodecContext *s);
  104. int(*hwaccel_get_buffer)(AVCodecContext *s, AVFrame *frame, int flags);
  105. int(*hwaccel_retrieve_data)(AVCodecContext *s, AVFrame *frame);
  106. enum AVPixelFormat hwaccel_pix_fmt;
  107. enum AVPixelFormat hwaccel_retrieved_pix_fmt;
  108. /* stats */
  109. // combined size of all the packets read
  110. uint64_t data_size;
  111. /* number of packets successfully read for this stream */
  112. uint64_t nb_packets;
  113. // number of frames/samples retrieved from the decoder
  114. uint64_t frames_decoded;
  115. uint64_t samples_decoded;
  116. } InputStream;
  117. int dxva2_init(AVCodecContext *s, HWND hwnd);
  118. int dxva2_retrieve_data_call(AVCodecContext *s, AVFrame *frame);
  119. #endif /* FFMPEG_DXVA2_H */

复制代码

  以上代码其实是从ffmpeg中抽出来的。HWAccelID为硬件加速器的ID,在初始化配置解码器的时候会用到,我们实际用的是HWACCEL_DXVA2。InputStream这个结构体水很深,包含了一些在初始化配置中会用到的数据,还包含了一些函数指针,注意这些函数指针的使用。我要说的其实是以下两个函数:

  1. int dxva2_init(AVCodecContext *s, HWND hwnd);
  2. int dxva2_retrieve_data_call(AVCodecContext *s, AVFrame *frame);

  函数dxva2_init是初始化配置dxva2解码器的入口,配置工作主要就是由它来完成。在文章最后我会上传整个工程的源码。前两篇翻译的文章的内容几乎都是为它服务的,我上传的源码中的ffmpeg_dxva2.cpp主要就是为了做这一部分工作,当然dxva2_retrieve_data_call也包含在了其中。要想看懂dxva2_init函数的逻辑,你最好看看前面两篇翻译的内容,另外你还需要懂一点D3D渲染的基本知识。
  函数dxva2_retrieve_data_call用来获得解码后的数据的。如我前面所说,如果不必要,最后不要再把它copy出来,直接用D3D绘制出来就行了,把数据从GPU再copy到内存中会极大的降低GPU的使用率,在我的试验中这样做完全没达到GPU加速的目的,反而是CPU的使用率增高了。所以你在我上传的源码中看到的是直接绘制数据。

复制代码

  1. static int dxva2_retrieve_data(AVCodecContext *s, AVFrame *frame)
  2. {
  3. LPDIRECT3DSURFACE9 surface = (LPDIRECT3DSURFACE9)frame->data[3];
  4. InputStream *ist = (InputStream *)s->opaque;
  5. DXVA2Context *ctx = (DXVA2Context *)ist->hwaccel_ctx;
  6. EnterCriticalSection(&cs);
  7. //直接渲染
  8. ctx->d3d9device->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
  9. ctx->d3d9device->BeginScene();
  10. if (m_pBackBuffer)
  11. {
  12. m_pBackBuffer->Release();
  13. m_pBackBuffer = NULL;
  14. }
  15. ctx->d3d9device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &m_pBackBuffer);
  16. GetClientRect(d3dpp.hDeviceWindow, &m_rtViewport);
  17. ctx->d3d9device->StretchRect(surface, NULL, m_pBackBuffer, &m_rtViewport, D3DTEXF_LINEAR);
  18. ctx->d3d9device->EndScene();
  19. ctx->d3d9device->Present(NULL, NULL, NULL, NULL);
  20. LeaveCriticalSection(&cs);
  21. return 0;
  22. }

复制代码

(2)实现
  有了ffmpeg_dxva2.h和ffmpeg_dxva2.cpp这两个文件后实现起来就非常简单了。
 主流程中配置dxva2部分的代码:

复制代码

  1. switch (codec->id)
  2. {
  3. case AV_CODEC_ID_MPEG2VIDEO:
  4. case AV_CODEC_ID_H264:
  5. case AV_CODEC_ID_VC1:
  6. case AV_CODEC_ID_WMV3:
  7. case AV_CODEC_ID_HEVC:
  8. case AV_CODEC_ID_VP9:
  9. {
  10. codecctx->thread_count = 1; // Multithreading is apparently not compatible with hardware decoding
  11. InputStream *ist = new InputStream();
  12. ist->hwaccel_id = HWACCEL_AUTO;
  13. ist->active_hwaccel_id = HWACCEL_AUTO;
  14. ist->hwaccel_device = "dxva2";
  15. ist->dec = codec;
  16. ist->dec_ctx = codecctx;
  17. codecctx->opaque = ist;
  18. if (dxva2_init(codecctx, hWnd) == 0)
  19. {
  20. codecctx->get_buffer2 = ist->hwaccel_get_buffer;
  21. codecctx->get_format = GetHwFormat;
  22. codecctx->thread_safe_callbacks = 1;
  23. break;
  24. }
  25. bAccel = false;
  26. break;
  27. }
  28. default:
  29. bAccel = false;
  30. break;
  31. }

复制代码

可以看出其中主要就是调用dxva2_init函数。
解码并渲染的代码:

复制代码

  1. if (pkt.stream_index == videoindex)
  2. {
  3. int got_picture = 0;
  4. DWORD t_start = GetTickCount();
  5. int bytes_used = avcodec_decode_video2(codecctx, picture, &got_picture, &pkt);
  6. if (got_picture)
  7. {
  8. if (bAccel)
  9. {
  10. //获取数据同时渲染
  11. dxva2_retrieve_data_call(codecctx, picture);
  12. DWORD t_end = GetTickCount();
  13. printf("dxva2 time using: %lu\n", t_end - t_start);
  14. }
  15. else
  16. {
  17. //非dxva2情形
  18. if (img_convert_ctx &&pFrameBGR && out_buffer)
  19. {
  20. //转换数据并渲染
  21. sws_scale(img_convert_ctx, (const uint8_t* const*)picture->data, picture->linesize, 0, codecctx->height, pFrameBGR->data, pFrameBGR->linesize);
  22. m_D3DVidRender.Render_YUV(out_buffer, picture->width, picture->height);
  23. DWORD t_end = GetTickCount();
  24. printf("normal time using: %lu\n", t_end - t_start);
  25. }
  26. }
  27. count++;
  28. }
  29. av_packet_unref(&pkt);
  30. }

复制代码

在dxva2_init函数中其实已经对D3D的渲染进行了配置,所以只需要穿进去窗口句柄,然后调用dxva2_retrieve_data_call函数就可以直接把数据绘制在句柄所对应得窗口上。

源码:http://download.csdn.net/download/qq_33892166/9698473

工程基于VS2013,需要对ffmpeg有一定了解,对D3D也要有一定的了解。注意在代码中修改要播放的视频的路径,否则控制台退出不正常,VS会卡死的,我也是刚发现有这个问题。最后自己修改一下控制台的代码。直接把调出控制台的代码注释掉也可以正常运行,不过就看不到调试信息了。

-——————————————————————————————-2017.3.5 更新——————————————————————-

本次更新只为解答一个问的人比较多的问题:如何在CPU占用不变的情况下,把硬解的数据再copy回显卡?

我的建议:最好不要这样做。如果你要对硬解出来的数据做进一步处理,我建议直接在显卡上进行,GPU并行计算对于做某些图像处理速度比CPU快好多。如果你渲染用的OpenGL,你可以用GLSL写shader;如果你渲染用的D3D,你可以用HLSL写shader;如果你渲染用的D3D11,compute shader将有可能完成你要求得更为复杂的图像处理(compute shader没用过,只看了点介绍,可能不确实);如果你能用CUDA,不要犹豫;如果你不能用CUDA,我推荐你OpenCL。如果以上都不行,我知识面也有限,也没有什么好办法。因为硬解出来的数据很大,从显存copy到内存必然很耗时间和CPU,而且从时间消耗上来看,从显存copy回内存的时间比硬解本身所花费的时间大好多,所以依我狭窄的知识面来看,如果你一定要copy回内存,我建议你干脆放弃硬解。

分类: 硬件解码

发表评论

表情:
评论列表 (有 0 条评论,617人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Chrome硬件加速

    > 提升浏览器丝滑度 电脑配置:Mac电脑(M1芯片) 问题描述:在以往使用 Chrome 浏览器的时候,访问特定网站总是会特别卡(例如知乎),这让我一度怀疑是不是 Ch

    相关 Android的硬件加速

    Android从3.0(API Level 11)开始,在绘制View的时候支持硬件加速,充分利用GPU的特性,使得绘制更加平滑,但是会多消耗一些内存。 开启或