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