Browse code

H264 DXVA2 implementation

It allows VLD H264 decoding using DXVA2 (GPU assisted decoding API under
VISTA and Windows 7).
It is implemented by using AVHWAccel API. It has been tested successfully
for some time in VLC using an nvidia card on Windows 7.

To compile it, you need to have the system header dxva2api.h (either from
microsoft or using http://downloads.videolan.org/pub/videolan/testing/contrib/dxva2api.h)
The generated libavcodec.dll does not depend directly on any new lib as
the necessary objects are given by the application using FFmpeg.

Originally committed as revision 21353 to svn://svn.ffmpeg.org/ffmpeg/trunk

Laurent Aimar authored on 2010/01/21 03:54:51
Showing 8 changed files
... ...
@@ -107,6 +107,7 @@ Configuration options:
107 107
   --disable-rdft           disable RDFT code
108 108
   --disable-vaapi          disable VAAPI code
109 109
   --disable-vdpau          disable VDPAU code
110
+  --disable-dxva2          disable DXVA2 code
110 111
   --enable-runtime-cpudetect detect cpu capabilities at runtime (bigger binary)
111 112
   --enable-hardcoded-tables use hardcoded tables instead of runtime generation
112 113
   --enable-memalign-hack   emulate memalign, interferes with memory debuggers
... ...
@@ -865,6 +866,7 @@ CONFIG_LIST="
865 865
     bzlib
866 866
     dct
867 867
     doc
868
+    dxva2
868 869
     fastdiv
869 870
     ffmpeg
870 871
     ffplay
... ...
@@ -1174,6 +1176,8 @@ h263_vaapi_hwaccel_select="vaapi h263_decoder"
1174 1174
 h263i_decoder_select="h263_decoder"
1175 1175
 h263p_encoder_select="h263_encoder"
1176 1176
 h264_decoder_select="golomb"
1177
+h264_dxva2_hwaccel_deps="dxva2api_h"
1178
+h264_dxva2_hwaccel_select="dxva2 h264_decoder"
1177 1179
 h264_vaapi_hwaccel_deps="va_va_h"
1178 1180
 h264_vaapi_hwaccel_select="vaapi"
1179 1181
 h264_vdpau_decoder_deps="vdpau_vdpau_h vdpau_vdpau_x11_h"
... ...
@@ -2399,6 +2403,7 @@ check_func_headers windows.h VirtualAlloc
2399 2399
 
2400 2400
 check_header conio.h
2401 2401
 check_header dlfcn.h
2402
+check_header dxva2api.h
2402 2403
 check_header malloc.h
2403 2404
 check_header poll.h
2404 2405
 check_header sys/mman.h
... ...
@@ -3,7 +3,7 @@ include $(SUBDIR)../config.mak
3 3
 NAME = avcodec
4 4
 FFLIBS = avutil
5 5
 
6
-HEADERS = avcodec.h opt.h vaapi.h vdpau.h xvmc.h
6
+HEADERS = avcodec.h dxva2.h opt.h vaapi.h vdpau.h xvmc.h
7 7
 
8 8
 OBJS = allcodecs.o                                                      \
9 9
        audioconvert.o                                                   \
... ...
@@ -135,6 +135,7 @@ OBJS-$(CONFIG_H263_ENCODER)            += mpegvideo_enc.o mpeg4video.o mpeg4vide
135 135
 OBJS-$(CONFIG_H264_DECODER)            += h264.o h264idct.o h264pred.o h264_loopfilter.o h264_direct.o cabac.o \
136 136
                                           h264_sei.o h264_ps.o h264_refs.o h264_cavlc.o h264_cabac.o\
137 137
                                           mpegvideo.o error_resilience.o
138
+OBJS-$(CONFIG_H264_DXVA2_HWACCEL)      += dxva2_h264.o
138 139
 OBJS-$(CONFIG_H264_ENCODER)            += h264enc.o h264dspenc.o
139 140
 OBJS-$(CONFIG_H264_VAAPI_HWACCEL)      += vaapi_h264.o
140 141
 OBJS-$(CONFIG_HUFFYUV_DECODER)         += huffyuv.o
... ...
@@ -55,6 +55,7 @@ void avcodec_register_all(void)
55 55
 
56 56
     /* hardware accelerators */
57 57
     REGISTER_HWACCEL (H263_VAAPI, h263_vaapi);
58
+    REGISTER_HWACCEL (H264_DXVA2, h264_dxva2);
58 59
     REGISTER_HWACCEL (H264_VAAPI, h264_vaapi);
59 60
     REGISTER_HWACCEL (MPEG2_VAAPI, mpeg2_vaapi);
60 61
     REGISTER_HWACCEL (MPEG4_VAAPI, mpeg4_vaapi);
61 62
new file mode 100644
... ...
@@ -0,0 +1,68 @@
0
+/*
1
+ * DXVA2 HW acceleration
2
+ *
3
+ * copyright (c) 2009 Laurent Aimar
4
+ *
5
+ * This file is part of FFmpeg.
6
+ *
7
+ * FFmpeg is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * FFmpeg is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with FFmpeg; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ */
21
+
22
+#ifndef AVCODEC_DXVA_H
23
+#define AVCODEC_DXVA_H
24
+
25
+#include <stdint.h>
26
+
27
+#include <dxva2api.h>
28
+
29
+/**
30
+ * This structure is used to provides the necessary configurations and data
31
+ * to the DXVA2 FFmpeg HWAccel implementation.
32
+ *
33
+ * The application must make it available as AVCodecContext.hwaccel_context.
34
+ */
35
+struct dxva_context {
36
+    /**
37
+     * DXVA2 decoder object
38
+     */
39
+    IDirectXVideoDecoder *decoder;
40
+
41
+    /**
42
+     * DXVA2 configuration used to create the decoder
43
+     */
44
+    const DXVA2_ConfigPictureDecode *cfg;
45
+
46
+    /**
47
+     * The number of surface in the surface array
48
+     */
49
+    unsigned surface_count;
50
+
51
+    /**
52
+     * The array of Direct3D surfaces used to create the decoder
53
+     */
54
+    LPDIRECT3DSURFACE9 *surface;
55
+
56
+    /**
57
+     * A bit field configuring the workarounds needed for using the decoder
58
+     */
59
+    uint64_t workaround;
60
+
61
+    /**
62
+     * Private to the FFmpeg AVHWAccel implementation
63
+     */
64
+    unsigned report_id;
65
+};
66
+
67
+#endif /* AVCODEC_DXVA_H */
0 68
new file mode 100644
... ...
@@ -0,0 +1,553 @@
0
+/*
1
+ * DXVA2 H264 HW acceleration.
2
+ *
3
+ * copyright (c) 2009 Laurent Aimar
4
+ *
5
+ * This file is part of FFmpeg.
6
+ *
7
+ * FFmpeg is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * FFmpeg is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with FFmpeg; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ */
21
+
22
+#include "dxva2.h"
23
+#include "avcodec.h"
24
+
25
+#include "mpegvideo.h"
26
+#include "h264.h"
27
+#include "h264data.h"
28
+
29
+struct dxva2_picture_context {
30
+    DXVA_PicParams_H264   pp;
31
+    DXVA_Qmatrix_H264     qm;
32
+    unsigned              slice_count;
33
+    DXVA_Slice_H264_Short slice_short[MAX_SLICES];
34
+    DXVA_Slice_H264_Long  slice_long[MAX_SLICES];
35
+    const uint8_t         *bitstream;
36
+    unsigned              bitstream_size;
37
+};
38
+
39
+static void *get_surface(const Picture *picture)
40
+{
41
+    return picture->data[3];
42
+}
43
+static unsigned get_surface_index(const struct dxva_context *ctx,
44
+                                  const Picture *picture)
45
+{
46
+    void *surface = get_surface(picture);
47
+    unsigned i;
48
+
49
+    for (i = 0; i < ctx->surface_count; i++)
50
+        if (ctx->surface[i] == surface)
51
+            return i;
52
+
53
+    assert(0);
54
+    return 0;
55
+}
56
+
57
+static void fill_picture_entry(DXVA_PicEntry_H264 *pic,
58
+                               unsigned index, unsigned flag)
59
+{
60
+    assert((index&0x7f) == index && (flag&0x01) == flag);
61
+    pic->bPicEntry = index | (flag << 7);
62
+}
63
+
64
+static void fill_picture_parameters(struct dxva_context *ctx, const H264Context *h,
65
+                                    DXVA_PicParams_H264 *pp)
66
+{
67
+    const MpegEncContext *s = &h->s;
68
+    const Picture *current_picture = s->current_picture_ptr;
69
+    int i;
70
+
71
+    memset(pp, 0, sizeof(*pp));
72
+    /* Configure current picture */
73
+    fill_picture_entry(&pp->CurrPic,
74
+                       get_surface_index(ctx, current_picture),
75
+                       s->picture_structure == PICT_BOTTOM_FIELD);
76
+    /* Configure the set of references */
77
+    pp->UsedForReferenceFlags  = 0;
78
+    pp->NonExistingFrameFlags  = 0;
79
+    for (i = 0; i < FF_ARRAY_ELEMS(pp->RefFrameList); i++) {
80
+        if (i < h->short_ref_count + h->long_ref_count) {
81
+            const Picture *r;
82
+            if (i < h->short_ref_count) {
83
+                r = h->short_ref[i];
84
+                assert(!r->long_ref);
85
+            } else {
86
+                r = h->long_ref[i - h->short_ref_count];
87
+                assert(r->long_ref);
88
+            }
89
+            fill_picture_entry(&pp->RefFrameList[i],
90
+                               get_surface_index(ctx, r),
91
+                               r->long_ref != 0);
92
+
93
+            if ((r->reference & PICT_TOP_FIELD) && r->field_poc[0] != INT_MAX)
94
+                pp->FieldOrderCntList[i][0] = r->field_poc[0];
95
+            if ((r->reference & PICT_BOTTOM_FIELD) && r->field_poc[1] != INT_MAX)
96
+                pp->FieldOrderCntList[i][1] = r->field_poc[1];
97
+
98
+            pp->FrameNumList[i] = r->long_ref ? r->pic_id : r->frame_num;
99
+            if (r->reference & PICT_TOP_FIELD)
100
+                pp->UsedForReferenceFlags |= 1 << (2*i + 0);
101
+            if (r->reference & PICT_BOTTOM_FIELD)
102
+                pp->UsedForReferenceFlags |= 1 << (2*i + 1);
103
+        } else {
104
+            pp->RefFrameList[i].bPicEntry = 0xff;
105
+            pp->FieldOrderCntList[i][0]   = 0;
106
+            pp->FieldOrderCntList[i][1]   = 0;
107
+            pp->FrameNumList[i]           = 0;
108
+        }
109
+    }
110
+
111
+    pp->wFrameWidthInMbsMinus1        = s->mb_width  - 1;
112
+    pp->wFrameHeightInMbsMinus1       = s->mb_height - 1;
113
+    pp->num_ref_frames                = h->sps.ref_frame_count;
114
+
115
+    pp->wBitFields                    = ((s->picture_structure != PICT_FRAME) <<  0) |
116
+                                        (h->sps.mb_aff                        <<  1) |
117
+                                        (h->sps.residual_color_transform_flag <<  2) |
118
+                                        /* sp_for_switch_flag (not implemented by FFmpeg) */
119
+                                        (0                                    <<  3) |
120
+                                        (h->sps.chroma_format_idc             <<  4) |
121
+                                        ((h->nal_ref_idc != 0)                <<  6) |
122
+                                        (h->pps.constrained_intra_pred        <<  7) |
123
+                                        (h->pps.weighted_pred                 <<  8) |
124
+                                        (h->pps.weighted_bipred_idc           <<  9) |
125
+                                        /* MbsConsecutiveFlag */
126
+                                        (1                                    << 11) |
127
+                                        (h->sps.frame_mbs_only_flag           << 12) |
128
+                                        (h->pps.transform_8x8_mode            << 13) |
129
+                                        ((h->sps.level_idc >= 31)             << 14) |
130
+                                        /* IntraPicFlag (Modified if we detect a non
131
+                                         * intra slice in decode_slice) */
132
+                                        (1                                    << 15);
133
+
134
+    pp->bit_depth_luma_minus8         = h->sps.bit_depth_luma - 8;
135
+    pp->bit_depth_chroma_minus8       = h->sps.bit_depth_chroma - 8;
136
+    pp->Reserved16Bits                = 3; /* FIXME is there a way to detect the right mode ? */
137
+    pp->StatusReportFeedbackNumber    = 1 + ctx->report_id++;
138
+    pp->CurrFieldOrderCnt[0] = 0;
139
+    if ((s->picture_structure & PICT_TOP_FIELD) &&
140
+        current_picture->field_poc[0] != INT_MAX)
141
+        pp->CurrFieldOrderCnt[0] = current_picture->field_poc[0];
142
+    pp->CurrFieldOrderCnt[1] = 0;
143
+    if ((s->picture_structure & PICT_BOTTOM_FIELD) &&
144
+        current_picture->field_poc[1] != INT_MAX)
145
+        pp->CurrFieldOrderCnt[1] = current_picture->field_poc[1];
146
+    pp->pic_init_qs_minus26           = h->pps.init_qs - 26;
147
+    pp->chroma_qp_index_offset        = h->pps.chroma_qp_index_offset[0];
148
+    pp->second_chroma_qp_index_offset = h->pps.chroma_qp_index_offset[1];
149
+    pp->ContinuationFlag              = 1;
150
+    pp->pic_init_qp_minus26           = h->pps.init_qp - 26;
151
+    pp->num_ref_idx_l0_active_minus1  = h->pps.ref_count[0] - 1;
152
+    pp->num_ref_idx_l1_active_minus1  = h->pps.ref_count[1] - 1;
153
+    pp->Reserved8BitsA                = 0;
154
+    pp->frame_num                     = h->frame_num;
155
+    pp->log2_max_frame_num_minus4     = h->sps.log2_max_frame_num - 4;
156
+    pp->pic_order_cnt_type            = h->sps.poc_type;
157
+    if (h->sps.poc_type == 0)
158
+        pp->log2_max_pic_order_cnt_lsb_minus4 = h->sps.log2_max_poc_lsb - 4;
159
+    else if (h->sps.poc_type == 1)
160
+        pp->delta_pic_order_always_zero_flag = h->sps.delta_pic_order_always_zero_flag;
161
+    pp->direct_8x8_inference_flag     = h->sps.direct_8x8_inference_flag;
162
+    pp->entropy_coding_mode_flag      = h->pps.cabac;
163
+    pp->pic_order_present_flag        = h->pps.pic_order_present;
164
+    pp->num_slice_groups_minus1       = h->pps.slice_group_count - 1;
165
+    pp->slice_group_map_type          = h->pps.mb_slice_group_map_type;
166
+    pp->deblocking_filter_control_present_flag = h->pps.deblocking_filter_parameters_present;
167
+    pp->redundant_pic_cnt_present_flag= h->pps.redundant_pic_cnt_present;
168
+    pp->Reserved8BitsB                = 0;
169
+    pp->slice_group_change_rate_minus1= 0;  /* XXX not implemented by FFmpeg */
170
+    //pp->SliceGroupMap[810];               /* XXX not implemented by FFmpeg */
171
+}
172
+
173
+static void fill_scaling_lists(const H264Context *h, DXVA_Qmatrix_H264 *qm)
174
+{
175
+    unsigned i, j;
176
+    memset(qm, 0, sizeof(*qm));
177
+    for (i = 0; i < 6; i++)
178
+        for (j = 0; j < 16; j++)
179
+            qm->bScalingLists4x4[i][j] = h->pps.scaling_matrix4[i][zigzag_scan[j]];
180
+
181
+    for (i = 0; i < 2; i++)
182
+        for (j = 0; j < 64; j++)
183
+            qm->bScalingLists8x8[i][j] = h->pps.scaling_matrix8[i][ff_zigzag_direct[j]];
184
+}
185
+
186
+static int is_slice_short(struct dxva_context *ctx)
187
+{
188
+    assert(ctx->cfg->ConfigBitstreamRaw == 1 ||
189
+           ctx->cfg->ConfigBitstreamRaw == 2);
190
+    return ctx->cfg->ConfigBitstreamRaw == 2;
191
+}
192
+
193
+static void fill_slice_short(DXVA_Slice_H264_Short *slice,
194
+                             unsigned position, unsigned size)
195
+{
196
+    memset(slice, 0, sizeof(*slice));
197
+    slice->BSNALunitDataLocation = position;
198
+    slice->SliceBytesInBuffer    = size;
199
+    slice->wBadSliceChopping     = 0;
200
+}
201
+
202
+static void fill_slice_long(AVCodecContext *avctx, DXVA_Slice_H264_Long *slice,
203
+                            unsigned position, unsigned size)
204
+{
205
+    H264Context *h = avctx->priv_data; /* FIXME Can't use const because of get_bits_count */
206
+    struct dxva_context *ctx = avctx->hwaccel_context;
207
+    MpegEncContext *s = &h->s;
208
+    unsigned list;
209
+
210
+    memset(slice, 0, sizeof(*slice));
211
+    slice->BSNALunitDataLocation = position;
212
+    slice->SliceBytesInBuffer    = size;
213
+    slice->wBadSliceChopping     = 0;
214
+
215
+    slice->first_mb_in_slice     = (s->mb_y >> FIELD_OR_MBAFF_PICTURE) * s->mb_width + s->mb_x;
216
+    slice->NumMbsForSlice        = 0; /* XXX it is set once we have all slices */
217
+    slice->BitOffsetToSliceData  = get_bits_count(&s->gb) + 8;
218
+    slice->slice_type            = ff_h264_get_slice_type(h);
219
+    if (h->slice_type_fixed)
220
+        slice->slice_type += 5;
221
+    slice->luma_log2_weight_denom       = h->luma_log2_weight_denom;
222
+    slice->chroma_log2_weight_denom     = h->chroma_log2_weight_denom;
223
+    if (h->list_count > 0)
224
+        slice->num_ref_idx_l0_active_minus1 = h->ref_count[0] - 1;
225
+    if (h->list_count > 1)
226
+        slice->num_ref_idx_l1_active_minus1 = h->ref_count[1] - 1;
227
+    slice->slice_alpha_c0_offset_div2   = h->slice_alpha_c0_offset / 2;
228
+    slice->slice_beta_offset_div2       = h->slice_beta_offset / 2;
229
+    slice->Reserved8Bits                = 0;
230
+
231
+    for (list = 0; list < 2; list++) {
232
+        unsigned i;
233
+        for (i = 0; i < FF_ARRAY_ELEMS(slice->RefPicList[list]); i++) {
234
+            if (list < h->list_count && i < h->ref_count[list]) {
235
+                const Picture *r = &h->ref_list[list][i];
236
+                unsigned plane;
237
+                fill_picture_entry(&slice->RefPicList[list][i],
238
+                                   get_surface_index(ctx, r),
239
+                                   r->reference == PICT_BOTTOM_FIELD);
240
+                for (plane = 0; plane < 3; plane++) {
241
+                    int w, o;
242
+                    if (plane == 0 && h->luma_weight_flag[list]) {
243
+                        w = h->luma_weight[list][i];
244
+                        o = h->luma_offset[list][i];
245
+                    } else if (plane >= 1 && h->chroma_weight_flag[list]) {
246
+                        w = h->chroma_weight[list][i][plane-1];
247
+                        o = h->chroma_offset[list][i][plane-1];
248
+                    } else {
249
+                        w = 1 << (plane == 0 ? h->luma_log2_weight_denom :
250
+                                               h->chroma_log2_weight_denom);
251
+                        o = 0;
252
+                    }
253
+                    slice->Weights[list][i][plane][0] = w;
254
+                    slice->Weights[list][i][plane][1] = o;
255
+                }
256
+            } else {
257
+                unsigned plane;
258
+                slice->RefPicList[list][i].bPicEntry = 0xff;
259
+                for (plane = 0; plane < 3; plane++) {
260
+                    slice->Weights[list][i][plane][0] = 0;
261
+                    slice->Weights[list][i][plane][1] = 0;
262
+                }
263
+            }
264
+        }
265
+    }
266
+    slice->slice_qs_delta    = 0; /* XXX not implemented by FFmpeg */
267
+    slice->slice_qp_delta    = s->qscale - h->pps.init_qp;
268
+    slice->redundant_pic_cnt = h->redundant_pic_count;
269
+    if (h->slice_type == FF_B_TYPE)
270
+        slice->direct_spatial_mv_pred_flag = h->direct_spatial_mv_pred;
271
+    slice->cabac_init_idc = h->pps.cabac ? h->cabac_init_idc : 0;
272
+    if (h->deblocking_filter < 2)
273
+        slice->disable_deblocking_filter_idc = 1 - h->deblocking_filter;
274
+    else
275
+        slice->disable_deblocking_filter_idc = h->deblocking_filter;
276
+    slice->slice_id = h->current_slice - 1;
277
+}
278
+
279
+static int commit_buffer(AVCodecContext *avctx,
280
+                         struct dxva_context *ctx,
281
+                         DXVA2_DecodeBufferDesc *dsc,
282
+                         unsigned type, const void *data, unsigned size,
283
+                         unsigned mb_count)
284
+{
285
+    void     *dxva_data;
286
+    unsigned dxva_size;
287
+    int      result;
288
+
289
+    if (FAILED(IDirectXVideoDecoder_GetBuffer(ctx->decoder, type,
290
+                                              &dxva_data, &dxva_size))) {
291
+        av_log(avctx, AV_LOG_ERROR, "Failed to get a buffer for %d\n", type);
292
+        return -1;
293
+    }
294
+    if (size <= dxva_size) {
295
+        memcpy(dxva_data, data, size);
296
+
297
+        memset(dsc, 0, sizeof(*dsc));
298
+        dsc->CompressedBufferType = type;
299
+        dsc->DataSize             = size;
300
+        dsc->NumMBsInBuffer       = mb_count;
301
+
302
+        result = 0;
303
+    } else {
304
+        av_log(avctx, AV_LOG_ERROR, "Buffer for type %d was too small\n", type);
305
+        result = -1;
306
+    }
307
+    if (FAILED(IDirectXVideoDecoder_ReleaseBuffer(ctx->decoder, type))) {
308
+        av_log(avctx, AV_LOG_ERROR, "Failed to release buffer type %d\n", type);
309
+        result = -1;
310
+    }
311
+    return result;
312
+}
313
+
314
+static int commit_bitstream_and_slice_buffer(AVCodecContext *avctx,
315
+                                             struct dxva_context *ctx,
316
+                                             struct dxva2_picture_context *ctx_pic,
317
+                                             DXVA2_DecodeBufferDesc *bs,
318
+                                             DXVA2_DecodeBufferDesc *sc,
319
+                                             unsigned mb_count)
320
+{
321
+    DXVA_Slice_H264_Short *slice = NULL;
322
+    uint8_t  *dxva_data, *current, *end;
323
+    unsigned dxva_size;
324
+    void     *slice_data;
325
+    unsigned slice_size;
326
+    unsigned padding;
327
+    unsigned i;
328
+
329
+    /* Create an annex B bitstream buffer with only slice NAL and finalize slice */
330
+    if (FAILED(IDirectXVideoDecoder_GetBuffer(ctx->decoder,
331
+                                               DXVA2_BitStreamDateBufferType,
332
+                                               &dxva_data, &dxva_size)))
333
+        return -1;
334
+    current = dxva_data;
335
+    end = dxva_data + dxva_size;
336
+
337
+    for (i = 0; i < ctx_pic->slice_count; i++) {
338
+        static const uint8_t start_code[] = { 0, 0, 1 };
339
+        static const unsigned start_code_size = sizeof(start_code);
340
+        unsigned position, size;
341
+
342
+        assert(offsetof(DXVA_Slice_H264_Short, BSNALunitDataLocation) ==
343
+               offsetof(DXVA_Slice_H264_Long,  BSNALunitDataLocation));
344
+        assert(offsetof(DXVA_Slice_H264_Short, SliceBytesInBuffer) ==
345
+               offsetof(DXVA_Slice_H264_Long,  SliceBytesInBuffer));
346
+
347
+        if (is_slice_short(ctx))
348
+            slice = &ctx_pic->slice_short[i];
349
+        else
350
+            slice = (DXVA_Slice_H264_Short*)&ctx_pic->slice_long[i];
351
+
352
+        position = slice->BSNALunitDataLocation;
353
+        size     = slice->SliceBytesInBuffer;
354
+        if (start_code_size + size > end - current) {
355
+            av_log(avctx, AV_LOG_ERROR, "Failed to build bitstream");
356
+            break;
357
+        }
358
+
359
+        slice->BSNALunitDataLocation = current - dxva_data;
360
+        slice->SliceBytesInBuffer    = start_code_size + size;
361
+
362
+        if (!is_slice_short(ctx)) {
363
+            DXVA_Slice_H264_Long *slice_long = (DXVA_Slice_H264_Long*)slice;
364
+            if (i < ctx_pic->slice_count - 1)
365
+                slice_long->NumMbsForSlice =
366
+                    slice_long[1].first_mb_in_slice - slice_long[0].first_mb_in_slice;
367
+            else
368
+                slice_long->NumMbsForSlice = mb_count - slice_long->first_mb_in_slice;
369
+        }
370
+
371
+        memcpy(current, start_code, start_code_size);
372
+        current += start_code_size;
373
+
374
+        memcpy(current, &ctx_pic->bitstream[position], size);
375
+        current += size;
376
+    }
377
+    padding = FFMIN(128 - ((current - dxva_data) & 127), end - current);
378
+    if (slice && padding > 0) {
379
+        memset(current, 0, padding);
380
+        current += padding;
381
+
382
+        slice->SliceBytesInBuffer += padding;
383
+    }
384
+    if (FAILED(IDirectXVideoDecoder_ReleaseBuffer(ctx->decoder,
385
+                                                  DXVA2_BitStreamDateBufferType)))
386
+        return -1;
387
+    if (i < ctx_pic->slice_count)
388
+        return -1;
389
+
390
+    memset(bs, 0, sizeof(*bs));
391
+    bs->CompressedBufferType = DXVA2_BitStreamDateBufferType;
392
+    bs->DataSize             = current - dxva_data;
393
+    bs->NumMBsInBuffer       = mb_count;
394
+
395
+    if (is_slice_short(ctx)) {
396
+        slice_data = ctx_pic->slice_short;
397
+        slice_size = ctx_pic->slice_count * sizeof(*ctx_pic->slice_short);
398
+    } else {
399
+        slice_data = ctx_pic->slice_long;
400
+        slice_size = ctx_pic->slice_count * sizeof(*ctx_pic->slice_long);
401
+    }
402
+    assert((bs->DataSize & 127) == 0);
403
+    return commit_buffer(avctx, ctx, sc,
404
+                         DXVA2_SliceControlBufferType,
405
+                         slice_data, slice_size, mb_count);
406
+}
407
+
408
+
409
+static int start_frame(AVCodecContext *avctx,
410
+                       av_unused const uint8_t *buffer,
411
+                       av_unused uint32_t size)
412
+{
413
+    const H264Context *h = avctx->priv_data;
414
+    struct dxva_context *ctx = avctx->hwaccel_context;
415
+    struct dxva2_picture_context *ctx_pic = h->s.current_picture_ptr->hwaccel_picture_private;
416
+
417
+    if (!ctx->decoder || !ctx->cfg || ctx->surface_count <= 0)
418
+        return -1;
419
+    assert(ctx_pic);
420
+
421
+    /* Fill up DXVA_PicParams_H264 */
422
+    fill_picture_parameters(ctx, h, &ctx_pic->pp);
423
+
424
+    /* Fill up DXVA_Qmatrix_H264 */
425
+    fill_scaling_lists(h, &ctx_pic->qm);
426
+
427
+    ctx_pic->slice_count    = 0;
428
+    ctx_pic->bitstream_size = 0;
429
+    ctx_pic->bitstream      = NULL;
430
+    return 0;
431
+}
432
+
433
+static int decode_slice(AVCodecContext *avctx,
434
+                        const uint8_t *buffer, uint32_t size)
435
+{
436
+    H264Context *h = avctx->priv_data; /* FIXME Can't use const because of get_bits_count */
437
+    struct dxva_context *ctx = avctx->hwaccel_context;
438
+    const Picture *current_picture = h->s.current_picture_ptr;
439
+    struct dxva2_picture_context *ctx_pic = current_picture->hwaccel_picture_private;
440
+    unsigned position;
441
+
442
+    if (ctx_pic->slice_count >= MAX_SLICES)
443
+        return -1;
444
+
445
+    if (!ctx_pic->bitstream)
446
+        ctx_pic->bitstream = buffer;
447
+    ctx_pic->bitstream_size += size;
448
+
449
+    position = buffer - ctx_pic->bitstream;
450
+    if (is_slice_short(ctx))
451
+        fill_slice_short(&ctx_pic->slice_short[ctx_pic->slice_count],
452
+                         position, size);
453
+    else
454
+        fill_slice_long(avctx, &ctx_pic->slice_long[ctx_pic->slice_count],
455
+                        position, size);
456
+    ctx_pic->slice_count++;
457
+
458
+    if (h->slice_type != FF_I_TYPE && h->slice_type != FF_SI_TYPE)
459
+        ctx_pic->pp.wBitFields &= ~(1 << 15); /* Set IntraPicFlag to 0 */
460
+    return 0;
461
+}
462
+
463
+static int end_frame(AVCodecContext *avctx)
464
+{
465
+    H264Context *h = avctx->priv_data;
466
+    MpegEncContext *s = &h->s;
467
+    const unsigned mb_count = s->mb_width * s->mb_height;
468
+    struct dxva_context *ctx = avctx->hwaccel_context;
469
+    const Picture *current_picture = h->s.current_picture_ptr;
470
+    struct dxva2_picture_context *ctx_pic = current_picture->hwaccel_picture_private;
471
+    unsigned               buffer_count = 0;
472
+    DXVA2_DecodeBufferDesc buffer[4];
473
+    DXVA2_DecodeExecuteParams exec;
474
+    int      result;
475
+
476
+    if (ctx_pic->slice_count <= 0 || ctx_pic->bitstream_size <= 0)
477
+        return -1;
478
+
479
+    if (FAILED(IDirectXVideoDecoder_BeginFrame(ctx->decoder,
480
+                                               get_surface(current_picture),
481
+                                               NULL))) {
482
+        av_log(avctx, AV_LOG_ERROR, "Failed to begin frame\n");
483
+        return -1;
484
+    }
485
+
486
+    result = commit_buffer(avctx, ctx, &buffer[buffer_count],
487
+                           DXVA2_PictureParametersBufferType,
488
+                           &ctx_pic->pp, sizeof(ctx_pic->pp), 0);
489
+    if (result) {
490
+        av_log(avctx, AV_LOG_ERROR,
491
+               "Failed to add picture parameter buffer\n");
492
+        goto end;
493
+    }
494
+    buffer_count++;
495
+
496
+    result = commit_buffer(avctx, ctx, &buffer[buffer_count],
497
+                           DXVA2_InverseQuantizationMatrixBufferType,
498
+                           &ctx_pic->qm, sizeof(ctx_pic->qm), 0);
499
+    if (result) {
500
+        av_log(avctx, AV_LOG_ERROR,
501
+               "Failed to add inverse quantization matrix buffer\n");
502
+        goto end;
503
+    }
504
+    buffer_count++;
505
+
506
+    result = commit_bitstream_and_slice_buffer(avctx, ctx, ctx_pic,
507
+                                               &buffer[buffer_count + 0],
508
+                                               &buffer[buffer_count + 1],
509
+                                               mb_count);
510
+    if (result) {
511
+        av_log(avctx, AV_LOG_ERROR,
512
+               "Failed to add bitstream or slice control buffer\n");
513
+        goto end;
514
+    }
515
+    buffer_count += 2;
516
+
517
+    /* TODO Film Grain when possible */
518
+
519
+    assert(buffer_count == 4);
520
+
521
+    memset(&exec, 0, sizeof(exec));
522
+    exec.NumCompBuffers      = buffer_count;
523
+    exec.pCompressedBuffers  = buffer;
524
+    exec.pExtensionData      = NULL;
525
+    if (FAILED(IDirectXVideoDecoder_Execute(ctx->decoder, &exec))) {
526
+        av_log(avctx, AV_LOG_ERROR, "Failed to execute\n");
527
+        result = -1;
528
+    }
529
+
530
+end:
531
+    if (FAILED(IDirectXVideoDecoder_EndFrame(ctx->decoder, NULL))) {
532
+        av_log(avctx, AV_LOG_ERROR, "Failed to end frame\n");
533
+        result = -1;
534
+    }
535
+
536
+    if (!result)
537
+        ff_draw_horiz_band(s, 0, s->avctx->height);
538
+    return result;
539
+}
540
+
541
+AVHWAccel h264_dxva2_hwaccel = {
542
+    .name           = "h264_dxva2",
543
+    .type           = CODEC_TYPE_VIDEO,
544
+    .id             = CODEC_ID_H264,
545
+    .pix_fmt        = PIX_FMT_DXVA2_VLD,
546
+    .capabilities   = 0,
547
+    .start_frame    = start_frame,
548
+    .decode_slice   = decode_slice,
549
+    .end_frame      = end_frame,
550
+    .priv_data_size = sizeof(struct dxva2_picture_context),
551
+};
552
+
... ...
@@ -81,6 +81,7 @@ const enum PixelFormat ff_pixfmt_list_420[] = {
81 81
 };
82 82
 
83 83
 const enum PixelFormat ff_hwaccel_pixfmt_list_420[] = {
84
+    PIX_FMT_DXVA2_VLD,
84 85
     PIX_FMT_VAAPI_VLD,
85 86
     PIX_FMT_YUV420P,
86 87
     PIX_FMT_NONE
... ...
@@ -646,6 +646,12 @@ const AVPixFmtDescriptor av_pix_fmt_descriptors[PIX_FMT_NB] = {
646 646
         },
647 647
         .flags = PIX_FMT_BE,
648 648
     },
649
+    [PIX_FMT_DXVA2_VLD] = {
650
+        .name = "dxva2_vld",
651
+        .log2_chroma_w = 1,
652
+        .log2_chroma_h = 1,
653
+        .flags = PIX_FMT_HWACCEL,
654
+    },
649 655
 };
650 656
 
651 657
 int av_get_bits_per_pixel(const AVPixFmtDescriptor *pixdesc)
... ...
@@ -126,6 +126,7 @@ enum PixelFormat {
126 126
     PIX_FMT_YUV444P16LE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
127 127
     PIX_FMT_YUV444P16BE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
128 128
     PIX_FMT_VDPAU_MPEG4,  ///< MPEG4 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
129
+    PIX_FMT_DXVA2_VLD,    ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer
129 130
     PIX_FMT_NB,        ///< number of pixel formats, DO NOT USE THIS if you want to link with shared libav* because the number of formats might differ between versions
130 131
 };
131 132