2 * This file is part of FFmpeg.
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.
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.
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
22 #include <va/va_enc_hevc.h>
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"
33 #include "h265_profile_level.h"
38 #include "vaapi_encode.h"
41 SEI_MASTERING_DISPLAY = 0x08,
42 SEI_CONTENT_LIGHT_LEVEL = 0x10,
45 typedef struct VAAPIEncodeH265Context {
46 VAAPIEncodeContext common;
57 unsigned int ctu_width;
58 unsigned int ctu_height;
65 int64_t last_idr_frame;
78 H265RawSlice raw_slice;
80 H265RawSEIMasteringDisplayColourVolume sei_mastering_display;
81 H265RawSEIContentLightLevelInfo sei_content_light_level;
83 CodedBitstreamContext *cbc;
84 CodedBitstreamFragment current_access_unit;
87 } VAAPIEncodeH265Context;
90 static int vaapi_encode_h265_write_access_unit(AVCodecContext *avctx,
91 char *data, size_t *data_len,
92 CodedBitstreamFragment *au)
94 VAAPIEncodeH265Context *priv = avctx->priv_data;
97 err = ff_cbs_write_fragment_data(priv->cbc, au);
99 av_log(avctx, AV_LOG_ERROR, "Failed to write packed header.\n");
103 if (*data_len < 8 * au->data_size - au->data_bit_padding) {
104 av_log(avctx, AV_LOG_ERROR, "Access unit too large: "
105 "%zu < %zu.\n", *data_len,
106 8 * au->data_size - au->data_bit_padding);
107 return AVERROR(ENOSPC);
110 memcpy(data, au->data, au->data_size);
111 *data_len = 8 * au->data_size - au->data_bit_padding;
116 static int vaapi_encode_h265_add_nal(AVCodecContext *avctx,
117 CodedBitstreamFragment *au,
120 VAAPIEncodeH265Context *priv = avctx->priv_data;
121 H265RawNALUnitHeader *header = nal_unit;
124 err = ff_cbs_insert_unit_content(priv->cbc, au, -1,
125 header->nal_unit_type, nal_unit, NULL);
127 av_log(avctx, AV_LOG_ERROR, "Failed to add NAL unit: "
128 "type = %d.\n", header->nal_unit_type);
135 static int vaapi_encode_h265_write_sequence_header(AVCodecContext *avctx,
136 char *data, size_t *data_len)
138 VAAPIEncodeH265Context *priv = avctx->priv_data;
139 CodedBitstreamFragment *au = &priv->current_access_unit;
142 if (priv->aud_needed) {
143 err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_aud);
146 priv->aud_needed = 0;
149 err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_vps);
153 err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_sps);
157 err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_pps);
161 err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
163 ff_cbs_fragment_uninit(priv->cbc, au);
167 static int vaapi_encode_h265_write_slice_header(AVCodecContext *avctx,
168 VAAPIEncodePicture *pic,
169 VAAPIEncodeSlice *slice,
170 char *data, size_t *data_len)
172 VAAPIEncodeH265Context *priv = avctx->priv_data;
173 CodedBitstreamFragment *au = &priv->current_access_unit;
176 if (priv->aud_needed) {
177 err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_aud);
180 priv->aud_needed = 0;
183 err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_slice);
187 err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
189 ff_cbs_fragment_uninit(priv->cbc, au);
193 static int vaapi_encode_h265_write_extra_header(AVCodecContext *avctx,
194 VAAPIEncodePicture *pic,
195 int index, int *type,
196 char *data, size_t *data_len)
198 VAAPIEncodeH265Context *priv = avctx->priv_data;
199 CodedBitstreamFragment *au = &priv->current_access_unit;
202 if (priv->sei_needed) {
203 H265RawSEI *sei = &priv->raw_sei;
205 if (priv->aud_needed) {
206 err = vaapi_encode_h265_add_nal(avctx, au, &priv->aud);
209 priv->aud_needed = 0;
212 *sei = (H265RawSEI) {
214 .nal_unit_type = HEVC_NAL_SEI_PREFIX,
216 .nuh_temporal_id_plus1 = 1,
222 if (priv->sei_needed & SEI_MASTERING_DISPLAY) {
223 sei->payload[i].payload_type = HEVC_SEI_TYPE_MASTERING_DISPLAY_INFO;
224 sei->payload[i].payload.mastering_display = priv->sei_mastering_display;
228 if (priv->sei_needed & SEI_CONTENT_LIGHT_LEVEL) {
229 sei->payload[i].payload_type = HEVC_SEI_TYPE_CONTENT_LIGHT_LEVEL_INFO;
230 sei->payload[i].payload.content_light_level = priv->sei_content_light_level;
234 sei->payload_count = i;
235 av_assert0(sei->payload_count > 0);
237 err = vaapi_encode_h265_add_nal(avctx, au, sei);
240 priv->sei_needed = 0;
242 err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
246 ff_cbs_fragment_uninit(priv->cbc, au);
248 *type = VAEncPackedHeaderRawData;
255 ff_cbs_fragment_uninit(priv->cbc, au);
259 static int vaapi_encode_h265_init_sequence_params(AVCodecContext *avctx)
261 VAAPIEncodeContext *ctx = avctx->priv_data;
262 VAAPIEncodeH265Context *priv = avctx->priv_data;
263 H265RawVPS *vps = &priv->raw_vps;
264 H265RawSPS *sps = &priv->raw_sps;
265 H265RawPPS *pps = &priv->raw_pps;
266 H265RawProfileTierLevel *ptl = &vps->profile_tier_level;
267 H265RawVUI *vui = &sps->vui;
268 VAEncSequenceParameterBufferHEVC *vseq = ctx->codec_sequence_params;
269 VAEncPictureParameterBufferHEVC *vpic = ctx->codec_picture_params;
270 const AVPixFmtDescriptor *desc;
271 int chroma_format, bit_depth;
274 memset(&priv->current_access_unit, 0,
275 sizeof(priv->current_access_unit));
277 memset(vps, 0, sizeof(*vps));
278 memset(sps, 0, sizeof(*sps));
279 memset(pps, 0, sizeof(*pps));
282 desc = av_pix_fmt_desc_get(priv->common.input_frames->sw_format);
284 if (desc->nb_components == 1) {
287 if (desc->log2_chroma_w == 1 && desc->log2_chroma_h == 1) {
289 } else if (desc->log2_chroma_w == 1 && desc->log2_chroma_h == 0) {
291 } else if (desc->log2_chroma_w == 0 && desc->log2_chroma_h == 0) {
294 av_log(avctx, AV_LOG_ERROR, "Chroma format of input pixel format "
295 "%s is not supported.\n", desc->name);
298 bit_depth = desc->comp[0].depth;
303 vps->nal_unit_header = (H265RawNALUnitHeader) {
304 .nal_unit_type = HEVC_NAL_VPS,
306 .nuh_temporal_id_plus1 = 1,
309 vps->vps_video_parameter_set_id = 0;
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;
317 ptl->general_profile_space = 0;
318 ptl->general_profile_idc = avctx->profile;
319 ptl->general_tier_flag = priv->tier;
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;
325 ptl->general_profile_compatibility_flag[4] = 1;
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;
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;
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;
340 ptl->general_intra_constraint_flag = ctx->gop_size == 1;
342 ptl->general_lower_bit_rate_constraint_flag = 1;
344 if (avctx->level != FF_LEVEL_UNKNOWN) {
345 ptl->general_level_idc = avctx->level;
347 const H265LevelDescriptor *level;
349 level = ff_h265_guess_level(ptl, avctx->bit_rate,
350 ctx->surface_width, ctx->surface_height,
351 1, 1, 1, (ctx->b_per_p > 0) + 1);
353 av_log(avctx, AV_LOG_VERBOSE, "Using level %s.\n", level->name);
354 ptl->general_level_idc = level->level_idc;
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;
364 vps->vps_sub_layer_ordering_info_present_flag = 0;
365 vps->vps_max_dec_pic_buffering_minus1[0] = (ctx->b_per_p > 0) + 1;
366 vps->vps_max_num_reorder_pics[0] = (ctx->b_per_p > 0);
367 vps->vps_max_latency_increase_plus1[0] = 0;
369 vps->vps_max_layer_id = 0;
370 vps->vps_num_layer_sets_minus1 = 0;
371 vps->layer_id_included_flag[0][0] = 1;
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;
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;
384 vps->vps_num_hrd_parameters = 0;
389 sps->nal_unit_header = (H265RawNALUnitHeader) {
390 .nal_unit_type = HEVC_NAL_SPS,
392 .nuh_temporal_id_plus1 = 1,
395 sps->sps_video_parameter_set_id = vps->vps_video_parameter_set_id;
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;
400 sps->profile_tier_level = vps->profile_tier_level;
402 sps->sps_seq_parameter_set_id = 0;
404 sps->chroma_format_idc = chroma_format;
405 sps->separate_colour_plane_flag = 0;
407 sps->pic_width_in_luma_samples = ctx->surface_width;
408 sps->pic_height_in_luma_samples = ctx->surface_height;
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) / 2;
416 sps->conf_win_top_offset = 0;
417 sps->conf_win_bottom_offset =
418 (ctx->surface_height - avctx->height) / 2;
420 sps->conformance_window_flag = 0;
423 sps->bit_depth_luma_minus8 = bit_depth - 8;
424 sps->bit_depth_chroma_minus8 = bit_depth - 8;
426 sps->log2_max_pic_order_cnt_lsb_minus4 = 8;
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];
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
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;
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;
457 sps->pcm_enabled_flag = 0;
459 // STRPSs should ideally be here rather than defined individually in
460 // each slice, but the structure isn't completely fixed so for now
462 sps->num_short_term_ref_pic_sets = 0;
463 sps->long_term_ref_pics_present_flag = 0;
465 sps->vui_parameters_present_flag = 1;
467 if (avctx->sample_aspect_ratio.num != 0 &&
468 avctx->sample_aspect_ratio.den != 0) {
469 static const AVRational sar_idc[] = {
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 },
477 for (i = 0; i < FF_ARRAY_ELEMS(sar_idc); i++) {
478 if (avctx->sample_aspect_ratio.num == sar_idc[i].num &&
479 avctx->sample_aspect_ratio.den == sar_idc[i].den) {
480 vui->aspect_ratio_idc = i;
484 if (i >= FF_ARRAY_ELEMS(sar_idc)) {
485 vui->aspect_ratio_idc = 255;
486 vui->sar_width = avctx->sample_aspect_ratio.num;
487 vui->sar_height = avctx->sample_aspect_ratio.den;
489 vui->aspect_ratio_info_present_flag = 1;
492 if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED ||
493 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
494 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
495 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
496 vui->video_signal_type_present_flag = 1;
497 vui->video_format = 5; // Unspecified.
498 vui->video_full_range_flag =
499 avctx->color_range == AVCOL_RANGE_JPEG;
501 if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
502 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
503 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
504 vui->colour_description_present_flag = 1;
505 vui->colour_primaries = avctx->color_primaries;
506 vui->transfer_characteristics = avctx->color_trc;
507 vui->matrix_coefficients = avctx->colorspace;
510 vui->video_format = 5;
511 vui->video_full_range_flag = 0;
512 vui->colour_primaries = avctx->color_primaries;
513 vui->transfer_characteristics = avctx->color_trc;
514 vui->matrix_coefficients = avctx->colorspace;
517 if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
518 vui->chroma_loc_info_present_flag = 1;
519 vui->chroma_sample_loc_type_top_field =
520 vui->chroma_sample_loc_type_bottom_field =
521 avctx->chroma_sample_location - 1;
524 vui->vui_timing_info_present_flag = 1;
525 vui->vui_num_units_in_tick = vps->vps_num_units_in_tick;
526 vui->vui_time_scale = vps->vps_time_scale;
527 vui->vui_poc_proportional_to_timing_flag = vps->vps_poc_proportional_to_timing_flag;
528 vui->vui_num_ticks_poc_diff_one_minus1 = vps->vps_num_ticks_poc_diff_one_minus1;
529 vui->vui_hrd_parameters_present_flag = 0;
531 vui->bitstream_restriction_flag = 1;
532 vui->motion_vectors_over_pic_boundaries_flag = 1;
533 vui->restricted_ref_pic_lists_flag = 1;
534 vui->max_bytes_per_pic_denom = 0;
535 vui->max_bits_per_min_cu_denom = 0;
536 vui->log2_max_mv_length_horizontal = 15;
537 vui->log2_max_mv_length_vertical = 15;
542 pps->nal_unit_header = (H265RawNALUnitHeader) {
543 .nal_unit_type = HEVC_NAL_PPS,
545 .nuh_temporal_id_plus1 = 1,
548 pps->pps_pic_parameter_set_id = 0;
549 pps->pps_seq_parameter_set_id = sps->sps_seq_parameter_set_id;
551 pps->num_ref_idx_l0_default_active_minus1 = 0;
552 pps->num_ref_idx_l1_default_active_minus1 = 0;
554 pps->init_qp_minus26 = priv->fixed_qp_idr - 26;
556 pps->cu_qp_delta_enabled_flag = (ctx->va_rc_mode != VA_RC_CQP);
557 pps->diff_cu_qp_delta_depth = 0;
559 pps->pps_loop_filter_across_slices_enabled_flag = 1;
562 // Fill VAAPI parameter buffers.
564 *vseq = (VAEncSequenceParameterBufferHEVC) {
565 .general_profile_idc = vps->profile_tier_level.general_profile_idc,
566 .general_level_idc = vps->profile_tier_level.general_level_idc,
567 .general_tier_flag = vps->profile_tier_level.general_tier_flag,
569 .intra_period = ctx->gop_size,
570 .intra_idr_period = ctx->gop_size,
571 .ip_period = ctx->b_per_p + 1,
572 .bits_per_second = ctx->va_bit_rate,
574 .pic_width_in_luma_samples = sps->pic_width_in_luma_samples,
575 .pic_height_in_luma_samples = sps->pic_height_in_luma_samples,
578 .chroma_format_idc = sps->chroma_format_idc,
579 .separate_colour_plane_flag = sps->separate_colour_plane_flag,
580 .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
581 .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
582 .scaling_list_enabled_flag = sps->scaling_list_enabled_flag,
583 .strong_intra_smoothing_enabled_flag =
584 sps->strong_intra_smoothing_enabled_flag,
585 .amp_enabled_flag = sps->amp_enabled_flag,
586 .sample_adaptive_offset_enabled_flag =
587 sps->sample_adaptive_offset_enabled_flag,
588 .pcm_enabled_flag = sps->pcm_enabled_flag,
589 .pcm_loop_filter_disabled_flag = sps->pcm_loop_filter_disabled_flag,
590 .sps_temporal_mvp_enabled_flag = sps->sps_temporal_mvp_enabled_flag,
593 .log2_min_luma_coding_block_size_minus3 =
594 sps->log2_min_luma_coding_block_size_minus3,
595 .log2_diff_max_min_luma_coding_block_size =
596 sps->log2_diff_max_min_luma_coding_block_size,
597 .log2_min_transform_block_size_minus2 =
598 sps->log2_min_luma_transform_block_size_minus2,
599 .log2_diff_max_min_transform_block_size =
600 sps->log2_diff_max_min_luma_transform_block_size,
601 .max_transform_hierarchy_depth_inter =
602 sps->max_transform_hierarchy_depth_inter,
603 .max_transform_hierarchy_depth_intra =
604 sps->max_transform_hierarchy_depth_intra,
606 .pcm_sample_bit_depth_luma_minus1 =
607 sps->pcm_sample_bit_depth_luma_minus1,
608 .pcm_sample_bit_depth_chroma_minus1 =
609 sps->pcm_sample_bit_depth_chroma_minus1,
610 .log2_min_pcm_luma_coding_block_size_minus3 =
611 sps->log2_min_pcm_luma_coding_block_size_minus3,
612 .log2_max_pcm_luma_coding_block_size_minus3 =
613 sps->log2_min_pcm_luma_coding_block_size_minus3 +
614 sps->log2_diff_max_min_pcm_luma_coding_block_size,
616 .vui_parameters_present_flag = 0,
619 *vpic = (VAEncPictureParameterBufferHEVC) {
620 .decoded_curr_pic = {
621 .picture_id = VA_INVALID_ID,
622 .flags = VA_PICTURE_HEVC_INVALID,
625 .coded_buf = VA_INVALID_ID,
627 .collocated_ref_pic_index = 0xff,
631 .pic_init_qp = pps->init_qp_minus26 + 26,
632 .diff_cu_qp_delta_depth = pps->diff_cu_qp_delta_depth,
633 .pps_cb_qp_offset = pps->pps_cb_qp_offset,
634 .pps_cr_qp_offset = pps->pps_cr_qp_offset,
636 .num_tile_columns_minus1 = pps->num_tile_columns_minus1,
637 .num_tile_rows_minus1 = pps->num_tile_rows_minus1,
639 .log2_parallel_merge_level_minus2 = pps->log2_parallel_merge_level_minus2,
640 .ctu_max_bitsize_allowed = 0,
642 .num_ref_idx_l0_default_active_minus1 =
643 pps->num_ref_idx_l0_default_active_minus1,
644 .num_ref_idx_l1_default_active_minus1 =
645 pps->num_ref_idx_l1_default_active_minus1,
647 .slice_pic_parameter_set_id = pps->pps_pic_parameter_set_id,
650 .sign_data_hiding_enabled_flag = pps->sign_data_hiding_enabled_flag,
651 .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
652 .transform_skip_enabled_flag = pps->transform_skip_enabled_flag,
653 .cu_qp_delta_enabled_flag = pps->cu_qp_delta_enabled_flag,
654 .weighted_pred_flag = pps->weighted_pred_flag,
655 .weighted_bipred_flag = pps->weighted_bipred_flag,
656 .transquant_bypass_enabled_flag = pps->transquant_bypass_enabled_flag,
657 .tiles_enabled_flag = pps->tiles_enabled_flag,
658 .entropy_coding_sync_enabled_flag = pps->entropy_coding_sync_enabled_flag,
659 .loop_filter_across_tiles_enabled_flag =
660 pps->loop_filter_across_tiles_enabled_flag,
661 .scaling_list_data_present_flag = (sps->sps_scaling_list_data_present_flag |
662 pps->pps_scaling_list_data_present_flag),
663 .screen_content_flag = 0,
664 .enable_gpu_weighted_prediction = 0,
665 .no_output_of_prior_pics_flag = 0,
672 static int vaapi_encode_h265_init_picture_params(AVCodecContext *avctx,
673 VAAPIEncodePicture *pic)
675 VAAPIEncodeH265Context *priv = avctx->priv_data;
676 VAEncPictureParameterBufferHEVC *vpic = pic->codec_picture_params;
679 if (pic->type == PICTURE_TYPE_IDR) {
680 av_assert0(pic->display_order == pic->encode_order);
682 priv->last_idr_frame = pic->display_order;
684 priv->slice_nal_unit = HEVC_NAL_IDR_W_RADL;
685 priv->slice_type = HEVC_SLICE_I;
688 av_assert0(pic->encode_order > priv->last_idr_frame);
690 if (pic->type == PICTURE_TYPE_I) {
691 priv->slice_nal_unit = HEVC_NAL_CRA_NUT;
692 priv->slice_type = HEVC_SLICE_I;
694 } else if (pic->type == PICTURE_TYPE_P) {
695 av_assert0(pic->refs[0]);
696 priv->slice_nal_unit = HEVC_NAL_TRAIL_R;
697 priv->slice_type = HEVC_SLICE_P;
700 av_assert0(pic->refs[0] && pic->refs[1]);
701 if (pic->refs[1]->type == PICTURE_TYPE_I)
702 priv->slice_nal_unit = HEVC_NAL_RASL_N;
704 priv->slice_nal_unit = HEVC_NAL_TRAIL_N;
705 priv->slice_type = HEVC_SLICE_B;
709 priv->pic_order_cnt = pic->display_order - priv->last_idr_frame;
712 priv->aud_needed = 1;
713 priv->raw_aud = (H265RawAUD) {
715 .nal_unit_type = HEVC_NAL_AUD,
717 .nuh_temporal_id_plus1 = 1,
719 .pic_type = priv->pic_type,
722 priv->aud_needed = 0;
725 priv->sei_needed = 0;
727 // Only look for the metadata on I/IDR frame on the output. We
728 // may force an IDR frame on the output where the medadata gets
729 // changed on the input frame.
730 if ((priv->sei & SEI_MASTERING_DISPLAY) &&
731 (pic->type == PICTURE_TYPE_I || pic->type == PICTURE_TYPE_IDR)) {
732 AVFrameSideData *sd =
733 av_frame_get_side_data(pic->input_image,
734 AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
737 AVMasteringDisplayMetadata *mdm =
738 (AVMasteringDisplayMetadata *)sd->data;
740 // SEI is needed when both the primaries and luminance are set
741 if (mdm->has_primaries && mdm->has_luminance) {
742 H265RawSEIMasteringDisplayColourVolume *mdcv =
743 &priv->sei_mastering_display;
744 const int mapping[3] = {1, 2, 0};
745 const int chroma_den = 50000;
746 const int luma_den = 10000;
748 for (i = 0; i < 3; i++) {
749 const int j = mapping[i];
750 mdcv->display_primaries_x[i] =
751 FFMIN(lrint(chroma_den *
752 av_q2d(mdm->display_primaries[j][0])),
754 mdcv->display_primaries_y[i] =
755 FFMIN(lrint(chroma_den *
756 av_q2d(mdm->display_primaries[j][1])),
760 mdcv->white_point_x =
761 FFMIN(lrint(chroma_den * av_q2d(mdm->white_point[0])),
763 mdcv->white_point_y =
764 FFMIN(lrint(chroma_den * av_q2d(mdm->white_point[1])),
767 mdcv->max_display_mastering_luminance =
768 lrint(luma_den * av_q2d(mdm->max_luminance));
769 mdcv->min_display_mastering_luminance =
770 FFMIN(lrint(luma_den * av_q2d(mdm->min_luminance)),
771 mdcv->max_display_mastering_luminance);
773 priv->sei_needed |= SEI_MASTERING_DISPLAY;
778 if ((priv->sei & SEI_CONTENT_LIGHT_LEVEL) &&
779 (pic->type == PICTURE_TYPE_I || pic->type == PICTURE_TYPE_IDR)) {
780 AVFrameSideData *sd =
781 av_frame_get_side_data(pic->input_image,
782 AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
785 AVContentLightMetadata *clm =
786 (AVContentLightMetadata *)sd->data;
787 H265RawSEIContentLightLevelInfo *clli =
788 &priv->sei_content_light_level;
790 clli->max_content_light_level = FFMIN(clm->MaxCLL, 65535);
791 clli->max_pic_average_light_level = FFMIN(clm->MaxFALL, 65535);
793 priv->sei_needed |= SEI_CONTENT_LIGHT_LEVEL;
797 vpic->decoded_curr_pic = (VAPictureHEVC) {
798 .picture_id = pic->recon_surface,
799 .pic_order_cnt = priv->pic_order_cnt,
803 for (i = 0; i < pic->nb_refs; i++) {
804 VAAPIEncodePicture *ref = pic->refs[i];
805 av_assert0(ref && ref->encode_order < pic->encode_order);
807 vpic->reference_frames[i] = (VAPictureHEVC) {
808 .picture_id = ref->recon_surface,
809 .pic_order_cnt = ref->display_order - priv->last_idr_frame,
810 .flags = (ref->display_order < pic->display_order ?
811 VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE : 0) |
812 (ref->display_order > pic->display_order ?
813 VA_PICTURE_HEVC_RPS_ST_CURR_AFTER : 0),
816 for (; i < FF_ARRAY_ELEMS(vpic->reference_frames); i++) {
817 vpic->reference_frames[i] = (VAPictureHEVC) {
818 .picture_id = VA_INVALID_ID,
819 .flags = VA_PICTURE_HEVC_INVALID,
823 vpic->coded_buf = pic->output_buffer;
825 vpic->nal_unit_type = priv->slice_nal_unit;
828 case PICTURE_TYPE_IDR:
829 vpic->pic_fields.bits.idr_pic_flag = 1;
830 vpic->pic_fields.bits.coding_type = 1;
831 vpic->pic_fields.bits.reference_pic_flag = 1;
834 vpic->pic_fields.bits.idr_pic_flag = 0;
835 vpic->pic_fields.bits.coding_type = 1;
836 vpic->pic_fields.bits.reference_pic_flag = 1;
839 vpic->pic_fields.bits.idr_pic_flag = 0;
840 vpic->pic_fields.bits.coding_type = 2;
841 vpic->pic_fields.bits.reference_pic_flag = 1;
844 vpic->pic_fields.bits.idr_pic_flag = 0;
845 vpic->pic_fields.bits.coding_type = 3;
846 vpic->pic_fields.bits.reference_pic_flag = 0;
849 av_assert0(0 && "invalid picture type");
857 static int vaapi_encode_h265_init_slice_params(AVCodecContext *avctx,
858 VAAPIEncodePicture *pic,
859 VAAPIEncodeSlice *slice)
861 VAAPIEncodeContext *ctx = avctx->priv_data;
862 VAAPIEncodeH265Context *priv = avctx->priv_data;
863 const H265RawSPS *sps = &priv->raw_sps;
864 const H265RawPPS *pps = &priv->raw_pps;
865 H265RawSliceHeader *sh = &priv->raw_slice.header;
866 VAEncPictureParameterBufferHEVC *vpic = pic->codec_picture_params;
867 VAEncSliceParameterBufferHEVC *vslice = slice->codec_slice_params;
870 sh->nal_unit_header = (H265RawNALUnitHeader) {
871 .nal_unit_type = priv->slice_nal_unit,
873 .nuh_temporal_id_plus1 = 1,
876 sh->slice_pic_parameter_set_id = pps->pps_pic_parameter_set_id;
878 // Currently we only support one slice per frame.
879 sh->first_slice_segment_in_pic_flag = 1;
880 sh->slice_segment_address = 0;
882 sh->slice_type = priv->slice_type;
884 sh->slice_pic_order_cnt_lsb = priv->pic_order_cnt &
885 (1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4)) - 1;
887 if (pic->type != PICTURE_TYPE_IDR) {
888 H265RawSTRefPicSet *rps;
889 VAAPIEncodePicture *st;
892 sh->short_term_ref_pic_set_sps_flag = 0;
894 rps = &sh->short_term_ref_pic_set;
895 memset(rps, 0, sizeof(*rps));
897 for (st = ctx->pic_start; st; st = st->next) {
898 if (st->encode_order >= pic->encode_order) {
903 for (i = 0; i < pic->nb_refs; i++) {
904 if (pic->refs[i] == st)
908 // Usually each picture always uses all of the others in the
909 // DPB as references. The one case we have to treat here is
910 // a non-IDR IRAP picture, which may need to hold unused
911 // references across itself to be used for the decoding of
912 // following RASL pictures. This looks for such an RASL
913 // picture, and keeps the reference if there is one.
914 VAAPIEncodePicture *rp;
915 for (rp = ctx->pic_start; rp; rp = rp->next) {
916 if (rp->encode_order < pic->encode_order)
918 if (rp->type != PICTURE_TYPE_B)
920 if (rp->refs[0] == st && rp->refs[1] == pic)
926 // This only works for one instance of each (delta_poc_sN_minus1
927 // is relative to the previous frame in the list, not relative to
928 // the current frame directly).
929 if (st->display_order < pic->display_order) {
930 rps->delta_poc_s0_minus1[rps->num_negative_pics] =
931 pic->display_order - st->display_order - 1;
932 rps->used_by_curr_pic_s0_flag[rps->num_negative_pics] = used;
933 ++rps->num_negative_pics;
935 rps->delta_poc_s1_minus1[rps->num_positive_pics] =
936 st->display_order - pic->display_order - 1;
937 rps->used_by_curr_pic_s1_flag[rps->num_positive_pics] = used;
938 ++rps->num_positive_pics;
942 sh->num_long_term_sps = 0;
943 sh->num_long_term_pics = 0;
945 sh->slice_temporal_mvp_enabled_flag =
946 sps->sps_temporal_mvp_enabled_flag;
947 if (sh->slice_temporal_mvp_enabled_flag) {
948 sh->collocated_from_l0_flag = sh->slice_type == HEVC_SLICE_B;
949 sh->collocated_ref_idx = 0;
952 sh->num_ref_idx_active_override_flag = 0;
953 sh->num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1;
954 sh->num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1;
957 sh->slice_sao_luma_flag = sh->slice_sao_chroma_flag =
958 sps->sample_adaptive_offset_enabled_flag;
960 if (pic->type == PICTURE_TYPE_B)
961 sh->slice_qp_delta = priv->fixed_qp_b - (pps->init_qp_minus26 + 26);
962 else if (pic->type == PICTURE_TYPE_P)
963 sh->slice_qp_delta = priv->fixed_qp_p - (pps->init_qp_minus26 + 26);
965 sh->slice_qp_delta = priv->fixed_qp_idr - (pps->init_qp_minus26 + 26);
968 *vslice = (VAEncSliceParameterBufferHEVC) {
969 .slice_segment_address = sh->slice_segment_address,
970 .num_ctu_in_slice = priv->ctu_width * priv->ctu_height,
972 .slice_type = sh->slice_type,
973 .slice_pic_parameter_set_id = sh->slice_pic_parameter_set_id,
975 .num_ref_idx_l0_active_minus1 = sh->num_ref_idx_l0_active_minus1,
976 .num_ref_idx_l1_active_minus1 = sh->num_ref_idx_l1_active_minus1,
978 .luma_log2_weight_denom = sh->luma_log2_weight_denom,
979 .delta_chroma_log2_weight_denom = sh->delta_chroma_log2_weight_denom,
981 .max_num_merge_cand = 5 - sh->five_minus_max_num_merge_cand,
983 .slice_qp_delta = sh->slice_qp_delta,
984 .slice_cb_qp_offset = sh->slice_cb_qp_offset,
985 .slice_cr_qp_offset = sh->slice_cr_qp_offset,
987 .slice_beta_offset_div2 = sh->slice_beta_offset_div2,
988 .slice_tc_offset_div2 = sh->slice_tc_offset_div2,
990 .slice_fields.bits = {
991 .last_slice_of_pic_flag = 1,
992 .dependent_slice_segment_flag = sh->dependent_slice_segment_flag,
993 .colour_plane_id = sh->colour_plane_id,
994 .slice_temporal_mvp_enabled_flag =
995 sh->slice_temporal_mvp_enabled_flag,
996 .slice_sao_luma_flag = sh->slice_sao_luma_flag,
997 .slice_sao_chroma_flag = sh->slice_sao_chroma_flag,
998 .num_ref_idx_active_override_flag =
999 sh->num_ref_idx_active_override_flag,
1000 .mvd_l1_zero_flag = sh->mvd_l1_zero_flag,
1001 .cabac_init_flag = sh->cabac_init_flag,
1002 .slice_deblocking_filter_disabled_flag =
1003 sh->slice_deblocking_filter_disabled_flag,
1004 .slice_loop_filter_across_slices_enabled_flag =
1005 sh->slice_loop_filter_across_slices_enabled_flag,
1006 .collocated_from_l0_flag = sh->collocated_from_l0_flag,
1010 for (i = 0; i < FF_ARRAY_ELEMS(vslice->ref_pic_list0); i++) {
1011 vslice->ref_pic_list0[i].picture_id = VA_INVALID_ID;
1012 vslice->ref_pic_list0[i].flags = VA_PICTURE_HEVC_INVALID;
1013 vslice->ref_pic_list1[i].picture_id = VA_INVALID_ID;
1014 vslice->ref_pic_list1[i].flags = VA_PICTURE_HEVC_INVALID;
1017 av_assert0(pic->nb_refs <= 2);
1018 if (pic->nb_refs >= 1) {
1019 // Backward reference for P- or B-frame.
1020 av_assert0(pic->type == PICTURE_TYPE_P ||
1021 pic->type == PICTURE_TYPE_B);
1022 vslice->ref_pic_list0[0] = vpic->reference_frames[0];
1024 if (pic->nb_refs >= 2) {
1025 // Forward reference for B-frame.
1026 av_assert0(pic->type == PICTURE_TYPE_B);
1027 vslice->ref_pic_list1[0] = vpic->reference_frames[1];
1033 static av_cold int vaapi_encode_h265_configure(AVCodecContext *avctx)
1035 VAAPIEncodeContext *ctx = avctx->priv_data;
1036 VAAPIEncodeH265Context *priv = avctx->priv_data;
1039 err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_HEVC, avctx);
1043 priv->ctu_width = FFALIGN(ctx->surface_width, 32) / 32;
1044 priv->ctu_height = FFALIGN(ctx->surface_height, 32) / 32;
1046 av_log(avctx, AV_LOG_VERBOSE, "Input %ux%u -> Surface %ux%u -> CTU %ux%u.\n",
1047 avctx->width, avctx->height, ctx->surface_width,
1048 ctx->surface_height, priv->ctu_width, priv->ctu_height);
1050 if (ctx->va_rc_mode == VA_RC_CQP) {
1051 priv->fixed_qp_p = priv->qp;
1052 if (avctx->i_quant_factor > 0.0)
1053 priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
1054 avctx->i_quant_offset) + 0.5);
1056 priv->fixed_qp_idr = priv->fixed_qp_p;
1057 if (avctx->b_quant_factor > 0.0)
1058 priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
1059 avctx->b_quant_offset) + 0.5);
1061 priv->fixed_qp_b = priv->fixed_qp_p;
1063 av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
1064 "%d / %d / %d for IDR- / P- / B-frames.\n",
1065 priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
1067 } else if (ctx->va_rc_mode == VA_RC_CBR ||
1068 ctx->va_rc_mode == VA_RC_VBR) {
1069 // These still need to be set for pic_init_qp/slice_qp_delta.
1070 priv->fixed_qp_idr = 30;
1071 priv->fixed_qp_p = 30;
1072 priv->fixed_qp_b = 30;
1075 av_assert0(0 && "Invalid RC mode.");
1081 static const VAAPIEncodeProfile vaapi_encode_h265_profiles[] = {
1082 { FF_PROFILE_HEVC_MAIN, 8, 3, 1, 1, VAProfileHEVCMain },
1083 { FF_PROFILE_HEVC_REXT, 8, 3, 1, 1, VAProfileHEVCMain },
1084 #if VA_CHECK_VERSION(0, 37, 0)
1085 { FF_PROFILE_HEVC_MAIN_10, 10, 3, 1, 1, VAProfileHEVCMain10 },
1086 { FF_PROFILE_HEVC_REXT, 10, 3, 1, 1, VAProfileHEVCMain10 },
1088 { FF_PROFILE_UNKNOWN }
1091 static const VAAPIEncodeType vaapi_encode_type_h265 = {
1092 .profiles = vaapi_encode_h265_profiles,
1094 .configure = &vaapi_encode_h265_configure,
1096 .sequence_params_size = sizeof(VAEncSequenceParameterBufferHEVC),
1097 .init_sequence_params = &vaapi_encode_h265_init_sequence_params,
1099 .picture_params_size = sizeof(VAEncPictureParameterBufferHEVC),
1100 .init_picture_params = &vaapi_encode_h265_init_picture_params,
1102 .slice_params_size = sizeof(VAEncSliceParameterBufferHEVC),
1103 .init_slice_params = &vaapi_encode_h265_init_slice_params,
1105 .sequence_header_type = VAEncPackedHeaderSequence,
1106 .write_sequence_header = &vaapi_encode_h265_write_sequence_header,
1108 .slice_header_type = VAEncPackedHeaderHEVC_Slice,
1109 .write_slice_header = &vaapi_encode_h265_write_slice_header,
1111 .write_extra_header = &vaapi_encode_h265_write_extra_header,
1114 static av_cold int vaapi_encode_h265_init(AVCodecContext *avctx)
1116 VAAPIEncodeContext *ctx = avctx->priv_data;
1117 VAAPIEncodeH265Context *priv = avctx->priv_data;
1119 ctx->codec = &vaapi_encode_type_h265;
1121 if (avctx->profile == FF_PROFILE_UNKNOWN)
1122 avctx->profile = priv->profile;
1123 if (avctx->level == FF_LEVEL_UNKNOWN)
1124 avctx->level = priv->level;
1126 if (avctx->level != FF_LEVEL_UNKNOWN && avctx->level & ~0xff) {
1127 av_log(avctx, AV_LOG_ERROR, "Invalid level %d: must fit "
1128 "in 8-bit unsigned integer.\n", avctx->level);
1129 return AVERROR(EINVAL);
1132 ctx->desired_packed_headers =
1133 VA_ENC_PACKED_HEADER_SEQUENCE | // VPS, SPS and PPS.
1134 VA_ENC_PACKED_HEADER_SLICE | // Slice headers.
1135 VA_ENC_PACKED_HEADER_MISC; // SEI
1137 ctx->surface_width = FFALIGN(avctx->width, 16);
1138 ctx->surface_height = FFALIGN(avctx->height, 16);
1140 return ff_vaapi_encode_init(avctx);
1143 static av_cold int vaapi_encode_h265_close(AVCodecContext *avctx)
1145 VAAPIEncodeH265Context *priv = avctx->priv_data;
1147 ff_cbs_close(&priv->cbc);
1149 return ff_vaapi_encode_close(avctx);
1152 #define OFFSET(x) offsetof(VAAPIEncodeH265Context, x)
1153 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
1154 static const AVOption vaapi_encode_h265_options[] = {
1155 VAAPI_ENCODE_COMMON_OPTIONS,
1157 { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
1158 OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 25 }, 0, 52, FLAGS },
1160 { "aud", "Include AUD",
1161 OFFSET(aud), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
1163 { "profile", "Set profile (general_profile_idc)",
1164 OFFSET(profile), AV_OPT_TYPE_INT,
1165 { .i64 = FF_PROFILE_UNKNOWN }, FF_PROFILE_UNKNOWN, 0xff, FLAGS, "profile" },
1167 #define PROFILE(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1168 { .i64 = value }, 0, 0, FLAGS, "profile"
1169 { PROFILE("main", FF_PROFILE_HEVC_MAIN) },
1170 { PROFILE("main10", FF_PROFILE_HEVC_MAIN_10) },
1171 { PROFILE("rext", FF_PROFILE_HEVC_REXT) },
1174 { "tier", "Set tier (general_tier_flag)",
1175 OFFSET(tier), AV_OPT_TYPE_INT,
1176 { .i64 = 0 }, 0, 1, FLAGS, "tier" },
1177 { "main", NULL, 0, AV_OPT_TYPE_CONST,
1178 { .i64 = 0 }, 0, 0, FLAGS, "tier" },
1179 { "high", NULL, 0, AV_OPT_TYPE_CONST,
1180 { .i64 = 1 }, 0, 0, FLAGS, "tier" },
1182 { "level", "Set level (general_level_idc)",
1183 OFFSET(level), AV_OPT_TYPE_INT,
1184 { .i64 = FF_LEVEL_UNKNOWN }, FF_LEVEL_UNKNOWN, 0xff, FLAGS, "level" },
1186 #define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1187 { .i64 = value }, 0, 0, FLAGS, "level"
1190 { LEVEL("2.1", 63) },
1192 { LEVEL("3.1", 93) },
1193 { LEVEL("4", 120) },
1194 { LEVEL("4.1", 123) },
1195 { LEVEL("5", 150) },
1196 { LEVEL("5.1", 153) },
1197 { LEVEL("5.2", 156) },
1198 { LEVEL("6", 180) },
1199 { LEVEL("6.1", 183) },
1200 { LEVEL("6.2", 186) },
1203 { "sei", "Set SEI to include",
1204 OFFSET(sei), AV_OPT_TYPE_FLAGS,
1205 { .i64 = SEI_MASTERING_DISPLAY | SEI_CONTENT_LIGHT_LEVEL },
1206 0, INT_MAX, FLAGS, "sei" },
1208 "Include HDR metadata for mastering display colour volume "
1209 "and content light level information",
1210 0, AV_OPT_TYPE_CONST,
1211 { .i64 = SEI_MASTERING_DISPLAY | SEI_CONTENT_LIGHT_LEVEL },
1212 INT_MIN, INT_MAX, FLAGS, "sei" },
1217 static const AVCodecDefault vaapi_encode_h265_defaults[] = {
1221 { "i_qfactor", "1" },
1222 { "i_qoffset", "0" },
1223 { "b_qfactor", "6/5" },
1224 { "b_qoffset", "0" },
1230 static const AVClass vaapi_encode_h265_class = {
1231 .class_name = "h265_vaapi",
1232 .item_name = av_default_item_name,
1233 .option = vaapi_encode_h265_options,
1234 .version = LIBAVUTIL_VERSION_INT,
1237 AVCodec ff_hevc_vaapi_encoder = {
1238 .name = "hevc_vaapi",
1239 .long_name = NULL_IF_CONFIG_SMALL("H.265/HEVC (VAAPI)"),
1240 .type = AVMEDIA_TYPE_VIDEO,
1241 .id = AV_CODEC_ID_HEVC,
1242 .priv_data_size = sizeof(VAAPIEncodeH265Context),
1243 .init = &vaapi_encode_h265_init,
1244 .encode2 = &ff_vaapi_encode2,
1245 .close = &vaapi_encode_h265_close,
1246 .priv_class = &vaapi_encode_h265_class,
1247 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
1248 .defaults = vaapi_encode_h265_defaults,
1249 .pix_fmts = (const enum AVPixelFormat[]) {
1253 .wrapper_name = "vaapi",