hevcdec: add a CUVID hwaccel
[ffmpeg.git] / libavcodec / cuvid_hevc.c
1 /*
2  * HEVC HW decode acceleration through CUVID
3  *
4  * Copyright (c) 2017 Anton Khirnov
5  *
6  * This file is part of Libav.
7  *
8  * Libav 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  * Libav 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 Libav; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include <cuviddec.h>
24 #include <stdint.h>
25 #include <string.h>
26
27 #include "avcodec.h"
28 #include "cuvid.h"
29 #include "decode.h"
30 #include "internal.h"
31 #include "hevcdec.h"
32 #include "hevc_data.h"
33
34 static void dpb_add(CUVIDHEVCPICPARAMS *pp, int idx, const HEVCFrame *src)
35 {
36     FrameDecodeData *fdd = (FrameDecodeData*)src->frame->opaque_ref->data;
37     const CUVIDFrame *cf = fdd->hwaccel_priv;
38
39     pp->RefPicIdx[idx]      = cf ? cf->idx : -1;
40     pp->PicOrderCntVal[idx] = src->poc;
41     pp->IsLongTerm[idx]     = !!(src->flags & HEVC_FRAME_FLAG_LONG_REF);
42 }
43
44 static void fill_scaling_lists(CUVIDHEVCPICPARAMS *ppc, const HEVCContext *s)
45 {
46     const ScalingList *sl = s->ps.pps->scaling_list_data_present_flag ?
47                             &s->ps.pps->scaling_list : &s->ps.sps->scaling_list;
48     int i, j, pos;
49
50     for (i = 0; i < 6; i++) {
51         for (j = 0; j < 16; j++) {
52             pos = 4 * ff_hevc_diag_scan4x4_y[j] + ff_hevc_diag_scan4x4_x[j];
53             ppc->ScalingList4x4[i][j] = sl->sl[0][i][pos];
54         }
55
56         for (j = 0; j < 64; j++) {
57             pos = 8 * ff_hevc_diag_scan8x8_y[j] + ff_hevc_diag_scan8x8_x[j];
58             ppc->ScalingList8x8[i][j]   = sl->sl[1][i][pos];
59             ppc->ScalingList16x16[i][j] = sl->sl[2][i][pos];
60
61             if (i < 2)
62                 ppc->ScalingList32x32[i][j] = sl->sl[3][i][pos];
63         }
64     }
65
66     memcpy(ppc->ScalingListDCCoeff16x16, sl->sl_dc[0], sizeof(ppc->ScalingListDCCoeff16x16));
67     memcpy(ppc->ScalingListDCCoeff32x32, sl->sl_dc[1], sizeof(ppc->ScalingListDCCoeff32x32));
68 }
69
70 static int cuvid_hevc_start_frame(AVCodecContext *avctx,
71                                   const uint8_t *buffer, uint32_t size)
72 {
73     const HEVCContext *s = avctx->priv_data;
74     const HEVCPPS *pps = s->ps.pps;
75     const HEVCSPS *sps = s->ps.sps;
76
77     CUVIDContext       *ctx = avctx->internal->hwaccel_priv_data;
78     CUVIDPICPARAMS      *pp = &ctx->pic_params;
79     CUVIDHEVCPICPARAMS *ppc = &pp->CodecSpecific.hevc;
80     FrameDecodeData *fdd;
81     CUVIDFrame *cf;
82
83     int i, j, dpb_size, ret;
84
85     ret = ff_cuvid_start_frame(avctx, s->ref->frame);
86     if (ret < 0)
87         return ret;
88
89     fdd = (FrameDecodeData*)s->ref->frame->opaque_ref->data;
90     cf  = (CUVIDFrame*)fdd->hwaccel_priv;
91
92     *pp = (CUVIDPICPARAMS) {
93         .PicWidthInMbs     = sps->width  / 16,
94         .FrameHeightInMbs  = sps->height / 16,
95         .CurrPicIdx        = cf->idx,
96         .ref_pic_flag      = 1,
97         .intra_pic_flag    = 0,
98
99         .CodecSpecific.hevc = {
100             .pic_width_in_luma_samples                    = sps->width,
101             .pic_height_in_luma_samples                   = sps->height,
102             .log2_min_luma_coding_block_size_minus3       = sps->log2_min_cb_size - 3,
103             .log2_diff_max_min_luma_coding_block_size     = sps->log2_diff_max_min_coding_block_size,
104             .log2_min_transform_block_size_minus2         = sps->log2_min_tb_size - 2,
105             .log2_diff_max_min_transform_block_size       = sps->log2_max_trafo_size - sps->log2_min_tb_size,
106             .pcm_enabled_flag                             = sps->pcm_enabled_flag,
107             .log2_min_pcm_luma_coding_block_size_minus3   = sps->pcm_enabled_flag ? sps->pcm.log2_min_pcm_cb_size - 3 : 0,
108             .log2_diff_max_min_pcm_luma_coding_block_size = sps->pcm.log2_max_pcm_cb_size - sps->pcm.log2_min_pcm_cb_size,
109             .pcm_sample_bit_depth_luma_minus1             = sps->pcm_enabled_flag ? sps->pcm.bit_depth - 1 : 0,
110             .pcm_sample_bit_depth_chroma_minus1           = sps->pcm_enabled_flag ? sps->pcm.bit_depth_chroma - 1 : 0,
111             .pcm_loop_filter_disabled_flag                = sps->pcm.loop_filter_disable_flag,
112             .strong_intra_smoothing_enabled_flag          = sps->sps_strong_intra_smoothing_enable_flag,
113             .max_transform_hierarchy_depth_intra          = sps->max_transform_hierarchy_depth_intra,
114             .max_transform_hierarchy_depth_inter          = sps->max_transform_hierarchy_depth_inter,
115             .amp_enabled_flag                             = sps->amp_enabled_flag,
116             .separate_colour_plane_flag                   = sps->separate_colour_plane_flag,
117             .log2_max_pic_order_cnt_lsb_minus4            = sps->log2_max_poc_lsb - 4,
118             .num_short_term_ref_pic_sets                  = sps->nb_st_rps,
119             .long_term_ref_pics_present_flag              = sps->long_term_ref_pics_present_flag,
120             .num_long_term_ref_pics_sps                   = sps->num_long_term_ref_pics_sps,
121             .sps_temporal_mvp_enabled_flag                = sps->sps_temporal_mvp_enabled_flag,
122             .sample_adaptive_offset_enabled_flag          = sps->sao_enabled,
123             .scaling_list_enable_flag                     = sps->scaling_list_enable_flag,
124             .IrapPicFlag                                  = IS_IRAP(s),
125             .IdrPicFlag                                   = IS_IDR(s),
126             .bit_depth_luma_minus8                        = sps->bit_depth - 8,
127             .bit_depth_chroma_minus8                      = sps->bit_depth - 8,
128
129             .dependent_slice_segments_enabled_flag        = pps->dependent_slice_segments_enabled_flag,
130             .slice_segment_header_extension_present_flag  = pps->slice_header_extension_present_flag,
131             .sign_data_hiding_enabled_flag                = pps->sign_data_hiding_flag,
132             .cu_qp_delta_enabled_flag                     = pps->cu_qp_delta_enabled_flag,
133             .diff_cu_qp_delta_depth                       = pps->diff_cu_qp_delta_depth,
134             .init_qp_minus26                              = pps->pic_init_qp_minus26,
135             .pps_cb_qp_offset                             = pps->cb_qp_offset,
136             .pps_cr_qp_offset                             = pps->cr_qp_offset,
137             .constrained_intra_pred_flag                  = pps->constrained_intra_pred_flag,
138             .weighted_pred_flag                           = pps->weighted_pred_flag,
139             .weighted_bipred_flag                         = pps->weighted_bipred_flag,
140             .transform_skip_enabled_flag                  = pps->transform_skip_enabled_flag,
141             .transquant_bypass_enabled_flag               = pps->transquant_bypass_enable_flag,
142             .entropy_coding_sync_enabled_flag             = pps->entropy_coding_sync_enabled_flag,
143             .log2_parallel_merge_level_minus2             = pps->log2_parallel_merge_level - 2,
144             .num_extra_slice_header_bits                  = pps->num_extra_slice_header_bits,
145             .loop_filter_across_tiles_enabled_flag        = pps->loop_filter_across_tiles_enabled_flag,
146             .loop_filter_across_slices_enabled_flag       = pps->seq_loop_filter_across_slices_enabled_flag,
147             .output_flag_present_flag                     = pps->output_flag_present_flag,
148             .num_ref_idx_l0_default_active_minus1         = pps->num_ref_idx_l0_default_active - 1,
149             .num_ref_idx_l1_default_active_minus1         = pps->num_ref_idx_l1_default_active - 1,
150             .lists_modification_present_flag              = pps->lists_modification_present_flag,
151             .cabac_init_present_flag                      = pps->cabac_init_present_flag,
152             .pps_slice_chroma_qp_offsets_present_flag     = pps->pic_slice_level_chroma_qp_offsets_present_flag,
153             .deblocking_filter_override_enabled_flag      = pps->deblocking_filter_override_enabled_flag,
154             .pps_deblocking_filter_disabled_flag          = pps->disable_dbf,
155             .pps_beta_offset_div2                         = pps->beta_offset / 2,
156             .pps_tc_offset_div2                           = pps->tc_offset / 2,
157             .tiles_enabled_flag                           = pps->tiles_enabled_flag,
158             .uniform_spacing_flag                         = pps->uniform_spacing_flag,
159             .num_tile_columns_minus1                      = pps->num_tile_columns - 1,
160             .num_tile_rows_minus1                         = pps->num_tile_rows - 1,
161
162             .NumBitsForShortTermRPSInSlice                = s->sh.short_term_rps ? s->sh.short_term_ref_pic_set_size : 0,
163             .NumDeltaPocsOfRefRpsIdx                      = s->sh.short_term_rps ? s->sh.short_term_rps->rps_idx_num_delta_pocs : 0,
164             .NumPocTotalCurr                              = s->rps[ST_CURR_BEF].nb_refs + s->rps[ST_CURR_AFT].nb_refs +
165                                                             s->rps[LT_CURR].nb_refs,
166             .NumPocStCurrBefore                           = s->rps[ST_CURR_BEF].nb_refs,
167             .NumPocStCurrAfter                            = s->rps[ST_CURR_AFT].nb_refs,
168             .NumPocLtCurr                                 = s->rps[LT_CURR].nb_refs,
169             .CurrPicOrderCntVal                           = s->ref->poc,
170         },
171     };
172
173     if (pps->num_tile_columns > FF_ARRAY_ELEMS(ppc->column_width_minus1) ||
174         pps->num_tile_rows    > FF_ARRAY_ELEMS(ppc->row_height_minus1)) {
175         av_log(avctx, AV_LOG_ERROR, "Too many tiles\n");
176         return AVERROR(ENOSYS);
177     }
178     for (i = 0; i < pps->num_tile_columns; i++)
179         ppc->column_width_minus1[i] = pps->column_width[i] - 1;
180     for (i = 0; i < pps->num_tile_rows; i++)
181         ppc->row_height_minus1[i] = pps->row_height[i] - 1;
182
183     if (s->rps[LT_CURR].nb_refs     > FF_ARRAY_ELEMS(ppc->RefPicSetLtCurr)       ||
184         s->rps[ST_CURR_BEF].nb_refs > FF_ARRAY_ELEMS(ppc->RefPicSetStCurrBefore) ||
185         s->rps[ST_CURR_AFT].nb_refs > FF_ARRAY_ELEMS(ppc->RefPicSetStCurrAfter)) {
186         av_log(avctx, AV_LOG_ERROR, "Too many reference frames\n");
187         return AVERROR(ENOSYS);
188     }
189
190     dpb_size = 0;
191     for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
192         const HEVCFrame *ref = &s->DPB[i];
193         if (!(ref->flags & (HEVC_FRAME_FLAG_SHORT_REF | HEVC_FRAME_FLAG_LONG_REF)))
194             continue;
195         if (dpb_size >= FF_ARRAY_ELEMS(ppc->RefPicIdx)) {
196             av_log(avctx, AV_LOG_ERROR, "Too many reference frames\n");
197             return AVERROR_INVALIDDATA;
198         }
199         dpb_add(ppc, dpb_size++, ref);
200
201     }
202     for (i = dpb_size; i < FF_ARRAY_ELEMS(ppc->RefPicIdx); i++)
203         ppc->RefPicIdx[i] = -1;
204
205     for (i = 0; i < s->rps[ST_CURR_BEF].nb_refs; i++) {
206         for (j = 0; j < dpb_size; j++) {
207             if (ppc->PicOrderCntVal[j] == s->rps[ST_CURR_BEF].list[i]) {
208                 ppc->RefPicSetStCurrBefore[i] = j;
209                 break;
210             }
211         }
212     }
213     for (i = 0; i < s->rps[ST_CURR_AFT].nb_refs; i++) {
214         for (j = 0; j < dpb_size; j++) {
215             if (ppc->PicOrderCntVal[j] == s->rps[ST_CURR_AFT].list[i]) {
216                 ppc->RefPicSetStCurrAfter[i] = j;
217                 break;
218             }
219         }
220     }
221     for (i = 0; i < s->rps[LT_CURR].nb_refs; i++) {
222         for (j = 0; j < dpb_size; j++) {
223             if (ppc->PicOrderCntVal[j] == s->rps[LT_CURR].list[i]) {
224                 ppc->RefPicSetLtCurr[i] = j;
225                 break;
226             }
227         }
228     }
229
230     fill_scaling_lists(ppc, s);
231
232     return 0;
233 }
234
235 static int cuvid_hevc_decode_slice(AVCodecContext *avctx, const uint8_t *buffer,
236                                    uint32_t size)
237 {
238     CUVIDContext *ctx = avctx->internal->hwaccel_priv_data;
239     void *tmp;
240
241     tmp = av_fast_realloc(ctx->bitstream, &ctx->bitstream_allocated,
242                           ctx->bitstream_len + size + 3);
243     if (!tmp)
244         return AVERROR(ENOMEM);
245     ctx->bitstream = tmp;
246
247     tmp = av_fast_realloc(ctx->slice_offsets, &ctx->slice_offsets_allocated,
248                           (ctx->nb_slices + 1) * sizeof(*ctx->slice_offsets));
249     if (!tmp)
250         return AVERROR(ENOMEM);
251     ctx->slice_offsets = tmp;
252
253     AV_WB24(ctx->bitstream + ctx->bitstream_len, 1);
254     memcpy(ctx->bitstream + ctx->bitstream_len + 3, buffer, size);
255     ctx->slice_offsets[ctx->nb_slices] = ctx->bitstream_len ;
256     ctx->bitstream_len += size + 3;
257     ctx->nb_slices++;
258
259     return 0;
260 }
261
262 static int cuvid_hevc_decode_init(AVCodecContext *avctx)
263 {
264     const HEVCContext *s = avctx->priv_data;
265     const HEVCSPS *sps = s->ps.sps;
266     return ff_cuvid_decode_init(avctx, sps->temporal_layer[sps->max_sub_layers - 1].max_dec_pic_buffering + 1);
267 }
268
269 AVHWAccel ff_hevc_cuvid_hwaccel = {
270     .name                 = "hevc_cuvid",
271     .type                 = AVMEDIA_TYPE_VIDEO,
272     .id                   = AV_CODEC_ID_HEVC,
273     .pix_fmt              = AV_PIX_FMT_CUDA,
274     .start_frame          = cuvid_hevc_start_frame,
275     .end_frame            = ff_cuvid_end_frame,
276     .decode_slice         = cuvid_hevc_decode_slice,
277     .init                 = cuvid_hevc_decode_init,
278     .uninit               = ff_cuvid_decode_uninit,
279     .priv_data_size       = sizeof(CUVIDContext),
280 };