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