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