From 8548d788726052e1e0082ffb7eb81271d429ecbe Mon Sep 17 00:00:00 2001
From: Wu Jianhua <toqsxw@outlook.com>
Date: Fri, 30 Sep 2022 22:42:36 +0800
Subject: [PATCH] avcodec: add D3D12VA hardware accelerated H264, HEVC, VP9,
 and AV1 decoding

The implementation is based on:
https://learn.microsoft.com/en-us/windows/win32/medfound/direct3d-12-video-overview

With the Direct3D 12 video decoding support, we can render or process
the decoded images by the pixel shaders or compute shaders directly
without the extra copy overhead.

The command below is how to enable d3d12va:
ffmpeg -hwaccel d3d12va -i input.mp4 output.mp4

Signed-off-by: Wu Jianhua <toqsxw@outlook.com>
---
 Changelog                      |   1 +
 configure                      |  13 +
 libavcodec/Makefile            |   6 +
 libavcodec/av1dec.c            |  10 +
 libavcodec/d3d12dec.c          | 547 ++++++++++++++++++++++++++
 libavcodec/d3d12dec.h          | 193 +++++++++
 libavcodec/d3d12dec_av1.c      | 440 +++++++++++++++++++++
 libavcodec/d3d12dec_h264.c     | 337 ++++++++++++++++
 libavcodec/d3d12dec_hevc.c     | 391 +++++++++++++++++++
 libavcodec/d3d12dec_vp9.c      | 294 ++++++++++++++
 libavcodec/h264_slice.c        |   4 +
 libavcodec/h264dec.c           |   5 +-
 libavcodec/hevcdec.c           |  10 +
 libavcodec/hwaccels.h          |   4 +
 libavcodec/hwconfig.h          |   2 +
 libavcodec/version.h           |   2 +-
 libavcodec/vp9.c               |   7 +
 libavutil/Makefile             |   3 +
 libavutil/hwcontext.c          |   4 +
 libavutil/hwcontext.h          |   1 +
 libavutil/hwcontext_d3d12va.c  | 687 +++++++++++++++++++++++++++++++++
 libavutil/hwcontext_d3d12va.h  | 234 +++++++++++
 libavutil/hwcontext_internal.h |   1 +
 libavutil/pixdesc.c            |   4 +
 libavutil/pixfmt.h             |   9 +
 libavutil/tests/hwdevice.c     |   2 +
 libavutil/version.h            |   4 +-
 27 files changed, 3211 insertions(+), 4 deletions(-)
 create mode 100644 libavcodec/d3d12dec.c
 create mode 100644 libavcodec/d3d12dec.h
 create mode 100644 libavcodec/d3d12dec_av1.c
 create mode 100644 libavcodec/d3d12dec_h264.c
 create mode 100644 libavcodec/d3d12dec_hevc.c
 create mode 100644 libavcodec/d3d12dec_vp9.c
 create mode 100644 libavutil/hwcontext_d3d12va.c
 create mode 100644 libavutil/hwcontext_d3d12va.h

diff --git a/Changelog b/Changelog
index 14ba8ac874..4d4417148b 100644
--- a/Changelog
+++ b/Changelog
@@ -17,6 +17,7 @@ version <next>:
 - APAC decoder and demuxer
 - Media 100i decoders
 - DTS to PTS reorder bsf
+- D3D12VA hardware accelerated H264, HEVC, VP9 and AV1 decoding
 
 
 version 5.1:
diff --git a/configure b/configure
index f3fd91f592..4916a889ca 100755
--- a/configure
+++ b/configure
@@ -337,6 +337,7 @@ External library support:
   --disable-cuda-llvm      disable CUDA compilation using clang [autodetect]
   --disable-cuvid          disable Nvidia CUVID support [autodetect]
   --disable-d3d11va        disable Microsoft Direct3D 11 video acceleration code [autodetect]
+  --disable-d3d12va        disable Microsoft Direct3D 12 video acceleration code [autodetect]
   --disable-dxva2          disable Microsoft DirectX 9 video acceleration code [autodetect]
   --disable-ffnvcodec      disable dynamically linked Nvidia code [autodetect]
   --enable-libdrm          enable DRM code (Linux) [no]
@@ -1897,6 +1898,7 @@ HWACCEL_AUTODETECT_LIBRARY_LIST="
     cuda_llvm
     cuvid
     d3d11va
+    d3d12va
     dxva2
     ffnvcodec
     nvdec
@@ -3021,6 +3023,7 @@ crystalhd_deps="libcrystalhd_libcrystalhd_if_h"
 cuda_deps="ffnvcodec"
 cuvid_deps="ffnvcodec"
 d3d11va_deps="dxva_h ID3D11VideoDecoder ID3D11VideoContext"
+d3d12va_deps="dxva_h ID3D12Device ID3D12VideoDecoder"
 dxva2_deps="dxva2api_h DXVA2_ConfigPictureDecode ole32 user32"
 ffnvcodec_deps_any="libdl LoadLibrary"
 nvdec_deps="ffnvcodec"
@@ -3033,6 +3036,8 @@ av1_d3d11va_hwaccel_deps="d3d11va DXVA_PicParams_AV1"
 av1_d3d11va_hwaccel_select="av1_decoder"
 av1_d3d11va2_hwaccel_deps="d3d11va DXVA_PicParams_AV1"
 av1_d3d11va2_hwaccel_select="av1_decoder"
+av1_d3d12dec_hwaccel_deps="d3d12va DXVA_PicParams_AV1"
+av1_d3d12dec_hwaccel_select="av1_decoder"
 av1_dxva2_hwaccel_deps="dxva2 DXVA_PicParams_AV1"
 av1_dxva2_hwaccel_select="av1_decoder"
 av1_nvdec_hwaccel_deps="nvdec CUVIDAV1PICPARAMS"
@@ -3049,6 +3054,8 @@ h264_d3d11va_hwaccel_deps="d3d11va"
 h264_d3d11va_hwaccel_select="h264_decoder"
 h264_d3d11va2_hwaccel_deps="d3d11va"
 h264_d3d11va2_hwaccel_select="h264_decoder"
+h264_d3d12dec_hwaccel_deps="d3d12va"
+h264_d3d12dec_hwaccel_select="h264_decoder"
 h264_dxva2_hwaccel_deps="dxva2"
 h264_dxva2_hwaccel_select="h264_decoder"
 h264_nvdec_hwaccel_deps="nvdec"
@@ -3063,6 +3070,8 @@ hevc_d3d11va_hwaccel_deps="d3d11va DXVA_PicParams_HEVC"
 hevc_d3d11va_hwaccel_select="hevc_decoder"
 hevc_d3d11va2_hwaccel_deps="d3d11va DXVA_PicParams_HEVC"
 hevc_d3d11va2_hwaccel_select="hevc_decoder"
+hevc_d3d12dec_hwaccel_deps="d3d12va DXVA_PicParams_HEVC"
+hevc_d3d12dec_hwaccel_select="hevc_decoder"
 hevc_dxva2_hwaccel_deps="dxva2 DXVA_PicParams_HEVC"
 hevc_dxva2_hwaccel_select="hevc_decoder"
 hevc_nvdec_hwaccel_deps="nvdec"
@@ -3127,6 +3136,8 @@ vp9_d3d11va_hwaccel_deps="d3d11va DXVA_PicParams_VP9"
 vp9_d3d11va_hwaccel_select="vp9_decoder"
 vp9_d3d11va2_hwaccel_deps="d3d11va DXVA_PicParams_VP9"
 vp9_d3d11va2_hwaccel_select="vp9_decoder"
+vp9_d3d12dec_hwaccel_deps="d3d12va DXVA_PicParams_VP9"
+vp9_d3d12dec_hwaccel_select="vp9_decoder"
 vp9_dxva2_hwaccel_deps="dxva2 DXVA_PicParams_VP9"
 vp9_dxva2_hwaccel_select="vp9_decoder"
 vp9_nvdec_hwaccel_deps="nvdec"
@@ -6439,6 +6450,8 @@ check_type "windows.h dxgi1_2.h" "IDXGIOutput1"
 check_type "windows.h dxgi1_5.h" "IDXGIOutput5"
 check_type "windows.h d3d11.h" "ID3D11VideoDecoder"
 check_type "windows.h d3d11.h" "ID3D11VideoContext"
+check_type "windows.h d3d12.h" "ID3D12Device"
+check_type "windows.h d3d12video.h" "ID3D12VideoDecoder"
 check_type "windows.h" "DPI_AWARENESS_CONTEXT" -D_WIN32_WINNT=0x0A00
 check_type "d3d9.h dxva2api.h" DXVA2_ConfigPictureDecode -D_WIN32_WINNT=0x0602
 check_func_headers mfapi.h MFCreateAlignedMemoryBuffer -lmfplat
diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index 37b63cadc2..2b351484d1 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -949,6 +949,7 @@ OBJS-$(CONFIG_ADPCM_ZORK_DECODER)         += adpcm.o adpcm_data.o
 
 # hardware accelerators
 OBJS-$(CONFIG_D3D11VA)                    += dxva2.o
+OBJS-$(CONFIG_D3D12VA)                    += d3d12dec.o
 OBJS-$(CONFIG_DXVA2)                      += dxva2.o
 OBJS-$(CONFIG_NVDEC)                      += nvdec.o
 OBJS-$(CONFIG_VAAPI)                      += vaapi_decode.o
@@ -957,6 +958,7 @@ OBJS-$(CONFIG_VDPAU)                      += vdpau.o
 
 OBJS-$(CONFIG_AV1_D3D11VA_HWACCEL)        += dxva2_av1.o
 OBJS-$(CONFIG_AV1_DXVA2_HWACCEL)          += dxva2_av1.o
+OBJS-$(CONFIG_AV1_D3D12DEC_HWACCEL)       += d3d12dec_av1.o
 OBJS-$(CONFIG_AV1_NVDEC_HWACCEL)          += nvdec_av1.o
 OBJS-$(CONFIG_AV1_VAAPI_HWACCEL)          += vaapi_av1.o
 OBJS-$(CONFIG_AV1_VDPAU_HWACCEL)          += vdpau_av1.o
@@ -964,6 +966,7 @@ OBJS-$(CONFIG_H263_VAAPI_HWACCEL)         += vaapi_mpeg4.o
 OBJS-$(CONFIG_H263_VIDEOTOOLBOX_HWACCEL)  += videotoolbox.o
 OBJS-$(CONFIG_H264_D3D11VA_HWACCEL)       += dxva2_h264.o
 OBJS-$(CONFIG_H264_DXVA2_HWACCEL)         += dxva2_h264.o
+OBJS-$(CONFIG_H264_D3D12DEC_HWACCEL)      += d3d12dec_h264.o
 OBJS-$(CONFIG_H264_NVDEC_HWACCEL)         += nvdec_h264.o
 OBJS-$(CONFIG_H264_QSV_HWACCEL)           += qsvdec.o
 OBJS-$(CONFIG_H264_VAAPI_HWACCEL)         += vaapi_h264.o
@@ -971,6 +974,7 @@ OBJS-$(CONFIG_H264_VDPAU_HWACCEL)         += vdpau_h264.o
 OBJS-$(CONFIG_H264_VIDEOTOOLBOX_HWACCEL)  += videotoolbox.o
 OBJS-$(CONFIG_HEVC_D3D11VA_HWACCEL)       += dxva2_hevc.o
 OBJS-$(CONFIG_HEVC_DXVA2_HWACCEL)         += dxva2_hevc.o
+OBJS-$(CONFIG_HEVC_D3D12DEC_HWACCEL)      += d3d12dec_hevc.o
 OBJS-$(CONFIG_HEVC_NVDEC_HWACCEL)         += nvdec_hevc.o
 OBJS-$(CONFIG_HEVC_QSV_HWACCEL)           += qsvdec.o
 OBJS-$(CONFIG_HEVC_VAAPI_HWACCEL)         += vaapi_hevc.o h265_profile_level.o
@@ -1001,6 +1005,7 @@ OBJS-$(CONFIG_VP8_NVDEC_HWACCEL)          += nvdec_vp8.o
 OBJS-$(CONFIG_VP8_VAAPI_HWACCEL)          += vaapi_vp8.o
 OBJS-$(CONFIG_VP9_D3D11VA_HWACCEL)        += dxva2_vp9.o
 OBJS-$(CONFIG_VP9_DXVA2_HWACCEL)          += dxva2_vp9.o
+OBJS-$(CONFIG_VP9_D3D12DEC_HWACCEL)       += d3d12dec_vp9.o
 OBJS-$(CONFIG_VP9_NVDEC_HWACCEL)          += nvdec_vp9.o
 OBJS-$(CONFIG_VP9_VAAPI_HWACCEL)          += vaapi_vp9.o
 OBJS-$(CONFIG_VP9_VDPAU_HWACCEL)          += vdpau_vp9.o
@@ -1241,6 +1246,7 @@ SKIPHEADERS                            += %_tablegen.h                  \
 
 SKIPHEADERS-$(CONFIG_AMF)              += amfenc.h
 SKIPHEADERS-$(CONFIG_D3D11VA)          += d3d11va.h dxva2_internal.h
+SKIPHEADERS-$(CONFIG_D3D12VA)          += d3d12va.h d3d12dec.h
 SKIPHEADERS-$(CONFIG_DXVA2)            += dxva2.h dxva2_internal.h
 SKIPHEADERS-$(CONFIG_JNI)              += ffjni.h
 SKIPHEADERS-$(CONFIG_LCMS2)            += fflcms2.h
diff --git a/libavcodec/av1dec.c b/libavcodec/av1dec.c
index 0c24eac842..24059fc831 100644
--- a/libavcodec/av1dec.c
+++ b/libavcodec/av1dec.c
@@ -440,6 +440,7 @@ static int get_pixel_format(AVCodecContext *avctx)
     enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
 #define HWACCEL_MAX (CONFIG_AV1_DXVA2_HWACCEL + \
                      CONFIG_AV1_D3D11VA_HWACCEL * 2 + \
+                     CONFIG_AV1_D3D12DEC_HWACCEL + \
                      CONFIG_AV1_NVDEC_HWACCEL + \
                      CONFIG_AV1_VAAPI_HWACCEL + \
                      CONFIG_AV1_VDPAU_HWACCEL)
@@ -514,6 +515,9 @@ static int get_pixel_format(AVCodecContext *avctx)
         *fmtp++ = AV_PIX_FMT_D3D11VA_VLD;
         *fmtp++ = AV_PIX_FMT_D3D11;
 #endif
+#if CONFIG_AV1_D3D12DEC_HWACCEL
+        *fmtp++ = AV_PIX_FMT_D3D12;
+#endif
 #if CONFIG_AV1_NVDEC_HWACCEL
         *fmtp++ = AV_PIX_FMT_CUDA;
 #endif
@@ -532,6 +536,9 @@ static int get_pixel_format(AVCodecContext *avctx)
         *fmtp++ = AV_PIX_FMT_D3D11VA_VLD;
         *fmtp++ = AV_PIX_FMT_D3D11;
 #endif
+#if CONFIG_AV1_D3D12DEC_HWACCEL
+        *fmtp++ = AV_PIX_FMT_D3D12;
+#endif
 #if CONFIG_AV1_NVDEC_HWACCEL
         *fmtp++ = AV_PIX_FMT_CUDA;
 #endif
@@ -1271,6 +1278,9 @@ const FFCodec ff_av1_decoder = {
 #if CONFIG_AV1_D3D11VA2_HWACCEL
         HWACCEL_D3D11VA2(av1),
 #endif
+#if CONFIG_AV1_D3D12DEC_HWACCEL
+        HWACCEL_D3D12DEC(av1),
+#endif
 #if CONFIG_AV1_NVDEC_HWACCEL
         HWACCEL_NVDEC(av1),
 #endif
diff --git a/libavcodec/d3d12dec.c b/libavcodec/d3d12dec.c
new file mode 100644
index 0000000000..6237ff54d4
--- /dev/null
+++ b/libavcodec/d3d12dec.c
@@ -0,0 +1,547 @@
+/*
+ * Direct3D 12 HW acceleration video decoder
+ *
+ * copyright (c) 2022 Wu Jianhua <toqsxw@outlook.com>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <assert.h>
+#include <string.h>
+#include <initguid.h>
+
+#include "libavutil/common.h"
+#include "libavutil/log.h"
+#include "libavutil/time.h"
+#include "libavutil/hwcontext_d3d12va.h"
+#include "avcodec.h"
+#include "decode.h"
+#include "d3d12dec.h"
+
+typedef struct CommandAllocator
+{
+    ID3D12CommandAllocator *command_allocator;
+    uint64_t fence_value;
+} CommandAllocator;
+
+UINT ff_d3d12dec_get_suitable_max_bitstream_size(AVCodecContext *avctx)
+{
+    UINT ret = avctx->width * avctx->height * 1.5;
+    switch (avctx->sw_pix_fmt) {
+    case AV_PIX_FMT_YUV420P10:
+        return ret * 2;
+
+    case AV_PIX_FMT_YUV420P:
+    default:
+        return ret;
+    }
+}
+
+static int d3d12dec_get_valid_command_allocator(AVCodecContext *avctx, ID3D12CommandAllocator **ppAllocator)
+{
+    HRESULT hr;
+    D3D12VADecodeContext *ctx = D3D12VA_DECODE_CONTEXT(avctx);
+    CommandAllocator allocator;
+
+    if (av_fifo_peek(ctx->allocator_queue, &allocator, 1, 0) >= 0) {
+        uint64_t completion = ID3D12Fence_GetCompletedValue(ctx->sync_ctx->fence);
+        if (completion >= allocator.fence_value) {
+            *ppAllocator = allocator.command_allocator;
+            av_fifo_read(ctx->allocator_queue, &allocator, 1);
+            return 0;
+        }
+    }
+
+    hr = ID3D12Device_CreateCommandAllocator(ctx->device_ctx->device, D3D12_COMMAND_LIST_TYPE_VIDEO_DECODE,
+        &IID_ID3D12CommandAllocator, ppAllocator);
+    if (FAILED(hr)) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to create a new command allocator!\n");
+        return AVERROR(EINVAL);
+    }
+
+    return 0;
+}
+
+static int d3d12dec_discard_command_allocator(AVCodecContext *avctx, ID3D12CommandAllocator *pAllocator, uint64_t fence_value)
+{
+    D3D12VADecodeContext *ctx = D3D12VA_DECODE_CONTEXT(avctx);
+
+    CommandAllocator allocator = {
+        .command_allocator = pAllocator,
+        .fence_value = fence_value
+    };
+
+    if (av_fifo_write(ctx->allocator_queue, &allocator, 1) < 0) {
+        D3D12_OBJECT_RELEASE(pAllocator);
+        return AVERROR(ENOMEM);
+    }
+
+    return 0;
+}
+
+static void bufref_free_interface(void *opaque, uint8_t *data)
+{
+    D3D12_OBJECT_RELEASE(opaque);
+}
+
+static AVBufferRef *bufref_wrap_interface(IUnknown *iface)
+{
+    return av_buffer_create((uint8_t*)iface, 1, bufref_free_interface, iface, 0);
+}
+
+static int d3d12dec_create_buffer(AVCodecContext *avctx, UINT size, ID3D12Resource **ppResouce)
+{
+    D3D12VADecodeContext *ctx = D3D12VA_DECODE_CONTEXT(avctx);
+
+    D3D12_HEAP_PROPERTIES heap_props = { .Type = D3D12_HEAP_TYPE_UPLOAD };
+
+    D3D12_RESOURCE_DESC desc = {
+        .Dimension        = D3D12_RESOURCE_DIMENSION_BUFFER,
+        .Alignment        = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT,
+        .Width            = size,
+        .Height           = 1,
+        .DepthOrArraySize = 1,
+        .MipLevels        = 1,
+        .Format           = DXGI_FORMAT_UNKNOWN,
+        .SampleDesc       = { .Count = 1, .Quality = 0 },
+        .Layout           = D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+        .Flags            = D3D12_RESOURCE_FLAG_NONE,
+    };
+
+    HRESULT hr = ID3D12Device_CreateCommittedResource(ctx->device_ctx->device, &heap_props, D3D12_HEAP_FLAG_NONE,
+        &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, &IID_ID3D12Resource, ppResouce);
+
+    if (FAILED(hr)) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to create d3d12 buffer.\n");
+        return  AVERROR(EINVAL);
+    }
+
+    return 0;
+}
+
+static int d3d12dec_wait_for_gpu(AVCodecContext *avctx)
+{
+    D3D12VADecodeContext *ctx      = D3D12VA_DECODE_CONTEXT(avctx);
+    AVD3D12VASyncContext *sync_ctx = ctx->sync_ctx;
+
+    return av_d3d12va_wait_queue_idle(sync_ctx, ctx->command_queue);
+}
+
+static int d3d12dec_create_decoder_heap(AVCodecContext *avctx)
+{
+    D3D12VADecodeContext   *ctx        = D3D12VA_DECODE_CONTEXT(avctx);
+    AVHWFramesContext      *frames_ctx = D3D12VA_FRAMES_CONTEXT(avctx);
+    AVD3D12VADeviceContext *hwctx      = ctx->device_ctx;
+
+    D3D12_VIDEO_DECODER_HEAP_DESC desc = {
+        .NodeMask      = 0,
+	    .Configuration = ctx->cfg,
+	    .DecodeWidth   = frames_ctx->width,
+	    .DecodeHeight  = frames_ctx->height,
+	    .Format        = av_d3d12va_map_sw_to_hw_format(frames_ctx->sw_format),
+	    .FrameRate     = { avctx->framerate.num, avctx->framerate.den },
+	    .BitRate       = avctx->bit_rate,
+        .MaxDecodePictureBufferCount = frames_ctx->initial_pool_size,
+    };
+
+    DX_CHECK(ID3D12VideoDevice_CreateVideoDecoderHeap(hwctx->video_device, &desc,
+        &IID_ID3D12VideoDecoderHeap, &ctx->decoder_heap));
+
+    return 0;
+
+fail:
+    if (ctx->decoder) {
+        av_log(avctx, AV_LOG_ERROR, "D3D12 doesn't support decoding frames with an extent "
+            "[width(%d), height(%d)], on your device!\n", frames_ctx->width, frames_ctx->height);
+    }
+
+    return AVERROR(EINVAL);
+}
+
+static int d3d12dec_create_decoder(AVCodecContext *avctx)
+{
+    D3D12_VIDEO_DECODER_DESC desc;
+    D3D12VADecodeContext   *ctx        = D3D12VA_DECODE_CONTEXT(avctx);
+    AVHWFramesContext      *frames_ctx = D3D12VA_FRAMES_CONTEXT(avctx);
+    AVD3D12VADeviceContext *hwctx      = ctx->device_ctx;
+
+    D3D12_FEATURE_DATA_VIDEO_DECODE_SUPPORT feature = {
+	    .NodeIndex     = 0,
+	    .Configuration = ctx->cfg,
+	    .Width         = frames_ctx->width,
+	    .Height        = frames_ctx->height,
+	    .DecodeFormat  = av_d3d12va_map_sw_to_hw_format(frames_ctx->sw_format),
+	    .FrameRate     = { avctx->framerate.num, avctx->framerate.den },
+	    .BitRate       = avctx->bit_rate,
+	};
+
+    DX_CHECK(ID3D12VideoDevice_CheckFeatureSupport(hwctx->video_device, D3D12_FEATURE_VIDEO_DECODE_SUPPORT, &feature, sizeof(feature)));
+    if (!(feature.SupportFlags & D3D12_VIDEO_DECODE_SUPPORT_FLAG_SUPPORTED) ||
+        !(feature.DecodeTier >= D3D12_VIDEO_DECODE_TIER_2)) {
+        av_log(avctx, AV_LOG_ERROR, "D3D12 decoder doesn't support on this device\n");
+        return AVERROR(EINVAL);
+    }
+
+    desc = (D3D12_VIDEO_DECODER_DESC) {
+        .NodeMask = 0,
+        .Configuration = ctx->cfg,
+    };
+
+    DX_CHECK(ID3D12VideoDevice_CreateVideoDecoder(hwctx->video_device, &desc, &IID_ID3D12VideoDecoder, &ctx->decoder));
+
+    ctx->decoder_ref = bufref_wrap_interface((IUnknown *)ctx->decoder);
+    if (!ctx->decoder_ref)
+        return AVERROR(ENOMEM);
+
+    return 0;
+
+fail:
+    return AVERROR(EINVAL);
+}
+
+static inline int d3d12va_get_num_surfaces(enum AVCodecID codec_id)
+{
+    int num_surfaces = 1;
+    if (codec_id == AV_CODEC_ID_H264 || codec_id == AV_CODEC_ID_HEVC)
+        num_surfaces += 16;
+    else if (codec_id == AV_CODEC_ID_VP9 || codec_id == AV_CODEC_ID_AV1)
+        num_surfaces += 8;
+    else
+        num_surfaces += 2;
+
+    return num_surfaces;
+}
+
+int ff_d3d12dec_common_frame_params(AVCodecContext *avctx, AVBufferRef *hw_frames_ctx)
+{
+    AVHWFramesContext      *frames_ctx   = (AVHWFramesContext *)hw_frames_ctx->data;
+    AVHWDeviceContext      *device_ctx   = frames_ctx->device_ctx;
+    AVD3D12VAFramesContext *frames_hwctx = frames_ctx->hwctx;
+
+    frames_ctx->format    = AV_PIX_FMT_D3D12;
+    frames_ctx->sw_format = avctx->sw_pix_fmt == AV_PIX_FMT_YUV420P10 ? AV_PIX_FMT_P010 : AV_PIX_FMT_NV12;
+    frames_ctx->width     = avctx->coded_width;
+    frames_ctx->height    = avctx->coded_height;
+
+    frames_ctx->initial_pool_size = d3d12va_get_num_surfaces(avctx->codec_id);
+
+    return 0;
+}
+
+int ff_d3d12dec_decode_init(AVCodecContext *avctx)
+{
+    int ret;
+    UINT bitstream_size;
+    AVHWFramesContext *frames_ctx;
+    D3D12VADecodeContext *ctx = D3D12VA_DECODE_CONTEXT(avctx);
+
+    ID3D12CommandAllocator *command_allocator = NULL;
+    D3D12_COMMAND_QUEUE_DESC queue_desc = {
+        .Type     = D3D12_COMMAND_LIST_TYPE_VIDEO_DECODE,
+        .Priority = 0,
+        .Flags    = D3D12_COMMAND_QUEUE_FLAG_NONE,
+        .NodeMask = 0
+    };
+
+    ctx->pix_fmt = avctx->hwaccel->pix_fmt;
+
+    ret = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_D3D12VA);
+    if (ret < 0)
+        return ret;
+
+    frames_ctx = D3D12VA_FRAMES_CONTEXT(avctx);
+    ctx->device_ctx = (AVD3D12VADeviceContext *)frames_ctx->device_ctx->hwctx;
+
+    if (frames_ctx->format != ctx->pix_fmt) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid pixfmt for hwaccel!\n");
+        goto fail;
+    }
+
+    ret = d3d12dec_create_decoder(avctx);
+    if (ret < 0)
+        goto fail;
+
+    ret = d3d12dec_create_decoder_heap(avctx);
+    if (ret < 0)
+        goto fail;
+
+    ctx->max_num_ref = frames_ctx->initial_pool_size;
+
+    bitstream_size = ff_d3d12dec_get_suitable_max_bitstream_size(avctx);
+    ctx->buffers = av_calloc(sizeof(ID3D12Resource *), ctx->max_num_ref);
+    for (int i = 0; i < ctx->max_num_ref; i++) {
+        ret = d3d12dec_create_buffer(avctx, bitstream_size, &ctx->buffers[i]);
+        if (ret < 0)
+            goto fail;
+    }
+
+    ctx->ref_resources = av_calloc(sizeof(ID3D12Resource *), ctx->max_num_ref);
+    if (!ctx->ref_resources)
+        return AVERROR(ENOMEM);
+
+    ctx->ref_subresources = av_calloc(sizeof(UINT), ctx->max_num_ref);
+    if (!ctx->ref_subresources)
+        return AVERROR(ENOMEM);
+
+    ctx->allocator_queue = av_fifo_alloc2(ctx->max_num_ref, sizeof(CommandAllocator), AV_FIFO_FLAG_AUTO_GROW);
+    if (!ctx->allocator_queue)
+        return AVERROR(ENOMEM);
+
+    ret = av_d3d12va_create_sync_context(ctx->device_ctx, &ctx->sync_ctx);
+    if (ret < 0)
+        goto fail;
+
+    ret = d3d12dec_get_valid_command_allocator(avctx, &command_allocator);
+    if (ret < 0)
+        goto fail;
+
+    DX_CHECK(ID3D12Device_CreateCommandQueue(ctx->device_ctx->device, &queue_desc,
+        &IID_ID3D12CommandQueue, &ctx->command_queue));
+
+    DX_CHECK(ID3D12Device_CreateCommandList(ctx->device_ctx->device, 0, queue_desc.Type,
+        command_allocator, NULL, &IID_ID3D12CommandList, &ctx->command_list));
+
+    DX_CHECK(ID3D12VideoDecodeCommandList_Close(ctx->command_list));
+
+    ID3D12CommandQueue_ExecuteCommandLists(ctx->command_queue, 1, (ID3D12CommandList **)&ctx->command_list);
+
+    d3d12dec_wait_for_gpu(avctx);
+
+    d3d12dec_discard_command_allocator(avctx, command_allocator, ctx->sync_ctx->fence_value);
+
+    return 0;
+
+fail:
+    D3D12_OBJECT_RELEASE(command_allocator);
+    ff_d3d12dec_decode_uninit(avctx);
+
+    return AVERROR(EINVAL);
+}
+
+int ff_d3d12dec_decode_uninit(AVCodecContext *avctx)
+{
+    int i, num_allocator = 0;
+    D3D12VADecodeContext *ctx = D3D12VA_DECODE_CONTEXT(avctx);
+    CommandAllocator allocator;
+
+    if (ctx->sync_ctx)
+        d3d12dec_wait_for_gpu(avctx);
+
+    av_freep(&ctx->ref_resources);
+
+    av_freep(&ctx->ref_subresources);
+
+    for (i = 0; i < ctx->max_num_ref; i++)
+        D3D12_OBJECT_RELEASE(ctx->buffers[i]);
+
+    av_freep(&ctx->buffers);
+
+    D3D12_OBJECT_RELEASE(ctx->command_list);
+
+    D3D12_OBJECT_RELEASE(ctx->command_queue);
+
+    if (ctx->allocator_queue) {
+        while (av_fifo_read(ctx->allocator_queue, &allocator, 1) >= 0) {
+            num_allocator++;
+            D3D12_OBJECT_RELEASE(allocator.command_allocator);
+        }
+
+        av_log(avctx, AV_LOG_VERBOSE, "Total number of command allocators reused: %d\n", num_allocator);
+    }
+
+    av_fifo_freep2(&ctx->allocator_queue);
+
+    av_d3d12va_release_sync_context(ctx->sync_ctx);
+
+    D3D12_OBJECT_RELEASE(ctx->decoder_heap);
+
+    av_buffer_unref(&ctx->decoder_ref);
+
+    return 0;
+}
+
+static ID3D12Resource *d3d12dec_get_surface(const AVFrame *frame)
+{
+    return (ID3D12Resource *)frame->data[0];
+}
+
+intptr_t ff_d3d12dec_get_surface_index(AVCodecContext *ctx, const AVFrame* frame)
+{
+    return (intptr_t)frame->data[1];
+}
+
+static AVD3D12VASyncContext *d3d12dec_get_sync_context(const AVFrame *frame)
+{
+    return (AVD3D12VASyncContext *)frame->data[2];
+}
+
+static int d3d12dec_begin_update_reference_frames(AVCodecContext *avctx, D3D12_RESOURCE_BARRIER *barriers, int index)
+{
+    D3D12VADecodeContext   *ctx          = D3D12VA_DECODE_CONTEXT(avctx);
+    AVHWFramesContext      *frames_ctx   = D3D12VA_FRAMES_CONTEXT(avctx);
+    AVD3D12VAFramesContext *frames_hwctx = frames_ctx->hwctx;
+
+    int num_barrier = 0;
+
+    for (int i = 0; i < ctx->max_num_ref; i++) {
+        if (ctx->ref_resources[i] && ctx->ref_resources[i] != frames_hwctx->texture_infos[index].texture) {
+            barriers[num_barrier].Type  = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+            barriers[num_barrier].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
+            barriers[num_barrier].Transition = (D3D12_RESOURCE_TRANSITION_BARRIER){
+                .pResource   = ctx->ref_resources[i],
+                .Subresource = 0,
+                .StateBefore = D3D12_RESOURCE_STATE_COMMON,
+                .StateAfter  = D3D12_RESOURCE_STATE_VIDEO_DECODE_READ,
+            };
+            num_barrier++;
+        }
+    }
+
+    return num_barrier;
+}
+
+static void d3d12dec_end_update_reference_frames(AVCodecContext *avctx, D3D12_RESOURCE_BARRIER *barriers, int index)
+{
+    D3D12VADecodeContext   *ctx          = D3D12VA_DECODE_CONTEXT(avctx);
+    AVHWFramesContext      *frames_ctx   = D3D12VA_FRAMES_CONTEXT(avctx);
+    AVD3D12VAFramesContext *frames_hwctx = frames_ctx->hwctx;
+    int num_barrier = 0;
+
+    for (int i = 0; i < ctx->max_num_ref; i++) {
+        if (ctx->ref_resources[i] && ctx->ref_resources[i] != frames_hwctx->texture_infos[index].texture) {
+            barriers[num_barrier].Transition.pResource = ctx->ref_resources[i];
+            barriers[num_barrier].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
+            barriers[num_barrier].Transition.StateBefore = D3D12_RESOURCE_STATE_VIDEO_DECODE_READ;
+            barriers[num_barrier].Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON;
+            num_barrier++;
+        }
+    }
+}
+
+int ff_d3d12dec_common_end_frame(AVCodecContext *avctx, AVFrame *frame,
+                              const void *pp, unsigned pp_size,
+                              const void *qm, unsigned qm_size,
+                              int(*update_input_arguments)(AVCodecContext *, D3D12_VIDEO_DECODE_INPUT_STREAM_ARGUMENTS *, ID3D12Resource *))
+{
+    int ret;
+    D3D12VADecodeContext   *ctx               = D3D12VA_DECODE_CONTEXT(avctx);
+    AVHWFramesContext      *frames_ctx        = D3D12VA_FRAMES_CONTEXT(avctx);
+    AVD3D12VAFramesContext *frames_hwctx      = frames_ctx->hwctx;
+    ID3D12CommandAllocator *command_allocator = NULL;
+
+    ID3D12Resource *resource = d3d12dec_get_surface(frame);
+    UINT index = ff_d3d12dec_get_surface_index(avctx, frame);
+    AVD3D12VASyncContext *sync_ctx = d3d12dec_get_sync_context(frame);
+
+    ID3D12VideoDecodeCommandList *cmd_list = ctx->command_list;
+    D3D12_RESOURCE_BARRIER barriers[D3D12VA_MAX_SURFACES] = { 0 };
+
+    D3D12_VIDEO_DECODE_INPUT_STREAM_ARGUMENTS input_args = {
+        .NumFrameArguments = 2,
+        .FrameArguments = {
+            [0] = {
+                .Type  = D3D12_VIDEO_DECODE_ARGUMENT_TYPE_PICTURE_PARAMETERS,
+                .Size  = pp_size,
+                .pData = (void *)pp,
+            },
+            [1] = {
+                .Type  = D3D12_VIDEO_DECODE_ARGUMENT_TYPE_INVERSE_QUANTIZATION_MATRIX,
+                .Size  = qm_size,
+                .pData = (void *)qm,
+            },
+        },
+        .pHeap = ctx->decoder_heap,
+    };
+
+    D3D12_VIDEO_DECODE_OUTPUT_STREAM_ARGUMENTS output_args = {
+        .ConversionArguments = 0,
+        .OutputSubresource   = 0,
+        .pOutputTexture2D    = resource,
+    };
+
+    UINT num_barrier = 1;
+    barriers[0] = (D3D12_RESOURCE_BARRIER) {
+        .Type  = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
+        .Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE,
+        .Transition = {
+            .pResource   = resource,
+            .Subresource = 0,
+            .StateBefore = D3D12_RESOURCE_STATE_COMMON,
+            .StateAfter  = D3D12_RESOURCE_STATE_VIDEO_DECODE_WRITE,
+        },
+    };
+
+    memset(ctx->ref_resources, 0, sizeof(ID3D12Resource *) * ctx->max_num_ref);
+    memset(ctx->ref_subresources, 0, sizeof(UINT) * ctx->max_num_ref);
+    input_args.ReferenceFrames.NumTexture2Ds = ctx->max_num_ref;
+    input_args.ReferenceFrames.ppTexture2Ds  = ctx->ref_resources;
+    input_args.ReferenceFrames.pSubresources = ctx->ref_subresources;
+
+    av_d3d12va_wait_idle(sync_ctx);
+
+    if (!qm)
+        input_args.NumFrameArguments = 1;
+
+    ret = update_input_arguments(avctx, &input_args, ctx->buffers[index]);
+    if (ret < 0)
+        return ret;
+
+    ret = d3d12dec_get_valid_command_allocator(avctx, &command_allocator);
+    if (ret < 0)
+        goto fail;
+
+    DX_CHECK(ID3D12CommandAllocator_Reset(command_allocator));
+
+    DX_CHECK(ID3D12VideoDecodeCommandList_Reset(cmd_list, command_allocator));
+
+    num_barrier += d3d12dec_begin_update_reference_frames(avctx, &barriers[1], index);
+
+    ID3D12VideoDecodeCommandList_ResourceBarrier(cmd_list, num_barrier, barriers);
+
+    ID3D12VideoDecodeCommandList_DecodeFrame(cmd_list, ctx->decoder, &output_args, &input_args);
+
+    barriers[0].Transition.StateBefore = barriers[0].Transition.StateAfter;
+    barriers[0].Transition.StateAfter  = D3D12_RESOURCE_STATE_COMMON;
+    d3d12dec_end_update_reference_frames(avctx, &barriers[1], index);
+
+    ID3D12VideoDecodeCommandList_ResourceBarrier(cmd_list, num_barrier, barriers);
+
+    DX_CHECK(ID3D12VideoDecodeCommandList_Close(cmd_list));
+
+    ID3D12CommandQueue_ExecuteCommandLists(ctx->command_queue, 1, (ID3D12CommandList **)&ctx->command_list);
+
+    DX_CHECK(ID3D12CommandQueue_Signal(ctx->command_queue, sync_ctx->fence, ++sync_ctx->fence_value));
+
+    DX_CHECK(ID3D12CommandQueue_Signal(ctx->command_queue, ctx->sync_ctx->fence, ++ctx->sync_ctx->fence_value));
+
+    ret = d3d12dec_discard_command_allocator(avctx, command_allocator, ctx->sync_ctx->fence_value);
+    if (ret < 0)
+        return ret;
+
+    if (ctx->device_ctx->sync) {
+        ret = d3d12dec_wait_for_gpu(avctx);
+        if (ret < 0)
+            return ret;
+    }
+
+    return 0;
+
+fail:
+    if (command_allocator)
+        d3d12dec_discard_command_allocator(avctx, command_allocator, ctx->sync_ctx->fence_value);
+    return AVERROR(EINVAL);
+}
diff --git a/libavcodec/d3d12dec.h b/libavcodec/d3d12dec.h
new file mode 100644
index 0000000000..0d77eec612
--- /dev/null
+++ b/libavcodec/d3d12dec.h
@@ -0,0 +1,193 @@
+/*
+ * Direct3D 12 HW acceleration video decoder
+ *
+ * copyright (c) 2022 Wu Jianhua <toqsxw@outlook.com>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_D3D12DEC_H
+#define AVCODEC_D3D12DEC_H
+
+#include "libavutil/fifo.h"
+#include "libavutil/hwcontext.h"
+#include "libavutil/hwcontext_d3d12va.h"
+#include "avcodec.h"
+#include "internal.h"
+
+#define D3D12DEC_MAX_SLICES 8
+
+/**
+ * @brief This structure is used to provides the necessary configurations and data
+ * to the FFmpeg Direct3D 12 HWAccel implementation for video decoder.
+ *
+ * The application must make it available as AVCodecContext.hwaccel_context.
+ */
+typedef struct D3D12VADecodeContext {
+    AVBufferRef *decoder_ref;
+
+    /**
+     * D3D12 video decoder
+     */
+    ID3D12VideoDecoder *decoder;
+
+    /**
+     * D3D12 video decoder heap
+     */
+    ID3D12VideoDecoderHeap *decoder_heap;
+
+    /**
+     * D3D12 configuration used to create the decoder
+     *
+     * Specified by decoders
+     */
+    D3D12_VIDEO_DECODE_CONFIGURATION cfg;
+
+    /**
+     * A cached queue for reusing the D3D12 command allocators
+     *
+     * @see https://learn.microsoft.com/en-us/windows/win32/direct3d12/recording-command-lists-and-bundles#id3d12commandallocator
+     */
+    AVFifo *allocator_queue;
+
+    /**
+     * D3D12 command queue
+     */
+    ID3D12CommandQueue *command_queue;
+
+    /**
+     * D3D12 video decode command list
+     */
+    ID3D12VideoDecodeCommandList *command_list;
+
+    /**
+     * The array of buffer resources used to upload compressed bitstream
+     *
+     * The buffers.length is the same as D3D12VADecodeContext.max_num_ref
+     */
+    ID3D12Resource **buffers;
+
+    /**
+     * The array of resources used for reference frames
+     *
+     * The ref_resources.length is the same as D3D12VADecodeContext.max_num_ref
+     */
+    ID3D12Resource **ref_resources;
+
+    /**
+     * The array of subresources used for reference frames
+     *
+     * The ref_subresources.length is the same as D3D12VADecodeContext.max_num_ref
+     */
+    UINT *ref_subresources;
+
+    /**
+     * Maximum number of reference frames
+     */
+    UINT max_num_ref;
+
+    /**
+     * The sync context used to sync command queue
+     */
+    AVD3D12VASyncContext *sync_ctx;
+
+    /**
+     * A pointer to AVD3D12VADeviceContext used to create D3D12 objects
+     */
+    AVD3D12VADeviceContext *device_ctx;
+
+    /**
+     * Pixel format
+     */
+    enum AVPixelFormat pix_fmt;
+
+    /**
+     * Private to the FFmpeg AVHWAccel implementation
+     */
+    unsigned report_id;
+} D3D12VADecodeContext;
+
+/**
+ * @}
+ */
+
+#define D3D12VA_DECODE_CONTEXT(avctx) ((D3D12VADecodeContext *)((avctx)->internal->hwaccel_priv_data))
+#define D3D12VA_FRAMES_CONTEXT(avctx) ((AVHWFramesContext *)(avctx)->hw_frames_ctx->data)
+
+/**
+ * @brief Get a suitable maximum bitstream size
+ *
+ * Creating and destroying a resource on d3d12 needs sync and reallocation, so use this function
+ * to help allocate a big enough bitstream buffer to avoid recreating resources when decoding.
+ *
+ * @param avctx
+ * @return the suitable size
+ */
+UINT ff_d3d12dec_get_suitable_max_bitstream_size(AVCodecContext *avctx);
+
+/**
+ * @brief init D3D12VADecodeContext
+ *
+ * @param avctx
+ * @return Error code (ret < 0 if failed)
+ */
+int ff_d3d12dec_decode_init(AVCodecContext *avctx);
+
+/**
+ * @brief uninit D3D12VADecodeContext
+ *
+ * @param avctx
+ * @return Error code (ret < 0 if failed)
+ */
+int ff_d3d12dec_decode_uninit(AVCodecContext *avctx);
+
+/**
+ * @brief d3d12dec common frame params
+ *
+ * @param avctx
+ * @param hw_frames_ctx
+ * @return Error code (ret < 0 if failed)
+ */
+int ff_d3d12dec_common_frame_params(AVCodecContext *avctx, AVBufferRef *hw_frames_ctx);
+
+/**
+ * @brief d3d12dec common end frame
+ *
+ * @param avctx    codec context
+ * @param frame    current output frame
+ * @param pp       picture parameters
+ * @param pp_size  the size of the picture parameters
+ * @param qm       quantization matrix
+ * @param qm_size  the size of the quantization matrix
+ * @param callback update decoder-specified input stream arguments
+ * @return Error code (ret < 0 if failed)
+ */
+int ff_d3d12dec_common_end_frame(AVCodecContext *avctx, AVFrame *frame,
+    const void *pp, unsigned pp_size,
+    const void *qm, unsigned qm_size,
+    int(*)(AVCodecContext *, D3D12_VIDEO_DECODE_INPUT_STREAM_ARGUMENTS *, ID3D12Resource *));
+
+/**
+ * @brief get surface index
+ *
+ * @param avctx
+ * @param frame
+ * @return index
+ */
+intptr_t ff_d3d12dec_get_surface_index(AVCodecContext *avctx, const AVFrame *frame);
+
+#endif /* AVCODEC_D3D12VA_DEC_H */
diff --git a/libavcodec/d3d12dec_av1.c b/libavcodec/d3d12dec_av1.c
new file mode 100644
index 0000000000..dffbc57805
--- /dev/null
+++ b/libavcodec/d3d12dec_av1.c
@@ -0,0 +1,440 @@
+/*
+ * Direct3D 12 AV1 HW acceleration
+ *
+ * copyright (c) 2022 Wu Jianhua <toqsxw@outlook.com>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "config_components.h"
+#include "libavutil/avassert.h"
+#include "av1dec.h"
+#include "d3d12dec.h"
+#include <dxva.h>
+
+#define MAX_TILES D3D12DEC_MAX_SLICES + 1
+
+typedef struct D3D12AV1DecodeContext {
+    D3D12VADecodeContext ctx;
+    uint8_t *bitstream_buffer;
+} D3D12AV1DecodeContext;
+
+#define D3D12_AV1_DECODE_CONTEXT(avctx) ((D3D12AV1DecodeContext *)D3D12VA_DECODE_CONTEXT(avctx))
+
+typedef struct D3D12DecodePictureContext {
+    DXVA_PicParams_AV1  pp;
+    unsigned            tile_count;
+    DXVA_Tile_AV1       tiles[MAX_TILES];
+    uint8_t            *bitstream;
+    unsigned            bitstream_size;
+} D3D12DecodePictureContext;
+
+static int get_bit_depth_from_seq(const AV1RawSequenceHeader *seq)
+{
+    if (seq->seq_profile == 2 && seq->color_config.high_bitdepth)
+        return seq->color_config.twelve_bit ? 12 : 10;
+    else if (seq->seq_profile <= 2 && seq->color_config.high_bitdepth)
+        return 10;
+    else
+        return 8;
+}
+
+static int fill_picture_parameters(AVCodecContext *avctx, const AV1DecContext *h,
+                                    DXVA_PicParams_AV1 *pp)
+{
+    int i,j, uses_lr;
+    const AV1RawSequenceHeader  *seq          = h->raw_seq;
+    const AV1RawFrameHeader     *frame_header = h->raw_frame_header;
+    const AV1RawFilmGrainParams *film_grain   = &h->cur_frame.film_grain;
+
+    unsigned char remap_lr_type[4] = { AV1_RESTORE_NONE, AV1_RESTORE_SWITCHABLE, AV1_RESTORE_WIENER, AV1_RESTORE_SGRPROJ };
+    int apply_grain = !(avctx->export_side_data & AV_CODEC_EXPORT_DATA_FILM_GRAIN) && film_grain->apply_grain;
+
+    memset(pp, 0, sizeof(*pp));
+
+    pp->width  = avctx->width;
+    pp->height = avctx->height;
+
+    pp->max_width  = seq->max_frame_width_minus_1 + 1;
+    pp->max_height = seq->max_frame_height_minus_1 + 1;
+
+    pp->CurrPicTextureIndex = ff_d3d12dec_get_surface_index(avctx, h->cur_frame.f);
+    pp->superres_denom      = frame_header->use_superres ? frame_header->coded_denom + AV1_SUPERRES_DENOM_MIN : AV1_SUPERRES_NUM;
+    pp->bitdepth            = get_bit_depth_from_seq(seq);
+    pp->seq_profile         = seq->seq_profile;
+
+    /* Tiling info */
+    pp->tiles.cols = frame_header->tile_cols;
+    pp->tiles.rows = frame_header->tile_rows;
+    pp->tiles.context_update_id = frame_header->context_update_tile_id;
+
+    for (i = 0; i < pp->tiles.cols; i++)
+        pp->tiles.widths[i] = frame_header->width_in_sbs_minus_1[i] + 1;
+
+    for (i = 0; i < pp->tiles.rows; i++)
+        pp->tiles.heights[i] = frame_header->height_in_sbs_minus_1[i] + 1;
+
+    /* Coding tools */
+    pp->coding.use_128x128_superblock       = seq->use_128x128_superblock;
+    pp->coding.intra_edge_filter            = seq->enable_intra_edge_filter;
+    pp->coding.interintra_compound          = seq->enable_interintra_compound;
+    pp->coding.masked_compound              = seq->enable_masked_compound;
+    pp->coding.warped_motion                = frame_header->allow_warped_motion;
+    pp->coding.dual_filter                  = seq->enable_dual_filter;
+    pp->coding.jnt_comp                     = seq->enable_jnt_comp;
+    pp->coding.screen_content_tools         = frame_header->allow_screen_content_tools;
+    pp->coding.integer_mv                   = frame_header->force_integer_mv || !(frame_header->frame_type & 1);
+    pp->coding.cdef                         = seq->enable_cdef;
+    pp->coding.restoration                  = seq->enable_restoration;
+    pp->coding.film_grain                   = seq->film_grain_params_present && !(avctx->export_side_data & AV_CODEC_EXPORT_DATA_FILM_GRAIN);
+    pp->coding.intrabc                      = frame_header->allow_intrabc;
+    pp->coding.high_precision_mv            = frame_header->allow_high_precision_mv;
+    pp->coding.switchable_motion_mode       = frame_header->is_motion_mode_switchable;
+    pp->coding.filter_intra                 = seq->enable_filter_intra;
+    pp->coding.disable_frame_end_update_cdf = frame_header->disable_frame_end_update_cdf;
+    pp->coding.disable_cdf_update           = frame_header->disable_cdf_update;
+    pp->coding.reference_mode               = frame_header->reference_select;
+    pp->coding.skip_mode                    = frame_header->skip_mode_present;
+    pp->coding.reduced_tx_set               = frame_header->reduced_tx_set;
+    pp->coding.superres                     = frame_header->use_superres;
+    pp->coding.tx_mode                      = frame_header->tx_mode;
+    pp->coding.use_ref_frame_mvs            = frame_header->use_ref_frame_mvs;
+    pp->coding.enable_ref_frame_mvs         = seq->enable_ref_frame_mvs;
+    pp->coding.reference_frame_update       = 1; // 0 for show_existing_frame with key frames, but those are not passed to the hwaccel
+
+    /* Format & Picture Info flags */
+    pp->format.frame_type     = frame_header->frame_type;
+    pp->format.show_frame     = frame_header->show_frame;
+    pp->format.showable_frame = frame_header->showable_frame;
+    pp->format.subsampling_x  = seq->color_config.subsampling_x;
+    pp->format.subsampling_y  = seq->color_config.subsampling_y;
+    pp->format.mono_chrome    = seq->color_config.mono_chrome;
+
+    /* References */
+    pp->primary_ref_frame = frame_header->primary_ref_frame;
+    pp->order_hint        = frame_header->order_hint;
+    pp->order_hint_bits   = seq->enable_order_hint ? seq->order_hint_bits_minus_1 + 1 : 0;
+
+    memset(pp->RefFrameMapTextureIndex, 0xFF, sizeof(pp->RefFrameMapTextureIndex));
+    for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
+        int8_t ref_idx = frame_header->ref_frame_idx[i];
+        AVFrame *ref_frame = h->ref[ref_idx].f;
+
+        pp->frame_refs[i].width  = ref_frame->width;
+        pp->frame_refs[i].height = ref_frame->height;
+        pp->frame_refs[i].Index  = ref_frame->buf[0] ? ref_idx : 0xFF;
+
+        /* Global Motion */
+        pp->frame_refs[i].wminvalid = h->cur_frame.gm_invalid[AV1_REF_FRAME_LAST + i];
+        pp->frame_refs[i].wmtype    = h->cur_frame.gm_type[AV1_REF_FRAME_LAST + i];
+        for (j = 0; j < 6; ++j) {
+             pp->frame_refs[i].wmmat[j] = h->cur_frame.gm_params[AV1_REF_FRAME_LAST + i][j];
+        }
+    }
+    for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
+        AVFrame *ref_frame = h->ref[i].f;
+        if (ref_frame->buf[0])
+            pp->RefFrameMapTextureIndex[i] = ff_d3d12dec_get_surface_index(avctx, ref_frame);
+    }
+
+    /* Loop filter parameters */
+    pp->loop_filter.filter_level[0]        = frame_header->loop_filter_level[0];
+    pp->loop_filter.filter_level[1]        = frame_header->loop_filter_level[1];
+    pp->loop_filter.filter_level_u         = frame_header->loop_filter_level[2];
+    pp->loop_filter.filter_level_v         = frame_header->loop_filter_level[3];
+    pp->loop_filter.sharpness_level        = frame_header->loop_filter_sharpness;
+    pp->loop_filter.mode_ref_delta_enabled = frame_header->loop_filter_delta_enabled;
+    pp->loop_filter.mode_ref_delta_update  = frame_header->loop_filter_delta_update;
+    pp->loop_filter.delta_lf_multi         = frame_header->delta_lf_multi;
+    pp->loop_filter.delta_lf_present       = frame_header->delta_lf_present;
+    pp->loop_filter.delta_lf_res           = frame_header->delta_lf_res;
+
+    for (i = 0; i < AV1_TOTAL_REFS_PER_FRAME; i++) {
+        pp->loop_filter.ref_deltas[i] = frame_header->loop_filter_ref_deltas[i];
+    }
+
+    pp->loop_filter.mode_deltas[0]                = frame_header->loop_filter_mode_deltas[0];
+    pp->loop_filter.mode_deltas[1]                = frame_header->loop_filter_mode_deltas[1];
+    pp->loop_filter.frame_restoration_type[0]     = remap_lr_type[frame_header->lr_type[0]];
+    pp->loop_filter.frame_restoration_type[1]     = remap_lr_type[frame_header->lr_type[1]];
+    pp->loop_filter.frame_restoration_type[2]     = remap_lr_type[frame_header->lr_type[2]];
+    uses_lr = frame_header->lr_type[0] || frame_header->lr_type[1] || frame_header->lr_type[2];
+    pp->loop_filter.log2_restoration_unit_size[0] = uses_lr ? (6 + frame_header->lr_unit_shift) : 8;
+    pp->loop_filter.log2_restoration_unit_size[1] = uses_lr ? (6 + frame_header->lr_unit_shift - frame_header->lr_uv_shift) : 8;
+    pp->loop_filter.log2_restoration_unit_size[2] = uses_lr ? (6 + frame_header->lr_unit_shift - frame_header->lr_uv_shift) : 8;
+
+    /* Quantization */
+    pp->quantization.delta_q_present = frame_header->delta_q_present;
+    pp->quantization.delta_q_res     = frame_header->delta_q_res;
+    pp->quantization.base_qindex     = frame_header->base_q_idx;
+    pp->quantization.y_dc_delta_q    = frame_header->delta_q_y_dc;
+    pp->quantization.u_dc_delta_q    = frame_header->delta_q_u_dc;
+    pp->quantization.v_dc_delta_q    = frame_header->delta_q_v_dc;
+    pp->quantization.u_ac_delta_q    = frame_header->delta_q_u_ac;
+    pp->quantization.v_ac_delta_q    = frame_header->delta_q_v_ac;
+    pp->quantization.qm_y            = frame_header->using_qmatrix ? frame_header->qm_y : 0xFF;
+    pp->quantization.qm_u            = frame_header->using_qmatrix ? frame_header->qm_u : 0xFF;
+    pp->quantization.qm_v            = frame_header->using_qmatrix ? frame_header->qm_v : 0xFF;
+
+    /* Cdef parameters */
+    pp->cdef.damping = frame_header->cdef_damping_minus_3;
+    pp->cdef.bits    = frame_header->cdef_bits;
+    for (i = 0; i < 8; i++) {
+        pp->cdef.y_strengths[i].primary    = frame_header->cdef_y_pri_strength[i];
+        pp->cdef.y_strengths[i].secondary  = frame_header->cdef_y_sec_strength[i];
+        pp->cdef.uv_strengths[i].primary   = frame_header->cdef_uv_pri_strength[i];
+        pp->cdef.uv_strengths[i].secondary = frame_header->cdef_uv_sec_strength[i];
+    }
+
+    /* Misc flags */
+    pp->interp_filter = frame_header->interpolation_filter;
+
+    /* Segmentation */
+    pp->segmentation.enabled         = frame_header->segmentation_enabled;
+    pp->segmentation.update_map      = frame_header->segmentation_update_map;
+    pp->segmentation.update_data     = frame_header->segmentation_update_data;
+    pp->segmentation.temporal_update = frame_header->segmentation_temporal_update;
+    for (i = 0; i < AV1_MAX_SEGMENTS; i++) {
+        for (j = 0; j < AV1_SEG_LVL_MAX; j++) {
+            pp->segmentation.feature_mask[i].mask |= frame_header->feature_enabled[i][j] << j;
+            pp->segmentation.feature_data[i][j]    = frame_header->feature_value[i][j];
+        }
+    }
+
+    /* Film grain */
+    if (apply_grain) {
+        pp->film_grain.apply_grain              = 1;
+        pp->film_grain.scaling_shift_minus8     = film_grain->grain_scaling_minus_8;
+        pp->film_grain.chroma_scaling_from_luma = film_grain->chroma_scaling_from_luma;
+        pp->film_grain.ar_coeff_lag             = film_grain->ar_coeff_lag;
+        pp->film_grain.ar_coeff_shift_minus6    = film_grain->ar_coeff_shift_minus_6;
+        pp->film_grain.grain_scale_shift        = film_grain->grain_scale_shift;
+        pp->film_grain.overlap_flag             = film_grain->overlap_flag;
+        pp->film_grain.clip_to_restricted_range = film_grain->clip_to_restricted_range;
+        pp->film_grain.matrix_coeff_is_identity = (seq->color_config.matrix_coefficients == AVCOL_SPC_RGB);
+
+        pp->film_grain.grain_seed               = film_grain->grain_seed;
+        pp->film_grain.num_y_points             = film_grain->num_y_points;
+        for (i = 0; i < film_grain->num_y_points; i++) {
+            pp->film_grain.scaling_points_y[i][0] = film_grain->point_y_value[i];
+            pp->film_grain.scaling_points_y[i][1] = film_grain->point_y_scaling[i];
+        }
+        pp->film_grain.num_cb_points            = film_grain->num_cb_points;
+        for (i = 0; i < film_grain->num_cb_points; i++) {
+            pp->film_grain.scaling_points_cb[i][0] = film_grain->point_cb_value[i];
+            pp->film_grain.scaling_points_cb[i][1] = film_grain->point_cb_scaling[i];
+        }
+        pp->film_grain.num_cr_points            = film_grain->num_cr_points;
+        for (i = 0; i < film_grain->num_cr_points; i++) {
+            pp->film_grain.scaling_points_cr[i][0] = film_grain->point_cr_value[i];
+            pp->film_grain.scaling_points_cr[i][1] = film_grain->point_cr_scaling[i];
+        }
+        for (i = 0; i < 24; i++) {
+            pp->film_grain.ar_coeffs_y[i] = film_grain->ar_coeffs_y_plus_128[i];
+        }
+        for (i = 0; i < 25; i++) {
+            pp->film_grain.ar_coeffs_cb[i] = film_grain->ar_coeffs_cb_plus_128[i];
+            pp->film_grain.ar_coeffs_cr[i] = film_grain->ar_coeffs_cr_plus_128[i];
+        }
+        pp->film_grain.cb_mult      = film_grain->cb_mult;
+        pp->film_grain.cb_luma_mult = film_grain->cb_luma_mult;
+        pp->film_grain.cr_mult      = film_grain->cr_mult;
+        pp->film_grain.cr_luma_mult = film_grain->cr_luma_mult;
+        pp->film_grain.cb_offset    = film_grain->cb_offset;
+        pp->film_grain.cr_offset    = film_grain->cr_offset;
+        pp->film_grain.cr_offset    = film_grain->cr_offset;
+    }
+
+    return 0;
+}
+
+static int d3d12dec_av1_start_frame(AVCodecContext *avctx, av_unused const uint8_t *buffer,  av_unused uint32_t size)
+{
+    const AV1DecContext       *h       = avctx->priv_data;
+    D3D12DecodePictureContext *ctx_pic = h->cur_frame.hwaccel_picture_private;
+
+    if (!D3D12VA_DECODE_CONTEXT(avctx))
+        return -1;
+
+    av_assert0(ctx_pic);
+
+    if (fill_picture_parameters(avctx, h, &ctx_pic->pp) < 0)
+        return -1;
+
+    ctx_pic->bitstream      = NULL;
+    ctx_pic->bitstream_size = 0;
+    ctx_pic->tile_count     = 0;
+
+    return 0;
+}
+
+static int d3d12dec_av1_decode_slice(AVCodecContext *avctx,
+                                   const uint8_t *buffer,
+                                   uint32_t size)
+{
+    const AV1DecContext       *h            = avctx->priv_data;
+    const AV1RawFrameHeader   *frame_header = h->raw_frame_header;
+    D3D12DecodePictureContext *ctx_pic      = h->cur_frame.hwaccel_picture_private;
+
+    ctx_pic->tile_count = frame_header->tile_cols * frame_header->tile_rows;
+
+    if (ctx_pic->tile_count > MAX_TILES)
+        return AVERROR(ENOSYS);
+
+    if (ctx_pic->tile_count == h->tg_end - h->tg_start + 1) {
+        ctx_pic->bitstream = (uint8_t *)buffer;
+        ctx_pic->bitstream_size = size;
+
+        for (uint32_t tile_num = 0; tile_num < ctx_pic->tile_count; tile_num++) {
+            ctx_pic->tiles[tile_num].DataOffset   = h->tile_group_info[tile_num].tile_offset;
+            ctx_pic->tiles[tile_num].DataSize     = h->tile_group_info[tile_num].tile_size;
+            ctx_pic->tiles[tile_num].row          = h->tile_group_info[tile_num].tile_row;
+            ctx_pic->tiles[tile_num].column       = h->tile_group_info[tile_num].tile_column;
+            ctx_pic->tiles[tile_num].anchor_frame = 0xFF;
+        }
+
+        return 0;
+    }
+
+    ctx_pic->bitstream = D3D12_AV1_DECODE_CONTEXT(avctx)->bitstream_buffer;
+    memcpy(ctx_pic->bitstream + ctx_pic->bitstream_size, buffer, size);
+
+    for (uint32_t tile_num = h->tg_start; tile_num <= h->tg_end; tile_num++) {
+        ctx_pic->tiles[tile_num].DataOffset   = ctx_pic->bitstream_size + h->tile_group_info[tile_num].tile_offset;
+        ctx_pic->tiles[tile_num].DataSize     = h->tile_group_info[tile_num].tile_size;
+        ctx_pic->tiles[tile_num].row          = h->tile_group_info[tile_num].tile_row;
+        ctx_pic->tiles[tile_num].column       = h->tile_group_info[tile_num].tile_column;
+        ctx_pic->tiles[tile_num].anchor_frame = 0xFF;
+    }
+
+    ctx_pic->bitstream_size += size;
+
+    return 0;
+}
+
+static int update_input_arguments(AVCodecContext *avctx, D3D12_VIDEO_DECODE_INPUT_STREAM_ARGUMENTS *input_args, ID3D12Resource *buffer)
+{
+    D3D12VADecodeContext      *ctx          = D3D12VA_DECODE_CONTEXT(avctx);
+    AVHWFramesContext         *frames_ctx   = D3D12VA_FRAMES_CONTEXT(avctx);
+    AVD3D12VAFramesContext    *frames_hwctx = frames_ctx->hwctx;
+    const AV1DecContext       *h            = avctx->priv_data;
+    D3D12DecodePictureContext *ctx_pic      = h->cur_frame.hwaccel_picture_private;
+
+    int i, index;
+    uint8_t *mapped_data;
+    D3D12_VIDEO_DECODE_FRAME_ARGUMENT *args;
+
+    if (FAILED(ID3D12Resource_Map(buffer, 0, NULL, &mapped_data))) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to map D3D12 Buffer resource!\n");
+        return AVERROR(EINVAL);
+    }
+
+    memcpy(mapped_data, ctx_pic->bitstream, ctx_pic->bitstream_size);
+
+    ID3D12Resource_Unmap(buffer, 0, NULL);
+
+    for (i = 0; i < ctx_pic->tile_count; i++) {
+        args = &input_args->FrameArguments[input_args->NumFrameArguments++];
+        args->Type  = D3D12_VIDEO_DECODE_ARGUMENT_TYPE_SLICE_CONTROL;
+        args->Size  = sizeof(DXVA_Tile_AV1);
+        args->pData = &ctx_pic->tiles[i];
+    }
+
+    input_args->CompressedBitstream = (D3D12_VIDEO_DECODE_COMPRESSED_BITSTREAM){
+        .pBuffer = buffer,
+        .Offset  = 0,
+        .Size    = ctx_pic->bitstream_size,
+    };
+
+    index = ctx_pic->pp.CurrPicTextureIndex;
+    ctx->ref_resources[index] = frames_hwctx->texture_infos[index].texture;
+
+    for (i = 0; i < FF_ARRAY_ELEMS(ctx_pic->pp.RefFrameMapTextureIndex); i++) {
+        index = ctx_pic->pp.RefFrameMapTextureIndex[i];
+        if (index != 0xFF) {
+            ctx->ref_resources[index] = frames_hwctx->texture_infos[index].texture;
+        }
+    }
+
+    return 0;
+}
+
+static int d3d12dec_av1_end_frame(AVCodecContext *avctx)
+{
+    int ret;
+    const AV1DecContext       *h       = avctx->priv_data;
+    D3D12VADecodeContext      *ctx     = D3D12VA_DECODE_CONTEXT(avctx);
+    D3D12DecodePictureContext *ctx_pic = h->cur_frame.hwaccel_picture_private;
+
+    if (ctx_pic->tiles <= 0 || ctx_pic->bitstream_size <= 0)
+        return -1;
+
+    ret = ff_d3d12dec_common_end_frame(avctx, h->cur_frame.f, &ctx_pic->pp, sizeof(ctx_pic->pp),
+                                      NULL, 0, update_input_arguments);
+
+    return ret;
+}
+
+static int d3d12dec_av1_decode_init(AVCodecContext *avctx)
+{
+    const AV1DecContext       *h       = avctx->priv_data;
+    D3D12VADecodeContext      *ctx     = D3D12VA_DECODE_CONTEXT(avctx);
+    D3D12AV1DecodeContext     *av1_ctx = D3D12_AV1_DECODE_CONTEXT(avctx);
+    D3D12DecodePictureContext *ctx_pic = h->cur_frame.hwaccel_picture_private;
+
+    if (avctx->profile != FF_PROFILE_AV1_MAIN)
+        return AVERROR(EINVAL);
+
+    ctx->cfg.DecodeProfile = D3D12_VIDEO_DECODE_PROFILE_AV1_PROFILE0;
+
+    if (!av1_ctx->bitstream_buffer) {
+        av1_ctx->bitstream_buffer = av_malloc(ff_d3d12dec_get_suitable_max_bitstream_size(avctx));
+        if (!av1_ctx->bitstream_buffer)
+            return AVERROR(ENOMEM);
+    }
+
+    return ff_d3d12dec_decode_init(avctx);
+}
+
+static int d3d12dec_av1_decode_uninit(AVCodecContext *avctx)
+{
+    const AV1DecContext       *h       = avctx->priv_data;
+    D3D12AV1DecodeContext     *ctx     = D3D12_AV1_DECODE_CONTEXT(avctx);
+    D3D12DecodePictureContext *ctx_pic = h->cur_frame.hwaccel_picture_private;
+
+    if (ctx->bitstream_buffer)
+        av_freep(&ctx->bitstream_buffer);
+
+    return ff_d3d12dec_decode_uninit(avctx);
+}
+
+#if CONFIG_AV1_D3D12DEC_HWACCEL
+const AVHWAccel ff_av1_d3d12dec_hwaccel = {
+    .name                 = "av1_d3d12dec",
+    .type                 = AVMEDIA_TYPE_VIDEO,
+    .id                   = AV_CODEC_ID_AV1,
+    .pix_fmt              = AV_PIX_FMT_D3D12,
+    .init                 = d3d12dec_av1_decode_init,
+    .uninit               = d3d12dec_av1_decode_uninit,
+    .start_frame          = d3d12dec_av1_start_frame,
+    .decode_slice         = d3d12dec_av1_decode_slice,
+    .end_frame            = d3d12dec_av1_end_frame,
+    .frame_params         = ff_d3d12dec_common_frame_params,
+    .frame_priv_data_size = sizeof(D3D12DecodePictureContext),
+    .priv_data_size       = sizeof(D3D12AV1DecodeContext),
+};
+#endif
diff --git a/libavcodec/d3d12dec_h264.c b/libavcodec/d3d12dec_h264.c
new file mode 100644
index 0000000000..77dccd372c
--- /dev/null
+++ b/libavcodec/d3d12dec_h264.c
@@ -0,0 +1,337 @@
+/*
+ * Direct3D 12 h264 HW acceleration
+ *
+ * copyright (c) 2022 Wu Jianhua <toqsxw@outlook.com>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "config_components.h"
+#include "libavutil/avassert.h"
+#include "h264dec.h"
+#include "h264data.h"
+#include "h264_ps.h"
+#include "mpegutils.h"
+#include "d3d12dec.h"
+#include <dxva.h>
+
+typedef struct D3D12DecodePictureContext {
+    DXVA_PicParams_H264   pp;
+    DXVA_Qmatrix_H264     qm;
+    unsigned              slice_count;
+    DXVA_Slice_H264_Short slice_short[D3D12DEC_MAX_SLICES];
+    const uint8_t         *bitstream;
+    unsigned              bitstream_size;
+} D3D12DecodePictureContext;
+
+static void fill_picture_entry(DXVA_PicEntry_H264 *pic,
+                               unsigned index, unsigned flag)
+{
+    assert((index & 0x7f) == index && (flag & 0x01) == flag);
+    pic->bPicEntry = index | (flag << 7);
+}
+
+static void fill_picture_parameters(AVCodecContext *avctx, const H264Context *h,
+                                    DXVA_PicParams_H264 *pp)
+{
+    D3D12VADecodeContext *ctx = D3D12VA_DECODE_CONTEXT(avctx);
+    const H264Picture *current_picture = h->cur_pic_ptr;
+    const SPS *sps = h->ps.sps;
+    const PPS *pps = h->ps.pps;
+    int i, j;
+
+    memset(pp, 0, sizeof(*pp));
+    /* Configure current picture */
+    fill_picture_entry(&pp->CurrPic,
+                       ff_d3d12dec_get_surface_index(avctx, current_picture->f),
+                       h->picture_structure == PICT_BOTTOM_FIELD);
+    /* Configure the set of references */
+    pp->UsedForReferenceFlags  = 0;
+    pp->NonExistingFrameFlags  = 0;
+    for (i = 0, j = 0; i < FF_ARRAY_ELEMS(pp->RefFrameList); i++) {
+        const H264Picture *r;
+        if (j < h->short_ref_count) {
+            r = h->short_ref[j++];
+        } else {
+            r = NULL;
+            while (!r && j < h->short_ref_count + 16)
+                r = h->long_ref[j++ - h->short_ref_count];
+        }
+        if (r) {
+            fill_picture_entry(&pp->RefFrameList[i],
+                               ff_d3d12dec_get_surface_index(avctx, r->f),
+                               r->long_ref != 0);
+
+            if ((r->reference & PICT_TOP_FIELD) && r->field_poc[0] != INT_MAX)
+                pp->FieldOrderCntList[i][0] = r->field_poc[0];
+            if ((r->reference & PICT_BOTTOM_FIELD) && r->field_poc[1] != INT_MAX)
+                pp->FieldOrderCntList[i][1] = r->field_poc[1];
+
+            pp->FrameNumList[i] = r->long_ref ? r->pic_id : r->frame_num;
+            if (r->reference & PICT_TOP_FIELD)
+                pp->UsedForReferenceFlags |= 1 << (2*i + 0);
+            if (r->reference & PICT_BOTTOM_FIELD)
+                pp->UsedForReferenceFlags |= 1 << (2*i + 1);
+        } else {
+            pp->RefFrameList[i].bPicEntry = 0xff;
+            pp->FieldOrderCntList[i][0]   = 0;
+            pp->FieldOrderCntList[i][1]   = 0;
+            pp->FrameNumList[i]           = 0;
+        }
+    }
+
+    pp->wFrameWidthInMbsMinus1        = h->mb_width  - 1;
+    pp->wFrameHeightInMbsMinus1       = h->mb_height - 1;
+    pp->num_ref_frames                = sps->ref_frame_count;
+
+    pp->wBitFields                    = ((h->picture_structure != PICT_FRAME) <<  0) |
+                                        ((sps->mb_aff &&
+                                        (h->picture_structure == PICT_FRAME)) <<  1) |
+                                        (sps->residual_color_transform_flag   <<  2) |
+                                        /* sp_for_switch_flag (not implemented by FFmpeg) */
+                                        (0                                    <<  3) |
+                                        (sps->chroma_format_idc               <<  4) |
+                                        ((h->nal_ref_idc != 0)                <<  6) |
+                                        (pps->constrained_intra_pred          <<  7) |
+                                        (pps->weighted_pred                   <<  8) |
+                                        (pps->weighted_bipred_idc             <<  9) |
+                                        /* MbsConsecutiveFlag */
+                                        (1                                    << 11) |
+                                        (sps->frame_mbs_only_flag             << 12) |
+                                        (pps->transform_8x8_mode              << 13) |
+                                        ((sps->level_idc >= 31)               << 14) |
+                                        /* IntraPicFlag (Modified if we detect a non
+                                         * intra slice in dxva2_h264_decode_slice) */
+                                        (1                                    << 15);
+
+    pp->bit_depth_luma_minus8         = sps->bit_depth_luma - 8;
+    pp->bit_depth_chroma_minus8       = sps->bit_depth_chroma - 8;
+    pp->Reserved16Bits                = 0;
+    pp->StatusReportFeedbackNumber    = ctx->report_id++;
+    pp->CurrFieldOrderCnt[0] = 0;
+    if ((h->picture_structure & PICT_TOP_FIELD) &&
+        current_picture->field_poc[0] != INT_MAX)
+        pp->CurrFieldOrderCnt[0] = current_picture->field_poc[0];
+    pp->CurrFieldOrderCnt[1] = 0;
+    if ((h->picture_structure & PICT_BOTTOM_FIELD) &&
+        current_picture->field_poc[1] != INT_MAX)
+        pp->CurrFieldOrderCnt[1] = current_picture->field_poc[1];
+    pp->pic_init_qs_minus26           = pps->init_qs - 26;
+    pp->chroma_qp_index_offset        = pps->chroma_qp_index_offset[0];
+    pp->second_chroma_qp_index_offset = pps->chroma_qp_index_offset[1];
+    pp->ContinuationFlag              = 1;
+    pp->pic_init_qp_minus26           = pps->init_qp - 26;
+    pp->num_ref_idx_l0_active_minus1  = pps->ref_count[0] - 1;
+    pp->num_ref_idx_l1_active_minus1  = pps->ref_count[1] - 1;
+    pp->Reserved8BitsA                = 0;
+    pp->frame_num                     = h->poc.frame_num;
+    pp->log2_max_frame_num_minus4     = sps->log2_max_frame_num - 4;
+    pp->pic_order_cnt_type            = sps->poc_type;
+    if (sps->poc_type == 0)
+        pp->log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_poc_lsb - 4;
+    else if (sps->poc_type == 1)
+        pp->delta_pic_order_always_zero_flag = sps->delta_pic_order_always_zero_flag;
+    pp->direct_8x8_inference_flag     = sps->direct_8x8_inference_flag;
+    pp->entropy_coding_mode_flag      = pps->cabac;
+    pp->pic_order_present_flag        = pps->pic_order_present;
+    pp->num_slice_groups_minus1       = pps->slice_group_count - 1;
+    pp->slice_group_map_type          = pps->mb_slice_group_map_type;
+    pp->deblocking_filter_control_present_flag = pps->deblocking_filter_parameters_present;
+    pp->redundant_pic_cnt_present_flag= pps->redundant_pic_cnt_present;
+    pp->Reserved8BitsB                = 0;
+    pp->slice_group_change_rate_minus1= 0;
+}
+
+static void fill_scaling_lists(const AVCodecContext *avctx, const H264Context *h, DXVA_Qmatrix_H264 *qm)
+{
+    const PPS *pps = h->ps.pps;
+    memset(qm, 0, sizeof(*qm));
+    int i, j;
+    for (i = 0; i < 6; i++)
+        for (j = 0; j < 16; j++)
+            qm->bScalingLists4x4[i][j] = pps->scaling_matrix4[i][j];
+
+    for (i = 0; i < 64; i++) {
+        qm->bScalingLists8x8[0][i] = pps->scaling_matrix8[0][i];
+        qm->bScalingLists8x8[1][i] = pps->scaling_matrix8[3][i];
+    }
+}
+
+static void fill_slice_short(DXVA_Slice_H264_Short *slice,
+                             unsigned position, unsigned size)
+{
+    memset(slice, 0, sizeof(*slice));
+    slice->BSNALunitDataLocation = position;
+    slice->SliceBytesInBuffer    = size;
+    slice->wBadSliceChopping     = 0;
+}
+
+static int d3d12dec_h264_start_frame(AVCodecContext *avctx,
+                                  av_unused const uint8_t *buffer,
+                                  av_unused uint32_t size)
+{
+    const H264Context                *h       = avctx->priv_data;
+    D3D12DecodePictureContext *ctx_pic = h->cur_pic_ptr->hwaccel_picture_private;
+
+    if (!D3D12VA_DECODE_CONTEXT(avctx))
+        return -1;
+
+    assert(ctx_pic);
+
+    fill_picture_parameters(avctx, h, &ctx_pic->pp);
+
+    fill_scaling_lists(avctx, h, &ctx_pic->qm);
+
+    ctx_pic->slice_count    = 0;
+    ctx_pic->bitstream_size = 0;
+    ctx_pic->bitstream      = NULL;
+
+    return 0;
+}
+
+static int d3d12dec_h264_decode_slice(AVCodecContext *avctx,
+                                   const uint8_t *buffer,
+                                   uint32_t size)
+{
+    unsigned position;
+    const H264Context *h = avctx->priv_data;
+    const H264SliceContext *sl = &h->slice_ctx[0];
+    const H264Picture *current_picture = h->cur_pic_ptr;
+    D3D12DecodePictureContext *ctx_pic = current_picture->hwaccel_picture_private;
+
+    if (ctx_pic->slice_count >= D3D12DEC_MAX_SLICES)
+        return -1;
+
+    if (!ctx_pic->bitstream)
+        ctx_pic->bitstream = buffer;
+    ctx_pic->bitstream_size += size;
+
+    position = buffer - ctx_pic->bitstream;
+    fill_slice_short(&ctx_pic->slice_short[ctx_pic->slice_count], position, size);
+    ctx_pic->slice_count++;
+
+    if (sl->slice_type != AV_PICTURE_TYPE_I && sl->slice_type != AV_PICTURE_TYPE_SI)
+        ctx_pic->pp.wBitFields &= ~(1 << 15); /* Set IntraPicFlag to 0 */
+
+    return 0;
+}
+
+#define START_CODE 65536
+#define START_CODE_SIZE 3
+static int update_input_arguments(AVCodecContext *avctx, D3D12_VIDEO_DECODE_INPUT_STREAM_ARGUMENTS *input_args, ID3D12Resource *buffer)
+{
+    D3D12VADecodeContext     *ctx          = D3D12VA_DECODE_CONTEXT(avctx);
+    AVHWFramesContext        *frames_ctx   = D3D12VA_FRAMES_CONTEXT(avctx);
+    AVD3D12VAFramesContext   *frames_hwctx = frames_ctx->hwctx;
+
+    const H264Context         *h               = avctx->priv_data;
+    const H264Picture         *current_picture = h->cur_pic_ptr;
+    D3D12DecodePictureContext *ctx_pic         = current_picture->hwaccel_picture_private;
+
+    int i, index;
+    uint8_t *mapped_data, *mapped_ptr;
+    DXVA_Slice_H264_Short *slice;
+    D3D12_VIDEO_DECODE_FRAME_ARGUMENT *args;
+
+    if (FAILED(ID3D12Resource_Map(buffer, 0, NULL, &mapped_data))) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to map D3D12 Buffer resource!\n");
+        return AVERROR(EINVAL);
+    }
+
+    mapped_ptr = mapped_data;
+    for (i = 0; i < ctx_pic->slice_count; i++) {
+        args = &input_args->FrameArguments[input_args->NumFrameArguments++];
+        args->Type  = D3D12_VIDEO_DECODE_ARGUMENT_TYPE_SLICE_CONTROL;
+        args->Size  = sizeof(DXVA_Slice_H264_Short);
+        args->pData = &ctx_pic->slice_short[i];
+
+        slice = &ctx_pic->slice_short[i];
+
+        *(uint32_t *)mapped_ptr = START_CODE;
+        mapped_ptr += START_CODE_SIZE;
+
+        memcpy(mapped_ptr, &ctx_pic->bitstream[slice->BSNALunitDataLocation], slice->SliceBytesInBuffer);
+        mapped_ptr += slice->SliceBytesInBuffer;
+    }
+
+    ID3D12Resource_Unmap(buffer, 0, NULL);
+
+    input_args->CompressedBitstream = (D3D12_VIDEO_DECODE_COMPRESSED_BITSTREAM){
+        .pBuffer = buffer,
+        .Offset  = 0,
+        .Size    = mapped_ptr - mapped_data,
+    };
+
+    index = ctx_pic->pp.CurrPic.Index7Bits;
+    ctx->ref_resources[index] = frames_hwctx->texture_infos[index].texture;
+
+    for (i = 0; i < FF_ARRAY_ELEMS(ctx_pic->pp.RefFrameList); i++) {
+        index = ctx_pic->pp.RefFrameList[i].Index7Bits;
+        if (index != 0x7f) {
+            ctx->ref_resources[index] = frames_hwctx->texture_infos[index].texture;
+        }
+    }
+
+    return 0;
+}
+
+static int d3d12dec_h264_end_frame(AVCodecContext *avctx)
+{
+    H264Context               *h       = avctx->priv_data;
+    D3D12DecodePictureContext *ctx_pic = h->cur_pic_ptr->hwaccel_picture_private;
+    H264SliceContext          *sl      = &h->slice_ctx[0];
+
+    int ret;
+
+    if (ctx_pic->slice_count <= 0 || ctx_pic->bitstream_size <= 0)
+        return -1;
+
+    ret = ff_d3d12dec_common_end_frame(avctx, h->cur_pic_ptr->f,
+                                      &ctx_pic->pp, sizeof(ctx_pic->pp),
+                                      &ctx_pic->qm, sizeof(ctx_pic->qm),
+                                      update_input_arguments);
+    if (!ret)
+        ff_h264_draw_horiz_band(h, sl, 0, h->avctx->height);
+
+    return ret;
+}
+
+static int d3d12dec_h264_decode_init(AVCodecContext *avctx)
+{
+    D3D12VADecodeContext *ctx = D3D12VA_DECODE_CONTEXT(avctx);
+
+    ctx->cfg.DecodeProfile = D3D12_VIDEO_DECODE_PROFILE_H264;
+
+    return ff_d3d12dec_decode_init(avctx);
+}
+
+#if CONFIG_H264_D3D12DEC_HWACCEL
+const AVHWAccel ff_h264_d3d12dec_hwaccel = {
+    .name                 = "h264_d3d12dec",
+    .type                 = AVMEDIA_TYPE_VIDEO,
+    .id                   = AV_CODEC_ID_H264,
+    .pix_fmt              = AV_PIX_FMT_D3D12,
+    .init                 = d3d12dec_h264_decode_init,
+    .uninit               = ff_d3d12dec_decode_uninit,
+    .start_frame          = d3d12dec_h264_start_frame,
+    .decode_slice         = d3d12dec_h264_decode_slice,
+    .end_frame            = d3d12dec_h264_end_frame,
+    .frame_params         = ff_d3d12dec_common_frame_params,
+    .frame_priv_data_size = sizeof(D3D12DecodePictureContext),
+    .priv_data_size       = sizeof(D3D12VADecodeContext),
+};
+#endif
diff --git a/libavcodec/d3d12dec_hevc.c b/libavcodec/d3d12dec_hevc.c
new file mode 100644
index 0000000000..8fa5a46685
--- /dev/null
+++ b/libavcodec/d3d12dec_hevc.c
@@ -0,0 +1,391 @@
+/*
+ * Direct3D 12 HEVC HW acceleration
+ *
+ * copyright (c) 2022 Wu Jianhua <toqsxw@outlook.com>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "config_components.h"
+
+#include "libavutil/avassert.h"
+#include "hevc_data.h"
+#include "hevcdec.h"
+#include "d3d12dec.h"
+#include <dxva.h>
+
+typedef struct D3D12DecodePictureContext {
+    DXVA_PicParams_HEVC    pp;
+    DXVA_Qmatrix_HEVC      qm;
+    unsigned               slice_count;
+    DXVA_Slice_HEVC_Short  slice_short[D3D12DEC_MAX_SLICES];
+    const uint8_t         *bitstream;
+    unsigned               bitstream_size;
+} D3D12DecodePictureContext;
+
+static void fill_picture_entry(DXVA_PicEntry_HEVC *pic,
+                               unsigned index, unsigned flag)
+{
+    av_assert0((index & 0x7f) == index && (flag & 0x01) == flag);
+    pic->bPicEntry = index | (flag << 7);
+}
+
+static int get_refpic_index(const DXVA_PicParams_HEVC *pp, int surface_index)
+{
+    int i;
+    for (i = 0; i < FF_ARRAY_ELEMS(pp->RefPicList); i++) {
+        if ((pp->RefPicList[i].bPicEntry & 0x7f) == surface_index)
+          return i;
+    }
+    return 0xff;
+}
+
+static void fill_picture_parameters(AVCodecContext *avctx, const HEVCContext *h,
+                                    DXVA_PicParams_HEVC *pp)
+{
+    D3D12VADecodeContext *ctx = D3D12VA_DECODE_CONTEXT(avctx);
+
+    const HEVCFrame *current_picture = h->ref;
+    const HEVCSPS *sps = h->ps.sps;
+    const HEVCPPS *pps = h->ps.pps;
+    int i, j;
+
+    memset(pp, 0, sizeof(*pp));
+
+    pp->PicWidthInMinCbsY  = sps->min_cb_width;
+    pp->PicHeightInMinCbsY = sps->min_cb_height;
+
+    pp->wFormatAndSequenceInfoFlags = (sps->chroma_format_idc             <<  0) |
+                                      (sps->separate_colour_plane_flag    <<  2) |
+                                      ((sps->bit_depth - 8)               <<  3) |
+                                      ((sps->bit_depth - 8)               <<  6) |
+                                      ((sps->log2_max_poc_lsb - 4)        <<  9) |
+                                      (0                                  << 13) |
+                                      (0                                  << 14) |
+                                      (0                                  << 15);
+
+    fill_picture_entry(&pp->CurrPic, ff_d3d12dec_get_surface_index(avctx, current_picture->frame), 0);
+
+    pp->sps_max_dec_pic_buffering_minus1         = sps->temporal_layer[sps->max_sub_layers - 1].max_dec_pic_buffering - 1;
+    pp->log2_min_luma_coding_block_size_minus3   = sps->log2_min_cb_size - 3;
+    pp->log2_diff_max_min_luma_coding_block_size = sps->log2_diff_max_min_coding_block_size;
+    pp->log2_min_transform_block_size_minus2     = sps->log2_min_tb_size - 2;
+    pp->log2_diff_max_min_transform_block_size   = sps->log2_max_trafo_size  - sps->log2_min_tb_size;
+    pp->max_transform_hierarchy_depth_inter      = sps->max_transform_hierarchy_depth_inter;
+    pp->max_transform_hierarchy_depth_intra      = sps->max_transform_hierarchy_depth_intra;
+    pp->num_short_term_ref_pic_sets              = sps->nb_st_rps;
+    pp->num_long_term_ref_pics_sps               = sps->num_long_term_ref_pics_sps;
+
+    pp->num_ref_idx_l0_default_active_minus1     = pps->num_ref_idx_l0_default_active - 1;
+    pp->num_ref_idx_l1_default_active_minus1     = pps->num_ref_idx_l1_default_active - 1;
+    pp->init_qp_minus26                          = pps->pic_init_qp_minus26;
+
+    if (h->sh.short_term_ref_pic_set_sps_flag == 0 && h->sh.short_term_rps) {
+        pp->ucNumDeltaPocsOfRefRpsIdx            = h->sh.short_term_rps->rps_idx_num_delta_pocs;
+        pp->wNumBitsForShortTermRPSInSlice       = h->sh.short_term_ref_pic_set_size;
+    }
+
+    pp->dwCodingParamToolFlags = (sps->scaling_list_enable_flag                  <<  0) |
+                                 (sps->amp_enabled_flag                          <<  1) |
+                                 (sps->sao_enabled                               <<  2) |
+                                 (sps->pcm_enabled_flag                          <<  3) |
+                                 ((sps->pcm_enabled_flag ? (sps->pcm.bit_depth - 1) : 0)            <<  4) |
+                                 ((sps->pcm_enabled_flag ? (sps->pcm.bit_depth_chroma - 1) : 0)     <<  8) |
+                                 ((sps->pcm_enabled_flag ? (sps->pcm.log2_min_pcm_cb_size - 3) : 0) << 12) |
+                                 ((sps->pcm_enabled_flag ? (sps->pcm.log2_max_pcm_cb_size - sps->pcm.log2_min_pcm_cb_size) : 0) << 14) |
+                                 (sps->pcm.loop_filter_disable_flag              << 16) |
+                                 (sps->long_term_ref_pics_present_flag           << 17) |
+                                 (sps->sps_temporal_mvp_enabled_flag             << 18) |
+                                 (sps->sps_strong_intra_smoothing_enable_flag    << 19) |
+                                 (pps->dependent_slice_segments_enabled_flag     << 20) |
+                                 (pps->output_flag_present_flag                  << 21) |
+                                 (pps->num_extra_slice_header_bits               << 22) |
+                                 (pps->sign_data_hiding_flag                     << 25) |
+                                 (pps->cabac_init_present_flag                   << 26) |
+                                 (0                                              << 27);
+
+    pp->dwCodingSettingPicturePropertyFlags = (pps->constrained_intra_pred_flag                   <<  0) |
+                                              (pps->transform_skip_enabled_flag                   <<  1) |
+                                              (pps->cu_qp_delta_enabled_flag                      <<  2) |
+                                              (pps->pic_slice_level_chroma_qp_offsets_present_flag <<  3) |
+                                              (pps->weighted_pred_flag                            <<  4) |
+                                              (pps->weighted_bipred_flag                          <<  5) |
+                                              (pps->transquant_bypass_enable_flag                 <<  6) |
+                                              (pps->tiles_enabled_flag                            <<  7) |
+                                              (pps->entropy_coding_sync_enabled_flag              <<  8) |
+                                              (pps->uniform_spacing_flag                          <<  9) |
+                                              ((pps->tiles_enabled_flag ? pps->loop_filter_across_tiles_enabled_flag : 0) << 10) |
+                                              (pps->seq_loop_filter_across_slices_enabled_flag    << 11) |
+                                              (pps->deblocking_filter_override_enabled_flag       << 12) |
+                                              (pps->disable_dbf                                   << 13) |
+                                              (pps->lists_modification_present_flag               << 14) |
+                                              (pps->slice_header_extension_present_flag           << 15) |
+                                              (IS_IRAP(h)                                         << 16) |
+                                              (IS_IDR(h)                                          << 17) |
+                                              /* IntraPicFlag */
+                                              (IS_IRAP(h)                                         << 18) |
+                                              (0                                                  << 19);
+    pp->pps_cb_qp_offset            = pps->cb_qp_offset;
+    pp->pps_cr_qp_offset            = pps->cr_qp_offset;
+    if (pps->tiles_enabled_flag) {
+        pp->num_tile_columns_minus1 = pps->num_tile_columns - 1;
+        pp->num_tile_rows_minus1    = pps->num_tile_rows - 1;
+
+        if (!pps->uniform_spacing_flag) {
+            for (i = 0; i < pps->num_tile_columns; i++)
+                pp->column_width_minus1[i] = pps->column_width[i] - 1;
+
+            for (i = 0; i < pps->num_tile_rows; i++)
+                pp->row_height_minus1[i] = pps->row_height[i] - 1;
+        }
+    }
+
+    pp->diff_cu_qp_delta_depth           = pps->diff_cu_qp_delta_depth;
+    pp->pps_beta_offset_div2             = pps->beta_offset / 2;
+    pp->pps_tc_offset_div2               = pps->tc_offset / 2;
+    pp->log2_parallel_merge_level_minus2 = pps->log2_parallel_merge_level - 2;
+    pp->CurrPicOrderCntVal               = h->poc;
+
+    // fill RefPicList from the DPB
+    for (i = 0, j = 0; i < FF_ARRAY_ELEMS(pp->RefPicList); i++) {
+        const HEVCFrame *frame = NULL;
+        while (!frame && j < FF_ARRAY_ELEMS(h->DPB)) {
+            if (&h->DPB[j] != current_picture && (h->DPB[j].flags & (HEVC_FRAME_FLAG_LONG_REF | HEVC_FRAME_FLAG_SHORT_REF)))
+                frame = &h->DPB[j];
+            j++;
+        }
+
+        if (frame) {
+            fill_picture_entry(&pp->RefPicList[i], ff_d3d12dec_get_surface_index(avctx, frame->frame), !!(frame->flags & HEVC_FRAME_FLAG_LONG_REF));
+            pp->PicOrderCntValList[i] = frame->poc;
+        } else {
+            pp->RefPicList[i].bPicEntry = 0xff;
+            pp->PicOrderCntValList[i]   = 0;
+        }
+    }
+
+    #define DO_REF_LIST(ref_idx, ref_list) { \
+        const RefPicList *rpl = &h->rps[ref_idx]; \
+        for (i = 0, j = 0; i < FF_ARRAY_ELEMS(pp->ref_list); i++) { \
+            const HEVCFrame *frame = NULL; \
+            while (!frame && j < rpl->nb_refs) \
+                frame = rpl->ref[j++]; \
+            if (frame && frame->flags & (HEVC_FRAME_FLAG_LONG_REF | HEVC_FRAME_FLAG_SHORT_REF)) \
+                pp->ref_list[i] = get_refpic_index(pp, ff_d3d12dec_get_surface_index(avctx, frame->frame)); \
+            else \
+                pp->ref_list[i] = 0xff; \
+        } \
+    }
+
+    // Fill short term and long term lists
+    DO_REF_LIST(ST_CURR_BEF, RefPicSetStCurrBefore);
+    DO_REF_LIST(ST_CURR_AFT, RefPicSetStCurrAfter);
+    DO_REF_LIST(LT_CURR, RefPicSetLtCurr);
+
+    pp->StatusReportFeedbackNumber = ctx->report_id++;
+}
+
+static void fill_scaling_lists(const AVCodecContext *avctx, const HEVCContext *h, DXVA_Qmatrix_HEVC *qm)
+{
+    unsigned i, j, pos;
+    const ScalingList *sl = h->ps.pps->scaling_list_data_present_flag ?
+                            &h->ps.pps->scaling_list : &h->ps.sps->scaling_list;
+
+    memset(qm, 0, sizeof(*qm));
+    for (i = 0; i < 6; i++) {
+        for (j = 0; j < 16; j++) {
+            pos = 4 * ff_hevc_diag_scan4x4_y[j] + ff_hevc_diag_scan4x4_x[j];
+            qm->ucScalingLists0[i][j] = sl->sl[0][i][pos];
+        }
+
+        for (j = 0; j < 64; j++) {
+            pos = 8 * ff_hevc_diag_scan8x8_y[j] + ff_hevc_diag_scan8x8_x[j];
+            qm->ucScalingLists1[i][j] = sl->sl[1][i][pos];
+            qm->ucScalingLists2[i][j] = sl->sl[2][i][pos];
+
+            if (i < 2)
+                qm->ucScalingLists3[i][j] = sl->sl[3][i * 3][pos];
+        }
+
+        qm->ucScalingListDCCoefSizeID2[i] = sl->sl_dc[0][i];
+        if (i < 2)
+            qm->ucScalingListDCCoefSizeID3[i] = sl->sl_dc[1][i * 3];
+    }
+}
+
+static void fill_slice_short(DXVA_Slice_HEVC_Short *slice, unsigned position, unsigned size)
+{
+    memset(slice, 0, sizeof(*slice));
+    slice->BSNALunitDataLocation = position;
+    slice->SliceBytesInBuffer    = size;
+    slice->wBadSliceChopping     = 0;
+}
+
+static int d3d12dec_hevc_start_frame(AVCodecContext *avctx, av_unused const uint8_t *buffer, av_unused uint32_t size)
+{
+    const HEVCContext         *h       = avctx->priv_data;
+    D3D12DecodePictureContext *ctx_pic = h->ref->hwaccel_picture_private;
+
+    if (!D3D12VA_DECODE_CONTEXT(avctx))
+        return -1;
+
+    av_assert0(ctx_pic);
+
+    fill_picture_parameters(avctx, h, &ctx_pic->pp);
+
+    fill_scaling_lists(avctx, h, &ctx_pic->qm);
+
+    ctx_pic->slice_count    = 0;
+    ctx_pic->bitstream_size = 0;
+    ctx_pic->bitstream      = NULL;
+
+    return 0;
+}
+
+static int d3d12dec_hevc_decode_slice(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size)
+{
+    const HEVCContext         *h               = avctx->priv_data;
+    const HEVCFrame           *current_picture = h->ref;
+    D3D12DecodePictureContext *ctx_pic         = current_picture->hwaccel_picture_private;
+    unsigned position;
+
+    if (ctx_pic->slice_count >= D3D12DEC_MAX_SLICES)
+        return -1;
+
+    if (!ctx_pic->bitstream)
+        ctx_pic->bitstream = buffer;
+    ctx_pic->bitstream_size += size;
+
+    position = buffer - ctx_pic->bitstream;
+    fill_slice_short(&ctx_pic->slice_short[ctx_pic->slice_count], position, size);
+    ctx_pic->slice_count++;
+
+    return 0;
+}
+
+#define START_CODE 65536
+#define START_CODE_SIZE 3
+static int update_input_arguments(AVCodecContext *avctx, D3D12_VIDEO_DECODE_INPUT_STREAM_ARGUMENTS *input_args, ID3D12Resource *buffer)
+{
+    D3D12VADecodeContext   *ctx          = D3D12VA_DECODE_CONTEXT(avctx);
+    AVHWFramesContext      *frames_ctx   = D3D12VA_FRAMES_CONTEXT(avctx);
+    AVD3D12VAFramesContext *frames_hwctx = frames_ctx->hwctx;
+
+    const HEVCContext         *h               = avctx->priv_data;
+    const HEVCFrame           *current_picture = h->ref;
+    D3D12DecodePictureContext *ctx_pic         = current_picture->hwaccel_picture_private;
+
+    int i, index;
+    uint8_t *mapped_data, *mapped_ptr;
+    DXVA_Slice_HEVC_Short *slice;
+    D3D12_VIDEO_DECODE_FRAME_ARGUMENT *args;
+
+    if (FAILED(ID3D12Resource_Map(buffer, 0, NULL, &mapped_data))) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to map D3D12 Buffer resource!\n");
+        return AVERROR(EINVAL);
+    }
+
+    mapped_ptr = mapped_data;
+    for (i = 0; i < ctx_pic->slice_count; i++) {
+        args = &input_args->FrameArguments[input_args->NumFrameArguments++];
+        args->Type  = D3D12_VIDEO_DECODE_ARGUMENT_TYPE_SLICE_CONTROL;
+        args->Size  = sizeof(ctx_pic->slice_short[i]);
+        args->pData = &ctx_pic->slice_short[i];
+
+        slice = &ctx_pic->slice_short[i];
+
+        *(uint32_t *)mapped_ptr = START_CODE;
+        mapped_ptr += START_CODE_SIZE;
+
+        memcpy(mapped_ptr, &ctx_pic->bitstream[slice->BSNALunitDataLocation], slice->SliceBytesInBuffer);
+        mapped_ptr += slice->SliceBytesInBuffer;
+    }
+
+    ID3D12Resource_Unmap(buffer, 0, NULL);
+
+    input_args->CompressedBitstream = (D3D12_VIDEO_DECODE_COMPRESSED_BITSTREAM){
+        .pBuffer = buffer,
+        .Offset  = 0,
+        .Size    = mapped_ptr - mapped_data,
+    };
+
+    index = ctx_pic->pp.CurrPic.Index7Bits;
+    ctx->ref_resources[index] = frames_hwctx->texture_infos[index].texture;
+
+    for (i = 0; i < FF_ARRAY_ELEMS(ctx_pic->pp.RefPicList); i++) {
+        index = ctx_pic->pp.RefPicList[i].Index7Bits;
+        if (index != 0x7f) {
+            ctx->ref_resources[index] = frames_hwctx->texture_infos[index].texture;
+        }
+    }
+
+    return 0;
+}
+
+static int d3d12dec_hevc_end_frame(AVCodecContext *avctx)
+{
+    HEVCContext               *h       = avctx->priv_data;
+    D3D12DecodePictureContext *ctx_pic = h->ref->hwaccel_picture_private;
+
+    int scale = ctx_pic->pp.dwCodingParamToolFlags & 1;
+
+    if (ctx_pic->slice_count <= 0 || ctx_pic->bitstream_size <= 0)
+        return -1;
+
+    return ff_d3d12dec_common_end_frame(avctx, h->ref->frame, &ctx_pic->pp, sizeof(ctx_pic->pp),
+               scale ? &ctx_pic->qm : NULL, scale ? sizeof(ctx_pic->qm) : 0, update_input_arguments);
+}
+
+static int d3d12dec_hevc_decode_init(AVCodecContext *avctx)
+{
+    HEVCContext          *h   = avctx->priv_data;
+    D3D12VADecodeContext *ctx = D3D12VA_DECODE_CONTEXT(avctx);
+
+    switch (avctx->profile) {
+    case FF_PROFILE_HEVC_MAIN_10:
+        ctx->cfg.DecodeProfile = D3D12_VIDEO_DECODE_PROFILE_HEVC_MAIN10;
+        break;
+
+    case FF_PROFILE_HEVC_MAIN_STILL_PICTURE:
+        av_log(avctx, AV_LOG_ERROR, "D3D12 doesn't support PROFILE_HEVC_MAIN_STILL_PICTURE!\n");
+        return AVERROR(EINVAL);
+
+    case FF_PROFILE_HEVC_MAIN:
+    default:
+        ctx->cfg.DecodeProfile = D3D12_VIDEO_DECODE_PROFILE_HEVC_MAIN;
+        break;
+    };
+
+    return ff_d3d12dec_decode_init(avctx);
+}
+
+#if CONFIG_HEVC_D3D12DEC_HWACCEL
+const AVHWAccel ff_hevc_d3d12dec_hwaccel = {
+    .name                 = "hevc_d3d12dec",
+    .type                 = AVMEDIA_TYPE_VIDEO,
+    .id                   = AV_CODEC_ID_HEVC,
+    .pix_fmt              = AV_PIX_FMT_D3D12,
+    .init                 = d3d12dec_hevc_decode_init,
+    .uninit               = ff_d3d12dec_decode_uninit,
+    .start_frame          = d3d12dec_hevc_start_frame,
+    .decode_slice         = d3d12dec_hevc_decode_slice,
+    .end_frame            = d3d12dec_hevc_end_frame,
+    .frame_params         = ff_d3d12dec_common_frame_params,
+    .frame_priv_data_size = sizeof(D3D12DecodePictureContext),
+    .priv_data_size       = sizeof(D3D12VADecodeContext),
+};
+#endif
diff --git a/libavcodec/d3d12dec_vp9.c b/libavcodec/d3d12dec_vp9.c
new file mode 100644
index 0000000000..16a33d4e31
--- /dev/null
+++ b/libavcodec/d3d12dec_vp9.c
@@ -0,0 +1,294 @@
+/*
+ * Direct3D 12 VP9 HW acceleration
+ *
+ * copyright (c) 2022 Wu Jianhua <toqsxw@outlook.com>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "config_components.h"
+
+#include "libavutil/avassert.h"
+#include "libavutil/pixdesc.h"
+
+#include "vp9shared.h"
+#include "d3d12dec.h"
+#include <dxva.h>
+
+typedef struct D3D12DecodePictureContext {
+    DXVA_PicParams_VP9    pp;
+    DXVA_Slice_VPx_Short  slice;
+    const uint8_t        *bitstream;
+    unsigned              bitstream_size;
+} D3D12DecodePictureContext;
+
+static void fill_picture_entry(DXVA_PicEntry_VPx *pic, unsigned index, unsigned flag)
+{
+    av_assert0((index & 0x7f) == index && (flag & 0x01) == flag);
+    pic->bPicEntry = index | (flag << 7);
+}
+
+static int fill_picture_parameters(AVCodecContext *avctx, const VP9SharedContext *h, DXVA_PicParams_VP9 *pp)
+{
+    int i;
+    D3D12VADecodeContext     *ctx     = D3D12VA_DECODE_CONTEXT(avctx);
+    const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
+
+    if (!pixdesc)
+        return -1;
+
+    memset(pp, 0, sizeof(*pp));
+
+    fill_picture_entry(&pp->CurrPic, ff_d3d12dec_get_surface_index(avctx, h->frames[CUR_FRAME].tf.f), 0);
+
+    pp->profile = h->h.profile;
+    pp->wFormatAndPictureInfoFlags = ((h->h.keyframe == 0)   <<  0) |
+                                     ((h->h.invisible == 0)  <<  1) |
+                                     (h->h.errorres          <<  2) |
+                                     (pixdesc->log2_chroma_w <<  3) | /* subsampling_x */
+                                     (pixdesc->log2_chroma_h <<  4) | /* subsampling_y */
+                                     (0                      <<  5) | /* extra_plane */
+                                     (h->h.refreshctx        <<  6) |
+                                     (h->h.parallelmode      <<  7) |
+                                     (h->h.intraonly         <<  8) |
+                                     (h->h.framectxid        <<  9) |
+                                     (h->h.resetctx          << 11) |
+                                     ((h->h.keyframe ? 0 : h->h.highprecisionmvs) << 13) |
+                                     (0                      << 14);  /* ReservedFormatInfo2Bits */
+
+    pp->width  = avctx->width;
+    pp->height = avctx->height;
+    pp->BitDepthMinus8Luma   = pixdesc->comp[0].depth - 8;
+    pp->BitDepthMinus8Chroma = pixdesc->comp[1].depth - 8;
+    /* swap 0/1 to match the reference */
+    pp->interp_filter = h->h.filtermode ^ (h->h.filtermode <= 1);
+    pp->Reserved8Bits = 0;
+
+    for (i = 0; i < 8; i++) {
+        if (h->refs[i].f->buf[0]) {
+            fill_picture_entry(&pp->ref_frame_map[i], ff_d3d12dec_get_surface_index(avctx, h->refs[i].f), 0);
+            pp->ref_frame_coded_width[i]  = h->refs[i].f->width;
+            pp->ref_frame_coded_height[i] = h->refs[i].f->height;
+        } else
+            pp->ref_frame_map[i].bPicEntry = 0xFF;
+    }
+
+    for (i = 0; i < 3; i++) {
+        uint8_t refidx = h->h.refidx[i];
+        if (h->refs[refidx].f->buf[0])
+            fill_picture_entry(&pp->frame_refs[i], ff_d3d12dec_get_surface_index(avctx, h->refs[refidx].f), 0);
+        else
+            pp->frame_refs[i].bPicEntry = 0xFF;
+
+        pp->ref_frame_sign_bias[i + 1] = h->h.signbias[i];
+    }
+
+    pp->filter_level    = h->h.filter.level;
+    pp->sharpness_level = h->h.filter.sharpness;
+
+    pp->wControlInfoFlags = (h->h.lf_delta.enabled   << 0) |
+                            (h->h.lf_delta.updated   << 1) |
+                            (h->h.use_last_frame_mvs << 2) |
+                            (0                       << 3);  /* ReservedControlInfo5Bits */
+
+    for (i = 0; i < 4; i++)
+        pp->ref_deltas[i]  = h->h.lf_delta.ref[i];
+
+    for (i = 0; i < 2; i++)
+        pp->mode_deltas[i]  = h->h.lf_delta.mode[i];
+
+    pp->base_qindex   = h->h.yac_qi;
+    pp->y_dc_delta_q  = h->h.ydc_qdelta;
+    pp->uv_dc_delta_q = h->h.uvdc_qdelta;
+    pp->uv_ac_delta_q = h->h.uvac_qdelta;
+
+    /* segmentation data */
+    pp->stVP9Segments.wSegmentInfoFlags = (h->h.segmentation.enabled       << 0) |
+                                          (h->h.segmentation.update_map    << 1) |
+                                          (h->h.segmentation.temporal      << 2) |
+                                          (h->h.segmentation.absolute_vals << 3) |
+                                          (0                               << 4);  /* ReservedSegmentFlags4Bits */
+
+    for (i = 0; i < 7; i++)
+        pp->stVP9Segments.tree_probs[i] = h->h.segmentation.prob[i];
+
+    if (h->h.segmentation.temporal)
+        for (i = 0; i < 3; i++)
+            pp->stVP9Segments.pred_probs[i] = h->h.segmentation.pred_prob[i];
+    else
+        memset(pp->stVP9Segments.pred_probs, 255, sizeof(pp->stVP9Segments.pred_probs));
+
+    for (i = 0; i < 8; i++) {
+        pp->stVP9Segments.feature_mask[i] = (h->h.segmentation.feat[i].q_enabled    << 0) |
+                                            (h->h.segmentation.feat[i].lf_enabled   << 1) |
+                                            (h->h.segmentation.feat[i].ref_enabled  << 2) |
+                                            (h->h.segmentation.feat[i].skip_enabled << 3);
+
+        pp->stVP9Segments.feature_data[i][0] = h->h.segmentation.feat[i].q_val;
+        pp->stVP9Segments.feature_data[i][1] = h->h.segmentation.feat[i].lf_val;
+        pp->stVP9Segments.feature_data[i][2] = h->h.segmentation.feat[i].ref_val;
+        pp->stVP9Segments.feature_data[i][3] = 0; /* no data for skip */
+    }
+
+    pp->log2_tile_cols = h->h.tiling.log2_tile_cols;
+    pp->log2_tile_rows = h->h.tiling.log2_tile_rows;
+
+    pp->uncompressed_header_size_byte_aligned = h->h.uncompressed_header_size;
+    pp->first_partition_size = h->h.compressed_header_size;
+
+    pp->StatusReportFeedbackNumber = ctx->report_id++;
+
+    return 0;
+}
+
+static void fill_slice_short(DXVA_Slice_VPx_Short *slice, unsigned position, unsigned size)
+{
+    memset(slice, 0, sizeof(*slice));
+    slice->BSNALunitDataLocation = position;
+    slice->SliceBytesInBuffer    = size;
+    slice->wBadSliceChopping     = 0;
+}
+
+static int d3d12dec_vp9_start_frame(AVCodecContext *avctx, av_unused const uint8_t *buffer, av_unused uint32_t size)
+{
+    const VP9SharedContext    *h       = avctx->priv_data;
+    D3D12DecodePictureContext *ctx_pic = h->frames[CUR_FRAME].hwaccel_picture_private;
+
+    if (!D3D12VA_DECODE_CONTEXT(avctx))
+        return -1;
+
+    av_assert0(ctx_pic);
+
+    if (fill_picture_parameters(avctx, h, &ctx_pic->pp) < 0)
+        return -1;
+
+    ctx_pic->bitstream_size = 0;
+    ctx_pic->bitstream = NULL;
+
+    return 0;
+}
+
+static int d3d12dec_vp9_decode_slice(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size)
+{
+    const VP9SharedContext    *h       = avctx->priv_data;
+    D3D12DecodePictureContext *ctx_pic = h->frames[CUR_FRAME].hwaccel_picture_private;
+    unsigned position;
+
+    if (!ctx_pic->bitstream)
+        ctx_pic->bitstream = buffer;
+    ctx_pic->bitstream_size += size;
+
+    position = buffer - ctx_pic->bitstream;
+    fill_slice_short(&ctx_pic->slice, position, size);
+
+    return 0;
+}
+
+static int update_input_arguments(AVCodecContext *avctx, D3D12_VIDEO_DECODE_INPUT_STREAM_ARGUMENTS *input_args, ID3D12Resource *buffer)
+{
+    D3D12VADecodeContext   *ctx          = D3D12VA_DECODE_CONTEXT(avctx);
+    AVHWFramesContext      *frames_ctx   = D3D12VA_FRAMES_CONTEXT(avctx);
+    AVD3D12VAFramesContext *frames_hwctx = frames_ctx->hwctx;
+
+    const VP9SharedContext    *h       = avctx->priv_data;
+    D3D12DecodePictureContext *ctx_pic = h->frames[CUR_FRAME].hwaccel_picture_private;
+
+    int index;
+    uint8_t *mapped_data;
+    D3D12_VIDEO_DECODE_FRAME_ARGUMENT *args;
+
+    if (FAILED(ID3D12Resource_Map(buffer, 0, NULL, &mapped_data))) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to map D3D12 Buffer resource!\n");
+        return AVERROR(EINVAL);
+    }
+
+    args = &input_args->FrameArguments[input_args->NumFrameArguments++];
+    args->Type  = D3D12_VIDEO_DECODE_ARGUMENT_TYPE_SLICE_CONTROL;
+    args->Size  = sizeof(ctx_pic->slice);
+    args->pData = &ctx_pic->slice;
+
+    memcpy(mapped_data, ctx_pic->bitstream, ctx_pic->slice.SliceBytesInBuffer);
+
+    ID3D12Resource_Unmap(buffer, 0, NULL);
+
+    input_args->CompressedBitstream = (D3D12_VIDEO_DECODE_COMPRESSED_BITSTREAM){
+        .pBuffer = buffer,
+        .Offset  = 0,
+        .Size    = ctx_pic->slice.SliceBytesInBuffer,
+    };
+
+    index = ctx_pic->pp.CurrPic.Index7Bits;
+    ctx->ref_resources[index] = frames_hwctx->texture_infos[index].texture;
+
+    for (int i = 0; i < FF_ARRAY_ELEMS(ctx_pic->pp.frame_refs); i++) {
+        index = ctx_pic->pp.frame_refs[i].Index7Bits;
+        if (index != 0x7f) {
+            ctx->ref_resources[index] = frames_hwctx->texture_infos[index].texture;
+        }
+    }
+
+    return 0;
+}
+
+static int d3d12dec_vp9_end_frame(AVCodecContext *avctx)
+{
+    VP9SharedContext          *h = avctx->priv_data;
+    D3D12DecodePictureContext *ctx_pic = h->frames[CUR_FRAME].hwaccel_picture_private;
+
+    if (ctx_pic->bitstream_size <= 0)
+        return -1;
+
+    return ff_d3d12dec_common_end_frame(avctx, h->frames[CUR_FRAME].tf.f,
+               &ctx_pic->pp, sizeof(ctx_pic->pp), NULL, 0, update_input_arguments);
+}
+
+static int d3d12dec_vp9_decode_init(AVCodecContext *avctx)
+{
+    D3D12VADecodeContext *ctx = D3D12VA_DECODE_CONTEXT(avctx);
+
+    switch (avctx->profile) {
+    case FF_PROFILE_VP9_2:
+    case FF_PROFILE_VP9_3:
+        ctx->cfg.DecodeProfile = D3D12_VIDEO_DECODE_PROFILE_VP9_10BIT_PROFILE2;
+        break;
+
+    case FF_PROFILE_VP9_0:
+    case FF_PROFILE_VP9_1:
+    default:
+        ctx->cfg.DecodeProfile = D3D12_VIDEO_DECODE_PROFILE_VP9;
+        break;
+    };
+
+    return ff_d3d12dec_decode_init(avctx);
+}
+
+#if CONFIG_VP9_D3D12DEC_HWACCEL
+const AVHWAccel ff_vp9_d3d12dec_hwaccel = {
+    .name                 = "vp9_d3d12dec",
+    .type                 = AVMEDIA_TYPE_VIDEO,
+    .id                   = AV_CODEC_ID_VP9,
+    .pix_fmt              = AV_PIX_FMT_D3D12,
+    .init                 = d3d12dec_vp9_decode_init,
+    .uninit               = ff_d3d12dec_decode_uninit,
+    .start_frame          = d3d12dec_vp9_start_frame,
+    .decode_slice         = d3d12dec_vp9_decode_slice,
+    .end_frame            = d3d12dec_vp9_end_frame,
+    .frame_params         = ff_d3d12dec_common_frame_params,
+    .frame_priv_data_size = sizeof(struct D3D12DecodePictureContext),
+    .priv_data_size       = sizeof(D3D12VADecodeContext),
+};
+#endif
diff --git a/libavcodec/h264_slice.c b/libavcodec/h264_slice.c
index 6f0a7c1fb7..0f8ee52329 100644
--- a/libavcodec/h264_slice.c
+++ b/libavcodec/h264_slice.c
@@ -792,6 +792,7 @@ static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
 {
 #define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \
                      (CONFIG_H264_D3D11VA_HWACCEL * 2) + \
+                     CONFIG_H264_D3D12DEC_HWACCEL + \
                      CONFIG_H264_NVDEC_HWACCEL + \
                      CONFIG_H264_VAAPI_HWACCEL + \
                      CONFIG_H264_VIDEOTOOLBOX_HWACCEL + \
@@ -880,6 +881,9 @@ static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
             *fmt++ = AV_PIX_FMT_D3D11VA_VLD;
             *fmt++ = AV_PIX_FMT_D3D11;
 #endif
+#if CONFIG_H264_D3D12DEC_HWACCEL
+            *fmt++ = AV_PIX_FMT_D3D12;
+#endif
 #if CONFIG_H264_VAAPI_HWACCEL
             *fmt++ = AV_PIX_FMT_VAAPI;
 #endif
diff --git a/libavcodec/h264dec.c b/libavcodec/h264dec.c
index 8f56f3ff92..445c3687f3 100644
--- a/libavcodec/h264dec.c
+++ b/libavcodec/h264dec.c
@@ -1086,7 +1086,10 @@ const FFCodec ff_h264_decoder = {
                                HWACCEL_D3D11VA(h264),
 #endif
 #if CONFIG_H264_D3D11VA2_HWACCEL
-                               HWACCEL_D3D11VA2(h264),
+                               HWACCEL_D3D11VA(h264),
+#endif
+#if CONFIG_H264_D3D12DEC_HWACCEL
+                               HWACCEL_D3D12DEC(h264),
 #endif
 #if CONFIG_H264_NVDEC_HWACCEL
                                HWACCEL_NVDEC(h264),
diff --git a/libavcodec/hevcdec.c b/libavcodec/hevcdec.c
index fb44d8d3f2..eee41835ca 100644
--- a/libavcodec/hevcdec.c
+++ b/libavcodec/hevcdec.c
@@ -403,6 +403,7 @@ static enum AVPixelFormat get_format(HEVCContext *s, const HEVCSPS *sps)
 {
 #define HWACCEL_MAX (CONFIG_HEVC_DXVA2_HWACCEL + \
                      CONFIG_HEVC_D3D11VA_HWACCEL * 2 + \
+                     CONFIG_HEVC_D3D12DEC_HWACCEL + \
                      CONFIG_HEVC_NVDEC_HWACCEL + \
                      CONFIG_HEVC_VAAPI_HWACCEL + \
                      CONFIG_HEVC_VIDEOTOOLBOX_HWACCEL + \
@@ -419,6 +420,9 @@ static enum AVPixelFormat get_format(HEVCContext *s, const HEVCSPS *sps)
         *fmt++ = AV_PIX_FMT_D3D11VA_VLD;
         *fmt++ = AV_PIX_FMT_D3D11;
 #endif
+#if CONFIG_HEVC_D3D12DEC_HWACCEL
+        *fmt++ = AV_PIX_FMT_D3D12;
+#endif
 #if CONFIG_HEVC_VAAPI_HWACCEL
         *fmt++ = AV_PIX_FMT_VAAPI;
 #endif
@@ -440,6 +444,9 @@ static enum AVPixelFormat get_format(HEVCContext *s, const HEVCSPS *sps)
         *fmt++ = AV_PIX_FMT_D3D11VA_VLD;
         *fmt++ = AV_PIX_FMT_D3D11;
 #endif
+#if CONFIG_HEVC_D3D12DEC_HWACCEL
+        *fmt++ = AV_PIX_FMT_D3D12;
+#endif
 #if CONFIG_HEVC_VAAPI_HWACCEL
         *fmt++ = AV_PIX_FMT_VAAPI;
 #endif
@@ -3878,6 +3885,9 @@ const FFCodec ff_hevc_decoder = {
 #if CONFIG_HEVC_D3D11VA2_HWACCEL
                                HWACCEL_D3D11VA2(hevc),
 #endif
+#if CONFIG_HEVC_D3D12DEC_HWACCEL
+                               HWACCEL_D3D12DEC(hevc),
+#endif
 #if CONFIG_HEVC_NVDEC_HWACCEL
                                HWACCEL_NVDEC(hevc),
 #endif
diff --git a/libavcodec/hwaccels.h b/libavcodec/hwaccels.h
index aca55831f3..2e1cc47486 100644
--- a/libavcodec/hwaccels.h
+++ b/libavcodec/hwaccels.h
@@ -23,6 +23,7 @@
 
 extern const AVHWAccel ff_av1_d3d11va_hwaccel;
 extern const AVHWAccel ff_av1_d3d11va2_hwaccel;
+extern const AVHWAccel ff_av1_d3d12dec_hwaccel;
 extern const AVHWAccel ff_av1_dxva2_hwaccel;
 extern const AVHWAccel ff_av1_nvdec_hwaccel;
 extern const AVHWAccel ff_av1_vaapi_hwaccel;
@@ -32,12 +33,14 @@ extern const AVHWAccel ff_h263_videotoolbox_hwaccel;
 extern const AVHWAccel ff_h264_d3d11va_hwaccel;
 extern const AVHWAccel ff_h264_d3d11va2_hwaccel;
 extern const AVHWAccel ff_h264_dxva2_hwaccel;
+extern const AVHWAccel ff_h264_d3d12dec_hwaccel;
 extern const AVHWAccel ff_h264_nvdec_hwaccel;
 extern const AVHWAccel ff_h264_vaapi_hwaccel;
 extern const AVHWAccel ff_h264_vdpau_hwaccel;
 extern const AVHWAccel ff_h264_videotoolbox_hwaccel;
 extern const AVHWAccel ff_hevc_d3d11va_hwaccel;
 extern const AVHWAccel ff_hevc_d3d11va2_hwaccel;
+extern const AVHWAccel ff_hevc_d3d12dec_hwaccel;
 extern const AVHWAccel ff_hevc_dxva2_hwaccel;
 extern const AVHWAccel ff_hevc_nvdec_hwaccel;
 extern const AVHWAccel ff_hevc_vaapi_hwaccel;
@@ -70,6 +73,7 @@ extern const AVHWAccel ff_vp8_nvdec_hwaccel;
 extern const AVHWAccel ff_vp8_vaapi_hwaccel;
 extern const AVHWAccel ff_vp9_d3d11va_hwaccel;
 extern const AVHWAccel ff_vp9_d3d11va2_hwaccel;
+extern const AVHWAccel ff_vp9_d3d12dec_hwaccel;
 extern const AVHWAccel ff_vp9_dxva2_hwaccel;
 extern const AVHWAccel ff_vp9_nvdec_hwaccel;
 extern const AVHWAccel ff_vp9_vaapi_hwaccel;
diff --git a/libavcodec/hwconfig.h b/libavcodec/hwconfig.h
index 721424912c..bd4e3f04b9 100644
--- a/libavcodec/hwconfig.h
+++ b/libavcodec/hwconfig.h
@@ -68,6 +68,8 @@ typedef struct AVCodecHWConfigInternal {
     HW_CONFIG_HWACCEL(1, 1, 1, DXVA2_VLD,    DXVA2,        ff_ ## codec ## _dxva2_hwaccel)
 #define HWACCEL_D3D11VA2(codec) \
     HW_CONFIG_HWACCEL(1, 1, 0, D3D11,        D3D11VA,      ff_ ## codec ## _d3d11va2_hwaccel)
+#define HWACCEL_D3D12DEC(codec) \
+    HW_CONFIG_HWACCEL(1, 1, 0, D3D12,        D3D12VA,      ff_ ## codec ## _d3d12dec_hwaccel)
 #define HWACCEL_NVDEC(codec) \
     HW_CONFIG_HWACCEL(1, 1, 0, CUDA,         CUDA,         ff_ ## codec ## _nvdec_hwaccel)
 #define HWACCEL_VAAPI(codec) \
diff --git a/libavcodec/version.h b/libavcodec/version.h
index ade18cddcd..f8abc803b6 100644
--- a/libavcodec/version.h
+++ b/libavcodec/version.h
@@ -29,7 +29,7 @@
 
 #include "version_major.h"
 
-#define LIBAVCODEC_VERSION_MINOR  50
+#define LIBAVCODEC_VERSION_MINOR  51
 #define LIBAVCODEC_VERSION_MICRO 100
 
 #define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
diff --git a/libavcodec/vp9.c b/libavcodec/vp9.c
index 7c0a246446..a997931063 100644
--- a/libavcodec/vp9.c
+++ b/libavcodec/vp9.c
@@ -184,6 +184,7 @@ static int update_size(AVCodecContext *avctx, int w, int h)
 {
 #define HWACCEL_MAX (CONFIG_VP9_DXVA2_HWACCEL + \
                      CONFIG_VP9_D3D11VA_HWACCEL * 2 + \
+                     CONFIG_VP9_D3D12DEC_HWACCEL + \
                      CONFIG_VP9_NVDEC_HWACCEL + \
                      CONFIG_VP9_VAAPI_HWACCEL + \
                      CONFIG_VP9_VDPAU_HWACCEL + \
@@ -210,6 +211,9 @@ static int update_size(AVCodecContext *avctx, int w, int h)
             *fmtp++ = AV_PIX_FMT_D3D11VA_VLD;
             *fmtp++ = AV_PIX_FMT_D3D11;
 #endif
+#if CONFIG_VP9_D3D12DEC_HWACCEL
+            *fmtp++ = AV_PIX_FMT_D3D12;
+#endif
 #if CONFIG_VP9_NVDEC_HWACCEL
             *fmtp++ = AV_PIX_FMT_CUDA;
 #endif
@@ -1897,6 +1901,9 @@ const FFCodec ff_vp9_decoder = {
 #if CONFIG_VP9_D3D11VA2_HWACCEL
                                HWACCEL_D3D11VA2(vp9),
 #endif
+#if CONFIG_VP9_D3D12DEC_HWACCEL
+                               HWACCEL_D3D12DEC(vp9),
+#endif
 #if CONFIG_VP9_NVDEC_HWACCEL
                                HWACCEL_NVDEC(vp9),
 #endif
diff --git a/libavutil/Makefile b/libavutil/Makefile
index 3d9c07aea8..121d87e9a5 100644
--- a/libavutil/Makefile
+++ b/libavutil/Makefile
@@ -40,6 +40,7 @@ HEADERS = adler32.h                                                     \
           hwcontext.h                                                   \
           hwcontext_cuda.h                                              \
           hwcontext_d3d11va.h                                           \
+          hwcontext_d3d12va.h                                           \
           hwcontext_drm.h                                               \
           hwcontext_dxva2.h                                             \
           hwcontext_qsv.h                                               \
@@ -185,6 +186,7 @@ OBJS = adler32.o                                                        \
 
 OBJS-$(CONFIG_CUDA)                     += hwcontext_cuda.o
 OBJS-$(CONFIG_D3D11VA)                  += hwcontext_d3d11va.o
+OBJS-$(CONFIG_D3D12VA)                  += hwcontext_d3d12va.o
 OBJS-$(CONFIG_DXVA2)                    += hwcontext_dxva2.o
 OBJS-$(CONFIG_LIBDRM)                   += hwcontext_drm.o
 OBJS-$(CONFIG_MACOS_KPERF)              += macos_kperf.o
@@ -208,6 +210,7 @@ SKIPHEADERS-$(HAVE_CUDA_H)             += hwcontext_cuda.h
 SKIPHEADERS-$(CONFIG_CUDA)             += hwcontext_cuda_internal.h     \
                                           cuda_check.h
 SKIPHEADERS-$(CONFIG_D3D11VA)          += hwcontext_d3d11va.h
+SKIPHEADERS-$(CONFIG_D3D12VA)          += hwcontext_d3d12va.h
 SKIPHEADERS-$(CONFIG_DXVA2)            += hwcontext_dxva2.h
 SKIPHEADERS-$(CONFIG_QSV)              += hwcontext_qsv.h
 SKIPHEADERS-$(CONFIG_OPENCL)           += hwcontext_opencl.h
diff --git a/libavutil/hwcontext.c b/libavutil/hwcontext.c
index ab9ad3703e..90971fbece 100644
--- a/libavutil/hwcontext.c
+++ b/libavutil/hwcontext.c
@@ -36,6 +36,9 @@ static const HWContextType * const hw_table[] = {
 #if CONFIG_D3D11VA
     &ff_hwcontext_type_d3d11va,
 #endif
+#if CONFIG_D3D12VA
+    &ff_hwcontext_type_d3d12va,
+#endif
 #if CONFIG_LIBDRM
     &ff_hwcontext_type_drm,
 #endif
@@ -71,6 +74,7 @@ static const char *const hw_type_names[] = {
     [AV_HWDEVICE_TYPE_DRM]    = "drm",
     [AV_HWDEVICE_TYPE_DXVA2]  = "dxva2",
     [AV_HWDEVICE_TYPE_D3D11VA] = "d3d11va",
+    [AV_HWDEVICE_TYPE_D3D12VA] = "d3d12va",
     [AV_HWDEVICE_TYPE_OPENCL] = "opencl",
     [AV_HWDEVICE_TYPE_QSV]    = "qsv",
     [AV_HWDEVICE_TYPE_VAAPI]  = "vaapi",
diff --git a/libavutil/hwcontext.h b/libavutil/hwcontext.h
index c18b7e1e8b..d8925c4574 100644
--- a/libavutil/hwcontext.h
+++ b/libavutil/hwcontext.h
@@ -33,6 +33,7 @@ enum AVHWDeviceType {
     AV_HWDEVICE_TYPE_QSV,
     AV_HWDEVICE_TYPE_VIDEOTOOLBOX,
     AV_HWDEVICE_TYPE_D3D11VA,
+    AV_HWDEVICE_TYPE_D3D12VA,
     AV_HWDEVICE_TYPE_DRM,
     AV_HWDEVICE_TYPE_OPENCL,
     AV_HWDEVICE_TYPE_MEDIACODEC,
diff --git a/libavutil/hwcontext_d3d12va.c b/libavutil/hwcontext_d3d12va.c
new file mode 100644
index 0000000000..cde259d659
--- /dev/null
+++ b/libavutil/hwcontext_d3d12va.c
@@ -0,0 +1,687 @@
+/*
+ * DirectX 12 HW acceleration.
+ *
+ * copyright (c) 2022 Wu Jianhua <toqsxw@outlook.com>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "config.h"
+#include "common.h"
+#include "hwcontext.h"
+#include "hwcontext_d3d12va.h"
+#include "hwcontext_internal.h"
+#include "imgutils.h"
+#include "pixdesc.h"
+#include "pixfmt.h"
+#include "thread.h"
+
+#include <initguid.h>
+#include <dxgi1_3.h>
+
+typedef HRESULT(WINAPI *PFN_CREATE_DXGI_FACTORY2)(UINT Flags, REFIID riid, void **ppFactory);
+
+static AVOnce functions_loaded = AV_ONCE_INIT;
+
+static PFN_CREATE_DXGI_FACTORY2 d3d12va_create_dxgi_factory2;
+static PFN_D3D12_CREATE_DEVICE d3d12va_create_device;
+static PFN_D3D12_GET_DEBUG_INTERFACE d3d12va_get_debug_interface;
+
+static av_cold void load_functions(void)
+{
+    HANDLE d3dlib, dxgilib;
+
+    d3dlib  = dlopen("d3d12.dll", 0);
+    dxgilib = dlopen("dxgi.dll", 0);
+    if (!d3dlib || !dxgilib)
+        return;
+
+    d3d12va_create_device = (PFN_D3D12_CREATE_DEVICE)GetProcAddress(d3dlib, "D3D12CreateDevice");
+    d3d12va_create_dxgi_factory2 = (PFN_CREATE_DXGI_FACTORY2)GetProcAddress(dxgilib, "CreateDXGIFactory2");
+    d3d12va_get_debug_interface = (PFN_D3D12_GET_DEBUG_INTERFACE)GetProcAddress(d3dlib, "D3D12GetDebugInterface");
+}
+
+typedef struct D3D12VAFramesContext {
+    int nb_surfaces;
+
+    int nb_surfaces_used;
+
+    DXGI_FORMAT format;
+
+    UINT luma_component_size;
+
+    ID3D12Resource *staging_buffer;
+} D3D12VAFramesContext;
+
+static const struct {
+    DXGI_FORMAT d3d_format;
+    enum AVPixelFormat pix_fmt;
+} supported_formats[] = {
+    { DXGI_FORMAT_NV12, AV_PIX_FMT_NV12 },
+    { DXGI_FORMAT_P010, AV_PIX_FMT_P010 },
+};
+
+DXGI_FORMAT av_d3d12va_map_sw_to_hw_format(enum AVPixelFormat pix_fmt)
+{
+    switch (pix_fmt) {
+    case AV_PIX_FMT_NV12:return DXGI_FORMAT_NV12;
+    case AV_PIX_FMT_P010:return DXGI_FORMAT_P010;
+    default:             return DXGI_FORMAT_UNKNOWN;
+    }
+}
+
+int av_d3d12va_create_sync_context(AVD3D12VADeviceContext *ctx, AVD3D12VASyncContext **sync_ctx)
+{
+    AVD3D12VASyncContext *sync;
+
+    *sync_ctx = av_mallocz(sizeof(AVD3D12VASyncContext));
+    sync = *sync_ctx;
+    DX_CHECK(ID3D12Device_CreateFence(ctx->device, sync->fence_value, D3D12_FENCE_FLAG_NONE, &IID_ID3D12Fence, &sync->fence));
+
+    sync->event = CreateEvent(NULL, FALSE, FALSE, NULL);
+    if (!sync->event)
+        goto fail;
+
+    return 0;
+
+fail:
+    return AVERROR(EINVAL);
+}
+
+int av_d3d12va_release_sync_context(AVD3D12VASyncContext *sync_ctx)
+{
+    if (!sync_ctx)
+        return 0;
+
+    int ret = av_d3d12va_wait_idle(sync_ctx);
+    if (ret < 0)
+        return ret;
+
+    D3D12_OBJECT_RELEASE(sync_ctx->fence);
+
+    if (sync_ctx->event && !CloseHandle(sync_ctx->event))
+        return AVERROR(EINVAL);
+
+    av_freep(&sync_ctx);
+
+    return 0;
+}
+
+int av_d3d12va_wait_for_fence_value(AVD3D12VASyncContext *sync_ctx, uint64_t fence_value)
+{
+    uint64_t completion = ID3D12Fence_GetCompletedValue(sync_ctx->fence);
+    if (completion < fence_value) {
+        if (FAILED(ID3D12Fence_SetEventOnCompletion(sync_ctx->fence, fence_value, sync_ctx->event)))
+            return AVERROR(EINVAL);
+
+        WaitForSingleObjectEx(sync_ctx->event, INFINITE, FALSE);
+    }
+
+    return 0;
+}
+
+int av_d3d12va_wait_idle(AVD3D12VASyncContext *ctx)
+{
+    return av_d3d12va_wait_for_fence_value(ctx, ctx->fence_value);
+}
+
+int av_d3d12va_wait_queue_idle(AVD3D12VASyncContext *sync_ctx, ID3D12CommandQueue *command_queue)
+{
+    DX_CHECK(ID3D12CommandQueue_Signal(command_queue, sync_ctx->fence, ++sync_ctx->fence_value));
+    return av_d3d12va_wait_idle(sync_ctx);
+
+fail:
+    return AVERROR(EINVAL);
+}
+
+static inline int create_resource(ID3D12Device *device, const D3D12_RESOURCE_DESC *desc, D3D12_RESOURCE_STATES states, ID3D12Resource **ppResource, int is_read_back)
+{
+    D3D12_HEAP_PROPERTIES props = {
+        .Type                 = is_read_back ? D3D12_HEAP_TYPE_READBACK : D3D12_HEAP_TYPE_DEFAULT,
+        .CPUPageProperty      = D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
+        .MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN,
+        .CreationNodeMask     = 0,
+        .VisibleNodeMask      = 0,
+    };
+
+    if (FAILED(ID3D12Device_CreateCommittedResource(device, &props, D3D12_HEAP_FLAG_NONE, desc,
+        states, NULL, &IID_ID3D12Resource, ppResource)))
+        return AVERROR(EINVAL);
+
+    return 0;
+}
+
+static int d3d12va_create_helper_objects(AVHWFramesContext *ctx)
+{
+    AVD3D12VADeviceContext *hwctx = ctx->device_ctx->hwctx;
+    D3D12_COMMAND_QUEUE_DESC queue_desc = {
+        .Type = D3D12_COMMAND_LIST_TYPE_DIRECT,
+        .Priority = 0,
+        .NodeMask = 0,
+    };
+
+    DX_CHECK(ID3D12Device_CreateCommandQueue(hwctx->device, &queue_desc,
+        &IID_ID3D12CommandQueue, &hwctx->command_queue));
+
+    DX_CHECK(ID3D12Device_CreateCommandAllocator(hwctx->device, queue_desc.Type,
+        &IID_ID3D12CommandAllocator, &hwctx->command_allocator));
+
+    DX_CHECK(ID3D12Device_CreateCommandList(hwctx->device, 0, queue_desc.Type,
+        hwctx->command_allocator, NULL, &IID_ID3D12GraphicsCommandList, &hwctx->command_list));
+
+    DX_CHECK(ID3D12GraphicsCommandList_Close(hwctx->command_list));
+
+    ID3D12CommandQueue_ExecuteCommandLists(hwctx->command_queue, 1, (ID3D12CommandList **)&hwctx->command_list);
+
+    return av_d3d12va_wait_queue_idle(hwctx->sync_ctx, hwctx->command_queue);
+
+fail:
+    return AVERROR(EINVAL);
+}
+
+static void d3d12va_frames_uninit(AVHWFramesContext *ctx)
+{
+    AVD3D12VAFramesContext *frames_hwctx = ctx->hwctx;
+    D3D12VAFramesContext   *s            = ctx->internal->priv;
+
+    D3D12_OBJECT_RELEASE(s->staging_buffer);
+
+    av_freep(&frames_hwctx->texture_infos);
+}
+
+static int d3d12va_frames_get_constraints(AVHWDeviceContext *ctx, const void *hwconfig, AVHWFramesConstraints *constraints)
+{
+    HRESULT hr;
+    int nb_sw_formats = 0;
+    AVD3D12VADeviceContext *device_hwctx = ctx->hwctx;
+
+    constraints->valid_sw_formats = av_malloc_array(FF_ARRAY_ELEMS(supported_formats) + 1,
+                                                    sizeof(*constraints->valid_sw_formats));
+    if (!constraints->valid_sw_formats)
+        return AVERROR(ENOMEM);
+
+    for (int i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++) {
+        D3D12_FEATURE_DATA_FORMAT_SUPPORT format_support = { supported_formats[i].d3d_format };
+        hr = ID3D12Device_CheckFeatureSupport(device_hwctx->device, D3D12_FEATURE_FORMAT_SUPPORT, &format_support, sizeof(format_support));
+        if (SUCCEEDED(hr) && (format_support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D))
+            constraints->valid_sw_formats[nb_sw_formats++] = supported_formats[i].pix_fmt;
+    }
+    constraints->valid_sw_formats[nb_sw_formats] = AV_PIX_FMT_NONE;
+
+    constraints->valid_hw_formats = av_malloc_array(2, sizeof(*constraints->valid_hw_formats));
+    if (!constraints->valid_hw_formats)
+        return AVERROR(ENOMEM);
+
+    constraints->valid_hw_formats[0] = AV_PIX_FMT_D3D12;
+    constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
+
+    return 0;
+}
+
+static void free_texture(void *opaque, uint8_t *data)
+{
+    AVD3D12FrameDescriptor *desc = (AVD3D12FrameDescriptor *)data;
+
+    if (desc->sync_ctx)
+        av_d3d12va_release_sync_context(desc->sync_ctx);
+
+    D3D12_OBJECT_RELEASE(desc->texture);
+    av_freep(&data);
+}
+
+static AVBufferRef *wrap_texture_buf(AVHWFramesContext *ctx, ID3D12Resource *texture, AVD3D12VASyncContext *sync_ctx)
+{
+    AVBufferRef *buf;
+    D3D12VAFramesContext   *s            = ctx->internal->priv;
+    AVD3D12VAFramesContext *frames_hwctx = ctx->hwctx;
+
+    AVD3D12FrameDescriptor *desc = av_mallocz(sizeof(*desc));
+    if (!desc)
+        goto fail;
+
+    if (s->nb_surfaces <= s->nb_surfaces_used) {
+        frames_hwctx->texture_infos = av_realloc_f(frames_hwctx->texture_infos,
+                                                   s->nb_surfaces_used + 1,
+                                                   sizeof(*frames_hwctx->texture_infos));
+        if (!frames_hwctx->texture_infos)
+            goto fail;
+        s->nb_surfaces = s->nb_surfaces_used + 1;
+    }
+
+    desc->texture  = texture;
+    desc->index    = s->nb_surfaces_used;
+    desc->sync_ctx = sync_ctx;
+
+    frames_hwctx->texture_infos[s->nb_surfaces_used].texture  = texture;
+    frames_hwctx->texture_infos[s->nb_surfaces_used].index    = desc->index;
+    frames_hwctx->texture_infos[s->nb_surfaces_used].sync_ctx = sync_ctx;
+    s->nb_surfaces_used++;
+
+    buf = av_buffer_create((uint8_t *)desc, sizeof(desc), free_texture, texture, 0);
+    if (!buf) {
+        D3D12_OBJECT_RELEASE(texture);
+        av_freep(&desc);
+        return NULL;
+    }
+
+    return buf;
+
+fail:
+    D3D12_OBJECT_RELEASE(texture);
+    av_d3d12va_release_sync_context(sync_ctx);
+    return NULL;
+}
+
+static AVBufferRef *d3d12va_pool_alloc(void *opaque, size_t size)
+{
+    AVHWFramesContext      *ctx          = (AVHWFramesContext *)opaque;
+    D3D12VAFramesContext   *s            = ctx->internal->priv;
+    AVD3D12VAFramesContext *hwctx        = ctx->hwctx;
+    AVD3D12VADeviceContext *device_hwctx = ctx->device_ctx->hwctx;
+
+    int ret;
+    ID3D12Resource *texture;
+    AVD3D12VASyncContext *sync_ctx;
+
+    D3D12_RESOURCE_DESC desc = {
+        .Dimension        = D3D12_RESOURCE_DIMENSION_TEXTURE2D,
+        .Alignment        = 0,
+        .Width            = ctx->width,
+        .Height           = ctx->height,
+        .DepthOrArraySize = 1,
+        .MipLevels        = 1,
+        .Format           = s->format,
+        .SampleDesc       = {.Count = 1, .Quality = 0 },
+        .Layout           = D3D12_TEXTURE_LAYOUT_UNKNOWN,
+        .Flags            = D3D12_RESOURCE_FLAG_NONE,
+    };
+
+    ret = create_resource(device_hwctx->device, &desc, D3D12_RESOURCE_STATE_COMMON, &texture, 0);
+    if (ret < 0)
+        return NULL;
+
+    ret = av_d3d12va_create_sync_context(device_hwctx, &sync_ctx);
+    if (ret < 0) {
+        D3D12_OBJECT_RELEASE(texture)
+            return NULL;
+    }
+
+    return wrap_texture_buf(ctx, texture, sync_ctx);
+}
+
+static int d3d12va_create_staging_buffer_resource(AVHWFramesContext *ctx, DXGI_FORMAT format)
+{
+    AVD3D12VADeviceContext *device_hwctx = ctx->device_ctx->hwctx;
+    D3D12VAFramesContext   *s            = ctx->internal->priv;
+
+    D3D12_RESOURCE_DESC desc = {
+        .Dimension          = D3D12_RESOURCE_DIMENSION_BUFFER,
+        .Alignment          = 0,
+        .Width              = 0,
+        .Height             = 1,
+        .DepthOrArraySize   = 1,
+        .MipLevels          = 1,
+	    .Format             = DXGI_FORMAT_UNKNOWN,
+	    .SampleDesc         = { .Count = 1, .Quality = 0 },
+        .Layout             = D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+        .Flags              = D3D12_RESOURCE_FLAG_NONE,
+    };
+
+    s->luma_component_size = FFALIGN(ctx->width, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT) * ctx->height * (format == DXGI_FORMAT_P010 ? 2 : 1);
+    desc.Width = s->luma_component_size + (s->luma_component_size >> 1);
+
+    return create_resource(device_hwctx->device, &desc, D3D12_RESOURCE_STATE_COPY_DEST, &s->staging_buffer, 1);
+}
+
+static int d3d12va_frames_init(AVHWFramesContext *ctx)
+{
+    AVD3D12VAFramesContext *hwctx        = ctx->hwctx;
+    AVD3D12VADeviceContext *device_hwctx = ctx->device_ctx->hwctx;
+    D3D12VAFramesContext   *s            = ctx->internal->priv;
+
+    int i;
+
+    if (ctx->initial_pool_size > D3D12VA_MAX_SURFACES) {
+        av_log(ctx, AV_LOG_WARNING, "Too big initial pool size(%d) for surfaces. "
+            "The size will be limited to %d automatically\n", ctx->initial_pool_size, D3D12VA_MAX_SURFACES);
+        ctx->initial_pool_size = D3D12VA_MAX_SURFACES;
+    }
+
+    for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++) {
+        if (ctx->sw_format == supported_formats[i].pix_fmt) {
+            s->format = supported_formats[i].d3d_format;
+            break;
+        }
+    }
+    if (i == FF_ARRAY_ELEMS(supported_formats)) {
+        av_log(ctx, AV_LOG_ERROR, "Unsupported pixel format: %s\n",
+               av_get_pix_fmt_name(ctx->sw_format));
+        return AVERROR(EINVAL);
+    }
+
+    hwctx->texture_infos = av_realloc_f(NULL, ctx->initial_pool_size, sizeof(*hwctx->texture_infos));
+    if (!hwctx->texture_infos)
+        return AVERROR(ENOMEM);
+
+    memset(hwctx->texture_infos, 0, ctx->initial_pool_size * sizeof(*hwctx->texture_infos));
+    s->nb_surfaces = ctx->initial_pool_size;
+
+    ctx->internal->pool_internal = av_buffer_pool_init2(sizeof(AVD3D12FrameDescriptor),
+        ctx, d3d12va_pool_alloc, NULL);
+
+    if (!ctx->internal->pool_internal)
+        return AVERROR(ENOMEM);
+
+    return 0;
+}
+
+static int d3d12va_get_buffer(AVHWFramesContext *ctx, AVFrame *frame)
+{
+    int ret;
+    AVD3D12FrameDescriptor *desc;
+
+    frame->buf[0] = av_buffer_pool_get(ctx->pool);
+    if (!frame->buf[0])
+        return AVERROR(ENOMEM);
+
+    ret = av_image_fill_arrays(frame->data, frame->linesize, frame->buf[0]->data,
+        ctx->sw_format, ctx->width, ctx->height, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
+    if (ret < 0)
+        return ret;
+
+    desc = (AVD3D12FrameDescriptor *)frame->buf[0]->data;
+    frame->data[0] = (uint8_t *)desc->texture;
+    frame->data[1] = (uint8_t *)desc->index;
+    frame->data[2] = (uint8_t *)desc->sync_ctx;
+
+    frame->format  = AV_PIX_FMT_D3D12;
+    frame->width   = ctx->width;
+    frame->height  = ctx->height;
+
+    return 0;
+}
+
+static int d3d12va_transfer_get_formats(AVHWFramesContext *ctx,
+                                        enum AVHWFrameTransferDirection dir,
+                                        enum AVPixelFormat **formats)
+{
+    D3D12VAFramesContext *s = ctx->internal->priv;
+    enum AVPixelFormat *fmts;
+
+    fmts = av_malloc_array(2, sizeof(*fmts));
+    if (!fmts)
+        return AVERROR(ENOMEM);
+
+    fmts[0] = ctx->sw_format;
+    fmts[1] = AV_PIX_FMT_NONE;
+
+    *formats = fmts;
+
+    return 0;
+}
+
+static int d3d12va_transfer_data(AVHWFramesContext *ctx, AVFrame *dst,
+                                 const AVFrame *src)
+{
+    AVD3D12VADeviceContext *hwctx        = ctx->device_ctx->hwctx;
+    AVD3D12VAFramesContext *frames_hwctx = ctx->hwctx;
+    D3D12VAFramesContext   *s            = ctx->internal->priv;
+
+    int ret;
+    int download = src->format == AV_PIX_FMT_D3D12;
+    const AVFrame *frame = download ? src : dst;
+    const AVFrame *other = download ? dst : src;
+    DXGI_FORMAT format = av_d3d12va_map_sw_to_hw_format(ctx->sw_format);
+
+    ID3D12Resource       *texture  = (ID3D12Resource *)      frame->data[0];
+    int                   index    = (intptr_t)              frame->data[1];
+    AVD3D12VASyncContext *sync_ctx = (AVD3D12VASyncContext *)frame->data[2];
+
+    uint8_t *mapped_data;
+    uint8_t *data[4];
+    int linesizes[4];
+
+    D3D12_TEXTURE_COPY_LOCATION staging_y_location;
+    D3D12_TEXTURE_COPY_LOCATION staging_uv_location;
+
+    D3D12_TEXTURE_COPY_LOCATION texture_y_location = {
+        .pResource        = texture,
+        .Type             = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
+        .SubresourceIndex = 0,
+    };
+
+    D3D12_TEXTURE_COPY_LOCATION texture_uv_location = {
+        .pResource        = texture,
+        .Type             = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
+        .SubresourceIndex = 1,
+    };
+
+    D3D12_RESOURCE_BARRIER barrier = {
+        .Type  = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
+        .Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE,
+        .Transition = {
+            .pResource   = texture,
+            .StateBefore = D3D12_RESOURCE_STATE_COMMON,
+            .StateAfter  = D3D12_RESOURCE_STATE_COPY_SOURCE,
+            .Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
+        }
+    };
+
+    if (frame->hw_frames_ctx->data != (uint8_t *)ctx || other->format != ctx->sw_format)
+        return AVERROR(EINVAL);
+
+    if (!s->staging_buffer) {
+        ret = d3d12va_create_staging_buffer_resource(ctx, format);
+        if (ret < 0)
+            return ret;
+    }
+
+    if (!hwctx->command_queue) {
+        ret = d3d12va_create_helper_objects(ctx);
+        if (ret < 0)
+            return ret;
+    }
+
+    for (int i = 0; i < 4; i++)
+        linesizes[i] = FFALIGN(frame->width * (format == DXGI_FORMAT_P010 ? 2 : 1), D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
+
+    staging_y_location = (D3D12_TEXTURE_COPY_LOCATION) {
+        .pResource = s->staging_buffer,
+        .Type      = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
+        .PlacedFootprint = {
+            .Offset = 0,
+            .Footprint = {
+                .Format   = format == DXGI_FORMAT_P010 ? DXGI_FORMAT_R16_UNORM : DXGI_FORMAT_R8_UNORM,
+                .Width    = ctx->width,
+                .Height   = ctx->height,
+                .Depth    = 1,
+                .RowPitch = linesizes[0],
+            },
+        },
+    };
+
+    staging_uv_location = (D3D12_TEXTURE_COPY_LOCATION) {
+        .pResource = s->staging_buffer,
+        .Type      = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
+        .PlacedFootprint = {
+            .Offset = s->luma_component_size,
+            .Footprint = {
+                .Format   = format == DXGI_FORMAT_P010 ? DXGI_FORMAT_R16G16_UNORM : DXGI_FORMAT_R8G8_UNORM,
+                .Width    = ctx->width  >> 1,
+                .Height   = ctx->height >> 1,
+                .Depth    = 1,
+                .RowPitch = linesizes[0],
+            },
+        },
+    };
+
+    DX_CHECK(ID3D12CommandAllocator_Reset(hwctx->command_allocator));
+
+    DX_CHECK(ID3D12GraphicsCommandList_Reset(hwctx->command_list, hwctx->command_allocator, NULL));
+
+    if (download) {
+        ID3D12GraphicsCommandList_ResourceBarrier(hwctx->command_list, 1, &barrier);
+
+        ID3D12GraphicsCommandList_CopyTextureRegion(hwctx->command_list,
+            &staging_y_location, 0, 0, 0, &texture_y_location, NULL);
+
+        ID3D12GraphicsCommandList_CopyTextureRegion(hwctx->command_list,
+            &staging_uv_location, 0, 0, 0, &texture_uv_location, NULL);
+
+        barrier.Transition.StateBefore = barrier.Transition.StateAfter;
+        barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON;
+        ID3D12GraphicsCommandList_ResourceBarrier(hwctx->command_list, 1, &barrier);
+
+        DX_CHECK(ID3D12GraphicsCommandList_Close(hwctx->command_list));
+
+        ret = av_d3d12va_wait_idle(sync_ctx);
+        if (ret)
+            return ret;
+
+        ID3D12CommandQueue_ExecuteCommandLists(hwctx->command_queue, 1, (ID3D12CommandList **)&hwctx->command_list);
+
+        ret = av_d3d12va_wait_queue_idle(hwctx->sync_ctx, hwctx->command_queue);;
+        if (ret)
+            return ret;
+
+        DX_CHECK(ID3D12Resource_Map(s->staging_buffer, 0, NULL, &mapped_data));
+        av_image_fill_pointers(data, ctx->sw_format, ctx->height, mapped_data, linesizes);
+
+        av_image_copy(dst->data, dst->linesize, data, linesizes,
+            ctx->sw_format, ctx->width, ctx->height);
+
+        ID3D12Resource_Unmap(s->staging_buffer, 0, NULL);
+    } else {
+        av_log(ctx, AV_LOG_ERROR, "Transfer data to AV_PIX_FMT_D3D12 is not supported yet!\n");
+        return AVERROR(EINVAL);
+    }
+
+    return 0;
+
+fail:
+    return AVERROR(EINVAL);
+}
+
+static int d3d12va_device_init(AVHWDeviceContext *hwdev)
+{
+    AVD3D12VADeviceContext *ctx = hwdev->hwctx;
+
+    if (!ctx->video_device)
+        DX_CHECK(ID3D12Device_QueryInterface(ctx->device, &IID_ID3D12VideoDevice, (void **)&ctx->video_device));
+
+    return av_d3d12va_create_sync_context(ctx, &ctx->sync_ctx);
+
+fail:
+    return AVERROR(EINVAL);
+}
+
+static void d3d12va_device_uninit(AVHWDeviceContext *hwdev)
+{
+    AVD3D12VADeviceContext *device_hwctx = hwdev->hwctx;
+
+    av_d3d12va_release_sync_context(device_hwctx->sync_ctx);
+
+    D3D12_OBJECT_RELEASE(device_hwctx->command_allocator);
+    D3D12_OBJECT_RELEASE(device_hwctx->command_list);
+    D3D12_OBJECT_RELEASE(device_hwctx->command_queue);
+    D3D12_OBJECT_RELEASE(device_hwctx->video_device);
+    D3D12_OBJECT_RELEASE(device_hwctx->device);
+}
+
+static int d3d12va_device_create(AVHWDeviceContext *ctx, const char *device,
+                                 AVDictionary *opts, int flags)
+{
+    AVD3D12VADeviceContext *device_hwctx = ctx->hwctx;
+
+    HRESULT hr;
+    UINT create_flags = 0;
+    IDXGIAdapter *pAdapter = NULL;
+
+    int ret;
+    int is_debug       = !!av_dict_get(opts, "debug", NULL, 0);
+    device_hwctx->sync = !!av_dict_get(opts, "sync",  NULL, 0);
+
+    if ((ret = ff_thread_once(&functions_loaded, load_functions)) != 0)
+        return AVERROR_UNKNOWN;
+
+    if (is_debug) {
+        ID3D12Debug *pDebug;
+        if (d3d12va_get_debug_interface && SUCCEEDED(d3d12va_get_debug_interface(&IID_ID3D12Debug, &pDebug))) {
+            create_flags |= DXGI_CREATE_FACTORY_DEBUG;
+            ID3D12Debug_EnableDebugLayer(pDebug);
+            D3D12_OBJECT_RELEASE(pDebug);
+            av_log(ctx, AV_LOG_INFO, "D3D12 debug layer is enabled!\n");
+        }
+    }
+
+    if (!device_hwctx->device) {
+        IDXGIFactory2 *pDXGIFactory = NULL;
+
+        if (!d3d12va_create_device || !d3d12va_create_dxgi_factory2) {
+            av_log(ctx, AV_LOG_ERROR, "Failed to load D3D12 library or its functions\n");
+            return AVERROR_UNKNOWN;
+        }
+
+        hr = d3d12va_create_dxgi_factory2(create_flags, &IID_IDXGIFactory2, (void **)&pDXGIFactory);
+        if (SUCCEEDED(hr)) {
+            int adapter = device ? atoi(device) : 0;
+            if (FAILED(IDXGIFactory2_EnumAdapters(pDXGIFactory, adapter, &pAdapter)))
+                pAdapter = NULL;
+            IDXGIFactory2_Release(pDXGIFactory);
+        }
+
+        if (pAdapter) {
+            DXGI_ADAPTER_DESC desc;
+            hr = IDXGIAdapter2_GetDesc(pAdapter, &desc);
+            if (!FAILED(hr)) {
+                av_log(ctx, AV_LOG_INFO, "Using device %04x:%04x (%ls).\n",
+                       desc.VendorId, desc.DeviceId, desc.Description);
+            }
+        }
+
+        hr = d3d12va_create_device((IUnknown *)pAdapter, D3D_FEATURE_LEVEL_12_0, &IID_ID3D12Device, &device_hwctx->device);
+        D3D12_OBJECT_RELEASE(pAdapter);
+        if (FAILED(hr)) {
+            av_log(ctx, AV_LOG_ERROR, "Failed to create DirectX3D 12 device (%lx)\n", (long)hr);
+            return AVERROR_UNKNOWN;
+        }
+    }
+
+    return 0;
+}
+
+const HWContextType ff_hwcontext_type_d3d12va = {
+    .type                   = AV_HWDEVICE_TYPE_D3D12VA,
+    .name                   = "D3D12VA",
+
+    .device_hwctx_size      = sizeof(AVD3D12VADeviceContext),
+    .frames_hwctx_size      = sizeof(AVD3D12VAFramesContext),
+    .frames_priv_size       = sizeof(D3D12VAFramesContext),
+
+    .device_create          = d3d12va_device_create,
+    .device_init            = d3d12va_device_init,
+    .device_uninit          = d3d12va_device_uninit,
+    .frames_get_constraints = d3d12va_frames_get_constraints,
+    .frames_init            = d3d12va_frames_init,
+    .frames_uninit          = d3d12va_frames_uninit,
+    .frames_get_buffer      = d3d12va_get_buffer,
+    .transfer_get_formats   = d3d12va_transfer_get_formats,
+    .transfer_data_to       = d3d12va_transfer_data,
+    .transfer_data_from     = d3d12va_transfer_data,
+
+    .pix_fmts               = (const enum AVPixelFormat[]){ AV_PIX_FMT_D3D12, AV_PIX_FMT_NONE },
+};
diff --git a/libavutil/hwcontext_d3d12va.h b/libavutil/hwcontext_d3d12va.h
new file mode 100644
index 0000000000..d699f9f4c7
--- /dev/null
+++ b/libavutil/hwcontext_d3d12va.h
@@ -0,0 +1,234 @@
+/*
+ * Direct3D 12 HW acceleration.
+ *
+ * copyright (c) 2022 Wu Jianhua <toqsxw@outlook.com>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_HWCONTEXT_D3D12VA_H
+#define AVUTIL_HWCONTEXT_D3D12VA_H
+
+/**
+ * @def COBJMACROS
+ *
+ * @brief Enable C style interface for D3D12
+ */
+#define COBJMACROS
+
+/**
+ * @file
+ * An API-specific header for AV_HWDEVICE_TYPE_D3D11VA.
+ *
+ */
+#include <stdint.h>
+#include <d3d12.h>
+#include <d3d12video.h>
+#include "compat/w32dlfcn.h"
+
+/**
+ * @def DX_CHECK
+ *
+ * @brief A check macro used by D3D12 functions highly frequently
+ */
+#define DX_CHECK(hr) if (FAILED(hr)) { \
+    av_log(NULL, AV_LOG_ERROR, "D3D12 error occurred! Please enable debug=1 and check the output for more details!\n"); \
+    goto fail; \
+}
+
+/**
+ * @def D3D12_OBJECT_RELEASE
+ *
+ * @brief A release macro used by D3D12 objects highly frequently
+ */
+#define D3D12_OBJECT_RELEASE(pInterface) if (pInterface) { \
+    IUnknown_Release((IUnknown *)pInterface); \
+    pInterface = NULL; \
+}
+
+/**
+ * @def D3D12VA_MAX_SURFACES
+ *
+ * @brief Maximum number surfaces
+ * The reference processing over decoding will be corrupted on some drivers
+ * if the max number of reference frames exceeds this.
+ */
+#define D3D12VA_MAX_SURFACES 32
+
+/**
+ * @brief This struct is used to sync d3d12 execution
+ *
+ */
+typedef struct AVD3D12VASyncContext {
+    ID3D12Fence *fence;
+
+    HANDLE event;
+
+    uint64_t fence_value;
+} AVD3D12VASyncContext;
+
+/**
+ * @brief This struct is allocated as AVHWDeviceContext.hwctx
+ *
+ */
+typedef struct AVD3D12VADeviceContext {
+    /**
+     * Device used for objects creation and access. This can also be
+     * used to set the libavcodec decoding device.
+     *
+     * Can be set by the user. This is the only mandatory field - the other
+     * device context fields are set from this and are available for convenience.
+     *
+     * Deallocating the AVHWDeviceContext will always release this interface,
+     * and it does not matter whether it was user-allocated.
+     */
+    ID3D12Device *device;
+
+    /**
+     * If unset, this will be set from the device field on init.
+     *
+     * Deallocating the AVHWDeviceContext will always release this interface,
+     * and it does not matter whether it was user-allocated.
+     */
+    ID3D12VideoDevice  *video_device;
+
+    /**
+     * D3D12 command queue used for texture transfer
+     */
+    ID3D12CommandQueue *command_queue;
+
+    /**
+     * D3D12 command allocator used for texture transfer
+     */
+    ID3D12CommandAllocator *command_allocator;
+
+    /**
+     * D3D12 command list used for texture transfer
+     */
+    ID3D12GraphicsCommandList *command_list;
+
+    /**
+     * Sync context used for texture transfer
+     */
+    AVD3D12VASyncContext *sync_ctx;
+
+    /**
+     * Specifed by sync=1 when init d3d12va
+     *
+     * Let all commands executed as a sync mode
+     */
+    int sync;
+} AVD3D12VADeviceContext;
+
+/**
+ * @brief D3D12 frame descriptor for pool allocation.
+ *
+ */
+typedef struct AVD3D12FrameDescriptor {
+    /**
+     * The texture in which the frame is located. The reference count is
+     * managed by the AVBufferRef, and destroying the reference will release
+     * the interface.
+     *
+     * Normally stored in AVFrame.data[0].
+     */
+    ID3D12Resource *texture;
+
+    /**
+     * The index into the array texture element representing the frame
+     *
+     * Normally stored in AVFrame.data[1] (cast from intptr_t).
+     */
+    intptr_t index;
+
+    /**
+     * The sync context for the texture
+     *
+     * Use av_d3d12va_wait_idle(sync_ctx) to ensure the decoding or encoding have been finised
+     * @see: https://learn.microsoft.com/en-us/windows/win32/medfound/direct3d-12-video-overview#directx-12-fences
+     *
+     * Normally stored in AVFrame.data[2].
+     */
+    AVD3D12VASyncContext *sync_ctx;
+} AVD3D12FrameDescriptor;
+
+/**
+ * @brief This struct is allocated as AVHWFramesContext.hwctx
+ *
+ */
+typedef struct AVD3D12VAFramesContext {
+    AVD3D12FrameDescriptor *texture_infos;
+} AVD3D12VAFramesContext;
+
+/**
+ * @brief Map sw pixel format to d3d12 format
+ *
+ * @param pix_fmt
+ * @return d3d12 specified format
+ */
+DXGI_FORMAT av_d3d12va_map_sw_to_hw_format(enum AVPixelFormat pix_fmt);
+
+/**
+ * @brief Create a AVD3D12VASyncContext
+ *
+ * @param ctx
+ * @param sync_ctx
+ * @return Error code (ret < 0 if failed)
+ */
+int av_d3d12va_create_sync_context(AVD3D12VADeviceContext *ctx, AVD3D12VASyncContext **sync_ctx);
+
+/**
+ * @brief Release a AVD3D12VASyncContext
+ *
+ * @param sync_ctx
+ * @return Error code (ret < 0 if failed), can be ignored
+ */
+int av_d3d12va_release_sync_context(AVD3D12VASyncContext *sync_ctx);
+
+/**
+ * @brief Wait for a specified fence value
+ *
+ * The execution fence values timeline may be like:
+ * #0 -> #1 -> #2 -> #3 ----------------> #n
+ *             ^
+ *             |
+ * Call av_d3d12va_wait_for_fence_value(2) will wait #2 execution to completed.
+ *
+ * @param sync_ctx
+ * @param fence_value
+ * @return Error code (ret < 0 if failed)
+ */
+int av_d3d12va_wait_for_fence_value(AVD3D12VASyncContext *sync_ctx, uint64_t fence_value);
+
+/**
+ * @brief Wait for the sync context to the idle state
+ *
+ * @param sync_ctx
+ * @return Error code (ret < 0 if failed)
+ */
+int av_d3d12va_wait_idle(AVD3D12VASyncContext *sync_ctx);
+
+/**
+ * @brief Wait for a specified command queue to the idle state
+ *
+ * @param sync_ctx
+ * @param command_queue
+ * @return Error code (ret < 0 if failed)
+ */
+int av_d3d12va_wait_queue_idle(AVD3D12VASyncContext *sync_ctx, ID3D12CommandQueue *command_queue);
+
+#endif /* AVUTIL_HWCONTEXT_D3D12VA_H */
diff --git a/libavutil/hwcontext_internal.h b/libavutil/hwcontext_internal.h
index e6266494ac..4df516ee6a 100644
--- a/libavutil/hwcontext_internal.h
+++ b/libavutil/hwcontext_internal.h
@@ -165,6 +165,7 @@ int ff_hwframe_map_replace(AVFrame *dst, const AVFrame *src);
 
 extern const HWContextType ff_hwcontext_type_cuda;
 extern const HWContextType ff_hwcontext_type_d3d11va;
+extern const HWContextType ff_hwcontext_type_d3d12va;
 extern const HWContextType ff_hwcontext_type_drm;
 extern const HWContextType ff_hwcontext_type_dxva2;
 extern const HWContextType ff_hwcontext_type_opencl;
diff --git a/libavutil/pixdesc.c b/libavutil/pixdesc.c
index ca3e204a0b..800913063c 100644
--- a/libavutil/pixdesc.c
+++ b/libavutil/pixdesc.c
@@ -2253,6 +2253,10 @@ static const AVPixFmtDescriptor av_pix_fmt_descriptors[AV_PIX_FMT_NB] = {
         .name = "d3d11",
         .flags = AV_PIX_FMT_FLAG_HWACCEL,
     },
+    [AV_PIX_FMT_D3D12] = {
+        .name = "d3d12",
+        .flags = AV_PIX_FMT_FLAG_HWACCEL,
+    },
     [AV_PIX_FMT_GBRPF32BE] = {
         .name = "gbrpf32be",
         .nb_components = 3,
diff --git a/libavutil/pixfmt.h b/libavutil/pixfmt.h
index 224670a731..e02620b1c7 100644
--- a/libavutil/pixfmt.h
+++ b/libavutil/pixfmt.h
@@ -304,6 +304,15 @@ enum AVPixelFormat {
      */
     AV_PIX_FMT_D3D11,
 
+    /**
+     * Hardware surfaces for Direct3D12.
+     *
+     * data[0] contains a ID3D12Resource pointer.
+     * data[1] contains the resource array index of the frame as intptr_t.
+     * data[2] contains the sync context for current resource
+     */
+    AV_PIX_FMT_D3D12,
+
     AV_PIX_FMT_GRAY9BE,   ///<        Y        , 9bpp, big-endian
     AV_PIX_FMT_GRAY9LE,   ///<        Y        , 9bpp, little-endian
 
diff --git a/libavutil/tests/hwdevice.c b/libavutil/tests/hwdevice.c
index 7eb355c988..0322bd9fcb 100644
--- a/libavutil/tests/hwdevice.c
+++ b/libavutil/tests/hwdevice.c
@@ -137,6 +137,8 @@ static const struct {
       { "0", "1", "2" } },
     { AV_HWDEVICE_TYPE_D3D11VA,
       { "0", "1", "2" } },
+    { AV_HWDEVICE_TYPE_D3D12VA,
+      { "0", "1", "2" } },
     { AV_HWDEVICE_TYPE_OPENCL,
       { "0.0", "0.1", "1.0", "1.1" } },
     { AV_HWDEVICE_TYPE_VAAPI,
diff --git a/libavutil/version.h b/libavutil/version.h
index cb0c928bd0..2df788e529 100644
--- a/libavutil/version.h
+++ b/libavutil/version.h
@@ -79,8 +79,8 @@
  */
 
 #define LIBAVUTIL_VERSION_MAJOR  57
-#define LIBAVUTIL_VERSION_MINOR  39
-#define LIBAVUTIL_VERSION_MICRO 101
+#define LIBAVUTIL_VERSION_MINOR  40
+#define LIBAVUTIL_VERSION_MICRO 100
 
 #define LIBAVUTIL_VERSION_INT   AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \
                                                LIBAVUTIL_VERSION_MINOR, \
-- 
2.32.0

