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