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