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