• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * AV1 HW decode acceleration through NVDEC
3  *
4  * Copyright (c) 2020 Timo Rothenpieler
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 "avcodec.h"
24 #include "nvdec.h"
25 #include "decode.h"
26 #include "internal.h"
27 #include "av1dec.h"
28 
29 
get_bit_depth_from_seq(const AV1RawSequenceHeader * seq)30 static int get_bit_depth_from_seq(const AV1RawSequenceHeader *seq)
31 {
32     if (seq->seq_profile == 2 && seq->color_config.high_bitdepth)
33         return seq->color_config.twelve_bit ? 12 : 10;
34     else if (seq->seq_profile <= 2 && seq->color_config.high_bitdepth)
35         return 10;
36     else
37         return 8;
38 }
39 
nvdec_av1_start_frame(AVCodecContext * avctx,const uint8_t * buffer,uint32_t size)40 static int nvdec_av1_start_frame(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size)
41 {
42     const AV1DecContext *s = avctx->priv_data;
43     const AV1RawSequenceHeader *seq = s->raw_seq;
44     const AV1RawFrameHeader *frame_header = s->raw_frame_header;
45     const AV1RawFilmGrainParams *film_grain = &s->cur_frame.film_grain;
46 
47     NVDECContext      *ctx = avctx->internal->hwaccel_priv_data;
48     CUVIDPICPARAMS     *pp = &ctx->pic_params;
49     CUVIDAV1PICPARAMS *ppc = &pp->CodecSpecific.av1;
50     FrameDecodeData *fdd;
51     NVDECFrame *cf;
52     AVFrame *cur_frame = s->cur_frame.f;
53 
54     unsigned char remap_lr_type[4] = { AV1_RESTORE_NONE, AV1_RESTORE_SWITCHABLE, AV1_RESTORE_WIENER, AV1_RESTORE_SGRPROJ };
55 
56     int apply_grain = !(avctx->export_side_data & AV_CODEC_EXPORT_DATA_FILM_GRAIN) && film_grain->apply_grain;
57     int ret, i, j;
58 
59     ret = ff_nvdec_start_frame_sep_ref(avctx, cur_frame, apply_grain);
60     if (ret < 0)
61         return ret;
62 
63     fdd = (FrameDecodeData*)cur_frame->private_ref->data;
64     cf  = (NVDECFrame*)fdd->hwaccel_priv;
65 
66     *pp = (CUVIDPICPARAMS) {
67         .PicWidthInMbs     = (cur_frame->width  + 15) / 16,
68         .FrameHeightInMbs  = (cur_frame->height + 15) / 16,
69         .CurrPicIdx        = cf->idx,
70         .ref_pic_flag      = !!frame_header->refresh_frame_flags,
71         .intra_pic_flag    = frame_header->frame_type == AV1_FRAME_INTRA_ONLY ||
72                              frame_header->frame_type == AV1_FRAME_KEY,
73 
74         .CodecSpecific.av1 = {
75             .width  = cur_frame->width,
76             .height = cur_frame->height,
77 
78             .frame_offset = frame_header->order_hint,
79             .decodePicIdx = cf->ref_idx,
80 
81             /* Sequence Header */
82             .profile                    = seq->seq_profile,
83             .use_128x128_superblock     = seq->use_128x128_superblock,
84             .subsampling_x              = seq->color_config.subsampling_x,
85             .subsampling_y              = seq->color_config.subsampling_y,
86             .mono_chrome                = seq->color_config.mono_chrome,
87             .bit_depth_minus8           = get_bit_depth_from_seq(seq) - 8,
88             .enable_filter_intra        = seq->enable_filter_intra,
89             .enable_intra_edge_filter   = seq->enable_intra_edge_filter,
90             .enable_interintra_compound = seq->enable_interintra_compound,
91             .enable_masked_compound     = seq->enable_masked_compound,
92             .enable_dual_filter         = seq->enable_dual_filter,
93             .enable_order_hint          = seq->enable_order_hint,
94             .order_hint_bits_minus1     = seq->order_hint_bits_minus_1,
95             .enable_jnt_comp            = seq->enable_jnt_comp,
96             .enable_superres            = seq->enable_superres,
97             .enable_cdef                = seq->enable_cdef,
98             .enable_restoration         = seq->enable_restoration,
99             .enable_fgs                 = seq->film_grain_params_present &&
100                                           !(avctx->export_side_data & AV_CODEC_EXPORT_DATA_FILM_GRAIN),
101 
102             /* Frame Header */
103             .frame_type                   = frame_header->frame_type,
104             .show_frame                   = frame_header->show_frame,
105             .disable_cdf_update           = frame_header->disable_cdf_update,
106             .allow_screen_content_tools   = frame_header->allow_screen_content_tools,
107             .force_integer_mv             = frame_header->force_integer_mv ||
108                                             frame_header->frame_type == AV1_FRAME_INTRA_ONLY ||
109                                             frame_header->frame_type == AV1_FRAME_KEY,
110             .coded_denom                  = frame_header->coded_denom,
111             .allow_intrabc                = frame_header->allow_intrabc,
112             .allow_high_precision_mv      = frame_header->allow_high_precision_mv,
113             .interp_filter                = frame_header->interpolation_filter,
114             .switchable_motion_mode       = frame_header->is_motion_mode_switchable,
115             .use_ref_frame_mvs            = frame_header->use_ref_frame_mvs,
116             .disable_frame_end_update_cdf = frame_header->disable_frame_end_update_cdf,
117             .delta_q_present              = frame_header->delta_q_present,
118             .delta_q_res                  = frame_header->delta_q_res,
119             .using_qmatrix                = frame_header->using_qmatrix,
120             .coded_lossless               = s->cur_frame.coded_lossless,
121             .use_superres                 = frame_header->use_superres,
122             .tx_mode                      = frame_header->tx_mode,
123             .reference_mode               = frame_header->reference_select,
124             .allow_warped_motion          = frame_header->allow_warped_motion,
125             .reduced_tx_set               = frame_header->reduced_tx_set,
126             .skip_mode                    = frame_header->skip_mode_present,
127 
128             /* Tiling Info */
129             .num_tile_cols          = frame_header->tile_cols,
130             .num_tile_rows          = frame_header->tile_rows,
131             .context_update_tile_id = frame_header->context_update_tile_id,
132 
133             /* CDEF */
134             .cdef_damping_minus_3 = frame_header->cdef_damping_minus_3,
135             .cdef_bits            = frame_header->cdef_bits,
136 
137             /* SkipModeFrames */
138             .SkipModeFrame0 = frame_header->skip_mode_present ?
139                               s->cur_frame.skip_mode_frame_idx[0] : 0,
140             .SkipModeFrame1 = frame_header->skip_mode_present ?
141                               s->cur_frame.skip_mode_frame_idx[1] : 0,
142 
143             /* QP Information */
144             .base_qindex     = frame_header->base_q_idx,
145             .qp_y_dc_delta_q = frame_header->delta_q_y_dc,
146             .qp_u_dc_delta_q = frame_header->delta_q_u_dc,
147             .qp_v_dc_delta_q = frame_header->delta_q_v_dc,
148             .qp_u_ac_delta_q = frame_header->delta_q_u_ac,
149             .qp_v_ac_delta_q = frame_header->delta_q_v_ac,
150             .qm_y            = frame_header->qm_y,
151             .qm_u            = frame_header->qm_u,
152             .qm_v            = frame_header->qm_v,
153 
154             /* Segmentation */
155             .segmentation_enabled         = frame_header->segmentation_enabled,
156             .segmentation_update_map      = frame_header->segmentation_update_map,
157             .segmentation_update_data     = frame_header->segmentation_update_data,
158             .segmentation_temporal_update = frame_header->segmentation_temporal_update,
159 
160             /* Loopfilter */
161             .loop_filter_level[0]       = frame_header->loop_filter_level[0],
162             .loop_filter_level[1]       = frame_header->loop_filter_level[1],
163             .loop_filter_level_u        = frame_header->loop_filter_level[2],
164             .loop_filter_level_v        = frame_header->loop_filter_level[3],
165             .loop_filter_sharpness      = frame_header->loop_filter_sharpness,
166             .loop_filter_delta_enabled  = frame_header->loop_filter_delta_enabled,
167             .loop_filter_delta_update   = frame_header->loop_filter_delta_update,
168             .loop_filter_mode_deltas[0] = frame_header->loop_filter_mode_deltas[0],
169             .loop_filter_mode_deltas[1] = frame_header->loop_filter_mode_deltas[1],
170             .delta_lf_present           = frame_header->delta_lf_present,
171             .delta_lf_res               = frame_header->delta_lf_res,
172             .delta_lf_multi             = frame_header->delta_lf_multi,
173 
174             /* Restoration */
175             .lr_type[0]      = remap_lr_type[frame_header->lr_type[0]],
176             .lr_type[1]      = remap_lr_type[frame_header->lr_type[1]],
177             .lr_type[2]      = remap_lr_type[frame_header->lr_type[2]],
178             .lr_unit_size[0] = 1 + frame_header->lr_unit_shift,
179             .lr_unit_size[1] = 1 + frame_header->lr_unit_shift - frame_header->lr_uv_shift,
180             .lr_unit_size[2] = 1 + frame_header->lr_unit_shift - frame_header->lr_uv_shift,
181 
182             /* Reference Frames */
183             .temporal_layer_id = s->cur_frame.temporal_id,
184             .spatial_layer_id  = s->cur_frame.spatial_id,
185 
186             /* Film Grain Params */
187             .apply_grain              = apply_grain,
188             .overlap_flag             = film_grain->overlap_flag,
189             .scaling_shift_minus8     = film_grain->grain_scaling_minus_8,
190             .chroma_scaling_from_luma = film_grain->chroma_scaling_from_luma,
191             .ar_coeff_lag             = film_grain->ar_coeff_lag,
192             .ar_coeff_shift_minus6    = film_grain->ar_coeff_shift_minus_6,
193             .grain_scale_shift        = film_grain->grain_scale_shift,
194             .clip_to_restricted_range = film_grain->clip_to_restricted_range,
195             .num_y_points             = film_grain->num_y_points,
196             .num_cb_points            = film_grain->num_cb_points,
197             .num_cr_points            = film_grain->num_cr_points,
198             .random_seed              = film_grain->grain_seed,
199             .cb_mult                  = film_grain->cb_mult,
200             .cb_luma_mult             = film_grain->cb_luma_mult,
201             .cb_offset                = film_grain->cb_offset,
202             .cr_mult                  = film_grain->cr_mult,
203             .cr_luma_mult             = film_grain->cr_luma_mult,
204             .cr_offset                = film_grain->cr_offset
205         }
206     };
207 
208     /* Tiling Info */
209     for (i = 0; i < frame_header->tile_cols; ++i) {
210         ppc->tile_widths[i] = frame_header->width_in_sbs_minus_1[i] + 1;
211     }
212     for (i = 0; i < frame_header->tile_rows; ++i) {
213         ppc->tile_heights[i] = frame_header->height_in_sbs_minus_1[i] + 1;
214     }
215 
216     /* CDEF */
217     for (i = 0; i < (1 << frame_header->cdef_bits); ++i) {
218         ppc->cdef_y_strength[i] = (frame_header->cdef_y_pri_strength[i] & 0x0F) | (frame_header->cdef_y_sec_strength[i] << 4);
219         ppc->cdef_uv_strength[i] = (frame_header->cdef_uv_pri_strength[i] & 0x0F) | (frame_header->cdef_uv_sec_strength[i] << 4);
220     }
221 
222     /* Segmentation */
223     for (i = 0; i < AV1_MAX_SEGMENTS; ++i) {
224         ppc->segmentation_feature_mask[i] = 0;
225         for (j = 0; j < AV1_SEG_LVL_MAX; ++j) {
226             ppc->segmentation_feature_mask[i] |= frame_header->feature_enabled[i][j] << j;
227             ppc->segmentation_feature_data[i][j] = frame_header->feature_value[i][j];
228         }
229     }
230 
231     for (i = 0; i < AV1_NUM_REF_FRAMES; ++i) {
232         /* Loopfilter */
233         ppc->loop_filter_ref_deltas[i] = frame_header->loop_filter_ref_deltas[i];
234 
235         /* Reference Frames */
236         ppc->ref_frame_map[i] = ff_nvdec_get_ref_idx(s->ref[i].f);
237     }
238 
239     if (frame_header->primary_ref_frame == AV1_PRIMARY_REF_NONE) {
240         ppc->primary_ref_frame = -1;
241     } else {
242         int8_t pri_ref_idx = frame_header->ref_frame_idx[frame_header->primary_ref_frame];
243         ppc->primary_ref_frame = ppc->ref_frame_map[pri_ref_idx];
244     }
245 
246     for (i = 0; i < AV1_REFS_PER_FRAME; ++i) {
247         /* Ref Frame List */
248         int8_t ref_idx = frame_header->ref_frame_idx[i];
249         AVFrame *ref_frame = s->ref[ref_idx].f;
250 
251         ppc->ref_frame[i].index = ppc->ref_frame_map[ref_idx];
252         ppc->ref_frame[i].width = ref_frame->width;
253         ppc->ref_frame[i].height = ref_frame->height;
254 
255         /* Global Motion */
256         ppc->global_motion[i].invalid = !frame_header->is_global[AV1_REF_FRAME_LAST + i];
257         ppc->global_motion[i].wmtype = s->cur_frame.gm_type[AV1_REF_FRAME_LAST + i];
258         for (j = 0; j < 6; ++j) {
259             ppc->global_motion[i].wmmat[j] = s->cur_frame.gm_params[AV1_REF_FRAME_LAST + i][j];
260         }
261     }
262 
263     /* Film Grain Params */
264     if (apply_grain) {
265         for (i = 0; i < 14; ++i) {
266             ppc->scaling_points_y[i][0] = film_grain->point_y_value[i];
267             ppc->scaling_points_y[i][1] = film_grain->point_y_scaling[i];
268         }
269         for (i = 0; i < 10; ++i) {
270             ppc->scaling_points_cb[i][0] = film_grain->point_cb_value[i];
271             ppc->scaling_points_cb[i][1] = film_grain->point_cb_scaling[i];
272             ppc->scaling_points_cr[i][0] = film_grain->point_cr_value[i];
273             ppc->scaling_points_cr[i][1] = film_grain->point_cr_scaling[i];
274         }
275         for (i = 0; i < 24; ++i) {
276             ppc->ar_coeffs_y[i] = (short)film_grain->ar_coeffs_y_plus_128[i] - 128;
277         }
278         for (i = 0; i < 25; ++i) {
279             ppc->ar_coeffs_cb[i] = (short)film_grain->ar_coeffs_cb_plus_128[i] - 128;
280             ppc->ar_coeffs_cr[i] = (short)film_grain->ar_coeffs_cr_plus_128[i] - 128;
281         }
282     }
283 
284     return 0;
285 }
286 
nvdec_av1_decode_slice(AVCodecContext * avctx,const uint8_t * buffer,uint32_t size)287 static int nvdec_av1_decode_slice(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size)
288 {
289     const AV1DecContext *s = avctx->priv_data;
290     const AV1RawFrameHeader *frame_header = s->raw_frame_header;
291     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
292     void *tmp;
293 
294     ctx->nb_slices = frame_header->tile_cols * frame_header->tile_rows;
295 
296     tmp = av_fast_realloc(ctx->slice_offsets, &ctx->slice_offsets_allocated,
297                           ctx->nb_slices * 2 * sizeof(*ctx->slice_offsets));
298     if (!tmp) {
299         return AVERROR(ENOMEM);
300     }
301     ctx->slice_offsets = tmp;
302 
303     /* Shortcut if all tiles are in the same buffer */
304     if (ctx->nb_slices == s->tg_end - s->tg_start + 1) {
305         ctx->bitstream = (uint8_t*)buffer;
306         ctx->bitstream_len = size;
307 
308         for (int i = 0; i < ctx->nb_slices; ++i) {
309             ctx->slice_offsets[i*2    ] = s->tile_group_info[i].tile_offset;
310             ctx->slice_offsets[i*2 + 1] = ctx->slice_offsets[i*2] + s->tile_group_info[i].tile_size;
311         }
312 
313         return 0;
314     }
315 
316     tmp = av_fast_realloc(ctx->bitstream_internal, &ctx->bitstream_allocated,
317                           ctx->bitstream_len + size);
318     if (!tmp) {
319         return AVERROR(ENOMEM);
320     }
321     ctx->bitstream = ctx->bitstream_internal = tmp;
322 
323     memcpy(ctx->bitstream + ctx->bitstream_len, buffer, size);
324 
325     for (uint32_t tile_num = s->tg_start; tile_num <= s->tg_end; ++tile_num) {
326         ctx->slice_offsets[tile_num*2    ] = ctx->bitstream_len + s->tile_group_info[tile_num].tile_offset;
327         ctx->slice_offsets[tile_num*2 + 1] = ctx->slice_offsets[tile_num*2] + s->tile_group_info[tile_num].tile_size;
328     }
329     ctx->bitstream_len += size;
330 
331     return 0;
332 }
333 
nvdec_av1_frame_params(AVCodecContext * avctx,AVBufferRef * hw_frames_ctx)334 static int nvdec_av1_frame_params(AVCodecContext *avctx, AVBufferRef *hw_frames_ctx)
335 {
336     /* Maximum of 8 reference frames, but potentially stored twice due to film grain */
337     return ff_nvdec_frame_params(avctx, hw_frames_ctx, 8 * 2, 0);
338 }
339 
340 const AVHWAccel ff_av1_nvdec_hwaccel = {
341     .name                 = "av1_nvdec",
342     .type                 = AVMEDIA_TYPE_VIDEO,
343     .id                   = AV_CODEC_ID_AV1,
344     .pix_fmt              = AV_PIX_FMT_CUDA,
345     .start_frame          = nvdec_av1_start_frame,
346     .end_frame            = ff_nvdec_simple_end_frame,
347     .decode_slice         = nvdec_av1_decode_slice,
348     .frame_params         = nvdec_av1_frame_params,
349     .init                 = ff_nvdec_decode_init,
350     .uninit               = ff_nvdec_decode_uninit,
351     .priv_data_size       = sizeof(NVDECContext),
352 };
353