1/*
2 * DXVA2 HEVC HW acceleration.
3 *
4 * copyright (c) 2014 - 2015 Hendrik Leppkes
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include "config_components.h"
24
25#include "libavutil/avassert.h"
26
27#include "dxva2_internal.h"
28#include "hevc_data.h"
29#include "hevcdec.h"
30
31#define MAX_SLICES 256
32
33struct hevc_dxva2_picture_context {
34    DXVA_PicParams_HEVC   pp;
35    DXVA_Qmatrix_HEVC     qm;
36    unsigned              slice_count;
37    DXVA_Slice_HEVC_Short slice_short[MAX_SLICES];
38    const uint8_t         *bitstream;
39    unsigned              bitstream_size;
40};
41
42static void fill_picture_entry(DXVA_PicEntry_HEVC *pic,
43                               unsigned index, unsigned flag)
44{
45    av_assert0((index & 0x7f) == index && (flag & 0x01) == flag);
46    pic->bPicEntry = index | (flag << 7);
47}
48
49static int get_refpic_index(const DXVA_PicParams_HEVC *pp, int surface_index)
50{
51    int i;
52    for (i = 0; i < FF_ARRAY_ELEMS(pp->RefPicList); i++) {
53        if ((pp->RefPicList[i].bPicEntry & 0x7f) == surface_index)
54          return i;
55    }
56    return 0xff;
57}
58
59static void fill_picture_parameters(const AVCodecContext *avctx, AVDXVAContext *ctx, const HEVCContext *h,
60                                    DXVA_PicParams_HEVC *pp)
61{
62    const HEVCFrame *current_picture = h->ref;
63    const HEVCSPS *sps = h->ps.sps;
64    const HEVCPPS *pps = h->ps.pps;
65    int i, j;
66
67    memset(pp, 0, sizeof(*pp));
68
69    pp->PicWidthInMinCbsY  = sps->min_cb_width;
70    pp->PicHeightInMinCbsY = sps->min_cb_height;
71
72    pp->wFormatAndSequenceInfoFlags = (sps->chroma_format_idc             <<  0) |
73                                      (sps->separate_colour_plane_flag    <<  2) |
74                                      ((sps->bit_depth - 8)               <<  3) |
75                                      ((sps->bit_depth - 8)               <<  6) |
76                                      ((sps->log2_max_poc_lsb - 4)        <<  9) |
77                                      (0                                  << 13) |
78                                      (0                                  << 14) |
79                                      (0                                  << 15);
80
81    fill_picture_entry(&pp->CurrPic, ff_dxva2_get_surface_index(avctx, ctx, current_picture->frame), 0);
82
83    pp->sps_max_dec_pic_buffering_minus1         = sps->temporal_layer[sps->max_sub_layers - 1].max_dec_pic_buffering - 1;
84    pp->log2_min_luma_coding_block_size_minus3   = sps->log2_min_cb_size - 3;
85    pp->log2_diff_max_min_luma_coding_block_size = sps->log2_diff_max_min_coding_block_size;
86    pp->log2_min_transform_block_size_minus2     = sps->log2_min_tb_size - 2;
87    pp->log2_diff_max_min_transform_block_size   = sps->log2_max_trafo_size  - sps->log2_min_tb_size;
88    pp->max_transform_hierarchy_depth_inter      = sps->max_transform_hierarchy_depth_inter;
89    pp->max_transform_hierarchy_depth_intra      = sps->max_transform_hierarchy_depth_intra;
90    pp->num_short_term_ref_pic_sets              = sps->nb_st_rps;
91    pp->num_long_term_ref_pics_sps               = sps->num_long_term_ref_pics_sps;
92
93    pp->num_ref_idx_l0_default_active_minus1     = pps->num_ref_idx_l0_default_active - 1;
94    pp->num_ref_idx_l1_default_active_minus1     = pps->num_ref_idx_l1_default_active - 1;
95    pp->init_qp_minus26                          = pps->pic_init_qp_minus26;
96
97    if (h->sh.short_term_ref_pic_set_sps_flag == 0 && h->sh.short_term_rps) {
98        pp->ucNumDeltaPocsOfRefRpsIdx            = h->sh.short_term_rps->rps_idx_num_delta_pocs;
99        pp->wNumBitsForShortTermRPSInSlice       = h->sh.short_term_ref_pic_set_size;
100    }
101
102    pp->dwCodingParamToolFlags = (sps->scaling_list_enable_flag                  <<  0) |
103                                 (sps->amp_enabled_flag                          <<  1) |
104                                 (sps->sao_enabled                               <<  2) |
105                                 (sps->pcm_enabled_flag                          <<  3) |
106                                 ((sps->pcm_enabled_flag ? (sps->pcm.bit_depth - 1) : 0)            <<  4) |
107                                 ((sps->pcm_enabled_flag ? (sps->pcm.bit_depth_chroma - 1) : 0)     <<  8) |
108                                 ((sps->pcm_enabled_flag ? (sps->pcm.log2_min_pcm_cb_size - 3) : 0) << 12) |
109                                 ((sps->pcm_enabled_flag ? (sps->pcm.log2_max_pcm_cb_size - sps->pcm.log2_min_pcm_cb_size) : 0) << 14) |
110                                 (sps->pcm.loop_filter_disable_flag              << 16) |
111                                 (sps->long_term_ref_pics_present_flag           << 17) |
112                                 (sps->sps_temporal_mvp_enabled_flag             << 18) |
113                                 (sps->sps_strong_intra_smoothing_enable_flag    << 19) |
114                                 (pps->dependent_slice_segments_enabled_flag     << 20) |
115                                 (pps->output_flag_present_flag                  << 21) |
116                                 (pps->num_extra_slice_header_bits               << 22) |
117                                 (pps->sign_data_hiding_flag                     << 25) |
118                                 (pps->cabac_init_present_flag                   << 26) |
119                                 (0                                              << 27);
120
121    pp->dwCodingSettingPicturePropertyFlags = (pps->constrained_intra_pred_flag                   <<  0) |
122                                              (pps->transform_skip_enabled_flag                   <<  1) |
123                                              (pps->cu_qp_delta_enabled_flag                      <<  2) |
124                                              (pps->pic_slice_level_chroma_qp_offsets_present_flag <<  3) |
125                                              (pps->weighted_pred_flag                            <<  4) |
126                                              (pps->weighted_bipred_flag                          <<  5) |
127                                              (pps->transquant_bypass_enable_flag                 <<  6) |
128                                              (pps->tiles_enabled_flag                            <<  7) |
129                                              (pps->entropy_coding_sync_enabled_flag              <<  8) |
130                                              (pps->uniform_spacing_flag                          <<  9) |
131                                              ((pps->tiles_enabled_flag ? pps->loop_filter_across_tiles_enabled_flag : 0) << 10) |
132                                              (pps->seq_loop_filter_across_slices_enabled_flag    << 11) |
133                                              (pps->deblocking_filter_override_enabled_flag       << 12) |
134                                              (pps->disable_dbf                                   << 13) |
135                                              (pps->lists_modification_present_flag               << 14) |
136                                              (pps->slice_header_extension_present_flag           << 15) |
137                                              (IS_IRAP(h)                                         << 16) |
138                                              (IS_IDR(h)                                          << 17) |
139                                              /* IntraPicFlag */
140                                              (IS_IRAP(h)                                         << 18) |
141                                              (0                                                  << 19);
142    pp->pps_cb_qp_offset            = pps->cb_qp_offset;
143    pp->pps_cr_qp_offset            = pps->cr_qp_offset;
144    if (pps->tiles_enabled_flag) {
145        pp->num_tile_columns_minus1 = pps->num_tile_columns - 1;
146        pp->num_tile_rows_minus1    = pps->num_tile_rows - 1;
147
148        if (!pps->uniform_spacing_flag) {
149            for (i = 0; i < pps->num_tile_columns; i++)
150                pp->column_width_minus1[i] = pps->column_width[i] - 1;
151
152            for (i = 0; i < pps->num_tile_rows; i++)
153                pp->row_height_minus1[i] = pps->row_height[i] - 1;
154        }
155    }
156
157    pp->diff_cu_qp_delta_depth           = pps->diff_cu_qp_delta_depth;
158    pp->pps_beta_offset_div2             = pps->beta_offset / 2;
159    pp->pps_tc_offset_div2               = pps->tc_offset / 2;
160    pp->log2_parallel_merge_level_minus2 = pps->log2_parallel_merge_level - 2;
161    pp->CurrPicOrderCntVal               = h->poc;
162
163    // fill RefPicList from the DPB
164    for (i = 0, j = 0; i < FF_ARRAY_ELEMS(pp->RefPicList); i++) {
165        const HEVCFrame *frame = NULL;
166        while (!frame && j < FF_ARRAY_ELEMS(h->DPB)) {
167            if (&h->DPB[j] != current_picture && (h->DPB[j].flags & (HEVC_FRAME_FLAG_LONG_REF | HEVC_FRAME_FLAG_SHORT_REF)))
168                frame = &h->DPB[j];
169            j++;
170        }
171
172        if (frame) {
173            fill_picture_entry(&pp->RefPicList[i], ff_dxva2_get_surface_index(avctx, ctx, frame->frame), !!(frame->flags & HEVC_FRAME_FLAG_LONG_REF));
174            pp->PicOrderCntValList[i] = frame->poc;
175        } else {
176            pp->RefPicList[i].bPicEntry = 0xff;
177            pp->PicOrderCntValList[i]   = 0;
178        }
179    }
180
181    #define DO_REF_LIST(ref_idx, ref_list) { \
182        const RefPicList *rpl = &h->rps[ref_idx]; \
183        for (i = 0, j = 0; i < FF_ARRAY_ELEMS(pp->ref_list); i++) { \
184            const HEVCFrame *frame = NULL; \
185            while (!frame && j < rpl->nb_refs) \
186                frame = rpl->ref[j++]; \
187            if (frame && frame->flags & (HEVC_FRAME_FLAG_LONG_REF | HEVC_FRAME_FLAG_SHORT_REF)) \
188                pp->ref_list[i] = get_refpic_index(pp, ff_dxva2_get_surface_index(avctx, ctx, frame->frame)); \
189            else \
190                pp->ref_list[i] = 0xff; \
191        } \
192    }
193
194    // Fill short term and long term lists
195    DO_REF_LIST(ST_CURR_BEF, RefPicSetStCurrBefore);
196    DO_REF_LIST(ST_CURR_AFT, RefPicSetStCurrAfter);
197    DO_REF_LIST(LT_CURR, RefPicSetLtCurr);
198
199    pp->StatusReportFeedbackNumber = 1 + DXVA_CONTEXT_REPORT_ID(avctx, ctx)++;
200}
201
202static void fill_scaling_lists(AVDXVAContext *ctx, const HEVCContext *h, DXVA_Qmatrix_HEVC *qm)
203{
204    unsigned i, j, pos;
205    const ScalingList *sl = h->ps.pps->scaling_list_data_present_flag ?
206                            &h->ps.pps->scaling_list : &h->ps.sps->scaling_list;
207
208    memset(qm, 0, sizeof(*qm));
209    for (i = 0; i < 6; i++) {
210        for (j = 0; j < 16; j++) {
211            pos = 4 * ff_hevc_diag_scan4x4_y[j] + ff_hevc_diag_scan4x4_x[j];
212            qm->ucScalingLists0[i][j] = sl->sl[0][i][pos];
213        }
214
215        for (j = 0; j < 64; j++) {
216            pos = 8 * ff_hevc_diag_scan8x8_y[j] + ff_hevc_diag_scan8x8_x[j];
217            qm->ucScalingLists1[i][j] = sl->sl[1][i][pos];
218            qm->ucScalingLists2[i][j] = sl->sl[2][i][pos];
219
220            if (i < 2)
221                qm->ucScalingLists3[i][j] = sl->sl[3][i * 3][pos];
222        }
223
224        qm->ucScalingListDCCoefSizeID2[i] = sl->sl_dc[0][i];
225        if (i < 2)
226            qm->ucScalingListDCCoefSizeID3[i] = sl->sl_dc[1][i * 3];
227    }
228}
229
230static void fill_slice_short(DXVA_Slice_HEVC_Short *slice,
231                             unsigned position, unsigned size)
232{
233    memset(slice, 0, sizeof(*slice));
234    slice->BSNALunitDataLocation = position;
235    slice->SliceBytesInBuffer    = size;
236    slice->wBadSliceChopping     = 0;
237}
238
239static int commit_bitstream_and_slice_buffer(AVCodecContext *avctx,
240                                             DECODER_BUFFER_DESC *bs,
241                                             DECODER_BUFFER_DESC *sc)
242{
243    const HEVCContext *h = avctx->priv_data;
244    AVDXVAContext *ctx = DXVA_CONTEXT(avctx);
245    const HEVCFrame *current_picture = h->ref;
246    struct hevc_dxva2_picture_context *ctx_pic = current_picture->hwaccel_picture_private;
247    DXVA_Slice_HEVC_Short *slice = NULL;
248    void     *dxva_data_ptr;
249    uint8_t  *dxva_data, *current, *end;
250    unsigned dxva_size;
251    void     *slice_data;
252    unsigned slice_size;
253    unsigned padding;
254    unsigned i;
255    unsigned type;
256
257    /* Create an annex B bitstream buffer with only slice NAL and finalize slice */
258#if CONFIG_D3D11VA
259    if (ff_dxva2_is_d3d11(avctx)) {
260        type = D3D11_VIDEO_DECODER_BUFFER_BITSTREAM;
261        if (FAILED(ID3D11VideoContext_GetDecoderBuffer(D3D11VA_CONTEXT(ctx)->video_context,
262                                                       D3D11VA_CONTEXT(ctx)->decoder,
263                                                       type,
264                                                       &dxva_size, &dxva_data_ptr)))
265            return -1;
266    }
267#endif
268#if CONFIG_DXVA2
269    if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {
270        type = DXVA2_BitStreamDateBufferType;
271        if (FAILED(IDirectXVideoDecoder_GetBuffer(DXVA2_CONTEXT(ctx)->decoder,
272                                                  type,
273                                                  &dxva_data_ptr, &dxva_size)))
274            return -1;
275    }
276#endif
277
278    dxva_data = dxva_data_ptr;
279    current = dxva_data;
280    end = dxva_data + dxva_size;
281
282    for (i = 0; i < ctx_pic->slice_count; i++) {
283        static const uint8_t start_code[] = { 0, 0, 1 };
284        static const unsigned start_code_size = sizeof(start_code);
285        unsigned position, size;
286
287        slice = &ctx_pic->slice_short[i];
288
289        position = slice->BSNALunitDataLocation;
290        size     = slice->SliceBytesInBuffer;
291        if (start_code_size + size > end - current) {
292            av_log(avctx, AV_LOG_ERROR, "Failed to build bitstream");
293            break;
294        }
295
296        slice->BSNALunitDataLocation = current - dxva_data;
297        slice->SliceBytesInBuffer    = start_code_size + size;
298
299        memcpy(current, start_code, start_code_size);
300        current += start_code_size;
301
302        memcpy(current, &ctx_pic->bitstream[position], size);
303        current += size;
304    }
305    padding = FFMIN(128 - ((current - dxva_data) & 127), end - current);
306    if (slice && padding > 0) {
307        memset(current, 0, padding);
308        current += padding;
309
310        slice->SliceBytesInBuffer += padding;
311    }
312#if CONFIG_D3D11VA
313    if (ff_dxva2_is_d3d11(avctx))
314        if (FAILED(ID3D11VideoContext_ReleaseDecoderBuffer(D3D11VA_CONTEXT(ctx)->video_context, D3D11VA_CONTEXT(ctx)->decoder, type)))
315            return -1;
316#endif
317#if CONFIG_DXVA2
318    if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD)
319        if (FAILED(IDirectXVideoDecoder_ReleaseBuffer(DXVA2_CONTEXT(ctx)->decoder, type)))
320            return -1;
321#endif
322    if (i < ctx_pic->slice_count)
323        return -1;
324
325#if CONFIG_D3D11VA
326    if (ff_dxva2_is_d3d11(avctx)) {
327        D3D11_VIDEO_DECODER_BUFFER_DESC *dsc11 = bs;
328        memset(dsc11, 0, sizeof(*dsc11));
329        dsc11->BufferType           = type;
330        dsc11->DataSize             = current - dxva_data;
331        dsc11->NumMBsInBuffer       = 0;
332
333        type = D3D11_VIDEO_DECODER_BUFFER_SLICE_CONTROL;
334    }
335#endif
336#if CONFIG_DXVA2
337    if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {
338        DXVA2_DecodeBufferDesc *dsc2 = bs;
339        memset(dsc2, 0, sizeof(*dsc2));
340        dsc2->CompressedBufferType = type;
341        dsc2->DataSize             = current - dxva_data;
342        dsc2->NumMBsInBuffer       = 0;
343
344        type = DXVA2_SliceControlBufferType;
345    }
346#endif
347
348    slice_data = ctx_pic->slice_short;
349    slice_size = ctx_pic->slice_count * sizeof(*ctx_pic->slice_short);
350
351    av_assert0(((current - dxva_data) & 127) == 0);
352    return ff_dxva2_commit_buffer(avctx, ctx, sc,
353                                  type,
354                                  slice_data, slice_size, 0);
355}
356
357
358static int dxva2_hevc_start_frame(AVCodecContext *avctx,
359                                  av_unused const uint8_t *buffer,
360                                  av_unused uint32_t size)
361{
362    const HEVCContext *h = avctx->priv_data;
363    AVDXVAContext *ctx = DXVA_CONTEXT(avctx);
364    struct hevc_dxva2_picture_context *ctx_pic = h->ref->hwaccel_picture_private;
365
366    if (!DXVA_CONTEXT_VALID(avctx, ctx))
367        return -1;
368    av_assert0(ctx_pic);
369
370    /* Fill up DXVA_PicParams_HEVC */
371    fill_picture_parameters(avctx, ctx, h, &ctx_pic->pp);
372
373    /* Fill up DXVA_Qmatrix_HEVC */
374    fill_scaling_lists(ctx, h, &ctx_pic->qm);
375
376    ctx_pic->slice_count    = 0;
377    ctx_pic->bitstream_size = 0;
378    ctx_pic->bitstream      = NULL;
379    return 0;
380}
381
382static int dxva2_hevc_decode_slice(AVCodecContext *avctx,
383                                   const uint8_t *buffer,
384                                   uint32_t size)
385{
386    const HEVCContext *h = avctx->priv_data;
387    const HEVCFrame *current_picture = h->ref;
388    struct hevc_dxva2_picture_context *ctx_pic = current_picture->hwaccel_picture_private;
389    unsigned position;
390
391    if (ctx_pic->slice_count >= MAX_SLICES)
392        return -1;
393
394    if (!ctx_pic->bitstream)
395        ctx_pic->bitstream = buffer;
396    ctx_pic->bitstream_size += size;
397
398    position = buffer - ctx_pic->bitstream;
399    fill_slice_short(&ctx_pic->slice_short[ctx_pic->slice_count], position, size);
400    ctx_pic->slice_count++;
401
402    return 0;
403}
404
405static int dxva2_hevc_end_frame(AVCodecContext *avctx)
406{
407    HEVCContext *h = avctx->priv_data;
408    struct hevc_dxva2_picture_context *ctx_pic = h->ref->hwaccel_picture_private;
409    int scale = ctx_pic->pp.dwCodingParamToolFlags & 1;
410    int ret;
411
412    if (ctx_pic->slice_count <= 0 || ctx_pic->bitstream_size <= 0)
413        return -1;
414
415    ret = ff_dxva2_common_end_frame(avctx, h->ref->frame,
416                                    &ctx_pic->pp, sizeof(ctx_pic->pp),
417                                    scale ? &ctx_pic->qm : NULL, scale ? sizeof(ctx_pic->qm) : 0,
418                                    commit_bitstream_and_slice_buffer);
419    return ret;
420}
421
422#if CONFIG_HEVC_DXVA2_HWACCEL
423const AVHWAccel ff_hevc_dxva2_hwaccel = {
424    .name           = "hevc_dxva2",
425    .type           = AVMEDIA_TYPE_VIDEO,
426    .id             = AV_CODEC_ID_HEVC,
427    .pix_fmt        = AV_PIX_FMT_DXVA2_VLD,
428    .init           = ff_dxva2_decode_init,
429    .uninit         = ff_dxva2_decode_uninit,
430    .start_frame    = dxva2_hevc_start_frame,
431    .decode_slice   = dxva2_hevc_decode_slice,
432    .end_frame      = dxva2_hevc_end_frame,
433    .frame_params   = ff_dxva2_common_frame_params,
434    .frame_priv_data_size = sizeof(struct hevc_dxva2_picture_context),
435    .priv_data_size = sizeof(FFDXVASharedContext),
436};
437#endif
438
439#if CONFIG_HEVC_D3D11VA_HWACCEL
440const AVHWAccel ff_hevc_d3d11va_hwaccel = {
441    .name           = "hevc_d3d11va",
442    .type           = AVMEDIA_TYPE_VIDEO,
443    .id             = AV_CODEC_ID_HEVC,
444    .pix_fmt        = AV_PIX_FMT_D3D11VA_VLD,
445    .init           = ff_dxva2_decode_init,
446    .uninit         = ff_dxva2_decode_uninit,
447    .start_frame    = dxva2_hevc_start_frame,
448    .decode_slice   = dxva2_hevc_decode_slice,
449    .end_frame      = dxva2_hevc_end_frame,
450    .frame_params   = ff_dxva2_common_frame_params,
451    .frame_priv_data_size = sizeof(struct hevc_dxva2_picture_context),
452    .priv_data_size = sizeof(FFDXVASharedContext),
453};
454#endif
455
456#if CONFIG_HEVC_D3D11VA2_HWACCEL
457const AVHWAccel ff_hevc_d3d11va2_hwaccel = {
458    .name           = "hevc_d3d11va2",
459    .type           = AVMEDIA_TYPE_VIDEO,
460    .id             = AV_CODEC_ID_HEVC,
461    .pix_fmt        = AV_PIX_FMT_D3D11,
462    .init           = ff_dxva2_decode_init,
463    .uninit         = ff_dxva2_decode_uninit,
464    .start_frame    = dxva2_hevc_start_frame,
465    .decode_slice   = dxva2_hevc_decode_slice,
466    .end_frame      = dxva2_hevc_end_frame,
467    .frame_params   = ff_dxva2_common_frame_params,
468    .frame_priv_data_size = sizeof(struct hevc_dxva2_picture_context),
469    .priv_data_size = sizeof(FFDXVASharedContext),
470};
471#endif
472