From 11e879389d85aab3cf51f10c4fe8eb4dfae5ef52 Mon Sep 17 00:00:00 2001
From: Wu Jianhua <toqsxw@outlook.com>
Date: Sat, 17 Dec 2022 02:30:29 +0800
Subject: [PATCH 5/6] avcodec: add D3D12VA hardware accelerated AV1 decoding

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

Signed-off-by: Wu Jianhua <toqsxw@outlook.com>
---
 configure                 |   2 +
 libavcodec/Makefile       |   1 +
 libavcodec/av1dec.c       |  10 +
 libavcodec/d3d12dec_av1.c | 442 ++++++++++++++++++++++++++++++++++++++
 libavcodec/hwaccels.h     |   1 +
 5 files changed, 456 insertions(+)
 create mode 100644 libavcodec/d3d12dec_av1.c

diff --git a/configure b/configure
index 569fcc0ab4..8c5c531760 100755
--- a/configure
+++ b/configure
@@ -3010,6 +3010,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"
diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index 188b61a9ad..37d9cc8ca8 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -970,6 +970,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
diff --git a/libavcodec/av1dec.c b/libavcodec/av1dec.c
index d83c902f1f..88aa1aad60 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_av1.c b/libavcodec/d3d12dec_av1.c
new file mode 100644
index 0000000000..cba7aa7c81
--- /dev/null
+++ b/libavcodec/d3d12dec_av1.c
@@ -0,0 +1,442 @@
+/*
+ * 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 256
+
+typedef struct D3D12AV1DecodeContext {
+    D3D12VADecodeContext ctx;
+    uint8_t *bitstream_buffer;
+} D3D12AV1DecodeContext;
+
+#define D3D12_AV1_DECODE_CONTEXT(avctx) ((D3D12AV1DecodeContext *)D3D12VA_DECODE_CONTEXT(avctx))
+
+typedef struct AV1DecodePictureContext {
+    DXVA_PicParams_AV1  pp;
+    unsigned            tile_count;
+    DXVA_Tile_AV1       tiles[MAX_TILES];
+    uint8_t            *bitstream;
+    unsigned            bitstream_size;
+} AV1DecodePictureContext;
+
+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;
+    AV1DecodePictureContext *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;
+    AV1DecodePictureContext *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;
+    AV1DecodePictureContext *ctx_pic      = h->cur_frame.hwaccel_picture_private;
+
+    int index;
+    uint8_t *mapped_data;
+
+    D3D12_VIDEO_DECODE_FRAME_ARGUMENT *args = &input_args->FrameArguments[input_args->NumFrameArguments++];
+    args->Type  = D3D12_VIDEO_DECODE_ARGUMENT_TYPE_SLICE_CONTROL;
+    args->Size  = sizeof(DXVA_Tile_AV1) * ctx_pic->tile_count;
+    args->pData = ctx_pic->tiles;
+
+    input_args->CompressedBitstream = (D3D12_VIDEO_DECODE_COMPRESSED_BITSTREAM){
+        .pBuffer = buffer,
+        .Offset  = 0,
+        .Size    = ctx_pic->bitstream_size,
+    };
+
+    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);
+
+    index = ctx_pic->pp.CurrPicTextureIndex;
+    ctx->ref_resources[index] = frames_hwctx->texture_infos[index].texture;
+
+    for (int 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);
+    AV1DecodePictureContext *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);
+    AV1DecodePictureContext *ctx_pic = h->cur_frame.hwaccel_picture_private;
+
+    int ret;
+
+    if (avctx->profile != FF_PROFILE_AV1_MAIN)
+        return AVERROR(EINVAL);
+
+    ctx->cfg.DecodeProfile = D3D12_VIDEO_DECODE_PROFILE_AV1_PROFILE0;
+
+    ret = ff_d3d12dec_decode_init(avctx);
+    if (ret < 0)
+        return ret;
+
+    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 0;
+}
+
+static int d3d12dec_av1_decode_uninit(AVCodecContext *avctx)
+{
+    const AV1DecContext     *h       = avctx->priv_data;
+    D3D12AV1DecodeContext   *ctx     = D3D12_AV1_DECODE_CONTEXT(avctx);
+    AV1DecodePictureContext *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(AV1DecodePictureContext),
+    .priv_data_size       = sizeof(D3D12AV1DecodeContext),
+};
+#endif
diff --git a/libavcodec/hwaccels.h b/libavcodec/hwaccels.h
index a36d138538..ea6224ccf9 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;
-- 
2.32.0

