avcodec/gsmdec_template: Fix runtime error: signed integer overflow: -22527 * 99113...
[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 "hevc.h"
28 #include "vaapi_decode.h"
29
30 typedef struct VAAPIDecodePictureHEVC {
31     VAPictureParameterBufferHEVC pic_param;
32     VASliceParameterBufferHEVC last_slice_param;
33     const uint8_t *last_buffer;
34     size_t         last_size;
35
36     VAAPIDecodePicture pic;
37 } VAAPIDecodePictureHEVC;
38
39 static void init_vaapi_pic(VAPictureHEVC *va_pic)
40 {
41     va_pic->picture_id    = VA_INVALID_ID;
42     va_pic->flags         = VA_PICTURE_HEVC_INVALID;
43     va_pic->pic_order_cnt = 0;
44 }
45
46 static void fill_vaapi_pic(VAPictureHEVC *va_pic, const HEVCFrame *pic, int rps_type)
47 {
48     va_pic->picture_id    = ff_vaapi_get_surface_id(pic->frame);
49     va_pic->pic_order_cnt = pic->poc;
50     va_pic->flags         = rps_type;
51
52     if (pic->flags & HEVC_FRAME_FLAG_LONG_REF)
53         va_pic->flags |= VA_PICTURE_HEVC_LONG_TERM_REFERENCE;
54
55     if (pic->frame->interlaced_frame) {
56         va_pic->flags |= VA_PICTURE_HEVC_FIELD_PIC;
57
58         if (!pic->frame->top_field_first)
59             va_pic->flags |= VA_PICTURE_HEVC_BOTTOM_FIELD;
60     }
61 }
62
63 static int find_frame_rps_type(const HEVCContext *h, const HEVCFrame *pic)
64 {
65     VASurfaceID pic_surf = ff_vaapi_get_surface_id(pic->frame);
66     int i;
67
68     for (i = 0; i < h->rps[ST_CURR_BEF].nb_refs; i++) {
69         if (pic_surf == ff_vaapi_get_surface_id(h->rps[ST_CURR_BEF].ref[i]->frame))
70             return VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE;
71     }
72
73     for (i = 0; i < h->rps[ST_CURR_AFT].nb_refs; i++) {
74         if (pic_surf == ff_vaapi_get_surface_id(h->rps[ST_CURR_AFT].ref[i]->frame))
75             return VA_PICTURE_HEVC_RPS_ST_CURR_AFTER;
76     }
77
78     for (i = 0; i < h->rps[LT_CURR].nb_refs; i++) {
79         if (pic_surf == ff_vaapi_get_surface_id(h->rps[LT_CURR].ref[i]->frame))
80             return VA_PICTURE_HEVC_RPS_LT_CURR;
81     }
82
83     return 0;
84 }
85
86 static void fill_vaapi_reference_frames(const HEVCContext *h, VAPictureParameterBufferHEVC *pp)
87 {
88     const HEVCFrame *current_picture = h->ref;
89     int i, j, rps_type;
90
91     for (i = 0, j = 0; i < FF_ARRAY_ELEMS(pp->ReferenceFrames); i++) {
92         const HEVCFrame *frame = NULL;
93
94         while (!frame && j < FF_ARRAY_ELEMS(h->DPB)) {
95             if (&h->DPB[j] != current_picture && (h->DPB[j].flags & (HEVC_FRAME_FLAG_LONG_REF | HEVC_FRAME_FLAG_SHORT_REF)))
96                 frame = &h->DPB[j];
97             j++;
98         }
99
100         init_vaapi_pic(&pp->ReferenceFrames[i]);
101
102         if (frame) {
103             rps_type = find_frame_rps_type(h, frame);
104             fill_vaapi_pic(&pp->ReferenceFrames[i], frame, rps_type);
105         }
106     }
107 }
108
109 static int vaapi_hevc_start_frame(AVCodecContext          *avctx,
110                                   av_unused const uint8_t *buffer,
111                                   av_unused uint32_t       size)
112 {
113     const HEVCContext        *h = avctx->priv_data;
114     VAAPIDecodePictureHEVC *pic = h->ref->hwaccel_picture_private;
115     const HEVCSPS          *sps = h->ps.sps;
116     const HEVCPPS          *pps = h->ps.pps;
117
118     const ScalingList *scaling_list = NULL;
119     int err, i;
120
121     pic->pic.output_surface = ff_vaapi_get_surface_id(h->ref->frame);
122
123     pic->pic_param = (VAPictureParameterBufferHEVC) {
124         .pic_fields.value                             = 0,
125         .slice_parsing_fields.value                   = 0,
126         .pic_width_in_luma_samples                    = sps->width,
127         .pic_height_in_luma_samples                   = sps->height,
128         .log2_min_luma_coding_block_size_minus3       = sps->log2_min_cb_size - 3,
129         .sps_max_dec_pic_buffering_minus1             = sps->temporal_layer[sps->max_sub_layers - 1].max_dec_pic_buffering - 1,
130         .log2_diff_max_min_luma_coding_block_size     = sps->log2_diff_max_min_coding_block_size,
131         .log2_min_transform_block_size_minus2         = sps->log2_min_tb_size - 2,
132         .log2_diff_max_min_transform_block_size       = sps->log2_max_trafo_size  - sps->log2_min_tb_size,
133         .max_transform_hierarchy_depth_inter          = sps->max_transform_hierarchy_depth_inter,
134         .max_transform_hierarchy_depth_intra          = sps->max_transform_hierarchy_depth_intra,
135         .num_short_term_ref_pic_sets                  = sps->nb_st_rps,
136         .num_long_term_ref_pic_sps                    = sps->num_long_term_ref_pics_sps,
137         .num_ref_idx_l0_default_active_minus1         = pps->num_ref_idx_l0_default_active - 1,
138         .num_ref_idx_l1_default_active_minus1         = pps->num_ref_idx_l1_default_active - 1,
139         .init_qp_minus26                              = pps->pic_init_qp_minus26,
140         .pps_cb_qp_offset                             = pps->cb_qp_offset,
141         .pps_cr_qp_offset                             = pps->cr_qp_offset,
142         .pcm_sample_bit_depth_luma_minus1             = sps->pcm.bit_depth - 1,
143         .pcm_sample_bit_depth_chroma_minus1           = sps->pcm.bit_depth_chroma - 1,
144         .log2_min_pcm_luma_coding_block_size_minus3   = sps->pcm.log2_min_pcm_cb_size - 3,
145         .log2_diff_max_min_pcm_luma_coding_block_size = sps->pcm.log2_max_pcm_cb_size - sps->pcm.log2_min_pcm_cb_size,
146         .diff_cu_qp_delta_depth                       = pps->diff_cu_qp_delta_depth,
147         .pps_beta_offset_div2                         = pps->beta_offset / 2,
148         .pps_tc_offset_div2                           = pps->tc_offset / 2,
149         .log2_parallel_merge_level_minus2             = pps->log2_parallel_merge_level - 2,
150         .bit_depth_luma_minus8                        = sps->bit_depth - 8,
151         .bit_depth_chroma_minus8                      = sps->bit_depth - 8,
152         .log2_max_pic_order_cnt_lsb_minus4            = sps->log2_max_poc_lsb - 4,
153         .num_extra_slice_header_bits                  = pps->num_extra_slice_header_bits,
154         .pic_fields.bits = {
155             .chroma_format_idc                          = sps->chroma_format_idc,
156             .tiles_enabled_flag                         = pps->tiles_enabled_flag,
157             .separate_colour_plane_flag                 = sps->separate_colour_plane_flag,
158             .pcm_enabled_flag                           = sps->pcm_enabled_flag,
159             .scaling_list_enabled_flag                  = sps->scaling_list_enable_flag,
160             .transform_skip_enabled_flag                = pps->transform_skip_enabled_flag,
161             .amp_enabled_flag                           = sps->amp_enabled_flag,
162             .strong_intra_smoothing_enabled_flag        = sps->sps_strong_intra_smoothing_enable_flag,
163             .sign_data_hiding_enabled_flag              = pps->sign_data_hiding_flag,
164             .constrained_intra_pred_flag                = pps->constrained_intra_pred_flag,
165             .cu_qp_delta_enabled_flag                   = pps->cu_qp_delta_enabled_flag,
166             .weighted_pred_flag                         = pps->weighted_pred_flag,
167             .weighted_bipred_flag                       = pps->weighted_bipred_flag,
168             .transquant_bypass_enabled_flag             = pps->transquant_bypass_enable_flag,
169             .entropy_coding_sync_enabled_flag           = pps->entropy_coding_sync_enabled_flag,
170             .pps_loop_filter_across_slices_enabled_flag = pps->seq_loop_filter_across_slices_enabled_flag,
171             .loop_filter_across_tiles_enabled_flag      = pps->loop_filter_across_tiles_enabled_flag,
172             .pcm_loop_filter_disabled_flag              = sps->pcm.loop_filter_disable_flag,
173         },
174         .slice_parsing_fields.bits = {
175             .lists_modification_present_flag             = pps->lists_modification_present_flag,
176             .long_term_ref_pics_present_flag             = sps->long_term_ref_pics_present_flag,
177             .sps_temporal_mvp_enabled_flag               = sps->sps_temporal_mvp_enabled_flag,
178             .cabac_init_present_flag                     = pps->cabac_init_present_flag,
179             .output_flag_present_flag                    = pps->output_flag_present_flag,
180             .dependent_slice_segments_enabled_flag       = pps->dependent_slice_segments_enabled_flag,
181             .pps_slice_chroma_qp_offsets_present_flag    = pps->pic_slice_level_chroma_qp_offsets_present_flag,
182             .sample_adaptive_offset_enabled_flag         = sps->sao_enabled,
183             .deblocking_filter_override_enabled_flag     = pps->deblocking_filter_override_enabled_flag,
184             .pps_disable_deblocking_filter_flag          = pps->disable_dbf,
185             .slice_segment_header_extension_present_flag = pps->slice_header_extension_present_flag,
186             .RapPicFlag                                  = IS_IRAP(h),
187             .IdrPicFlag                                  = IS_IDR(h),
188             .IntraPicFlag                                = IS_IRAP(h),
189         },
190     };
191
192     fill_vaapi_pic(&pic->pic_param.CurrPic, h->ref, 0);
193     fill_vaapi_reference_frames(h, &pic->pic_param);
194
195     if (pps->tiles_enabled_flag) {
196         pic->pic_param.num_tile_columns_minus1 = pps->num_tile_columns - 1;
197         pic->pic_param.num_tile_rows_minus1    = pps->num_tile_rows - 1;
198
199         for (i = 0; i < pps->num_tile_columns; i++)
200             pic->pic_param.column_width_minus1[i] = pps->column_width[i] - 1;
201
202         for (i = 0; i < pps->num_tile_rows; i++)
203             pic->pic_param.row_height_minus1[i] = pps->row_height[i] - 1;
204     }
205
206     if (h->sh.short_term_ref_pic_set_sps_flag == 0 && h->sh.short_term_rps) {
207         pic->pic_param.st_rps_bits = h->sh.short_term_ref_pic_set_size;
208     } else {
209         pic->pic_param.st_rps_bits = 0;
210     }
211
212     err = ff_vaapi_decode_make_param_buffer(avctx, &pic->pic,
213                                             VAPictureParameterBufferType,
214                                             &pic->pic_param, sizeof(pic->pic_param));
215     if (err < 0)
216         goto fail;
217
218     if (pps->scaling_list_data_present_flag)
219         scaling_list = &pps->scaling_list;
220     else if (sps->scaling_list_enable_flag)
221         scaling_list = &sps->scaling_list;
222
223     if (scaling_list) {
224         VAIQMatrixBufferHEVC iq_matrix;
225         int j;
226
227         for (i = 0; i < 6; i++) {
228             for (j = 0; j < 16; j++)
229                 iq_matrix.ScalingList4x4[i][j] = scaling_list->sl[0][i][j];
230             for (j = 0; j < 64; j++) {
231                 iq_matrix.ScalingList8x8[i][j]   = scaling_list->sl[1][i][j];
232                 iq_matrix.ScalingList16x16[i][j] = scaling_list->sl[2][i][j];
233                 if (i < 2)
234                     iq_matrix.ScalingList32x32[i][j] = scaling_list->sl[3][i * 3][j];
235             }
236             iq_matrix.ScalingListDC16x16[i] = scaling_list->sl_dc[0][i];
237             if (i < 2)
238                 iq_matrix.ScalingListDC32x32[i] = scaling_list->sl_dc[1][i * 3];
239         }
240
241         err = ff_vaapi_decode_make_param_buffer(avctx, &pic->pic,
242                                                 VAIQMatrixBufferType,
243                                                 &iq_matrix, sizeof(iq_matrix));
244         if (err < 0)
245             goto fail;
246     }
247
248     return 0;
249
250 fail:
251     ff_vaapi_decode_cancel(avctx, &pic->pic);
252     return err;
253 }
254
255 static int vaapi_hevc_end_frame(AVCodecContext *avctx)
256 {
257     const HEVCContext        *h = avctx->priv_data;
258     VAAPIDecodePictureHEVC *pic = h->ref->hwaccel_picture_private;
259     int ret;
260
261     if (pic->last_size) {
262         pic->last_slice_param.LongSliceFlags.fields.LastSliceOfPic = 1;
263         ret = ff_vaapi_decode_make_slice_buffer(avctx, &pic->pic,
264                                                 &pic->last_slice_param, sizeof(pic->last_slice_param),
265                                                 pic->last_buffer, pic->last_size);
266         if (ret < 0)
267             goto fail;
268     }
269
270
271     ret = ff_vaapi_decode_issue(avctx, &pic->pic);
272     if (ret < 0)
273         goto fail;
274
275     return 0;
276 fail:
277     ff_vaapi_decode_cancel(avctx, &pic->pic);
278     return ret;
279 }
280
281 static void fill_pred_weight_table(const HEVCContext *h,
282                                    const SliceHeader *sh,
283                                    VASliceParameterBufferHEVC *slice_param)
284 {
285     int i;
286
287     memset(slice_param->delta_luma_weight_l0,   0, sizeof(slice_param->delta_luma_weight_l0));
288     memset(slice_param->delta_luma_weight_l1,   0, sizeof(slice_param->delta_luma_weight_l1));
289     memset(slice_param->luma_offset_l0,         0, sizeof(slice_param->luma_offset_l0));
290     memset(slice_param->luma_offset_l1,         0, sizeof(slice_param->luma_offset_l1));
291     memset(slice_param->delta_chroma_weight_l0, 0, sizeof(slice_param->delta_chroma_weight_l0));
292     memset(slice_param->delta_chroma_weight_l1, 0, sizeof(slice_param->delta_chroma_weight_l1));
293     memset(slice_param->ChromaOffsetL0,         0, sizeof(slice_param->ChromaOffsetL0));
294     memset(slice_param->ChromaOffsetL1,         0, sizeof(slice_param->ChromaOffsetL1));
295
296     slice_param->delta_chroma_log2_weight_denom = 0;
297     slice_param->luma_log2_weight_denom         = 0;
298
299     if (sh->slice_type == I_SLICE ||
300         (sh->slice_type == P_SLICE && !h->ps.pps->weighted_pred_flag) ||
301         (sh->slice_type == B_SLICE && !h->ps.pps->weighted_bipred_flag))
302         return;
303
304     slice_param->luma_log2_weight_denom = sh->luma_log2_weight_denom;
305
306     if (h->ps.sps->chroma_format_idc) {
307         slice_param->delta_chroma_log2_weight_denom = sh->chroma_log2_weight_denom - sh->luma_log2_weight_denom;
308     }
309
310     for (i = 0; i < 15 && i < sh->nb_refs[L0]; i++) {
311         slice_param->delta_luma_weight_l0[i] = sh->luma_weight_l0[i] - (1 << sh->luma_log2_weight_denom);
312         slice_param->luma_offset_l0[i] = sh->luma_offset_l0[i];
313         slice_param->delta_chroma_weight_l0[i][0] = sh->chroma_weight_l0[i][0] - (1 << sh->chroma_log2_weight_denom);
314         slice_param->delta_chroma_weight_l0[i][1] = sh->chroma_weight_l0[i][1] - (1 << sh->chroma_log2_weight_denom);
315         slice_param->ChromaOffsetL0[i][0] = sh->chroma_offset_l0[i][0];
316         slice_param->ChromaOffsetL0[i][1] = sh->chroma_offset_l0[i][1];
317     }
318
319     if (sh->slice_type == B_SLICE) {
320         for (i = 0; i < 15 && i < sh->nb_refs[L1]; i++) {
321             slice_param->delta_luma_weight_l1[i] = sh->luma_weight_l1[i] - (1 << sh->luma_log2_weight_denom);
322             slice_param->luma_offset_l1[i] = sh->luma_offset_l1[i];
323             slice_param->delta_chroma_weight_l1[i][0] = sh->chroma_weight_l1[i][0] - (1 << sh->chroma_log2_weight_denom);
324             slice_param->delta_chroma_weight_l1[i][1] = sh->chroma_weight_l1[i][1] - (1 << sh->chroma_log2_weight_denom);
325             slice_param->ChromaOffsetL1[i][0] = sh->chroma_offset_l1[i][0];
326             slice_param->ChromaOffsetL1[i][1] = sh->chroma_offset_l1[i][1];
327         }
328     }
329 }
330
331 static uint8_t get_ref_pic_index(const HEVCContext *h, const HEVCFrame *frame)
332 {
333     VAAPIDecodePictureHEVC *pic = h->ref->hwaccel_picture_private;
334     VAPictureParameterBufferHEVC *pp = &pic->pic_param;
335     uint8_t i;
336
337     if (!frame)
338         return 0xff;
339
340     for (i = 0; i < FF_ARRAY_ELEMS(pp->ReferenceFrames); i++) {
341         VASurfaceID pid = pp->ReferenceFrames[i].picture_id;
342         int poc = pp->ReferenceFrames[i].pic_order_cnt;
343         if (pid != VA_INVALID_ID && pid == ff_vaapi_get_surface_id(frame->frame) && poc == frame->poc)
344             return i;
345     }
346
347     return 0xff;
348 }
349
350 static int vaapi_hevc_decode_slice(AVCodecContext *avctx,
351                                    const uint8_t  *buffer,
352                                    uint32_t        size)
353 {
354     const HEVCContext        *h = avctx->priv_data;
355     const SliceHeader       *sh = &h->sh;
356     VAAPIDecodePictureHEVC *pic = h->ref->hwaccel_picture_private;
357
358     int nb_list = (sh->slice_type == B_SLICE) ?
359                   2 : (sh->slice_type == I_SLICE ? 0 : 1);
360
361     int err, i, list_idx;
362
363     if (!sh->first_slice_in_pic_flag) {
364         err = ff_vaapi_decode_make_slice_buffer(avctx, &pic->pic,
365                                                 &pic->last_slice_param, sizeof(pic->last_slice_param),
366                                                 pic->last_buffer, pic->last_size);
367         pic->last_buffer = NULL;
368         pic->last_size   = 0;
369         if (err) {
370             ff_vaapi_decode_cancel(avctx, &pic->pic);
371             return err;
372         }
373     }
374
375     pic->last_slice_param = (VASliceParameterBufferHEVC) {
376         .slice_data_size               = size,
377         .slice_data_offset             = 0,
378         .slice_data_flag               = VA_SLICE_DATA_FLAG_ALL,
379         /* Add 1 to the bits count here to account for the byte_alignment bit, which
380          * always is at least one bit and not accounted for otherwise. */
381         .slice_data_byte_offset        = (get_bits_count(&h->HEVClc->gb) + 1 + 7) / 8,
382         .slice_segment_address         = sh->slice_segment_addr,
383         .slice_qp_delta                = sh->slice_qp_delta,
384         .slice_cb_qp_offset            = sh->slice_cb_qp_offset,
385         .slice_cr_qp_offset            = sh->slice_cr_qp_offset,
386         .slice_beta_offset_div2        = sh->beta_offset / 2,
387         .slice_tc_offset_div2          = sh->tc_offset / 2,
388         .collocated_ref_idx            = sh->slice_temporal_mvp_enabled_flag ? sh->collocated_ref_idx : 0xFF,
389         .five_minus_max_num_merge_cand = sh->slice_type == I_SLICE ? 0 : 5 - sh->max_num_merge_cand,
390         .num_ref_idx_l0_active_minus1  = sh->nb_refs[L0] ? sh->nb_refs[L0] - 1 : 0,
391         .num_ref_idx_l1_active_minus1  = sh->nb_refs[L1] ? sh->nb_refs[L1] - 1 : 0,
392
393         .LongSliceFlags.fields = {
394             .dependent_slice_segment_flag                 = sh->dependent_slice_segment_flag,
395             .slice_type                                   = sh->slice_type,
396             .color_plane_id                               = sh->colour_plane_id,
397             .mvd_l1_zero_flag                             = sh->mvd_l1_zero_flag,
398             .cabac_init_flag                              = sh->cabac_init_flag,
399             .slice_temporal_mvp_enabled_flag              = sh->slice_temporal_mvp_enabled_flag,
400             .slice_deblocking_filter_disabled_flag        = sh->disable_deblocking_filter_flag,
401             .collocated_from_l0_flag                      = sh->collocated_list == L0 ? 1 : 0,
402             .slice_loop_filter_across_slices_enabled_flag = sh->slice_loop_filter_across_slices_enabled_flag,
403             .slice_sao_luma_flag                          = sh->slice_sample_adaptive_offset_flag[0],
404             .slice_sao_chroma_flag                        = sh->slice_sample_adaptive_offset_flag[1],
405         },
406     };
407
408     memset(pic->last_slice_param.RefPicList, 0xFF, sizeof(pic->last_slice_param.RefPicList));
409
410     for (list_idx = 0; list_idx < nb_list; list_idx++) {
411         RefPicList *rpl = &h->ref->refPicList[list_idx];
412
413         for (i = 0; i < rpl->nb_refs; i++)
414             pic->last_slice_param.RefPicList[list_idx][i] = get_ref_pic_index(h, rpl->ref[i]);
415     }
416
417     fill_pred_weight_table(h, sh, &pic->last_slice_param);
418
419     pic->last_buffer = buffer;
420     pic->last_size   = size;
421
422     return 0;
423 }
424
425 AVHWAccel ff_hevc_vaapi_hwaccel = {
426     .name                 = "hevc_vaapi",
427     .type                 = AVMEDIA_TYPE_VIDEO,
428     .id                   = AV_CODEC_ID_HEVC,
429     .pix_fmt              = AV_PIX_FMT_VAAPI,
430     .start_frame          = vaapi_hevc_start_frame,
431     .end_frame            = vaapi_hevc_end_frame,
432     .decode_slice         = vaapi_hevc_decode_slice,
433     .frame_priv_data_size = sizeof(VAAPIDecodePictureHEVC),
434     .init                 = ff_vaapi_decode_init,
435     .uninit               = ff_vaapi_decode_uninit,
436     .priv_data_size       = sizeof(VAAPIDecodeContext),
437 };