Imported Upstream version 6.1
[platform/upstream/ffmpeg.git] / libavcodec / vaapi_hevc.c
1 /*
2  * HEVC HW decode acceleration through VA API
3  *
4  * Copyright (C) 2015 Timo Rothenpieler <timo@rothenpieler.org>
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 <va/va.h>
24 #include <va/va_dec_hevc.h>
25
26 #include "avcodec.h"
27 #include "hevcdec.h"
28 #include "hwaccel_internal.h"
29 #include "vaapi_decode.h"
30 #include "vaapi_hevc.h"
31 #include "h265_profile_level.h"
32
33 typedef struct VAAPIDecodePictureHEVC {
34 #if VA_CHECK_VERSION(1, 2, 0)
35     VAPictureParameterBufferHEVCExtension pic_param;
36     VASliceParameterBufferHEVCExtension last_slice_param;
37 #else
38     VAPictureParameterBufferHEVC pic_param;
39     VASliceParameterBufferHEVC last_slice_param;
40 #endif
41     const uint8_t *last_buffer;
42     size_t         last_size;
43
44     VAAPIDecodePicture pic;
45 } VAAPIDecodePictureHEVC;
46
47 static void init_vaapi_pic(VAPictureHEVC *va_pic)
48 {
49     va_pic->picture_id    = VA_INVALID_ID;
50     va_pic->flags         = VA_PICTURE_HEVC_INVALID;
51     va_pic->pic_order_cnt = 0;
52 }
53
54 static void fill_vaapi_pic(VAPictureHEVC *va_pic, const HEVCFrame *pic, int rps_type)
55 {
56     va_pic->picture_id    = ff_vaapi_get_surface_id(pic->frame);
57     va_pic->pic_order_cnt = pic->poc;
58     va_pic->flags         = rps_type;
59
60     if (pic->flags & HEVC_FRAME_FLAG_LONG_REF)
61         va_pic->flags |= VA_PICTURE_HEVC_LONG_TERM_REFERENCE;
62
63     if (pic->frame->flags & AV_FRAME_FLAG_INTERLACED) {
64         va_pic->flags |= VA_PICTURE_HEVC_FIELD_PIC;
65
66         if (!(pic->frame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST))
67             va_pic->flags |= VA_PICTURE_HEVC_BOTTOM_FIELD;
68     }
69 }
70
71 static int find_frame_rps_type(const HEVCContext *h, const HEVCFrame *pic)
72 {
73     VASurfaceID pic_surf = ff_vaapi_get_surface_id(pic->frame);
74     const HEVCFrame *current_picture = h->ref;
75     int i;
76
77     for (i = 0; i < h->rps[ST_CURR_BEF].nb_refs; i++) {
78         if (pic_surf == ff_vaapi_get_surface_id(h->rps[ST_CURR_BEF].ref[i]->frame))
79             return VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE;
80     }
81
82     for (i = 0; i < h->rps[ST_CURR_AFT].nb_refs; i++) {
83         if (pic_surf == ff_vaapi_get_surface_id(h->rps[ST_CURR_AFT].ref[i]->frame))
84             return VA_PICTURE_HEVC_RPS_ST_CURR_AFTER;
85     }
86
87     for (i = 0; i < h->rps[LT_CURR].nb_refs; i++) {
88         if (pic_surf == ff_vaapi_get_surface_id(h->rps[LT_CURR].ref[i]->frame))
89             return VA_PICTURE_HEVC_RPS_LT_CURR;
90     }
91
92     if (h->ps.pps->pps_curr_pic_ref_enabled_flag && current_picture->poc == pic->poc)
93         return VA_PICTURE_HEVC_LONG_TERM_REFERENCE;
94
95     return 0;
96 }
97
98 static void fill_vaapi_reference_frames(const HEVCContext *h, VAPictureParameterBufferHEVC *pp)
99 {
100     const HEVCFrame *current_picture = h->ref;
101     int i, j, rps_type;
102
103     for (i = 0, j = 0; i < FF_ARRAY_ELEMS(pp->ReferenceFrames); i++) {
104         const HEVCFrame *frame = NULL;
105
106         while (!frame && j < FF_ARRAY_ELEMS(h->DPB)) {
107             if ((&h->DPB[j] != current_picture || h->ps.pps->pps_curr_pic_ref_enabled_flag) &&
108                 (h->DPB[j].flags & (HEVC_FRAME_FLAG_LONG_REF | HEVC_FRAME_FLAG_SHORT_REF)))
109                 frame = &h->DPB[j];
110             j++;
111         }
112
113         init_vaapi_pic(&pp->ReferenceFrames[i]);
114
115         if (frame) {
116             rps_type = find_frame_rps_type(h, frame);
117             fill_vaapi_pic(&pp->ReferenceFrames[i], frame, rps_type);
118         }
119     }
120 }
121
122 static int vaapi_hevc_start_frame(AVCodecContext          *avctx,
123                                   av_unused const uint8_t *buffer,
124                                   av_unused uint32_t       size)
125 {
126     const HEVCContext        *h = avctx->priv_data;
127     VAAPIDecodePictureHEVC *pic = h->ref->hwaccel_picture_private;
128     const HEVCSPS          *sps = h->ps.sps;
129     const HEVCPPS          *pps = h->ps.pps;
130
131     const ScalingList *scaling_list = NULL;
132     int pic_param_size, err, i;
133
134 #if VA_CHECK_VERSION(1, 2, 0)
135     int num_comps, pre_palette_size;
136 #endif
137
138     VAPictureParameterBufferHEVC *pic_param = (VAPictureParameterBufferHEVC *)&pic->pic_param;
139
140     pic->pic.output_surface = ff_vaapi_get_surface_id(h->ref->frame);
141
142     *pic_param = (VAPictureParameterBufferHEVC) {
143         .pic_width_in_luma_samples                    = sps->width,
144         .pic_height_in_luma_samples                   = sps->height,
145         .log2_min_luma_coding_block_size_minus3       = sps->log2_min_cb_size - 3,
146         .sps_max_dec_pic_buffering_minus1             = sps->temporal_layer[sps->max_sub_layers - 1].max_dec_pic_buffering - 1,
147         .log2_diff_max_min_luma_coding_block_size     = sps->log2_diff_max_min_coding_block_size,
148         .log2_min_transform_block_size_minus2         = sps->log2_min_tb_size - 2,
149         .log2_diff_max_min_transform_block_size       = sps->log2_max_trafo_size  - sps->log2_min_tb_size,
150         .max_transform_hierarchy_depth_inter          = sps->max_transform_hierarchy_depth_inter,
151         .max_transform_hierarchy_depth_intra          = sps->max_transform_hierarchy_depth_intra,
152         .num_short_term_ref_pic_sets                  = sps->nb_st_rps,
153         .num_long_term_ref_pic_sps                    = sps->num_long_term_ref_pics_sps,
154         .num_ref_idx_l0_default_active_minus1         = pps->num_ref_idx_l0_default_active - 1,
155         .num_ref_idx_l1_default_active_minus1         = pps->num_ref_idx_l1_default_active - 1,
156         .init_qp_minus26                              = pps->pic_init_qp_minus26,
157         .pps_cb_qp_offset                             = pps->cb_qp_offset,
158         .pps_cr_qp_offset                             = pps->cr_qp_offset,
159         .pcm_sample_bit_depth_luma_minus1             = sps->pcm.bit_depth - 1,
160         .pcm_sample_bit_depth_chroma_minus1           = sps->pcm.bit_depth_chroma - 1,
161         .log2_min_pcm_luma_coding_block_size_minus3   = sps->pcm.log2_min_pcm_cb_size - 3,
162         .log2_diff_max_min_pcm_luma_coding_block_size = sps->pcm.log2_max_pcm_cb_size - sps->pcm.log2_min_pcm_cb_size,
163         .diff_cu_qp_delta_depth                       = pps->diff_cu_qp_delta_depth,
164         .pps_beta_offset_div2                         = pps->beta_offset / 2,
165         .pps_tc_offset_div2                           = pps->tc_offset / 2,
166         .log2_parallel_merge_level_minus2             = pps->log2_parallel_merge_level - 2,
167         .bit_depth_luma_minus8                        = sps->bit_depth - 8,
168         .bit_depth_chroma_minus8                      = sps->bit_depth - 8,
169         .log2_max_pic_order_cnt_lsb_minus4            = sps->log2_max_poc_lsb - 4,
170         .num_extra_slice_header_bits                  = pps->num_extra_slice_header_bits,
171         .pic_fields.bits = {
172             .chroma_format_idc                          = sps->chroma_format_idc,
173             .tiles_enabled_flag                         = pps->tiles_enabled_flag,
174             .separate_colour_plane_flag                 = sps->separate_colour_plane_flag,
175             .pcm_enabled_flag                           = sps->pcm_enabled_flag,
176             .scaling_list_enabled_flag                  = sps->scaling_list_enable_flag,
177             .transform_skip_enabled_flag                = pps->transform_skip_enabled_flag,
178             .amp_enabled_flag                           = sps->amp_enabled_flag,
179             .strong_intra_smoothing_enabled_flag        = sps->sps_strong_intra_smoothing_enable_flag,
180             .sign_data_hiding_enabled_flag              = pps->sign_data_hiding_flag,
181             .constrained_intra_pred_flag                = pps->constrained_intra_pred_flag,
182             .cu_qp_delta_enabled_flag                   = pps->cu_qp_delta_enabled_flag,
183             .weighted_pred_flag                         = pps->weighted_pred_flag,
184             .weighted_bipred_flag                       = pps->weighted_bipred_flag,
185             .transquant_bypass_enabled_flag             = pps->transquant_bypass_enable_flag,
186             .entropy_coding_sync_enabled_flag           = pps->entropy_coding_sync_enabled_flag,
187             .pps_loop_filter_across_slices_enabled_flag = pps->seq_loop_filter_across_slices_enabled_flag,
188             .loop_filter_across_tiles_enabled_flag      = pps->loop_filter_across_tiles_enabled_flag,
189             .pcm_loop_filter_disabled_flag              = sps->pcm.loop_filter_disable_flag,
190         },
191         .slice_parsing_fields.bits = {
192             .lists_modification_present_flag             = pps->lists_modification_present_flag,
193             .long_term_ref_pics_present_flag             = sps->long_term_ref_pics_present_flag,
194             .sps_temporal_mvp_enabled_flag               = sps->sps_temporal_mvp_enabled_flag,
195             .cabac_init_present_flag                     = pps->cabac_init_present_flag,
196             .output_flag_present_flag                    = pps->output_flag_present_flag,
197             .dependent_slice_segments_enabled_flag       = pps->dependent_slice_segments_enabled_flag,
198             .pps_slice_chroma_qp_offsets_present_flag    = pps->pic_slice_level_chroma_qp_offsets_present_flag,
199             .sample_adaptive_offset_enabled_flag         = sps->sao_enabled,
200             .deblocking_filter_override_enabled_flag     = pps->deblocking_filter_override_enabled_flag,
201             .pps_disable_deblocking_filter_flag          = pps->disable_dbf,
202             .slice_segment_header_extension_present_flag = pps->slice_header_extension_present_flag,
203             .RapPicFlag                                  = IS_IRAP(h),
204             .IdrPicFlag                                  = IS_IDR(h),
205             .IntraPicFlag                                = IS_IRAP(h),
206         },
207     };
208
209     fill_vaapi_pic(&pic_param->CurrPic, h->ref, 0);
210     fill_vaapi_reference_frames(h, pic_param);
211
212     if (pps->tiles_enabled_flag) {
213         pic_param->num_tile_columns_minus1 = pps->num_tile_columns - 1;
214         pic_param->num_tile_rows_minus1    = pps->num_tile_rows - 1;
215
216         for (i = 0; i < pps->num_tile_columns; i++)
217             pic_param->column_width_minus1[i] = pps->column_width[i] - 1;
218
219         for (i = 0; i < pps->num_tile_rows; i++)
220             pic_param->row_height_minus1[i] = pps->row_height[i] - 1;
221     }
222
223     if (h->sh.short_term_ref_pic_set_sps_flag == 0 && h->sh.short_term_rps) {
224         pic_param->st_rps_bits = h->sh.short_term_ref_pic_set_size;
225     } else {
226         pic_param->st_rps_bits = 0;
227     }
228
229 #if VA_CHECK_VERSION(1, 2, 0)
230     if (avctx->profile == AV_PROFILE_HEVC_REXT ||
231         avctx->profile == AV_PROFILE_HEVC_SCC) {
232         pic->pic_param.rext = (VAPictureParameterBufferHEVCRext) {
233             .range_extension_pic_fields.bits  = {
234                 .transform_skip_rotation_enabled_flag       = sps->transform_skip_rotation_enabled_flag,
235                 .transform_skip_context_enabled_flag        = sps->transform_skip_context_enabled_flag,
236                 .implicit_rdpcm_enabled_flag                = sps->implicit_rdpcm_enabled_flag,
237                 .explicit_rdpcm_enabled_flag                = sps->explicit_rdpcm_enabled_flag,
238                 .extended_precision_processing_flag         = sps->extended_precision_processing_flag,
239                 .intra_smoothing_disabled_flag              = sps->intra_smoothing_disabled_flag,
240                 .high_precision_offsets_enabled_flag        = sps->high_precision_offsets_enabled_flag,
241                 .persistent_rice_adaptation_enabled_flag    = sps->persistent_rice_adaptation_enabled_flag,
242                 .cabac_bypass_alignment_enabled_flag        = sps->cabac_bypass_alignment_enabled_flag,
243                 .cross_component_prediction_enabled_flag    = pps->cross_component_prediction_enabled_flag,
244                 .chroma_qp_offset_list_enabled_flag         = pps->chroma_qp_offset_list_enabled_flag,
245             },
246             .diff_cu_chroma_qp_offset_depth                 = pps->diff_cu_chroma_qp_offset_depth,
247             .chroma_qp_offset_list_len_minus1               = pps->chroma_qp_offset_list_len_minus1,
248             .log2_sao_offset_scale_luma                     = pps->log2_sao_offset_scale_luma,
249             .log2_sao_offset_scale_chroma                   = pps->log2_sao_offset_scale_chroma,
250             .log2_max_transform_skip_block_size_minus2      = pps->log2_max_transform_skip_block_size - 2,
251         };
252
253         for (i = 0; i < 6; i++)
254             pic->pic_param.rext.cb_qp_offset_list[i]        = pps->cb_qp_offset_list[i];
255         for (i = 0; i < 6; i++)
256             pic->pic_param.rext.cr_qp_offset_list[i]        = pps->cr_qp_offset_list[i];
257     }
258
259     pre_palette_size = pps->pps_palette_predictor_initializers_present_flag ?
260                        pps->pps_num_palette_predictor_initializers :
261                        (sps->sps_palette_predictor_initializers_present_flag ?
262                        sps->sps_num_palette_predictor_initializers :
263                        0);
264
265     if (avctx->profile == AV_PROFILE_HEVC_SCC) {
266         pic->pic_param.scc = (VAPictureParameterBufferHEVCScc) {
267             .screen_content_pic_fields.bits = {
268                 .pps_curr_pic_ref_enabled_flag              = pps->pps_curr_pic_ref_enabled_flag,
269                 .palette_mode_enabled_flag                  = sps->palette_mode_enabled_flag,
270                 .motion_vector_resolution_control_idc       = sps->motion_vector_resolution_control_idc,
271                 .intra_boundary_filtering_disabled_flag     = sps->intra_boundary_filtering_disabled_flag,
272                 .residual_adaptive_colour_transform_enabled_flag
273                                                             = pps->residual_adaptive_colour_transform_enabled_flag,
274                 .pps_slice_act_qp_offsets_present_flag      = pps->pps_slice_act_qp_offsets_present_flag,
275             },
276             .palette_max_size                               = sps->palette_max_size,
277             .delta_palette_max_predictor_size               = sps->delta_palette_max_predictor_size,
278             .predictor_palette_size                         = pre_palette_size,
279             .pps_act_y_qp_offset_plus5                      = pps->residual_adaptive_colour_transform_enabled_flag ?
280                                                               pps->pps_act_y_qp_offset + 5 : 0,
281             .pps_act_cb_qp_offset_plus5                     = pps->residual_adaptive_colour_transform_enabled_flag ?
282                                                               pps->pps_act_cb_qp_offset + 5 : 0,
283             .pps_act_cr_qp_offset_plus3                     = pps->residual_adaptive_colour_transform_enabled_flag ?
284                                                               pps->pps_act_cr_qp_offset + 3 : 0,
285         };
286
287         num_comps = pps->monochrome_palette_flag ? 1 : 3;
288         for (int comp = 0; comp < num_comps; comp++)
289             for (int j = 0; j < pre_palette_size; j++)
290                 pic->pic_param.scc.predictor_palette_entries[comp][j] =
291                     pps->pps_palette_predictor_initializers_present_flag ?
292                     pps->pps_palette_predictor_initializer[comp][j]:
293                     sps->sps_palette_predictor_initializer[comp][j];
294     }
295
296 #endif
297     pic_param_size = avctx->profile >= AV_PROFILE_HEVC_REXT ?
298                             sizeof(pic->pic_param) : sizeof(VAPictureParameterBufferHEVC);
299
300     err = ff_vaapi_decode_make_param_buffer(avctx, &pic->pic,
301                                             VAPictureParameterBufferType,
302                                             &pic->pic_param, pic_param_size);
303     if (err < 0)
304         goto fail;
305
306     if (pps->scaling_list_data_present_flag)
307         scaling_list = &pps->scaling_list;
308     else if (sps->scaling_list_enable_flag)
309         scaling_list = &sps->scaling_list;
310
311     if (scaling_list) {
312         VAIQMatrixBufferHEVC iq_matrix;
313         int j;
314
315         for (i = 0; i < 6; i++) {
316             for (j = 0; j < 16; j++)
317                 iq_matrix.ScalingList4x4[i][j] = scaling_list->sl[0][i][j];
318             for (j = 0; j < 64; j++) {
319                 iq_matrix.ScalingList8x8[i][j]   = scaling_list->sl[1][i][j];
320                 iq_matrix.ScalingList16x16[i][j] = scaling_list->sl[2][i][j];
321                 if (i < 2)
322                     iq_matrix.ScalingList32x32[i][j] = scaling_list->sl[3][i * 3][j];
323             }
324             iq_matrix.ScalingListDC16x16[i] = scaling_list->sl_dc[0][i];
325             if (i < 2)
326                 iq_matrix.ScalingListDC32x32[i] = scaling_list->sl_dc[1][i * 3];
327         }
328
329         err = ff_vaapi_decode_make_param_buffer(avctx, &pic->pic,
330                                                 VAIQMatrixBufferType,
331                                                 &iq_matrix, sizeof(iq_matrix));
332         if (err < 0)
333             goto fail;
334     }
335
336     return 0;
337
338 fail:
339     ff_vaapi_decode_cancel(avctx, &pic->pic);
340     return err;
341 }
342
343 static int vaapi_hevc_end_frame(AVCodecContext *avctx)
344 {
345     const HEVCContext        *h = avctx->priv_data;
346     VAAPIDecodePictureHEVC *pic = h->ref->hwaccel_picture_private;
347     VASliceParameterBufferHEVC *last_slice_param = (VASliceParameterBufferHEVC *)&pic->last_slice_param;
348     int ret;
349
350     int slice_param_size = avctx->profile >= AV_PROFILE_HEVC_REXT ?
351                             sizeof(pic->last_slice_param) : sizeof(VASliceParameterBufferHEVC);
352
353     if (pic->last_size) {
354         last_slice_param->LongSliceFlags.fields.LastSliceOfPic = 1;
355         ret = ff_vaapi_decode_make_slice_buffer(avctx, &pic->pic,
356                                                 &pic->last_slice_param, slice_param_size,
357                                                 pic->last_buffer, pic->last_size);
358         if (ret < 0)
359             goto fail;
360     }
361
362
363     ret = ff_vaapi_decode_issue(avctx, &pic->pic);
364     if (ret < 0)
365         goto fail;
366
367     return 0;
368 fail:
369     ff_vaapi_decode_cancel(avctx, &pic->pic);
370     return ret;
371 }
372
373 static void fill_pred_weight_table(AVCodecContext *avctx,
374                                    const HEVCContext *h,
375                                    const SliceHeader *sh,
376                                    VASliceParameterBufferHEVC *slice_param)
377 {
378     int i;
379 #if VA_CHECK_VERSION(1, 2, 0)
380     int is_rext = avctx->profile >= AV_PROFILE_HEVC_REXT;
381 #else
382     int is_rext = 0;
383     if (avctx->profile >= AV_PROFILE_HEVC_REXT)
384         av_log(avctx, AV_LOG_WARNING, "Please consider to update to VAAPI 1.2.0 "
385                "or above, which can support REXT related setting correctly.\n");
386 #endif
387
388     memset(slice_param->delta_luma_weight_l0,   0, sizeof(slice_param->delta_luma_weight_l0));
389     memset(slice_param->delta_luma_weight_l1,   0, sizeof(slice_param->delta_luma_weight_l1));
390     memset(slice_param->luma_offset_l0,         0, sizeof(slice_param->luma_offset_l0));
391     memset(slice_param->luma_offset_l1,         0, sizeof(slice_param->luma_offset_l1));
392     memset(slice_param->delta_chroma_weight_l0, 0, sizeof(slice_param->delta_chroma_weight_l0));
393     memset(slice_param->delta_chroma_weight_l1, 0, sizeof(slice_param->delta_chroma_weight_l1));
394     memset(slice_param->ChromaOffsetL0,         0, sizeof(slice_param->ChromaOffsetL0));
395     memset(slice_param->ChromaOffsetL1,         0, sizeof(slice_param->ChromaOffsetL1));
396
397     slice_param->delta_chroma_log2_weight_denom = 0;
398     slice_param->luma_log2_weight_denom         = 0;
399
400     if (sh->slice_type == HEVC_SLICE_I ||
401         (sh->slice_type == HEVC_SLICE_P && !h->ps.pps->weighted_pred_flag) ||
402         (sh->slice_type == HEVC_SLICE_B && !h->ps.pps->weighted_bipred_flag))
403         return;
404
405     slice_param->luma_log2_weight_denom = sh->luma_log2_weight_denom;
406
407     if (h->ps.sps->chroma_format_idc) {
408         slice_param->delta_chroma_log2_weight_denom = sh->chroma_log2_weight_denom - sh->luma_log2_weight_denom;
409     }
410
411     for (i = 0; i < 15 && i < sh->nb_refs[L0]; i++) {
412         slice_param->delta_luma_weight_l0[i] = sh->luma_weight_l0[i] - (1 << sh->luma_log2_weight_denom);
413         slice_param->delta_chroma_weight_l0[i][0] = sh->chroma_weight_l0[i][0] - (1 << sh->chroma_log2_weight_denom);
414         slice_param->delta_chroma_weight_l0[i][1] = sh->chroma_weight_l0[i][1] - (1 << sh->chroma_log2_weight_denom);
415         if (!is_rext) {
416             slice_param->luma_offset_l0[i] = sh->luma_offset_l0[i];
417             slice_param->ChromaOffsetL0[i][0] = sh->chroma_offset_l0[i][0];
418             slice_param->ChromaOffsetL0[i][1] = sh->chroma_offset_l0[i][1];
419         }
420     }
421
422     if (sh->slice_type == HEVC_SLICE_B) {
423         for (i = 0; i < 15 && i < sh->nb_refs[L1]; i++) {
424             slice_param->delta_luma_weight_l1[i] = sh->luma_weight_l1[i] - (1 << sh->luma_log2_weight_denom);
425             slice_param->delta_chroma_weight_l1[i][0] = sh->chroma_weight_l1[i][0] - (1 << sh->chroma_log2_weight_denom);
426             slice_param->delta_chroma_weight_l1[i][1] = sh->chroma_weight_l1[i][1] - (1 << sh->chroma_log2_weight_denom);
427             if (!is_rext) {
428                 slice_param->luma_offset_l1[i] = sh->luma_offset_l1[i];
429                 slice_param->ChromaOffsetL1[i][0] = sh->chroma_offset_l1[i][0];
430                 slice_param->ChromaOffsetL1[i][1] = sh->chroma_offset_l1[i][1];
431             }
432         }
433     }
434 }
435
436 static uint8_t get_ref_pic_index(const HEVCContext *h, const HEVCFrame *frame)
437 {
438     VAAPIDecodePictureHEVC *pic = h->ref->hwaccel_picture_private;
439     VAPictureParameterBufferHEVC *pp = (VAPictureParameterBufferHEVC *)&pic->pic_param;
440     uint8_t i;
441
442     if (!frame)
443         return 0xff;
444
445     for (i = 0; i < FF_ARRAY_ELEMS(pp->ReferenceFrames); i++) {
446         VASurfaceID pid = pp->ReferenceFrames[i].picture_id;
447         int poc = pp->ReferenceFrames[i].pic_order_cnt;
448         if (pid != VA_INVALID_ID && pid == ff_vaapi_get_surface_id(frame->frame) && poc == frame->poc)
449             return i;
450     }
451
452     return 0xff;
453 }
454
455 static int vaapi_hevc_decode_slice(AVCodecContext *avctx,
456                                    const uint8_t  *buffer,
457                                    uint32_t        size)
458 {
459     const HEVCContext        *h = avctx->priv_data;
460     const SliceHeader       *sh = &h->sh;
461     VAAPIDecodePictureHEVC *pic = h->ref->hwaccel_picture_private;
462     VASliceParameterBufferHEVC *last_slice_param = (VASliceParameterBufferHEVC *)&pic->last_slice_param;
463
464     int slice_param_size = avctx->profile >= AV_PROFILE_HEVC_REXT ?
465                             sizeof(pic->last_slice_param) : sizeof(VASliceParameterBufferHEVC);
466
467     int nb_list = (sh->slice_type == HEVC_SLICE_B) ?
468                   2 : (sh->slice_type == HEVC_SLICE_I ? 0 : 1);
469
470     int err, i, list_idx;
471
472     if (!sh->first_slice_in_pic_flag) {
473         err = ff_vaapi_decode_make_slice_buffer(avctx, &pic->pic,
474                                                 &pic->last_slice_param, slice_param_size,
475                                                 pic->last_buffer, pic->last_size);
476         pic->last_buffer = NULL;
477         pic->last_size   = 0;
478         if (err) {
479             ff_vaapi_decode_cancel(avctx, &pic->pic);
480             return err;
481         }
482     }
483
484     *last_slice_param = (VASliceParameterBufferHEVC) {
485         .slice_data_size               = size,
486         .slice_data_offset             = 0,
487         .slice_data_flag               = VA_SLICE_DATA_FLAG_ALL,
488         /* Add 1 to the bits count here to account for the byte_alignment bit, which
489          * always is at least one bit and not accounted for otherwise. */
490         .slice_data_byte_offset        = (get_bits_count(&h->HEVClc->gb) + 1 + 7) / 8,
491         .slice_segment_address         = sh->slice_segment_addr,
492         .slice_qp_delta                = sh->slice_qp_delta,
493         .slice_cb_qp_offset            = sh->slice_cb_qp_offset,
494         .slice_cr_qp_offset            = sh->slice_cr_qp_offset,
495         .slice_beta_offset_div2        = sh->beta_offset / 2,
496         .slice_tc_offset_div2          = sh->tc_offset / 2,
497         .collocated_ref_idx            = sh->slice_temporal_mvp_enabled_flag ? sh->collocated_ref_idx : 0xFF,
498         .five_minus_max_num_merge_cand = sh->slice_type == HEVC_SLICE_I ? 0 : 5 - sh->max_num_merge_cand,
499         .num_ref_idx_l0_active_minus1  = sh->nb_refs[L0] ? sh->nb_refs[L0] - 1 : 0,
500         .num_ref_idx_l1_active_minus1  = sh->nb_refs[L1] ? sh->nb_refs[L1] - 1 : 0,
501
502         .LongSliceFlags.fields = {
503             .dependent_slice_segment_flag                 = sh->dependent_slice_segment_flag,
504             .slice_type                                   = sh->slice_type,
505             .color_plane_id                               = sh->colour_plane_id,
506             .mvd_l1_zero_flag                             = sh->mvd_l1_zero_flag,
507             .cabac_init_flag                              = sh->cabac_init_flag,
508             .slice_temporal_mvp_enabled_flag              = sh->slice_temporal_mvp_enabled_flag,
509             .slice_deblocking_filter_disabled_flag        = sh->disable_deblocking_filter_flag,
510             .collocated_from_l0_flag                      = sh->collocated_list == L0 ? 1 : 0,
511             .slice_loop_filter_across_slices_enabled_flag = sh->slice_loop_filter_across_slices_enabled_flag,
512             .slice_sao_luma_flag                          = sh->slice_sample_adaptive_offset_flag[0],
513             .slice_sao_chroma_flag                        = sh->slice_sample_adaptive_offset_flag[1],
514         },
515     };
516
517     memset(last_slice_param->RefPicList, 0xFF, sizeof(last_slice_param->RefPicList));
518
519     for (list_idx = 0; list_idx < nb_list; list_idx++) {
520         RefPicList *rpl = &h->ref->refPicList[list_idx];
521
522         for (i = 0; i < rpl->nb_refs; i++)
523             last_slice_param->RefPicList[list_idx][i] = get_ref_pic_index(h, rpl->ref[i]);
524     }
525
526     fill_pred_weight_table(avctx, h, sh, last_slice_param);
527
528 #if VA_CHECK_VERSION(1, 2, 0)
529     if (avctx->profile >= AV_PROFILE_HEVC_REXT) {
530         pic->last_slice_param.rext = (VASliceParameterBufferHEVCRext) {
531             .slice_ext_flags.bits = {
532                 .cu_chroma_qp_offset_enabled_flag = sh->cu_chroma_qp_offset_enabled_flag,
533                 .use_integer_mv_flag = sh->use_integer_mv_flag,
534             },
535             .slice_act_y_qp_offset  = sh->slice_act_y_qp_offset,
536             .slice_act_cb_qp_offset = sh->slice_act_cb_qp_offset,
537             .slice_act_cr_qp_offset = sh->slice_act_cr_qp_offset,
538         };
539         for (i = 0; i < 15 && i < sh->nb_refs[L0]; i++) {
540             pic->last_slice_param.rext.luma_offset_l0[i] = sh->luma_offset_l0[i];
541             pic->last_slice_param.rext.ChromaOffsetL0[i][0] = sh->chroma_offset_l0[i][0];
542             pic->last_slice_param.rext.ChromaOffsetL0[i][1] = sh->chroma_offset_l0[i][1];
543         }
544
545         if (sh->slice_type == HEVC_SLICE_B) {
546             for (i = 0; i < 15 && i < sh->nb_refs[L1]; i++) {
547                 pic->last_slice_param.rext.luma_offset_l1[i] = sh->luma_offset_l1[i];
548                 pic->last_slice_param.rext.ChromaOffsetL1[i][0] = sh->chroma_offset_l1[i][0];
549                 pic->last_slice_param.rext.ChromaOffsetL1[i][1] = sh->chroma_offset_l1[i][1];
550             }
551         }
552     }
553 #endif
554
555     pic->last_buffer = buffer;
556     pic->last_size   = size;
557
558     return 0;
559 }
560
561 static int ptl_convert(const PTLCommon *general_ptl, H265RawProfileTierLevel *h265_raw_ptl)
562 {
563     h265_raw_ptl->general_profile_space = general_ptl->profile_space;
564     h265_raw_ptl->general_tier_flag     = general_ptl->tier_flag;
565     h265_raw_ptl->general_profile_idc   = general_ptl->profile_idc;
566
567     memcpy(h265_raw_ptl->general_profile_compatibility_flag,
568                                   general_ptl->profile_compatibility_flag, 32 * sizeof(uint8_t));
569
570 #define copy_field(name) h265_raw_ptl->general_ ## name = general_ptl->name
571     copy_field(progressive_source_flag);
572     copy_field(interlaced_source_flag);
573     copy_field(non_packed_constraint_flag);
574     copy_field(frame_only_constraint_flag);
575     copy_field(max_12bit_constraint_flag);
576     copy_field(max_10bit_constraint_flag);
577     copy_field(max_8bit_constraint_flag);
578     copy_field(max_422chroma_constraint_flag);
579     copy_field(max_420chroma_constraint_flag);
580     copy_field(max_monochrome_constraint_flag);
581     copy_field(intra_constraint_flag);
582     copy_field(one_picture_only_constraint_flag);
583     copy_field(lower_bit_rate_constraint_flag);
584     copy_field(max_14bit_constraint_flag);
585     copy_field(inbld_flag);
586     copy_field(level_idc);
587 #undef copy_field
588
589     return 0;
590 }
591
592 /*
593  * Find exact va_profile for HEVC Range Extension and Screen Content Coding Extension
594  */
595 VAProfile ff_vaapi_parse_hevc_rext_scc_profile(AVCodecContext *avctx)
596 {
597     const HEVCContext *h = avctx->priv_data;
598     const HEVCSPS *sps = h->ps.sps;
599     const PTL *ptl = &sps->ptl;
600     const PTLCommon *general_ptl = &ptl->general_ptl;
601     const H265ProfileDescriptor *profile;
602     H265RawProfileTierLevel h265_raw_ptl = {0};
603
604     /* convert PTLCommon to H265RawProfileTierLevel */
605     ptl_convert(general_ptl, &h265_raw_ptl);
606
607     profile = ff_h265_get_profile(&h265_raw_ptl);
608     if (!profile) {
609         av_log(avctx, AV_LOG_WARNING, "HEVC profile is not found.\n");
610         goto end;
611     } else {
612         av_log(avctx, AV_LOG_VERBOSE, "HEVC profile %s is found.\n", profile->name);
613     }
614
615 #if VA_CHECK_VERSION(1, 2, 0)
616     if (!strcmp(profile->name, "Main 12") ||
617         !strcmp(profile->name, "Main 12 Intra"))
618         return VAProfileHEVCMain12;
619     else if (!strcmp(profile->name, "Main 4:2:2 10") ||
620         !strcmp(profile->name, "Main 4:2:2 10 Intra"))
621         return VAProfileHEVCMain422_10;
622     else if (!strcmp(profile->name, "Main 4:2:2 12") ||
623         !strcmp(profile->name, "Main 4:2:2 12 Intra"))
624         return VAProfileHEVCMain422_12;
625     else if (!strcmp(profile->name, "Main 4:4:4") ||
626              !strcmp(profile->name, "Main 4:4:4 Intra"))
627         return VAProfileHEVCMain444;
628     else if (!strcmp(profile->name, "Main 4:4:4 10") ||
629              !strcmp(profile->name, "Main 4:4:4 10 Intra"))
630         return VAProfileHEVCMain444_10;
631     else if (!strcmp(profile->name, "Main 4:4:4 12") ||
632              !strcmp(profile->name, "Main 4:4:4 12 Intra"))
633         return VAProfileHEVCMain444_12;
634     else if (!strcmp(profile->name, "Screen-Extended Main"))
635         return VAProfileHEVCSccMain;
636     else if (!strcmp(profile->name, "Screen-Extended Main 10"))
637         return VAProfileHEVCSccMain10;
638     else if (!strcmp(profile->name, "Screen-Extended Main 4:4:4"))
639         return VAProfileHEVCSccMain444;
640 #if VA_CHECK_VERSION(1, 8, 0)
641     else if (!strcmp(profile->name, "Screen-Extended Main 4:4:4 10"))
642         return VAProfileHEVCSccMain444_10;
643 #endif
644 #else
645     av_log(avctx, AV_LOG_WARNING, "HEVC profile %s is "
646            "not supported with this VA version.\n", profile->name);
647 #endif
648
649 end:
650     if (avctx->hwaccel_flags & AV_HWACCEL_FLAG_ALLOW_PROFILE_MISMATCH) {
651         // Default to selecting Main profile if profile mismatch is allowed
652         return VAProfileHEVCMain;
653     } else
654         return VAProfileNone;
655 }
656
657 const FFHWAccel ff_hevc_vaapi_hwaccel = {
658     .p.name               = "hevc_vaapi",
659     .p.type               = AVMEDIA_TYPE_VIDEO,
660     .p.id                 = AV_CODEC_ID_HEVC,
661     .p.pix_fmt            = AV_PIX_FMT_VAAPI,
662     .start_frame          = vaapi_hevc_start_frame,
663     .end_frame            = vaapi_hevc_end_frame,
664     .decode_slice         = vaapi_hevc_decode_slice,
665     .frame_priv_data_size = sizeof(VAAPIDecodePictureHEVC),
666     .init                 = ff_vaapi_decode_init,
667     .uninit               = ff_vaapi_decode_uninit,
668     .frame_params         = ff_vaapi_common_frame_params,
669     .priv_data_size       = sizeof(VAAPIDecodeContext),
670     .caps_internal        = HWACCEL_CAP_ASYNC_SAFE,
671 };