vaapi_encode: Add common options between all encoders
[ffmpeg.git] / libavcodec / vaapi_encode_h265.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <string.h>
20
21 #include <va/va.h>
22 #include <va/va_enc_hevc.h>
23
24 #include "libavutil/avassert.h"
25 #include "libavutil/common.h"
26 #include "libavutil/opt.h"
27 #include "libavutil/mastering_display_metadata.h"
28
29 #include "avcodec.h"
30 #include "cbs.h"
31 #include "cbs_h265.h"
32 #include "hevc.h"
33 #include "hevc_sei.h"
34 #include "internal.h"
35 #include "put_bits.h"
36 #include "vaapi_encode.h"
37
38 enum {
39     SEI_MASTERING_DISPLAY       = 0x08,
40     SEI_CONTENT_LIGHT_LEVEL     = 0x10,
41 };
42
43 typedef struct VAAPIEncodeH265Context {
44     VAAPIEncodeContext common;
45
46     // User options.
47     int qp;
48     int aud;
49     int profile;
50     int level;
51     int sei;
52
53     // Derived settings.
54     unsigned int ctu_width;
55     unsigned int ctu_height;
56
57     int fixed_qp_idr;
58     int fixed_qp_p;
59     int fixed_qp_b;
60
61     // Stream state.
62     int64_t last_idr_frame;
63     int pic_order_cnt;
64
65     int slice_nal_unit;
66     int slice_type;
67     int pic_type;
68
69     // Writer structures.
70     H265RawAUD   raw_aud;
71     H265RawVPS   raw_vps;
72     H265RawSPS   raw_sps;
73     H265RawPPS   raw_pps;
74     H265RawSEI   raw_sei;
75     H265RawSlice raw_slice;
76
77     H265RawSEIMasteringDisplayColourVolume sei_mastering_display;
78     H265RawSEIContentLightLevelInfo        sei_content_light_level;
79
80     CodedBitstreamContext *cbc;
81     CodedBitstreamFragment current_access_unit;
82     int aud_needed;
83     int sei_needed;
84 } VAAPIEncodeH265Context;
85
86
87 static int vaapi_encode_h265_write_access_unit(AVCodecContext *avctx,
88                                                char *data, size_t *data_len,
89                                                CodedBitstreamFragment *au)
90 {
91     VAAPIEncodeH265Context *priv = avctx->priv_data;
92     int err;
93
94     err = ff_cbs_write_fragment_data(priv->cbc, au);
95     if (err < 0) {
96         av_log(avctx, AV_LOG_ERROR, "Failed to write packed header.\n");
97         return err;
98     }
99
100     if (*data_len < 8 * au->data_size - au->data_bit_padding) {
101         av_log(avctx, AV_LOG_ERROR, "Access unit too large: "
102                "%zu < %zu.\n", *data_len,
103                8 * au->data_size - au->data_bit_padding);
104         return AVERROR(ENOSPC);
105     }
106
107     memcpy(data, au->data, au->data_size);
108     *data_len = 8 * au->data_size - au->data_bit_padding;
109
110     return 0;
111 }
112
113 static int vaapi_encode_h265_add_nal(AVCodecContext *avctx,
114                                      CodedBitstreamFragment *au,
115                                      void *nal_unit)
116 {
117     VAAPIEncodeH265Context *priv = avctx->priv_data;
118     H265RawNALUnitHeader *header = nal_unit;
119     int err;
120
121     err = ff_cbs_insert_unit_content(priv->cbc, au, -1,
122                                      header->nal_unit_type, nal_unit, NULL);
123     if (err < 0) {
124         av_log(avctx, AV_LOG_ERROR, "Failed to add NAL unit: "
125                "type = %d.\n", header->nal_unit_type);
126         return err;
127     }
128
129     return 0;
130 }
131
132 static int vaapi_encode_h265_write_sequence_header(AVCodecContext *avctx,
133                                                    char *data, size_t *data_len)
134 {
135     VAAPIEncodeH265Context *priv = avctx->priv_data;
136     CodedBitstreamFragment   *au = &priv->current_access_unit;
137     int err;
138
139     if (priv->aud_needed) {
140         err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_aud);
141         if (err < 0)
142             goto fail;
143         priv->aud_needed = 0;
144     }
145
146     err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_vps);
147     if (err < 0)
148         goto fail;
149
150     err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_sps);
151     if (err < 0)
152         goto fail;
153
154     err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_pps);
155     if (err < 0)
156         goto fail;
157
158     err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
159 fail:
160     ff_cbs_fragment_uninit(priv->cbc, au);
161     return err;
162 }
163
164 static int vaapi_encode_h265_write_slice_header(AVCodecContext *avctx,
165                                                 VAAPIEncodePicture *pic,
166                                                 VAAPIEncodeSlice *slice,
167                                                 char *data, size_t *data_len)
168 {
169     VAAPIEncodeH265Context *priv = avctx->priv_data;
170     CodedBitstreamFragment   *au = &priv->current_access_unit;
171     int err;
172
173     if (priv->aud_needed) {
174         err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_aud);
175         if (err < 0)
176             goto fail;
177         priv->aud_needed = 0;
178     }
179
180     err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_slice);
181     if (err < 0)
182         goto fail;
183
184     err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
185 fail:
186     ff_cbs_fragment_uninit(priv->cbc, au);
187     return err;
188 }
189
190 static int vaapi_encode_h265_write_extra_header(AVCodecContext *avctx,
191                                                 VAAPIEncodePicture *pic,
192                                                 int index, int *type,
193                                                 char *data, size_t *data_len)
194 {
195     VAAPIEncodeH265Context *priv = avctx->priv_data;
196     CodedBitstreamFragment   *au = &priv->current_access_unit;
197     int err, i;
198
199     if (priv->sei_needed) {
200         H265RawSEI *sei = &priv->raw_sei;
201
202         if (priv->aud_needed) {
203             err = vaapi_encode_h265_add_nal(avctx, au, &priv->aud);
204             if (err < 0)
205                 goto fail;
206             priv->aud_needed = 0;
207         }
208
209         *sei = (H265RawSEI) {
210             .nal_unit_header = {
211                 .nal_unit_type         = HEVC_NAL_SEI_PREFIX,
212                 .nuh_layer_id          = 0,
213                 .nuh_temporal_id_plus1 = 1,
214             },
215         };
216
217         i = 0;
218
219         if (priv->sei_needed & SEI_MASTERING_DISPLAY) {
220             sei->payload[i].payload_type = HEVC_SEI_TYPE_MASTERING_DISPLAY_INFO;
221             sei->payload[i].payload.mastering_display = priv->sei_mastering_display;
222             ++i;
223         }
224
225         if (priv->sei_needed & SEI_CONTENT_LIGHT_LEVEL) {
226             sei->payload[i].payload_type = HEVC_SEI_TYPE_CONTENT_LIGHT_LEVEL_INFO;
227             sei->payload[i].payload.content_light_level = priv->sei_content_light_level;
228             ++i;
229         }
230
231         sei->payload_count = i;
232         av_assert0(sei->payload_count > 0);
233
234         err = vaapi_encode_h265_add_nal(avctx, au, sei);
235         if (err < 0)
236             goto fail;
237         priv->sei_needed = 0;
238
239         err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
240         if (err < 0)
241             goto fail;
242
243         ff_cbs_fragment_uninit(priv->cbc, au);
244
245         *type = VAEncPackedHeaderRawData;
246         return 0;
247     } else {
248         return AVERROR_EOF;
249     }
250
251 fail:
252     ff_cbs_fragment_uninit(priv->cbc, au);
253     return err;
254 }
255
256 static int vaapi_encode_h265_init_sequence_params(AVCodecContext *avctx)
257 {
258     VAAPIEncodeContext                *ctx = avctx->priv_data;
259     VAAPIEncodeH265Context           *priv = avctx->priv_data;
260     H265RawVPS                        *vps = &priv->raw_vps;
261     H265RawSPS                        *sps = &priv->raw_sps;
262     H265RawPPS                        *pps = &priv->raw_pps;
263     H265RawVUI                        *vui = &sps->vui;
264     VAEncSequenceParameterBufferHEVC *vseq = ctx->codec_sequence_params;
265     VAEncPictureParameterBufferHEVC  *vpic = ctx->codec_picture_params;
266     int i;
267
268     memset(&priv->current_access_unit, 0,
269            sizeof(priv->current_access_unit));
270
271     memset(vps, 0, sizeof(*vps));
272     memset(sps, 0, sizeof(*sps));
273     memset(pps, 0, sizeof(*pps));
274
275
276     // VPS
277
278     vps->nal_unit_header = (H265RawNALUnitHeader) {
279         .nal_unit_type         = HEVC_NAL_VPS,
280         .nuh_layer_id          = 0,
281         .nuh_temporal_id_plus1 = 1,
282     };
283
284     vps->vps_video_parameter_set_id = 0;
285
286     vps->vps_base_layer_internal_flag  = 1;
287     vps->vps_base_layer_available_flag = 1;
288     vps->vps_max_layers_minus1         = 0;
289     vps->vps_max_sub_layers_minus1     = 0;
290     vps->vps_temporal_id_nesting_flag  = 1;
291
292     vps->profile_tier_level = (H265RawProfileTierLevel) {
293         .general_profile_space = 0,
294         .general_profile_idc   = avctx->profile,
295         .general_tier_flag     = 0,
296
297         .general_progressive_source_flag    = 1,
298         .general_interlaced_source_flag     = 0,
299         .general_non_packed_constraint_flag = 1,
300         .general_frame_only_constraint_flag = 1,
301
302         .general_level_idc     = avctx->level,
303     };
304     vps->profile_tier_level.general_profile_compatibility_flag[avctx->profile & 31] = 1;
305
306     vps->vps_sub_layer_ordering_info_present_flag = 0;
307     vps->vps_max_dec_pic_buffering_minus1[0]      = (ctx->b_per_p > 0) + 1;
308     vps->vps_max_num_reorder_pics[0]              = (ctx->b_per_p > 0);
309     vps->vps_max_latency_increase_plus1[0]        = 0;
310
311     vps->vps_max_layer_id             = 0;
312     vps->vps_num_layer_sets_minus1    = 0;
313     vps->layer_id_included_flag[0][0] = 1;
314
315     vps->vps_timing_info_present_flag = 1;
316     if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
317         vps->vps_num_units_in_tick  = avctx->framerate.den;
318         vps->vps_time_scale         = avctx->framerate.num;
319         vps->vps_poc_proportional_to_timing_flag = 1;
320         vps->vps_num_ticks_poc_diff_one_minus1   = 0;
321     } else {
322         vps->vps_num_units_in_tick  = avctx->time_base.num;
323         vps->vps_time_scale         = avctx->time_base.den;
324         vps->vps_poc_proportional_to_timing_flag = 0;
325     }
326     vps->vps_num_hrd_parameters = 0;
327
328
329     // SPS
330
331     sps->nal_unit_header = (H265RawNALUnitHeader) {
332         .nal_unit_type         = HEVC_NAL_SPS,
333         .nuh_layer_id          = 0,
334         .nuh_temporal_id_plus1 = 1,
335     };
336
337     sps->sps_video_parameter_set_id = vps->vps_video_parameter_set_id;
338
339     sps->sps_max_sub_layers_minus1    = vps->vps_max_sub_layers_minus1;
340     sps->sps_temporal_id_nesting_flag = vps->vps_temporal_id_nesting_flag;
341
342     sps->profile_tier_level = vps->profile_tier_level;
343
344     sps->sps_seq_parameter_set_id = 0;
345
346     sps->chroma_format_idc          = 1; // YUV 4:2:0.
347     sps->separate_colour_plane_flag = 0;
348
349     sps->pic_width_in_luma_samples  = ctx->surface_width;
350     sps->pic_height_in_luma_samples = ctx->surface_height;
351
352     if (avctx->width  != ctx->surface_width ||
353         avctx->height != ctx->surface_height) {
354         sps->conformance_window_flag = 1;
355         sps->conf_win_left_offset   = 0;
356         sps->conf_win_right_offset  =
357             (ctx->surface_width - avctx->width) / 2;
358         sps->conf_win_top_offset    = 0;
359         sps->conf_win_bottom_offset =
360             (ctx->surface_height - avctx->height) / 2;
361     } else {
362         sps->conformance_window_flag = 0;
363     }
364
365     sps->bit_depth_luma_minus8 =
366         avctx->profile == FF_PROFILE_HEVC_MAIN_10 ? 2 : 0;
367     sps->bit_depth_chroma_minus8 = sps->bit_depth_luma_minus8;
368
369     sps->log2_max_pic_order_cnt_lsb_minus4 = 8;
370
371     sps->sps_sub_layer_ordering_info_present_flag =
372         vps->vps_sub_layer_ordering_info_present_flag;
373     for (i = 0; i <= sps->sps_max_sub_layers_minus1; i++) {
374         sps->sps_max_dec_pic_buffering_minus1[i] =
375             vps->vps_max_dec_pic_buffering_minus1[i];
376         sps->sps_max_num_reorder_pics[i] =
377             vps->vps_max_num_reorder_pics[i];
378         sps->sps_max_latency_increase_plus1[i] =
379             vps->vps_max_latency_increase_plus1[i];
380     }
381
382     // These have to come from the capabilities of the encoder.  We have no
383     // way to query them, so just hardcode parameters which work on the Intel
384     // driver.
385     // CTB size from 8x8 to 32x32.
386     sps->log2_min_luma_coding_block_size_minus3   = 0;
387     sps->log2_diff_max_min_luma_coding_block_size = 2;
388     // Transform size from 4x4 to 32x32.
389     sps->log2_min_luma_transform_block_size_minus2   = 0;
390     sps->log2_diff_max_min_luma_transform_block_size = 3;
391     // Full transform hierarchy allowed (2-5).
392     sps->max_transform_hierarchy_depth_inter = 3;
393     sps->max_transform_hierarchy_depth_intra = 3;
394     // AMP works.
395     sps->amp_enabled_flag = 1;
396     // SAO and temporal MVP do not work.
397     sps->sample_adaptive_offset_enabled_flag = 0;
398     sps->sps_temporal_mvp_enabled_flag       = 0;
399
400     sps->pcm_enabled_flag = 0;
401
402     // STRPSs should ideally be here rather than defined individually in
403     // each slice, but the structure isn't completely fixed so for now
404     // don't bother.
405     sps->num_short_term_ref_pic_sets     = 0;
406     sps->long_term_ref_pics_present_flag = 0;
407
408     sps->vui_parameters_present_flag = 1;
409
410     if (avctx->sample_aspect_ratio.num != 0 &&
411         avctx->sample_aspect_ratio.den != 0) {
412         static const AVRational sar_idc[] = {
413             {   0,  0 },
414             {   1,  1 }, {  12, 11 }, {  10, 11 }, {  16, 11 },
415             {  40, 33 }, {  24, 11 }, {  20, 11 }, {  32, 11 },
416             {  80, 33 }, {  18, 11 }, {  15, 11 }, {  64, 33 },
417             { 160, 99 }, {   4,  3 }, {   3,  2 }, {   2,  1 },
418         };
419         int i;
420         for (i = 0; i < FF_ARRAY_ELEMS(sar_idc); i++) {
421             if (avctx->sample_aspect_ratio.num == sar_idc[i].num &&
422                 avctx->sample_aspect_ratio.den == sar_idc[i].den) {
423                 vui->aspect_ratio_idc = i;
424                 break;
425             }
426         }
427         if (i >= FF_ARRAY_ELEMS(sar_idc)) {
428             vui->aspect_ratio_idc = 255;
429             vui->sar_width  = avctx->sample_aspect_ratio.num;
430             vui->sar_height = avctx->sample_aspect_ratio.den;
431         }
432         vui->aspect_ratio_info_present_flag = 1;
433     }
434
435     if (avctx->color_range     != AVCOL_RANGE_UNSPECIFIED ||
436         avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
437         avctx->color_trc       != AVCOL_TRC_UNSPECIFIED ||
438         avctx->colorspace      != AVCOL_SPC_UNSPECIFIED) {
439         vui->video_signal_type_present_flag = 1;
440         vui->video_format      = 5; // Unspecified.
441         vui->video_full_range_flag =
442             avctx->color_range == AVCOL_RANGE_JPEG;
443
444         if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
445             avctx->color_trc       != AVCOL_TRC_UNSPECIFIED ||
446             avctx->colorspace      != AVCOL_SPC_UNSPECIFIED) {
447             vui->colour_description_present_flag = 1;
448             vui->colour_primaries         = avctx->color_primaries;
449             vui->transfer_characteristics = avctx->color_trc;
450             vui->matrix_coefficients      = avctx->colorspace;
451         }
452     } else {
453         vui->video_format             = 5;
454         vui->video_full_range_flag    = 0;
455         vui->colour_primaries         = avctx->color_primaries;
456         vui->transfer_characteristics = avctx->color_trc;
457         vui->matrix_coefficients      = avctx->colorspace;
458     }
459
460     if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
461         vui->chroma_loc_info_present_flag = 1;
462         vui->chroma_sample_loc_type_top_field    =
463         vui->chroma_sample_loc_type_bottom_field =
464             avctx->chroma_sample_location - 1;
465     }
466
467     vui->vui_timing_info_present_flag        = 1;
468     vui->vui_num_units_in_tick               = vps->vps_num_units_in_tick;
469     vui->vui_time_scale                      = vps->vps_time_scale;
470     vui->vui_poc_proportional_to_timing_flag = vps->vps_poc_proportional_to_timing_flag;
471     vui->vui_num_ticks_poc_diff_one_minus1   = vps->vps_num_ticks_poc_diff_one_minus1;
472     vui->vui_hrd_parameters_present_flag     = 0;
473
474     vui->bitstream_restriction_flag    = 1;
475     vui->motion_vectors_over_pic_boundaries_flag = 1;
476     vui->restricted_ref_pic_lists_flag = 1;
477     vui->max_bytes_per_pic_denom       = 0;
478     vui->max_bits_per_min_cu_denom     = 0;
479     vui->log2_max_mv_length_horizontal = 15;
480     vui->log2_max_mv_length_vertical   = 15;
481
482
483     // PPS
484
485     pps->nal_unit_header = (H265RawNALUnitHeader) {
486         .nal_unit_type         = HEVC_NAL_PPS,
487         .nuh_layer_id          = 0,
488         .nuh_temporal_id_plus1 = 1,
489     };
490
491     pps->pps_pic_parameter_set_id = 0;
492     pps->pps_seq_parameter_set_id = sps->sps_seq_parameter_set_id;
493
494     pps->num_ref_idx_l0_default_active_minus1 = 0;
495     pps->num_ref_idx_l1_default_active_minus1 = 0;
496
497     pps->init_qp_minus26 = priv->fixed_qp_idr - 26;
498
499     pps->cu_qp_delta_enabled_flag = (ctx->va_rc_mode != VA_RC_CQP);
500     pps->diff_cu_qp_delta_depth   = 0;
501
502     pps->pps_loop_filter_across_slices_enabled_flag = 1;
503
504
505     // Fill VAAPI parameter buffers.
506
507     *vseq = (VAEncSequenceParameterBufferHEVC) {
508         .general_profile_idc = vps->profile_tier_level.general_profile_idc,
509         .general_level_idc   = vps->profile_tier_level.general_level_idc,
510         .general_tier_flag   = vps->profile_tier_level.general_tier_flag,
511
512         .intra_period     = avctx->gop_size,
513         .intra_idr_period = avctx->gop_size,
514         .ip_period        = ctx->b_per_p + 1,
515         .bits_per_second   = avctx->bit_rate,
516
517         .pic_width_in_luma_samples  = sps->pic_width_in_luma_samples,
518         .pic_height_in_luma_samples = sps->pic_height_in_luma_samples,
519
520         .seq_fields.bits = {
521             .chroma_format_idc             = sps->chroma_format_idc,
522             .separate_colour_plane_flag    = sps->separate_colour_plane_flag,
523             .bit_depth_luma_minus8         = sps->bit_depth_luma_minus8,
524             .bit_depth_chroma_minus8       = sps->bit_depth_chroma_minus8,
525             .scaling_list_enabled_flag     = sps->scaling_list_enabled_flag,
526             .strong_intra_smoothing_enabled_flag =
527                 sps->strong_intra_smoothing_enabled_flag,
528             .amp_enabled_flag              = sps->amp_enabled_flag,
529             .sample_adaptive_offset_enabled_flag =
530                 sps->sample_adaptive_offset_enabled_flag,
531             .pcm_enabled_flag              = sps->pcm_enabled_flag,
532             .pcm_loop_filter_disabled_flag = sps->pcm_loop_filter_disabled_flag,
533             .sps_temporal_mvp_enabled_flag = sps->sps_temporal_mvp_enabled_flag,
534         },
535
536         .log2_min_luma_coding_block_size_minus3 =
537             sps->log2_min_luma_coding_block_size_minus3,
538         .log2_diff_max_min_luma_coding_block_size =
539             sps->log2_diff_max_min_luma_coding_block_size,
540         .log2_min_transform_block_size_minus2 =
541             sps->log2_min_luma_transform_block_size_minus2,
542         .log2_diff_max_min_transform_block_size =
543             sps->log2_diff_max_min_luma_transform_block_size,
544         .max_transform_hierarchy_depth_inter =
545             sps->max_transform_hierarchy_depth_inter,
546         .max_transform_hierarchy_depth_intra =
547             sps->max_transform_hierarchy_depth_intra,
548
549         .pcm_sample_bit_depth_luma_minus1 =
550             sps->pcm_sample_bit_depth_luma_minus1,
551         .pcm_sample_bit_depth_chroma_minus1 =
552             sps->pcm_sample_bit_depth_chroma_minus1,
553         .log2_min_pcm_luma_coding_block_size_minus3 =
554             sps->log2_min_pcm_luma_coding_block_size_minus3,
555         .log2_max_pcm_luma_coding_block_size_minus3 =
556             sps->log2_min_pcm_luma_coding_block_size_minus3 +
557             sps->log2_diff_max_min_pcm_luma_coding_block_size,
558
559         .vui_parameters_present_flag = 0,
560     };
561
562     *vpic = (VAEncPictureParameterBufferHEVC) {
563         .decoded_curr_pic = {
564             .picture_id = VA_INVALID_ID,
565             .flags      = VA_PICTURE_HEVC_INVALID,
566         },
567
568         .coded_buf = VA_INVALID_ID,
569
570         .collocated_ref_pic_index = 0xff,
571
572         .last_picture = 0,
573
574         .pic_init_qp            = pps->init_qp_minus26 + 26,
575         .diff_cu_qp_delta_depth = pps->diff_cu_qp_delta_depth,
576         .pps_cb_qp_offset       = pps->pps_cb_qp_offset,
577         .pps_cr_qp_offset       = pps->pps_cr_qp_offset,
578
579         .num_tile_columns_minus1 = pps->num_tile_columns_minus1,
580         .num_tile_rows_minus1    = pps->num_tile_rows_minus1,
581
582         .log2_parallel_merge_level_minus2 = pps->log2_parallel_merge_level_minus2,
583         .ctu_max_bitsize_allowed          = 0,
584
585         .num_ref_idx_l0_default_active_minus1 =
586             pps->num_ref_idx_l0_default_active_minus1,
587         .num_ref_idx_l1_default_active_minus1 =
588             pps->num_ref_idx_l1_default_active_minus1,
589
590         .slice_pic_parameter_set_id = pps->pps_pic_parameter_set_id,
591
592         .pic_fields.bits = {
593             .sign_data_hiding_enabled_flag  = pps->sign_data_hiding_enabled_flag,
594             .constrained_intra_pred_flag    = pps->constrained_intra_pred_flag,
595             .transform_skip_enabled_flag    = pps->transform_skip_enabled_flag,
596             .cu_qp_delta_enabled_flag       = pps->cu_qp_delta_enabled_flag,
597             .weighted_pred_flag             = pps->weighted_pred_flag,
598             .weighted_bipred_flag           = pps->weighted_bipred_flag,
599             .transquant_bypass_enabled_flag = pps->transquant_bypass_enabled_flag,
600             .tiles_enabled_flag             = pps->tiles_enabled_flag,
601             .entropy_coding_sync_enabled_flag = pps->entropy_coding_sync_enabled_flag,
602             .loop_filter_across_tiles_enabled_flag =
603                 pps->loop_filter_across_tiles_enabled_flag,
604             .scaling_list_data_present_flag = (sps->sps_scaling_list_data_present_flag |
605                                                pps->pps_scaling_list_data_present_flag),
606             .screen_content_flag            = 0,
607             .enable_gpu_weighted_prediction = 0,
608             .no_output_of_prior_pics_flag   = 0,
609         },
610     };
611
612     return 0;
613 }
614
615 static int vaapi_encode_h265_init_picture_params(AVCodecContext *avctx,
616                                                  VAAPIEncodePicture *pic)
617 {
618     VAAPIEncodeH265Context          *priv = avctx->priv_data;
619     VAEncPictureParameterBufferHEVC *vpic = pic->codec_picture_params;
620     int i;
621
622     if (pic->type == PICTURE_TYPE_IDR) {
623         av_assert0(pic->display_order == pic->encode_order);
624
625         priv->last_idr_frame = pic->display_order;
626
627         priv->slice_nal_unit = HEVC_NAL_IDR_W_RADL;
628         priv->slice_type     = HEVC_SLICE_I;
629         priv->pic_type       = 0;
630     } else {
631         av_assert0(pic->encode_order > priv->last_idr_frame);
632
633         if (pic->type == PICTURE_TYPE_I) {
634             priv->slice_nal_unit = HEVC_NAL_CRA_NUT;
635             priv->slice_type     = HEVC_SLICE_I;
636             priv->pic_type       = 0;
637         } else if (pic->type == PICTURE_TYPE_P) {
638             av_assert0(pic->refs[0]);
639             priv->slice_nal_unit = HEVC_NAL_TRAIL_R;
640             priv->slice_type     = HEVC_SLICE_P;
641             priv->pic_type       = 1;
642         } else {
643             av_assert0(pic->refs[0] && pic->refs[1]);
644             if (pic->refs[1]->type == PICTURE_TYPE_I)
645                 priv->slice_nal_unit = HEVC_NAL_RASL_N;
646             else
647                 priv->slice_nal_unit = HEVC_NAL_TRAIL_N;
648             priv->slice_type = HEVC_SLICE_B;
649             priv->pic_type   = 2;
650         }
651     }
652     priv->pic_order_cnt = pic->display_order - priv->last_idr_frame;
653
654     if (priv->aud) {
655         priv->aud_needed = 1;
656         priv->raw_aud = (H265RawAUD) {
657             .nal_unit_header = {
658                 .nal_unit_type         = HEVC_NAL_AUD,
659                 .nuh_layer_id          = 0,
660                 .nuh_temporal_id_plus1 = 1,
661             },
662             .pic_type = priv->pic_type,
663         };
664     } else {
665         priv->aud_needed = 0;
666     }
667
668     priv->sei_needed = 0;
669
670     // Only look for the metadata on I/IDR frame on the output. We
671     // may force an IDR frame on the output where the medadata gets
672     // changed on the input frame.
673     if ((priv->sei & SEI_MASTERING_DISPLAY) &&
674         (pic->type == PICTURE_TYPE_I || pic->type == PICTURE_TYPE_IDR)) {
675         AVFrameSideData *sd =
676             av_frame_get_side_data(pic->input_image,
677                                    AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
678
679         if (sd) {
680             AVMasteringDisplayMetadata *mdm =
681                 (AVMasteringDisplayMetadata *)sd->data;
682
683             // SEI is needed when both the primaries and luminance are set
684             if (mdm->has_primaries && mdm->has_luminance) {
685                 H265RawSEIMasteringDisplayColourVolume *mdcv =
686                     &priv->sei_mastering_display;
687                 const int mapping[3] = {1, 2, 0};
688                 const int chroma_den = 50000;
689                 const int luma_den   = 10000;
690
691                 for (i = 0; i < 3; i++) {
692                     const int j = mapping[i];
693                     mdcv->display_primaries_x[i] =
694                         FFMIN(lrint(chroma_den *
695                                     av_q2d(mdm->display_primaries[j][0])),
696                               chroma_den);
697                     mdcv->display_primaries_y[i] =
698                         FFMIN(lrint(chroma_den *
699                                     av_q2d(mdm->display_primaries[j][1])),
700                               chroma_den);
701                 }
702
703                 mdcv->white_point_x =
704                     FFMIN(lrint(chroma_den * av_q2d(mdm->white_point[0])),
705                           chroma_den);
706                 mdcv->white_point_y =
707                     FFMIN(lrint(chroma_den * av_q2d(mdm->white_point[1])),
708                           chroma_den);
709
710                 mdcv->max_display_mastering_luminance =
711                     lrint(luma_den * av_q2d(mdm->max_luminance));
712                 mdcv->min_display_mastering_luminance =
713                     FFMIN(lrint(luma_den * av_q2d(mdm->min_luminance)),
714                           mdcv->max_display_mastering_luminance);
715
716                 priv->sei_needed |= SEI_MASTERING_DISPLAY;
717             }
718         }
719     }
720
721     if ((priv->sei & SEI_CONTENT_LIGHT_LEVEL) &&
722         (pic->type == PICTURE_TYPE_I || pic->type == PICTURE_TYPE_IDR)) {
723         AVFrameSideData *sd =
724             av_frame_get_side_data(pic->input_image,
725                                    AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
726
727         if (sd) {
728             AVContentLightMetadata *clm =
729                 (AVContentLightMetadata *)sd->data;
730             H265RawSEIContentLightLevelInfo *clli =
731                 &priv->sei_content_light_level;
732
733             clli->max_content_light_level     = FFMIN(clm->MaxCLL,  65535);
734             clli->max_pic_average_light_level = FFMIN(clm->MaxFALL, 65535);
735
736             priv->sei_needed |= SEI_CONTENT_LIGHT_LEVEL;
737         }
738     }
739
740     vpic->decoded_curr_pic = (VAPictureHEVC) {
741         .picture_id    = pic->recon_surface,
742         .pic_order_cnt = priv->pic_order_cnt,
743         .flags         = 0,
744     };
745
746     for (i = 0; i < pic->nb_refs; i++) {
747         VAAPIEncodePicture *ref = pic->refs[i];
748         av_assert0(ref && ref->encode_order < pic->encode_order);
749
750         vpic->reference_frames[i] = (VAPictureHEVC) {
751             .picture_id    = ref->recon_surface,
752             .pic_order_cnt = ref->display_order - priv->last_idr_frame,
753             .flags = (ref->display_order < pic->display_order ?
754                       VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE : 0) |
755                      (ref->display_order > pic->display_order ?
756                       VA_PICTURE_HEVC_RPS_ST_CURR_AFTER  : 0),
757         };
758     }
759     for (; i < FF_ARRAY_ELEMS(vpic->reference_frames); i++) {
760         vpic->reference_frames[i] = (VAPictureHEVC) {
761             .picture_id = VA_INVALID_ID,
762             .flags      = VA_PICTURE_HEVC_INVALID,
763         };
764     }
765
766     vpic->coded_buf = pic->output_buffer;
767
768     vpic->nal_unit_type = priv->slice_nal_unit;
769
770     switch (pic->type) {
771     case PICTURE_TYPE_IDR:
772         vpic->pic_fields.bits.idr_pic_flag       = 1;
773         vpic->pic_fields.bits.coding_type        = 1;
774         vpic->pic_fields.bits.reference_pic_flag = 1;
775         break;
776     case PICTURE_TYPE_I:
777         vpic->pic_fields.bits.idr_pic_flag       = 0;
778         vpic->pic_fields.bits.coding_type        = 1;
779         vpic->pic_fields.bits.reference_pic_flag = 1;
780         break;
781     case PICTURE_TYPE_P:
782         vpic->pic_fields.bits.idr_pic_flag       = 0;
783         vpic->pic_fields.bits.coding_type        = 2;
784         vpic->pic_fields.bits.reference_pic_flag = 1;
785         break;
786     case PICTURE_TYPE_B:
787         vpic->pic_fields.bits.idr_pic_flag       = 0;
788         vpic->pic_fields.bits.coding_type        = 3;
789         vpic->pic_fields.bits.reference_pic_flag = 0;
790         break;
791     default:
792         av_assert0(0 && "invalid picture type");
793     }
794
795     pic->nb_slices = 1;
796
797     return 0;
798 }
799
800 static int vaapi_encode_h265_init_slice_params(AVCodecContext *avctx,
801                                                VAAPIEncodePicture *pic,
802                                                VAAPIEncodeSlice *slice)
803 {
804     VAAPIEncodeContext                *ctx = avctx->priv_data;
805     VAAPIEncodeH265Context           *priv = avctx->priv_data;
806     const H265RawSPS                  *sps = &priv->raw_sps;
807     const H265RawPPS                  *pps = &priv->raw_pps;
808     H265RawSliceHeader                 *sh = &priv->raw_slice.header;
809     VAEncPictureParameterBufferHEVC  *vpic = pic->codec_picture_params;
810     VAEncSliceParameterBufferHEVC  *vslice = slice->codec_slice_params;
811     int i;
812
813     sh->nal_unit_header = (H265RawNALUnitHeader) {
814         .nal_unit_type         = priv->slice_nal_unit,
815         .nuh_layer_id          = 0,
816         .nuh_temporal_id_plus1 = 1,
817     };
818
819     sh->slice_pic_parameter_set_id      = pps->pps_pic_parameter_set_id;
820
821     // Currently we only support one slice per frame.
822     sh->first_slice_segment_in_pic_flag = 1;
823     sh->slice_segment_address           = 0;
824
825     sh->slice_type = priv->slice_type;
826
827     sh->slice_pic_order_cnt_lsb = priv->pic_order_cnt &
828         (1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4)) - 1;
829
830     if (pic->type != PICTURE_TYPE_IDR) {
831         H265RawSTRefPicSet *rps;
832         VAAPIEncodePicture *st;
833         int used;
834
835         sh->short_term_ref_pic_set_sps_flag = 0;
836
837         rps = &sh->short_term_ref_pic_set;
838         memset(rps, 0, sizeof(*rps));
839
840         for (st = ctx->pic_start; st; st = st->next) {
841             if (st->encode_order >= pic->encode_order) {
842                 // Not yet in DPB.
843                 continue;
844             }
845             used = 0;
846             for (i = 0; i < pic->nb_refs; i++) {
847                 if (pic->refs[i] == st)
848                     used = 1;
849             }
850             if (!used) {
851                 // Usually each picture always uses all of the others in the
852                 // DPB as references.  The one case we have to treat here is
853                 // a non-IDR IRAP picture, which may need to hold unused
854                 // references across itself to be used for the decoding of
855                 // following RASL pictures.  This looks for such an RASL
856                 // picture, and keeps the reference if there is one.
857                 VAAPIEncodePicture *rp;
858                 for (rp = ctx->pic_start; rp; rp = rp->next) {
859                     if (rp->encode_order < pic->encode_order)
860                         continue;
861                     if (rp->type != PICTURE_TYPE_B)
862                         continue;
863                     if (rp->refs[0] == st && rp->refs[1] == pic)
864                         break;
865                 }
866                 if (!rp)
867                     continue;
868             }
869             // This only works for one instance of each (delta_poc_sN_minus1
870             // is relative to the previous frame in the list, not relative to
871             // the current frame directly).
872             if (st->display_order < pic->display_order) {
873                 rps->delta_poc_s0_minus1[rps->num_negative_pics] =
874                     pic->display_order - st->display_order - 1;
875                 rps->used_by_curr_pic_s0_flag[rps->num_negative_pics] = used;
876                 ++rps->num_negative_pics;
877             } else {
878                 rps->delta_poc_s1_minus1[rps->num_positive_pics] =
879                     st->display_order - pic->display_order - 1;
880                 rps->used_by_curr_pic_s1_flag[rps->num_positive_pics] = used;
881                 ++rps->num_positive_pics;
882             }
883         }
884
885         sh->num_long_term_sps  = 0;
886         sh->num_long_term_pics = 0;
887
888         sh->slice_temporal_mvp_enabled_flag =
889             sps->sps_temporal_mvp_enabled_flag;
890         if (sh->slice_temporal_mvp_enabled_flag) {
891             sh->collocated_from_l0_flag = sh->slice_type == HEVC_SLICE_B;
892             sh->collocated_ref_idx      = 0;
893         }
894
895         sh->num_ref_idx_active_override_flag = 0;
896         sh->num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1;
897         sh->num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1;
898     }
899
900     sh->slice_sao_luma_flag = sh->slice_sao_chroma_flag =
901         sps->sample_adaptive_offset_enabled_flag;
902
903     if (pic->type == PICTURE_TYPE_B)
904         sh->slice_qp_delta = priv->fixed_qp_b - (pps->init_qp_minus26 + 26);
905     else if (pic->type == PICTURE_TYPE_P)
906         sh->slice_qp_delta = priv->fixed_qp_p - (pps->init_qp_minus26 + 26);
907     else
908         sh->slice_qp_delta = priv->fixed_qp_idr - (pps->init_qp_minus26 + 26);
909
910
911     *vslice = (VAEncSliceParameterBufferHEVC) {
912         .slice_segment_address = sh->slice_segment_address,
913         .num_ctu_in_slice      = priv->ctu_width * priv->ctu_height,
914
915         .slice_type                 = sh->slice_type,
916         .slice_pic_parameter_set_id = sh->slice_pic_parameter_set_id,
917
918         .num_ref_idx_l0_active_minus1 = sh->num_ref_idx_l0_active_minus1,
919         .num_ref_idx_l1_active_minus1 = sh->num_ref_idx_l1_active_minus1,
920
921         .luma_log2_weight_denom         = sh->luma_log2_weight_denom,
922         .delta_chroma_log2_weight_denom = sh->delta_chroma_log2_weight_denom,
923
924         .max_num_merge_cand = 5 - sh->five_minus_max_num_merge_cand,
925
926         .slice_qp_delta     = sh->slice_qp_delta,
927         .slice_cb_qp_offset = sh->slice_cb_qp_offset,
928         .slice_cr_qp_offset = sh->slice_cr_qp_offset,
929
930         .slice_beta_offset_div2 = sh->slice_beta_offset_div2,
931         .slice_tc_offset_div2   = sh->slice_tc_offset_div2,
932
933         .slice_fields.bits = {
934             .last_slice_of_pic_flag       = 1,
935             .dependent_slice_segment_flag = sh->dependent_slice_segment_flag,
936             .colour_plane_id              = sh->colour_plane_id,
937             .slice_temporal_mvp_enabled_flag =
938                 sh->slice_temporal_mvp_enabled_flag,
939             .slice_sao_luma_flag          = sh->slice_sao_luma_flag,
940             .slice_sao_chroma_flag        = sh->slice_sao_chroma_flag,
941             .num_ref_idx_active_override_flag =
942                 sh->num_ref_idx_active_override_flag,
943             .mvd_l1_zero_flag             = sh->mvd_l1_zero_flag,
944             .cabac_init_flag              = sh->cabac_init_flag,
945             .slice_deblocking_filter_disabled_flag =
946                 sh->slice_deblocking_filter_disabled_flag,
947             .slice_loop_filter_across_slices_enabled_flag =
948                 sh->slice_loop_filter_across_slices_enabled_flag,
949             .collocated_from_l0_flag      = sh->collocated_from_l0_flag,
950         },
951     };
952
953     for (i = 0; i < FF_ARRAY_ELEMS(vslice->ref_pic_list0); i++) {
954         vslice->ref_pic_list0[i].picture_id = VA_INVALID_ID;
955         vslice->ref_pic_list0[i].flags      = VA_PICTURE_HEVC_INVALID;
956         vslice->ref_pic_list1[i].picture_id = VA_INVALID_ID;
957         vslice->ref_pic_list1[i].flags      = VA_PICTURE_HEVC_INVALID;
958     }
959
960     av_assert0(pic->nb_refs <= 2);
961     if (pic->nb_refs >= 1) {
962         // Backward reference for P- or B-frame.
963         av_assert0(pic->type == PICTURE_TYPE_P ||
964                    pic->type == PICTURE_TYPE_B);
965         vslice->ref_pic_list0[0] = vpic->reference_frames[0];
966     }
967     if (pic->nb_refs >= 2) {
968         // Forward reference for B-frame.
969         av_assert0(pic->type == PICTURE_TYPE_B);
970         vslice->ref_pic_list1[0] = vpic->reference_frames[1];
971     }
972
973     return 0;
974 }
975
976 static av_cold int vaapi_encode_h265_configure(AVCodecContext *avctx)
977 {
978     VAAPIEncodeContext      *ctx = avctx->priv_data;
979     VAAPIEncodeH265Context *priv = avctx->priv_data;
980     int err;
981
982     err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_HEVC, avctx);
983     if (err < 0)
984         return err;
985
986     priv->ctu_width     = FFALIGN(ctx->surface_width,  32) / 32;
987     priv->ctu_height    = FFALIGN(ctx->surface_height, 32) / 32;
988
989     av_log(avctx, AV_LOG_VERBOSE, "Input %ux%u -> Surface %ux%u -> CTU %ux%u.\n",
990            avctx->width, avctx->height, ctx->surface_width,
991            ctx->surface_height, priv->ctu_width, priv->ctu_height);
992
993     if (ctx->va_rc_mode == VA_RC_CQP) {
994         priv->fixed_qp_p = priv->qp;
995         if (avctx->i_quant_factor > 0.0)
996             priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
997                                         avctx->i_quant_offset) + 0.5);
998         else
999             priv->fixed_qp_idr = priv->fixed_qp_p;
1000         if (avctx->b_quant_factor > 0.0)
1001             priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
1002                                       avctx->b_quant_offset) + 0.5);
1003         else
1004             priv->fixed_qp_b = priv->fixed_qp_p;
1005
1006         av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
1007                "%d / %d / %d for IDR- / P- / B-frames.\n",
1008                priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
1009
1010     } else if (ctx->va_rc_mode == VA_RC_CBR ||
1011                ctx->va_rc_mode == VA_RC_VBR) {
1012         // These still need to be  set for pic_init_qp/slice_qp_delta.
1013         priv->fixed_qp_idr = 30;
1014         priv->fixed_qp_p   = 30;
1015         priv->fixed_qp_b   = 30;
1016
1017         av_log(avctx, AV_LOG_DEBUG, "Using %s-bitrate = %"PRId64" bps.\n",
1018                ctx->va_rc_mode == VA_RC_CBR ? "constant" : "variable",
1019                avctx->bit_rate);
1020
1021     } else {
1022         av_assert0(0 && "Invalid RC mode.");
1023     }
1024
1025     return 0;
1026 }
1027
1028 static const VAAPIEncodeProfile vaapi_encode_h265_profiles[] = {
1029     { FF_PROFILE_HEVC_MAIN,     8, 3, 1, 1, VAProfileHEVCMain       },
1030 #if VA_CHECK_VERSION(0, 37, 0)
1031     { FF_PROFILE_HEVC_MAIN_10, 10, 3, 1, 1, VAProfileHEVCMain10     },
1032 #endif
1033     { FF_PROFILE_UNKNOWN }
1034 };
1035
1036 static const VAAPIEncodeType vaapi_encode_type_h265 = {
1037     .profiles              = vaapi_encode_h265_profiles,
1038
1039     .configure             = &vaapi_encode_h265_configure,
1040
1041     .sequence_params_size  = sizeof(VAEncSequenceParameterBufferHEVC),
1042     .init_sequence_params  = &vaapi_encode_h265_init_sequence_params,
1043
1044     .picture_params_size   = sizeof(VAEncPictureParameterBufferHEVC),
1045     .init_picture_params   = &vaapi_encode_h265_init_picture_params,
1046
1047     .slice_params_size     = sizeof(VAEncSliceParameterBufferHEVC),
1048     .init_slice_params     = &vaapi_encode_h265_init_slice_params,
1049
1050     .sequence_header_type  = VAEncPackedHeaderSequence,
1051     .write_sequence_header = &vaapi_encode_h265_write_sequence_header,
1052
1053     .slice_header_type     = VAEncPackedHeaderHEVC_Slice,
1054     .write_slice_header    = &vaapi_encode_h265_write_slice_header,
1055
1056     .write_extra_header    = &vaapi_encode_h265_write_extra_header,
1057 };
1058
1059 static av_cold int vaapi_encode_h265_init(AVCodecContext *avctx)
1060 {
1061     VAAPIEncodeContext      *ctx = avctx->priv_data;
1062     VAAPIEncodeH265Context *priv = avctx->priv_data;
1063
1064     ctx->codec = &vaapi_encode_type_h265;
1065
1066     if (avctx->profile == FF_PROFILE_UNKNOWN)
1067         avctx->profile = priv->profile;
1068     if (avctx->level == FF_LEVEL_UNKNOWN)
1069         avctx->level = priv->level;
1070
1071     if (avctx->bit_rate > 0) {
1072         if (avctx->rc_max_rate == avctx->bit_rate)
1073             ctx->va_rc_mode = VA_RC_CBR;
1074         else
1075             ctx->va_rc_mode = VA_RC_VBR;
1076     } else
1077         ctx->va_rc_mode = VA_RC_CQP;
1078
1079     ctx->va_packed_headers =
1080         VA_ENC_PACKED_HEADER_SEQUENCE | // VPS, SPS and PPS.
1081         VA_ENC_PACKED_HEADER_SLICE    | // Slice headers.
1082         VA_ENC_PACKED_HEADER_MISC;      // SEI
1083
1084     ctx->surface_width  = FFALIGN(avctx->width,  16);
1085     ctx->surface_height = FFALIGN(avctx->height, 16);
1086
1087     return ff_vaapi_encode_init(avctx);
1088 }
1089
1090 static av_cold int vaapi_encode_h265_close(AVCodecContext *avctx)
1091 {
1092     VAAPIEncodeH265Context *priv = avctx->priv_data;
1093
1094     ff_cbs_close(&priv->cbc);
1095
1096     return ff_vaapi_encode_close(avctx);
1097 }
1098
1099 #define OFFSET(x) offsetof(VAAPIEncodeH265Context, x)
1100 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
1101 static const AVOption vaapi_encode_h265_options[] = {
1102     VAAPI_ENCODE_COMMON_OPTIONS,
1103
1104     { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
1105       OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 25 }, 0, 52, FLAGS },
1106
1107     { "aud", "Include AUD",
1108       OFFSET(aud), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
1109
1110     { "profile", "Set profile (general_profile_idc)",
1111       OFFSET(profile), AV_OPT_TYPE_INT,
1112       { .i64 = FF_PROFILE_UNKNOWN }, FF_PROFILE_UNKNOWN, 0xff, FLAGS, "profile" },
1113
1114 #define PROFILE(name, value)  name, NULL, 0, AV_OPT_TYPE_CONST, \
1115       { .i64 = value }, 0, 0, FLAGS, "profile"
1116     { PROFILE("main",               FF_PROFILE_HEVC_MAIN) },
1117     { PROFILE("main10",             FF_PROFILE_HEVC_MAIN_10) },
1118 #undef PROFILE
1119
1120     { "level", "Set level (general_level_idc)",
1121       OFFSET(level), AV_OPT_TYPE_INT,
1122       { .i64 = 153 }, 0x00, 0xff, FLAGS, "level" },
1123
1124 #define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1125       { .i64 = value }, 0, 0, FLAGS, "level"
1126     { LEVEL("1",    30) },
1127     { LEVEL("2",    60) },
1128     { LEVEL("2.1",  63) },
1129     { LEVEL("3",    90) },
1130     { LEVEL("3.1",  93) },
1131     { LEVEL("4",   120) },
1132     { LEVEL("4.1", 123) },
1133     { LEVEL("5",   150) },
1134     { LEVEL("5.1", 153) },
1135     { LEVEL("5.2", 156) },
1136     { LEVEL("6",   180) },
1137     { LEVEL("6.1", 183) },
1138     { LEVEL("6.2", 186) },
1139 #undef LEVEL
1140
1141     { "sei", "Set SEI to include",
1142       OFFSET(sei), AV_OPT_TYPE_FLAGS,
1143       { .i64 = SEI_MASTERING_DISPLAY | SEI_CONTENT_LIGHT_LEVEL },
1144       0, INT_MAX, FLAGS, "sei" },
1145     { "hdr",
1146       "Include HDR metadata for mastering display colour volume "
1147       "and content light level information",
1148       0, AV_OPT_TYPE_CONST,
1149       { .i64 = SEI_MASTERING_DISPLAY | SEI_CONTENT_LIGHT_LEVEL },
1150       INT_MIN, INT_MAX, FLAGS, "sei" },
1151
1152     { NULL },
1153 };
1154
1155 static const AVCodecDefault vaapi_encode_h265_defaults[] = {
1156     { "b",              "0"   },
1157     { "bf",             "2"   },
1158     { "g",              "120" },
1159     { "i_qfactor",      "1"   },
1160     { "i_qoffset",      "0"   },
1161     { "b_qfactor",      "6/5" },
1162     { "b_qoffset",      "0"   },
1163     { NULL },
1164 };
1165
1166 static const AVClass vaapi_encode_h265_class = {
1167     .class_name = "h265_vaapi",
1168     .item_name  = av_default_item_name,
1169     .option     = vaapi_encode_h265_options,
1170     .version    = LIBAVUTIL_VERSION_INT,
1171 };
1172
1173 AVCodec ff_hevc_vaapi_encoder = {
1174     .name           = "hevc_vaapi",
1175     .long_name      = NULL_IF_CONFIG_SMALL("H.265/HEVC (VAAPI)"),
1176     .type           = AVMEDIA_TYPE_VIDEO,
1177     .id             = AV_CODEC_ID_HEVC,
1178     .priv_data_size = sizeof(VAAPIEncodeH265Context),
1179     .init           = &vaapi_encode_h265_init,
1180     .encode2        = &ff_vaapi_encode2,
1181     .close          = &vaapi_encode_h265_close,
1182     .priv_class     = &vaapi_encode_h265_class,
1183     .capabilities   = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
1184     .defaults       = vaapi_encode_h265_defaults,
1185     .pix_fmts = (const enum AVPixelFormat[]) {
1186         AV_PIX_FMT_VAAPI,
1187         AV_PIX_FMT_NONE,
1188     },
1189     .wrapper_name   = "vaapi",
1190 };