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"
37 #include "vaapi_encode.h"
40 SEI_MASTERING_DISPLAY = 0x08,
41 SEI_CONTENT_LIGHT_LEVEL = 0x10,
44 typedef struct VAAPIEncodeH265Context {
45 VAAPIEncodeContext common;
55 unsigned int ctu_width;
56 unsigned int ctu_height;
63 int64_t last_idr_frame;
76 H265RawSlice raw_slice;
78 H265RawSEIMasteringDisplayColourVolume sei_mastering_display;
79 H265RawSEIContentLightLevelInfo sei_content_light_level;
81 CodedBitstreamContext *cbc;
82 CodedBitstreamFragment current_access_unit;
85 } VAAPIEncodeH265Context;
88 static int vaapi_encode_h265_write_access_unit(AVCodecContext *avctx,
89 char *data, size_t *data_len,
90 CodedBitstreamFragment *au)
92 VAAPIEncodeH265Context *priv = avctx->priv_data;
95 err = ff_cbs_write_fragment_data(priv->cbc, au);
97 av_log(avctx, AV_LOG_ERROR, "Failed to write packed header.\n");
101 if (*data_len < 8 * au->data_size - au->data_bit_padding) {
102 av_log(avctx, AV_LOG_ERROR, "Access unit too large: "
103 "%zu < %zu.\n", *data_len,
104 8 * au->data_size - au->data_bit_padding);
105 return AVERROR(ENOSPC);
108 memcpy(data, au->data, au->data_size);
109 *data_len = 8 * au->data_size - au->data_bit_padding;
114 static int vaapi_encode_h265_add_nal(AVCodecContext *avctx,
115 CodedBitstreamFragment *au,
118 VAAPIEncodeH265Context *priv = avctx->priv_data;
119 H265RawNALUnitHeader *header = nal_unit;
122 err = ff_cbs_insert_unit_content(priv->cbc, au, -1,
123 header->nal_unit_type, nal_unit, NULL);
125 av_log(avctx, AV_LOG_ERROR, "Failed to add NAL unit: "
126 "type = %d.\n", header->nal_unit_type);
133 static int vaapi_encode_h265_write_sequence_header(AVCodecContext *avctx,
134 char *data, size_t *data_len)
136 VAAPIEncodeH265Context *priv = avctx->priv_data;
137 CodedBitstreamFragment *au = &priv->current_access_unit;
140 if (priv->aud_needed) {
141 err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_aud);
144 priv->aud_needed = 0;
147 err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_vps);
151 err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_sps);
155 err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_pps);
159 err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
161 ff_cbs_fragment_uninit(priv->cbc, au);
165 static int vaapi_encode_h265_write_slice_header(AVCodecContext *avctx,
166 VAAPIEncodePicture *pic,
167 VAAPIEncodeSlice *slice,
168 char *data, size_t *data_len)
170 VAAPIEncodeH265Context *priv = avctx->priv_data;
171 CodedBitstreamFragment *au = &priv->current_access_unit;
174 if (priv->aud_needed) {
175 err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_aud);
178 priv->aud_needed = 0;
181 err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_slice);
185 err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
187 ff_cbs_fragment_uninit(priv->cbc, au);
191 static int vaapi_encode_h265_write_extra_header(AVCodecContext *avctx,
192 VAAPIEncodePicture *pic,
193 int index, int *type,
194 char *data, size_t *data_len)
196 VAAPIEncodeH265Context *priv = avctx->priv_data;
197 CodedBitstreamFragment *au = &priv->current_access_unit;
200 if (priv->sei_needed) {
201 H265RawSEI *sei = &priv->raw_sei;
203 if (priv->aud_needed) {
204 err = vaapi_encode_h265_add_nal(avctx, au, &priv->aud);
207 priv->aud_needed = 0;
210 *sei = (H265RawSEI) {
212 .nal_unit_type = HEVC_NAL_SEI_PREFIX,
214 .nuh_temporal_id_plus1 = 1,
220 if (priv->sei_needed & SEI_MASTERING_DISPLAY) {
221 sei->payload[i].payload_type = HEVC_SEI_TYPE_MASTERING_DISPLAY_INFO;
222 sei->payload[i].payload.mastering_display = priv->sei_mastering_display;
226 if (priv->sei_needed & SEI_CONTENT_LIGHT_LEVEL) {
227 sei->payload[i].payload_type = HEVC_SEI_TYPE_CONTENT_LIGHT_LEVEL_INFO;
228 sei->payload[i].payload.content_light_level = priv->sei_content_light_level;
232 sei->payload_count = i;
233 av_assert0(sei->payload_count > 0);
235 err = vaapi_encode_h265_add_nal(avctx, au, sei);
238 priv->sei_needed = 0;
240 err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
244 ff_cbs_fragment_uninit(priv->cbc, au);
246 *type = VAEncPackedHeaderRawData;
253 ff_cbs_fragment_uninit(priv->cbc, au);
257 static int vaapi_encode_h265_init_sequence_params(AVCodecContext *avctx)
259 VAAPIEncodeContext *ctx = avctx->priv_data;
260 VAAPIEncodeH265Context *priv = avctx->priv_data;
261 H265RawVPS *vps = &priv->raw_vps;
262 H265RawSPS *sps = &priv->raw_sps;
263 H265RawPPS *pps = &priv->raw_pps;
264 H265RawProfileTierLevel *ptl = &vps->profile_tier_level;
265 H265RawVUI *vui = &sps->vui;
266 VAEncSequenceParameterBufferHEVC *vseq = ctx->codec_sequence_params;
267 VAEncPictureParameterBufferHEVC *vpic = ctx->codec_picture_params;
268 const AVPixFmtDescriptor *desc;
269 int chroma_format, bit_depth;
272 memset(&priv->current_access_unit, 0,
273 sizeof(priv->current_access_unit));
275 memset(vps, 0, sizeof(*vps));
276 memset(sps, 0, sizeof(*sps));
277 memset(pps, 0, sizeof(*pps));
280 desc = av_pix_fmt_desc_get(priv->common.input_frames->sw_format);
282 if (desc->nb_components == 1) {
285 if (desc->log2_chroma_w == 1 && desc->log2_chroma_h == 1) {
287 } else if (desc->log2_chroma_w == 1 && desc->log2_chroma_h == 0) {
289 } else if (desc->log2_chroma_w == 0 && desc->log2_chroma_h == 0) {
292 av_log(avctx, AV_LOG_ERROR, "Chroma format of input pixel format "
293 "%s is not supported.\n", desc->name);
296 bit_depth = desc->comp[0].depth;
301 vps->nal_unit_header = (H265RawNALUnitHeader) {
302 .nal_unit_type = HEVC_NAL_VPS,
304 .nuh_temporal_id_plus1 = 1,
307 vps->vps_video_parameter_set_id = 0;
309 vps->vps_base_layer_internal_flag = 1;
310 vps->vps_base_layer_available_flag = 1;
311 vps->vps_max_layers_minus1 = 0;
312 vps->vps_max_sub_layers_minus1 = 0;
313 vps->vps_temporal_id_nesting_flag = 1;
315 ptl->general_profile_space = 0;
316 ptl->general_profile_idc = avctx->profile;
317 ptl->general_tier_flag = 0;
319 if (chroma_format == 1) {
320 ptl->general_profile_compatibility_flag[1] = bit_depth == 8;
321 ptl->general_profile_compatibility_flag[2] = bit_depth <= 10;
323 ptl->general_profile_compatibility_flag[4] = 1;
325 ptl->general_progressive_source_flag = 1;
326 ptl->general_interlaced_source_flag = 0;
327 ptl->general_non_packed_constraint_flag = 1;
328 ptl->general_frame_only_constraint_flag = 1;
330 ptl->general_max_12bit_constraint_flag = bit_depth <= 12;
331 ptl->general_max_10bit_constraint_flag = bit_depth <= 10;
332 ptl->general_max_8bit_constraint_flag = bit_depth == 8;
334 ptl->general_max_422chroma_constraint_flag = chroma_format <= 2;
335 ptl->general_max_420chroma_constraint_flag = chroma_format <= 1;
336 ptl->general_max_monochrome_constraint_flag = chroma_format == 0;
338 ptl->general_intra_constraint_flag = ctx->gop_size == 1;
340 ptl->general_lower_bit_rate_constraint_flag = 1;
342 ptl->general_level_idc = avctx->level;
344 vps->vps_sub_layer_ordering_info_present_flag = 0;
345 vps->vps_max_dec_pic_buffering_minus1[0] = (ctx->b_per_p > 0) + 1;
346 vps->vps_max_num_reorder_pics[0] = (ctx->b_per_p > 0);
347 vps->vps_max_latency_increase_plus1[0] = 0;
349 vps->vps_max_layer_id = 0;
350 vps->vps_num_layer_sets_minus1 = 0;
351 vps->layer_id_included_flag[0][0] = 1;
353 vps->vps_timing_info_present_flag = 1;
354 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
355 vps->vps_num_units_in_tick = avctx->framerate.den;
356 vps->vps_time_scale = avctx->framerate.num;
357 vps->vps_poc_proportional_to_timing_flag = 1;
358 vps->vps_num_ticks_poc_diff_one_minus1 = 0;
360 vps->vps_num_units_in_tick = avctx->time_base.num;
361 vps->vps_time_scale = avctx->time_base.den;
362 vps->vps_poc_proportional_to_timing_flag = 0;
364 vps->vps_num_hrd_parameters = 0;
369 sps->nal_unit_header = (H265RawNALUnitHeader) {
370 .nal_unit_type = HEVC_NAL_SPS,
372 .nuh_temporal_id_plus1 = 1,
375 sps->sps_video_parameter_set_id = vps->vps_video_parameter_set_id;
377 sps->sps_max_sub_layers_minus1 = vps->vps_max_sub_layers_minus1;
378 sps->sps_temporal_id_nesting_flag = vps->vps_temporal_id_nesting_flag;
380 sps->profile_tier_level = vps->profile_tier_level;
382 sps->sps_seq_parameter_set_id = 0;
384 sps->chroma_format_idc = chroma_format;
385 sps->separate_colour_plane_flag = 0;
387 sps->pic_width_in_luma_samples = ctx->surface_width;
388 sps->pic_height_in_luma_samples = ctx->surface_height;
390 if (avctx->width != ctx->surface_width ||
391 avctx->height != ctx->surface_height) {
392 sps->conformance_window_flag = 1;
393 sps->conf_win_left_offset = 0;
394 sps->conf_win_right_offset =
395 (ctx->surface_width - avctx->width) / 2;
396 sps->conf_win_top_offset = 0;
397 sps->conf_win_bottom_offset =
398 (ctx->surface_height - avctx->height) / 2;
400 sps->conformance_window_flag = 0;
403 sps->bit_depth_luma_minus8 = bit_depth - 8;
404 sps->bit_depth_chroma_minus8 = bit_depth - 8;
406 sps->log2_max_pic_order_cnt_lsb_minus4 = 8;
408 sps->sps_sub_layer_ordering_info_present_flag =
409 vps->vps_sub_layer_ordering_info_present_flag;
410 for (i = 0; i <= sps->sps_max_sub_layers_minus1; i++) {
411 sps->sps_max_dec_pic_buffering_minus1[i] =
412 vps->vps_max_dec_pic_buffering_minus1[i];
413 sps->sps_max_num_reorder_pics[i] =
414 vps->vps_max_num_reorder_pics[i];
415 sps->sps_max_latency_increase_plus1[i] =
416 vps->vps_max_latency_increase_plus1[i];
419 // These have to come from the capabilities of the encoder. We have no
420 // way to query them, so just hardcode parameters which work on the Intel
422 // CTB size from 8x8 to 32x32.
423 sps->log2_min_luma_coding_block_size_minus3 = 0;
424 sps->log2_diff_max_min_luma_coding_block_size = 2;
425 // Transform size from 4x4 to 32x32.
426 sps->log2_min_luma_transform_block_size_minus2 = 0;
427 sps->log2_diff_max_min_luma_transform_block_size = 3;
428 // Full transform hierarchy allowed (2-5).
429 sps->max_transform_hierarchy_depth_inter = 3;
430 sps->max_transform_hierarchy_depth_intra = 3;
432 sps->amp_enabled_flag = 1;
433 // SAO and temporal MVP do not work.
434 sps->sample_adaptive_offset_enabled_flag = 0;
435 sps->sps_temporal_mvp_enabled_flag = 0;
437 sps->pcm_enabled_flag = 0;
439 // STRPSs should ideally be here rather than defined individually in
440 // each slice, but the structure isn't completely fixed so for now
442 sps->num_short_term_ref_pic_sets = 0;
443 sps->long_term_ref_pics_present_flag = 0;
445 sps->vui_parameters_present_flag = 1;
447 if (avctx->sample_aspect_ratio.num != 0 &&
448 avctx->sample_aspect_ratio.den != 0) {
449 static const AVRational sar_idc[] = {
451 { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 },
452 { 40, 33 }, { 24, 11 }, { 20, 11 }, { 32, 11 },
453 { 80, 33 }, { 18, 11 }, { 15, 11 }, { 64, 33 },
454 { 160, 99 }, { 4, 3 }, { 3, 2 }, { 2, 1 },
457 for (i = 0; i < FF_ARRAY_ELEMS(sar_idc); i++) {
458 if (avctx->sample_aspect_ratio.num == sar_idc[i].num &&
459 avctx->sample_aspect_ratio.den == sar_idc[i].den) {
460 vui->aspect_ratio_idc = i;
464 if (i >= FF_ARRAY_ELEMS(sar_idc)) {
465 vui->aspect_ratio_idc = 255;
466 vui->sar_width = avctx->sample_aspect_ratio.num;
467 vui->sar_height = avctx->sample_aspect_ratio.den;
469 vui->aspect_ratio_info_present_flag = 1;
472 if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED ||
473 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
474 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
475 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
476 vui->video_signal_type_present_flag = 1;
477 vui->video_format = 5; // Unspecified.
478 vui->video_full_range_flag =
479 avctx->color_range == AVCOL_RANGE_JPEG;
481 if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
482 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
483 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
484 vui->colour_description_present_flag = 1;
485 vui->colour_primaries = avctx->color_primaries;
486 vui->transfer_characteristics = avctx->color_trc;
487 vui->matrix_coefficients = avctx->colorspace;
490 vui->video_format = 5;
491 vui->video_full_range_flag = 0;
492 vui->colour_primaries = avctx->color_primaries;
493 vui->transfer_characteristics = avctx->color_trc;
494 vui->matrix_coefficients = avctx->colorspace;
497 if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
498 vui->chroma_loc_info_present_flag = 1;
499 vui->chroma_sample_loc_type_top_field =
500 vui->chroma_sample_loc_type_bottom_field =
501 avctx->chroma_sample_location - 1;
504 vui->vui_timing_info_present_flag = 1;
505 vui->vui_num_units_in_tick = vps->vps_num_units_in_tick;
506 vui->vui_time_scale = vps->vps_time_scale;
507 vui->vui_poc_proportional_to_timing_flag = vps->vps_poc_proportional_to_timing_flag;
508 vui->vui_num_ticks_poc_diff_one_minus1 = vps->vps_num_ticks_poc_diff_one_minus1;
509 vui->vui_hrd_parameters_present_flag = 0;
511 vui->bitstream_restriction_flag = 1;
512 vui->motion_vectors_over_pic_boundaries_flag = 1;
513 vui->restricted_ref_pic_lists_flag = 1;
514 vui->max_bytes_per_pic_denom = 0;
515 vui->max_bits_per_min_cu_denom = 0;
516 vui->log2_max_mv_length_horizontal = 15;
517 vui->log2_max_mv_length_vertical = 15;
522 pps->nal_unit_header = (H265RawNALUnitHeader) {
523 .nal_unit_type = HEVC_NAL_PPS,
525 .nuh_temporal_id_plus1 = 1,
528 pps->pps_pic_parameter_set_id = 0;
529 pps->pps_seq_parameter_set_id = sps->sps_seq_parameter_set_id;
531 pps->num_ref_idx_l0_default_active_minus1 = 0;
532 pps->num_ref_idx_l1_default_active_minus1 = 0;
534 pps->init_qp_minus26 = priv->fixed_qp_idr - 26;
536 pps->cu_qp_delta_enabled_flag = (ctx->va_rc_mode != VA_RC_CQP);
537 pps->diff_cu_qp_delta_depth = 0;
539 pps->pps_loop_filter_across_slices_enabled_flag = 1;
542 // Fill VAAPI parameter buffers.
544 *vseq = (VAEncSequenceParameterBufferHEVC) {
545 .general_profile_idc = vps->profile_tier_level.general_profile_idc,
546 .general_level_idc = vps->profile_tier_level.general_level_idc,
547 .general_tier_flag = vps->profile_tier_level.general_tier_flag,
549 .intra_period = ctx->gop_size,
550 .intra_idr_period = ctx->gop_size,
551 .ip_period = ctx->b_per_p + 1,
552 .bits_per_second = ctx->va_bit_rate,
554 .pic_width_in_luma_samples = sps->pic_width_in_luma_samples,
555 .pic_height_in_luma_samples = sps->pic_height_in_luma_samples,
558 .chroma_format_idc = sps->chroma_format_idc,
559 .separate_colour_plane_flag = sps->separate_colour_plane_flag,
560 .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
561 .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
562 .scaling_list_enabled_flag = sps->scaling_list_enabled_flag,
563 .strong_intra_smoothing_enabled_flag =
564 sps->strong_intra_smoothing_enabled_flag,
565 .amp_enabled_flag = sps->amp_enabled_flag,
566 .sample_adaptive_offset_enabled_flag =
567 sps->sample_adaptive_offset_enabled_flag,
568 .pcm_enabled_flag = sps->pcm_enabled_flag,
569 .pcm_loop_filter_disabled_flag = sps->pcm_loop_filter_disabled_flag,
570 .sps_temporal_mvp_enabled_flag = sps->sps_temporal_mvp_enabled_flag,
573 .log2_min_luma_coding_block_size_minus3 =
574 sps->log2_min_luma_coding_block_size_minus3,
575 .log2_diff_max_min_luma_coding_block_size =
576 sps->log2_diff_max_min_luma_coding_block_size,
577 .log2_min_transform_block_size_minus2 =
578 sps->log2_min_luma_transform_block_size_minus2,
579 .log2_diff_max_min_transform_block_size =
580 sps->log2_diff_max_min_luma_transform_block_size,
581 .max_transform_hierarchy_depth_inter =
582 sps->max_transform_hierarchy_depth_inter,
583 .max_transform_hierarchy_depth_intra =
584 sps->max_transform_hierarchy_depth_intra,
586 .pcm_sample_bit_depth_luma_minus1 =
587 sps->pcm_sample_bit_depth_luma_minus1,
588 .pcm_sample_bit_depth_chroma_minus1 =
589 sps->pcm_sample_bit_depth_chroma_minus1,
590 .log2_min_pcm_luma_coding_block_size_minus3 =
591 sps->log2_min_pcm_luma_coding_block_size_minus3,
592 .log2_max_pcm_luma_coding_block_size_minus3 =
593 sps->log2_min_pcm_luma_coding_block_size_minus3 +
594 sps->log2_diff_max_min_pcm_luma_coding_block_size,
596 .vui_parameters_present_flag = 0,
599 *vpic = (VAEncPictureParameterBufferHEVC) {
600 .decoded_curr_pic = {
601 .picture_id = VA_INVALID_ID,
602 .flags = VA_PICTURE_HEVC_INVALID,
605 .coded_buf = VA_INVALID_ID,
607 .collocated_ref_pic_index = 0xff,
611 .pic_init_qp = pps->init_qp_minus26 + 26,
612 .diff_cu_qp_delta_depth = pps->diff_cu_qp_delta_depth,
613 .pps_cb_qp_offset = pps->pps_cb_qp_offset,
614 .pps_cr_qp_offset = pps->pps_cr_qp_offset,
616 .num_tile_columns_minus1 = pps->num_tile_columns_minus1,
617 .num_tile_rows_minus1 = pps->num_tile_rows_minus1,
619 .log2_parallel_merge_level_minus2 = pps->log2_parallel_merge_level_minus2,
620 .ctu_max_bitsize_allowed = 0,
622 .num_ref_idx_l0_default_active_minus1 =
623 pps->num_ref_idx_l0_default_active_minus1,
624 .num_ref_idx_l1_default_active_minus1 =
625 pps->num_ref_idx_l1_default_active_minus1,
627 .slice_pic_parameter_set_id = pps->pps_pic_parameter_set_id,
630 .sign_data_hiding_enabled_flag = pps->sign_data_hiding_enabled_flag,
631 .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
632 .transform_skip_enabled_flag = pps->transform_skip_enabled_flag,
633 .cu_qp_delta_enabled_flag = pps->cu_qp_delta_enabled_flag,
634 .weighted_pred_flag = pps->weighted_pred_flag,
635 .weighted_bipred_flag = pps->weighted_bipred_flag,
636 .transquant_bypass_enabled_flag = pps->transquant_bypass_enabled_flag,
637 .tiles_enabled_flag = pps->tiles_enabled_flag,
638 .entropy_coding_sync_enabled_flag = pps->entropy_coding_sync_enabled_flag,
639 .loop_filter_across_tiles_enabled_flag =
640 pps->loop_filter_across_tiles_enabled_flag,
641 .scaling_list_data_present_flag = (sps->sps_scaling_list_data_present_flag |
642 pps->pps_scaling_list_data_present_flag),
643 .screen_content_flag = 0,
644 .enable_gpu_weighted_prediction = 0,
645 .no_output_of_prior_pics_flag = 0,
652 static int vaapi_encode_h265_init_picture_params(AVCodecContext *avctx,
653 VAAPIEncodePicture *pic)
655 VAAPIEncodeH265Context *priv = avctx->priv_data;
656 VAEncPictureParameterBufferHEVC *vpic = pic->codec_picture_params;
659 if (pic->type == PICTURE_TYPE_IDR) {
660 av_assert0(pic->display_order == pic->encode_order);
662 priv->last_idr_frame = pic->display_order;
664 priv->slice_nal_unit = HEVC_NAL_IDR_W_RADL;
665 priv->slice_type = HEVC_SLICE_I;
668 av_assert0(pic->encode_order > priv->last_idr_frame);
670 if (pic->type == PICTURE_TYPE_I) {
671 priv->slice_nal_unit = HEVC_NAL_CRA_NUT;
672 priv->slice_type = HEVC_SLICE_I;
674 } else if (pic->type == PICTURE_TYPE_P) {
675 av_assert0(pic->refs[0]);
676 priv->slice_nal_unit = HEVC_NAL_TRAIL_R;
677 priv->slice_type = HEVC_SLICE_P;
680 av_assert0(pic->refs[0] && pic->refs[1]);
681 if (pic->refs[1]->type == PICTURE_TYPE_I)
682 priv->slice_nal_unit = HEVC_NAL_RASL_N;
684 priv->slice_nal_unit = HEVC_NAL_TRAIL_N;
685 priv->slice_type = HEVC_SLICE_B;
689 priv->pic_order_cnt = pic->display_order - priv->last_idr_frame;
692 priv->aud_needed = 1;
693 priv->raw_aud = (H265RawAUD) {
695 .nal_unit_type = HEVC_NAL_AUD,
697 .nuh_temporal_id_plus1 = 1,
699 .pic_type = priv->pic_type,
702 priv->aud_needed = 0;
705 priv->sei_needed = 0;
707 // Only look for the metadata on I/IDR frame on the output. We
708 // may force an IDR frame on the output where the medadata gets
709 // changed on the input frame.
710 if ((priv->sei & SEI_MASTERING_DISPLAY) &&
711 (pic->type == PICTURE_TYPE_I || pic->type == PICTURE_TYPE_IDR)) {
712 AVFrameSideData *sd =
713 av_frame_get_side_data(pic->input_image,
714 AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
717 AVMasteringDisplayMetadata *mdm =
718 (AVMasteringDisplayMetadata *)sd->data;
720 // SEI is needed when both the primaries and luminance are set
721 if (mdm->has_primaries && mdm->has_luminance) {
722 H265RawSEIMasteringDisplayColourVolume *mdcv =
723 &priv->sei_mastering_display;
724 const int mapping[3] = {1, 2, 0};
725 const int chroma_den = 50000;
726 const int luma_den = 10000;
728 for (i = 0; i < 3; i++) {
729 const int j = mapping[i];
730 mdcv->display_primaries_x[i] =
731 FFMIN(lrint(chroma_den *
732 av_q2d(mdm->display_primaries[j][0])),
734 mdcv->display_primaries_y[i] =
735 FFMIN(lrint(chroma_den *
736 av_q2d(mdm->display_primaries[j][1])),
740 mdcv->white_point_x =
741 FFMIN(lrint(chroma_den * av_q2d(mdm->white_point[0])),
743 mdcv->white_point_y =
744 FFMIN(lrint(chroma_den * av_q2d(mdm->white_point[1])),
747 mdcv->max_display_mastering_luminance =
748 lrint(luma_den * av_q2d(mdm->max_luminance));
749 mdcv->min_display_mastering_luminance =
750 FFMIN(lrint(luma_den * av_q2d(mdm->min_luminance)),
751 mdcv->max_display_mastering_luminance);
753 priv->sei_needed |= SEI_MASTERING_DISPLAY;
758 if ((priv->sei & SEI_CONTENT_LIGHT_LEVEL) &&
759 (pic->type == PICTURE_TYPE_I || pic->type == PICTURE_TYPE_IDR)) {
760 AVFrameSideData *sd =
761 av_frame_get_side_data(pic->input_image,
762 AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
765 AVContentLightMetadata *clm =
766 (AVContentLightMetadata *)sd->data;
767 H265RawSEIContentLightLevelInfo *clli =
768 &priv->sei_content_light_level;
770 clli->max_content_light_level = FFMIN(clm->MaxCLL, 65535);
771 clli->max_pic_average_light_level = FFMIN(clm->MaxFALL, 65535);
773 priv->sei_needed |= SEI_CONTENT_LIGHT_LEVEL;
777 vpic->decoded_curr_pic = (VAPictureHEVC) {
778 .picture_id = pic->recon_surface,
779 .pic_order_cnt = priv->pic_order_cnt,
783 for (i = 0; i < pic->nb_refs; i++) {
784 VAAPIEncodePicture *ref = pic->refs[i];
785 av_assert0(ref && ref->encode_order < pic->encode_order);
787 vpic->reference_frames[i] = (VAPictureHEVC) {
788 .picture_id = ref->recon_surface,
789 .pic_order_cnt = ref->display_order - priv->last_idr_frame,
790 .flags = (ref->display_order < pic->display_order ?
791 VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE : 0) |
792 (ref->display_order > pic->display_order ?
793 VA_PICTURE_HEVC_RPS_ST_CURR_AFTER : 0),
796 for (; i < FF_ARRAY_ELEMS(vpic->reference_frames); i++) {
797 vpic->reference_frames[i] = (VAPictureHEVC) {
798 .picture_id = VA_INVALID_ID,
799 .flags = VA_PICTURE_HEVC_INVALID,
803 vpic->coded_buf = pic->output_buffer;
805 vpic->nal_unit_type = priv->slice_nal_unit;
808 case PICTURE_TYPE_IDR:
809 vpic->pic_fields.bits.idr_pic_flag = 1;
810 vpic->pic_fields.bits.coding_type = 1;
811 vpic->pic_fields.bits.reference_pic_flag = 1;
814 vpic->pic_fields.bits.idr_pic_flag = 0;
815 vpic->pic_fields.bits.coding_type = 1;
816 vpic->pic_fields.bits.reference_pic_flag = 1;
819 vpic->pic_fields.bits.idr_pic_flag = 0;
820 vpic->pic_fields.bits.coding_type = 2;
821 vpic->pic_fields.bits.reference_pic_flag = 1;
824 vpic->pic_fields.bits.idr_pic_flag = 0;
825 vpic->pic_fields.bits.coding_type = 3;
826 vpic->pic_fields.bits.reference_pic_flag = 0;
829 av_assert0(0 && "invalid picture type");
837 static int vaapi_encode_h265_init_slice_params(AVCodecContext *avctx,
838 VAAPIEncodePicture *pic,
839 VAAPIEncodeSlice *slice)
841 VAAPIEncodeContext *ctx = avctx->priv_data;
842 VAAPIEncodeH265Context *priv = avctx->priv_data;
843 const H265RawSPS *sps = &priv->raw_sps;
844 const H265RawPPS *pps = &priv->raw_pps;
845 H265RawSliceHeader *sh = &priv->raw_slice.header;
846 VAEncPictureParameterBufferHEVC *vpic = pic->codec_picture_params;
847 VAEncSliceParameterBufferHEVC *vslice = slice->codec_slice_params;
850 sh->nal_unit_header = (H265RawNALUnitHeader) {
851 .nal_unit_type = priv->slice_nal_unit,
853 .nuh_temporal_id_plus1 = 1,
856 sh->slice_pic_parameter_set_id = pps->pps_pic_parameter_set_id;
858 // Currently we only support one slice per frame.
859 sh->first_slice_segment_in_pic_flag = 1;
860 sh->slice_segment_address = 0;
862 sh->slice_type = priv->slice_type;
864 sh->slice_pic_order_cnt_lsb = priv->pic_order_cnt &
865 (1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4)) - 1;
867 if (pic->type != PICTURE_TYPE_IDR) {
868 H265RawSTRefPicSet *rps;
869 VAAPIEncodePicture *st;
872 sh->short_term_ref_pic_set_sps_flag = 0;
874 rps = &sh->short_term_ref_pic_set;
875 memset(rps, 0, sizeof(*rps));
877 for (st = ctx->pic_start; st; st = st->next) {
878 if (st->encode_order >= pic->encode_order) {
883 for (i = 0; i < pic->nb_refs; i++) {
884 if (pic->refs[i] == st)
888 // Usually each picture always uses all of the others in the
889 // DPB as references. The one case we have to treat here is
890 // a non-IDR IRAP picture, which may need to hold unused
891 // references across itself to be used for the decoding of
892 // following RASL pictures. This looks for such an RASL
893 // picture, and keeps the reference if there is one.
894 VAAPIEncodePicture *rp;
895 for (rp = ctx->pic_start; rp; rp = rp->next) {
896 if (rp->encode_order < pic->encode_order)
898 if (rp->type != PICTURE_TYPE_B)
900 if (rp->refs[0] == st && rp->refs[1] == pic)
906 // This only works for one instance of each (delta_poc_sN_minus1
907 // is relative to the previous frame in the list, not relative to
908 // the current frame directly).
909 if (st->display_order < pic->display_order) {
910 rps->delta_poc_s0_minus1[rps->num_negative_pics] =
911 pic->display_order - st->display_order - 1;
912 rps->used_by_curr_pic_s0_flag[rps->num_negative_pics] = used;
913 ++rps->num_negative_pics;
915 rps->delta_poc_s1_minus1[rps->num_positive_pics] =
916 st->display_order - pic->display_order - 1;
917 rps->used_by_curr_pic_s1_flag[rps->num_positive_pics] = used;
918 ++rps->num_positive_pics;
922 sh->num_long_term_sps = 0;
923 sh->num_long_term_pics = 0;
925 sh->slice_temporal_mvp_enabled_flag =
926 sps->sps_temporal_mvp_enabled_flag;
927 if (sh->slice_temporal_mvp_enabled_flag) {
928 sh->collocated_from_l0_flag = sh->slice_type == HEVC_SLICE_B;
929 sh->collocated_ref_idx = 0;
932 sh->num_ref_idx_active_override_flag = 0;
933 sh->num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1;
934 sh->num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1;
937 sh->slice_sao_luma_flag = sh->slice_sao_chroma_flag =
938 sps->sample_adaptive_offset_enabled_flag;
940 if (pic->type == PICTURE_TYPE_B)
941 sh->slice_qp_delta = priv->fixed_qp_b - (pps->init_qp_minus26 + 26);
942 else if (pic->type == PICTURE_TYPE_P)
943 sh->slice_qp_delta = priv->fixed_qp_p - (pps->init_qp_minus26 + 26);
945 sh->slice_qp_delta = priv->fixed_qp_idr - (pps->init_qp_minus26 + 26);
948 *vslice = (VAEncSliceParameterBufferHEVC) {
949 .slice_segment_address = sh->slice_segment_address,
950 .num_ctu_in_slice = priv->ctu_width * priv->ctu_height,
952 .slice_type = sh->slice_type,
953 .slice_pic_parameter_set_id = sh->slice_pic_parameter_set_id,
955 .num_ref_idx_l0_active_minus1 = sh->num_ref_idx_l0_active_minus1,
956 .num_ref_idx_l1_active_minus1 = sh->num_ref_idx_l1_active_minus1,
958 .luma_log2_weight_denom = sh->luma_log2_weight_denom,
959 .delta_chroma_log2_weight_denom = sh->delta_chroma_log2_weight_denom,
961 .max_num_merge_cand = 5 - sh->five_minus_max_num_merge_cand,
963 .slice_qp_delta = sh->slice_qp_delta,
964 .slice_cb_qp_offset = sh->slice_cb_qp_offset,
965 .slice_cr_qp_offset = sh->slice_cr_qp_offset,
967 .slice_beta_offset_div2 = sh->slice_beta_offset_div2,
968 .slice_tc_offset_div2 = sh->slice_tc_offset_div2,
970 .slice_fields.bits = {
971 .last_slice_of_pic_flag = 1,
972 .dependent_slice_segment_flag = sh->dependent_slice_segment_flag,
973 .colour_plane_id = sh->colour_plane_id,
974 .slice_temporal_mvp_enabled_flag =
975 sh->slice_temporal_mvp_enabled_flag,
976 .slice_sao_luma_flag = sh->slice_sao_luma_flag,
977 .slice_sao_chroma_flag = sh->slice_sao_chroma_flag,
978 .num_ref_idx_active_override_flag =
979 sh->num_ref_idx_active_override_flag,
980 .mvd_l1_zero_flag = sh->mvd_l1_zero_flag,
981 .cabac_init_flag = sh->cabac_init_flag,
982 .slice_deblocking_filter_disabled_flag =
983 sh->slice_deblocking_filter_disabled_flag,
984 .slice_loop_filter_across_slices_enabled_flag =
985 sh->slice_loop_filter_across_slices_enabled_flag,
986 .collocated_from_l0_flag = sh->collocated_from_l0_flag,
990 for (i = 0; i < FF_ARRAY_ELEMS(vslice->ref_pic_list0); i++) {
991 vslice->ref_pic_list0[i].picture_id = VA_INVALID_ID;
992 vslice->ref_pic_list0[i].flags = VA_PICTURE_HEVC_INVALID;
993 vslice->ref_pic_list1[i].picture_id = VA_INVALID_ID;
994 vslice->ref_pic_list1[i].flags = VA_PICTURE_HEVC_INVALID;
997 av_assert0(pic->nb_refs <= 2);
998 if (pic->nb_refs >= 1) {
999 // Backward reference for P- or B-frame.
1000 av_assert0(pic->type == PICTURE_TYPE_P ||
1001 pic->type == PICTURE_TYPE_B);
1002 vslice->ref_pic_list0[0] = vpic->reference_frames[0];
1004 if (pic->nb_refs >= 2) {
1005 // Forward reference for B-frame.
1006 av_assert0(pic->type == PICTURE_TYPE_B);
1007 vslice->ref_pic_list1[0] = vpic->reference_frames[1];
1013 static av_cold int vaapi_encode_h265_configure(AVCodecContext *avctx)
1015 VAAPIEncodeContext *ctx = avctx->priv_data;
1016 VAAPIEncodeH265Context *priv = avctx->priv_data;
1019 err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_HEVC, avctx);
1023 priv->ctu_width = FFALIGN(ctx->surface_width, 32) / 32;
1024 priv->ctu_height = FFALIGN(ctx->surface_height, 32) / 32;
1026 av_log(avctx, AV_LOG_VERBOSE, "Input %ux%u -> Surface %ux%u -> CTU %ux%u.\n",
1027 avctx->width, avctx->height, ctx->surface_width,
1028 ctx->surface_height, priv->ctu_width, priv->ctu_height);
1030 if (ctx->va_rc_mode == VA_RC_CQP) {
1031 priv->fixed_qp_p = priv->qp;
1032 if (avctx->i_quant_factor > 0.0)
1033 priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
1034 avctx->i_quant_offset) + 0.5);
1036 priv->fixed_qp_idr = priv->fixed_qp_p;
1037 if (avctx->b_quant_factor > 0.0)
1038 priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
1039 avctx->b_quant_offset) + 0.5);
1041 priv->fixed_qp_b = priv->fixed_qp_p;
1043 av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
1044 "%d / %d / %d for IDR- / P- / B-frames.\n",
1045 priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
1047 } else if (ctx->va_rc_mode == VA_RC_CBR ||
1048 ctx->va_rc_mode == VA_RC_VBR) {
1049 // These still need to be set for pic_init_qp/slice_qp_delta.
1050 priv->fixed_qp_idr = 30;
1051 priv->fixed_qp_p = 30;
1052 priv->fixed_qp_b = 30;
1055 av_assert0(0 && "Invalid RC mode.");
1061 static const VAAPIEncodeProfile vaapi_encode_h265_profiles[] = {
1062 { FF_PROFILE_HEVC_MAIN, 8, 3, 1, 1, VAProfileHEVCMain },
1063 { FF_PROFILE_HEVC_REXT, 8, 3, 1, 1, VAProfileHEVCMain },
1064 #if VA_CHECK_VERSION(0, 37, 0)
1065 { FF_PROFILE_HEVC_MAIN_10, 10, 3, 1, 1, VAProfileHEVCMain10 },
1066 { FF_PROFILE_HEVC_REXT, 10, 3, 1, 1, VAProfileHEVCMain10 },
1068 { FF_PROFILE_UNKNOWN }
1071 static const VAAPIEncodeType vaapi_encode_type_h265 = {
1072 .profiles = vaapi_encode_h265_profiles,
1074 .configure = &vaapi_encode_h265_configure,
1076 .sequence_params_size = sizeof(VAEncSequenceParameterBufferHEVC),
1077 .init_sequence_params = &vaapi_encode_h265_init_sequence_params,
1079 .picture_params_size = sizeof(VAEncPictureParameterBufferHEVC),
1080 .init_picture_params = &vaapi_encode_h265_init_picture_params,
1082 .slice_params_size = sizeof(VAEncSliceParameterBufferHEVC),
1083 .init_slice_params = &vaapi_encode_h265_init_slice_params,
1085 .sequence_header_type = VAEncPackedHeaderSequence,
1086 .write_sequence_header = &vaapi_encode_h265_write_sequence_header,
1088 .slice_header_type = VAEncPackedHeaderHEVC_Slice,
1089 .write_slice_header = &vaapi_encode_h265_write_slice_header,
1091 .write_extra_header = &vaapi_encode_h265_write_extra_header,
1094 static av_cold int vaapi_encode_h265_init(AVCodecContext *avctx)
1096 VAAPIEncodeContext *ctx = avctx->priv_data;
1097 VAAPIEncodeH265Context *priv = avctx->priv_data;
1099 ctx->codec = &vaapi_encode_type_h265;
1101 if (avctx->profile == FF_PROFILE_UNKNOWN)
1102 avctx->profile = priv->profile;
1103 if (avctx->level == FF_LEVEL_UNKNOWN)
1104 avctx->level = priv->level;
1106 ctx->desired_packed_headers =
1107 VA_ENC_PACKED_HEADER_SEQUENCE | // VPS, SPS and PPS.
1108 VA_ENC_PACKED_HEADER_SLICE | // Slice headers.
1109 VA_ENC_PACKED_HEADER_MISC; // SEI
1111 ctx->surface_width = FFALIGN(avctx->width, 16);
1112 ctx->surface_height = FFALIGN(avctx->height, 16);
1114 return ff_vaapi_encode_init(avctx);
1117 static av_cold int vaapi_encode_h265_close(AVCodecContext *avctx)
1119 VAAPIEncodeH265Context *priv = avctx->priv_data;
1121 ff_cbs_close(&priv->cbc);
1123 return ff_vaapi_encode_close(avctx);
1126 #define OFFSET(x) offsetof(VAAPIEncodeH265Context, x)
1127 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
1128 static const AVOption vaapi_encode_h265_options[] = {
1129 VAAPI_ENCODE_COMMON_OPTIONS,
1131 { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
1132 OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 25 }, 0, 52, FLAGS },
1134 { "aud", "Include AUD",
1135 OFFSET(aud), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
1137 { "profile", "Set profile (general_profile_idc)",
1138 OFFSET(profile), AV_OPT_TYPE_INT,
1139 { .i64 = FF_PROFILE_UNKNOWN }, FF_PROFILE_UNKNOWN, 0xff, FLAGS, "profile" },
1141 #define PROFILE(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1142 { .i64 = value }, 0, 0, FLAGS, "profile"
1143 { PROFILE("main", FF_PROFILE_HEVC_MAIN) },
1144 { PROFILE("main10", FF_PROFILE_HEVC_MAIN_10) },
1145 { PROFILE("rext", FF_PROFILE_HEVC_REXT) },
1148 { "level", "Set level (general_level_idc)",
1149 OFFSET(level), AV_OPT_TYPE_INT,
1150 { .i64 = 153 }, 0x00, 0xff, FLAGS, "level" },
1152 #define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1153 { .i64 = value }, 0, 0, FLAGS, "level"
1156 { LEVEL("2.1", 63) },
1158 { LEVEL("3.1", 93) },
1159 { LEVEL("4", 120) },
1160 { LEVEL("4.1", 123) },
1161 { LEVEL("5", 150) },
1162 { LEVEL("5.1", 153) },
1163 { LEVEL("5.2", 156) },
1164 { LEVEL("6", 180) },
1165 { LEVEL("6.1", 183) },
1166 { LEVEL("6.2", 186) },
1169 { "sei", "Set SEI to include",
1170 OFFSET(sei), AV_OPT_TYPE_FLAGS,
1171 { .i64 = SEI_MASTERING_DISPLAY | SEI_CONTENT_LIGHT_LEVEL },
1172 0, INT_MAX, FLAGS, "sei" },
1174 "Include HDR metadata for mastering display colour volume "
1175 "and content light level information",
1176 0, AV_OPT_TYPE_CONST,
1177 { .i64 = SEI_MASTERING_DISPLAY | SEI_CONTENT_LIGHT_LEVEL },
1178 INT_MIN, INT_MAX, FLAGS, "sei" },
1183 static const AVCodecDefault vaapi_encode_h265_defaults[] = {
1187 { "i_qfactor", "1" },
1188 { "i_qoffset", "0" },
1189 { "b_qfactor", "6/5" },
1190 { "b_qoffset", "0" },
1196 static const AVClass vaapi_encode_h265_class = {
1197 .class_name = "h265_vaapi",
1198 .item_name = av_default_item_name,
1199 .option = vaapi_encode_h265_options,
1200 .version = LIBAVUTIL_VERSION_INT,
1203 AVCodec ff_hevc_vaapi_encoder = {
1204 .name = "hevc_vaapi",
1205 .long_name = NULL_IF_CONFIG_SMALL("H.265/HEVC (VAAPI)"),
1206 .type = AVMEDIA_TYPE_VIDEO,
1207 .id = AV_CODEC_ID_HEVC,
1208 .priv_data_size = sizeof(VAAPIEncodeH265Context),
1209 .init = &vaapi_encode_h265_init,
1210 .encode2 = &ff_vaapi_encode2,
1211 .close = &vaapi_encode_h265_close,
1212 .priv_class = &vaapi_encode_h265_class,
1213 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
1214 .defaults = vaapi_encode_h265_defaults,
1215 .pix_fmts = (const enum AVPixelFormat[]) {
1219 .wrapper_name = "vaapi",