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_h264.h>
24 #include "libavutil/avassert.h"
25 #include "libavutil/common.h"
26 #include "libavutil/internal.h"
27 #include "libavutil/opt.h"
35 #include "vaapi_encode.h"
39 SEI_IDENTIFIER = 0x02,
40 SEI_RECOVERY_POINT = 0x04,
43 // Random (version 4) ISO 11578 UUID.
44 static const uint8_t vaapi_encode_h264_sei_identifier_uuid[16] = {
45 0x59, 0x94, 0x8b, 0x28, 0x11, 0xec, 0x45, 0xaf,
46 0x96, 0x75, 0x19, 0xd4, 0x1f, 0xea, 0xa9, 0x4d,
49 typedef struct VAAPIEncodeH264Context {
50 VAAPIEncodeContext common;
73 int64_t last_idr_frame;
74 int64_t idr_pic_count;
83 CodedBitstreamContext *cbc;
84 CodedBitstreamFragment current_access_unit;
90 H264RawSlice raw_slice;
92 H264RawSEIBufferingPeriod sei_buffering_period;
93 H264RawSEIPicTiming sei_pic_timing;
94 H264RawSEIRecoveryPoint sei_recovery_point;
95 H264RawSEIUserDataUnregistered sei_identifier;
96 char *sei_identifier_string;
100 int sei_cbr_workaround_needed;
101 } VAAPIEncodeH264Context;
104 static int vaapi_encode_h264_write_access_unit(AVCodecContext *avctx,
105 char *data, size_t *data_len,
106 CodedBitstreamFragment *au)
108 VAAPIEncodeH264Context *priv = avctx->priv_data;
111 err = ff_cbs_write_fragment_data(priv->cbc, au);
113 av_log(avctx, AV_LOG_ERROR, "Failed to write packed header.\n");
117 if (*data_len < 8 * au->data_size - au->data_bit_padding) {
118 av_log(avctx, AV_LOG_ERROR, "Access unit too large: "
119 "%zu < %zu.\n", *data_len,
120 8 * au->data_size - au->data_bit_padding);
121 return AVERROR(ENOSPC);
124 memcpy(data, au->data, au->data_size);
125 *data_len = 8 * au->data_size - au->data_bit_padding;
130 static int vaapi_encode_h264_add_nal(AVCodecContext *avctx,
131 CodedBitstreamFragment *au,
134 VAAPIEncodeH264Context *priv = avctx->priv_data;
135 H264RawNALUnitHeader *header = nal_unit;
138 err = ff_cbs_insert_unit_content(priv->cbc, au, -1,
139 header->nal_unit_type, nal_unit, NULL);
141 av_log(avctx, AV_LOG_ERROR, "Failed to add NAL unit: "
142 "type = %d.\n", header->nal_unit_type);
149 static int vaapi_encode_h264_write_sequence_header(AVCodecContext *avctx,
150 char *data, size_t *data_len)
152 VAAPIEncodeH264Context *priv = avctx->priv_data;
153 CodedBitstreamFragment *au = &priv->current_access_unit;
156 if (priv->aud_needed) {
157 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_aud);
160 priv->aud_needed = 0;
163 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_sps);
167 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_pps);
171 err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
173 ff_cbs_fragment_uninit(priv->cbc, au);
177 static int vaapi_encode_h264_write_slice_header(AVCodecContext *avctx,
178 VAAPIEncodePicture *pic,
179 VAAPIEncodeSlice *slice,
180 char *data, size_t *data_len)
182 VAAPIEncodeH264Context *priv = avctx->priv_data;
183 CodedBitstreamFragment *au = &priv->current_access_unit;
186 if (priv->aud_needed) {
187 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_aud);
190 priv->aud_needed = 0;
193 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_slice);
197 err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
199 ff_cbs_fragment_uninit(priv->cbc, au);
203 static int vaapi_encode_h264_write_extra_header(AVCodecContext *avctx,
204 VAAPIEncodePicture *pic,
205 int index, int *type,
206 char *data, size_t *data_len)
208 VAAPIEncodeH264Context *priv = avctx->priv_data;
209 CodedBitstreamFragment *au = &priv->current_access_unit;
212 if (priv->sei_needed) {
213 H264RawSEI *sei = &priv->raw_sei;
215 if (priv->aud_needed) {
216 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_aud);
219 priv->aud_needed = 0;
222 *sei = (H264RawSEI) {
224 .nal_unit_type = H264_NAL_SEI,
230 if (priv->sei_needed & SEI_IDENTIFIER) {
231 sei->payload[i].payload_type = H264_SEI_TYPE_USER_DATA_UNREGISTERED;
232 sei->payload[i].payload.user_data_unregistered = priv->sei_identifier;
235 if (priv->sei_needed & SEI_TIMING) {
236 if (pic->type == PICTURE_TYPE_IDR) {
237 sei->payload[i].payload_type = H264_SEI_TYPE_BUFFERING_PERIOD;
238 sei->payload[i].payload.buffering_period = priv->sei_buffering_period;
241 sei->payload[i].payload_type = H264_SEI_TYPE_PIC_TIMING;
242 sei->payload[i].payload.pic_timing = priv->sei_pic_timing;
245 if (priv->sei_needed & SEI_RECOVERY_POINT) {
246 sei->payload[i].payload_type = H264_SEI_TYPE_RECOVERY_POINT;
247 sei->payload[i].payload.recovery_point = priv->sei_recovery_point;
251 sei->payload_count = i;
252 av_assert0(sei->payload_count > 0);
254 err = vaapi_encode_h264_add_nal(avctx, au, sei);
257 priv->sei_needed = 0;
259 err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
263 ff_cbs_fragment_uninit(priv->cbc, au);
265 *type = VAEncPackedHeaderRawData;
269 } else if (priv->sei_cbr_workaround_needed) {
270 // Insert a zero-length header using the old SEI type. This is
271 // required to avoid triggering broken behaviour on Intel platforms
272 // in CBR mode where an invalid SEI message is generated by the
273 // driver and inserted into the stream.
275 *type = VAEncPackedHeaderH264_SEI;
276 priv->sei_cbr_workaround_needed = 0;
285 ff_cbs_fragment_uninit(priv->cbc, au);
289 static int vaapi_encode_h264_init_sequence_params(AVCodecContext *avctx)
291 VAAPIEncodeContext *ctx = avctx->priv_data;
292 VAAPIEncodeH264Context *priv = avctx->priv_data;
293 H264RawSPS *sps = &priv->raw_sps;
294 H264RawPPS *pps = &priv->raw_pps;
295 VAEncSequenceParameterBufferH264 *vseq = ctx->codec_sequence_params;
296 VAEncPictureParameterBufferH264 *vpic = ctx->codec_picture_params;
298 memset(&priv->current_access_unit, 0,
299 sizeof(priv->current_access_unit));
301 memset(sps, 0, sizeof(*sps));
302 memset(pps, 0, sizeof(*pps));
304 sps->nal_unit_header.nal_ref_idc = 3;
305 sps->nal_unit_header.nal_unit_type = H264_NAL_SPS;
307 sps->profile_idc = avctx->profile & 0xff;
308 sps->constraint_set1_flag =
309 !!(avctx->profile & FF_PROFILE_H264_CONSTRAINED);
310 sps->constraint_set3_flag =
311 !!(avctx->profile & FF_PROFILE_H264_INTRA);
313 sps->level_idc = avctx->level;
315 sps->seq_parameter_set_id = 0;
316 sps->chroma_format_idc = 1;
318 sps->log2_max_frame_num_minus4 = 4;
319 sps->pic_order_cnt_type = 0;
320 sps->log2_max_pic_order_cnt_lsb_minus4 =
321 av_clip(av_log2(ctx->b_per_p + 1) - 2, 0, 12);
323 sps->max_num_ref_frames =
324 (avctx->profile & FF_PROFILE_H264_INTRA) ? 0 :
325 1 + (ctx->b_per_p > 0);
327 sps->pic_width_in_mbs_minus1 = priv->mb_width - 1;
328 sps->pic_height_in_map_units_minus1 = priv->mb_height - 1;
330 sps->frame_mbs_only_flag = 1;
331 sps->direct_8x8_inference_flag = 1;
333 if (avctx->width != 16 * priv->mb_width ||
334 avctx->height != 16 * priv->mb_height) {
335 sps->frame_cropping_flag = 1;
337 sps->frame_crop_left_offset = 0;
338 sps->frame_crop_right_offset =
339 (16 * priv->mb_width - avctx->width) / 2;
340 sps->frame_crop_top_offset = 0;
341 sps->frame_crop_bottom_offset =
342 (16 * priv->mb_height - avctx->height) / 2;
344 sps->frame_cropping_flag = 0;
347 sps->vui_parameters_present_flag = 1;
349 if (avctx->sample_aspect_ratio.num != 0 &&
350 avctx->sample_aspect_ratio.den != 0) {
351 static const AVRational sar_idc[] = {
353 { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 },
354 { 40, 33 }, { 24, 11 }, { 20, 11 }, { 32, 11 },
355 { 80, 33 }, { 18, 11 }, { 15, 11 }, { 64, 33 },
356 { 160, 99 }, { 4, 3 }, { 3, 2 }, { 2, 1 },
359 for (i = 0; i < FF_ARRAY_ELEMS(sar_idc); i++) {
360 if (avctx->sample_aspect_ratio.num == sar_idc[i].num &&
361 avctx->sample_aspect_ratio.den == sar_idc[i].den) {
362 sps->vui.aspect_ratio_idc = i;
366 if (i >= FF_ARRAY_ELEMS(sar_idc)) {
367 sps->vui.aspect_ratio_idc = 255;
368 sps->vui.sar_width = avctx->sample_aspect_ratio.num;
369 sps->vui.sar_height = avctx->sample_aspect_ratio.den;
371 sps->vui.aspect_ratio_info_present_flag = 1;
374 if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED ||
375 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
376 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
377 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
378 sps->vui.video_signal_type_present_flag = 1;
379 sps->vui.video_format = 5; // Unspecified.
380 sps->vui.video_full_range_flag =
381 avctx->color_range == AVCOL_RANGE_JPEG;
383 if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
384 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
385 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
386 sps->vui.colour_description_present_flag = 1;
387 sps->vui.colour_primaries = avctx->color_primaries;
388 sps->vui.transfer_characteristics = avctx->color_trc;
389 sps->vui.matrix_coefficients = avctx->colorspace;
392 sps->vui.video_format = 5;
393 sps->vui.video_full_range_flag = 0;
394 sps->vui.colour_primaries = avctx->color_primaries;
395 sps->vui.transfer_characteristics = avctx->color_trc;
396 sps->vui.matrix_coefficients = avctx->colorspace;
399 if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
400 sps->vui.chroma_loc_info_present_flag = 1;
401 sps->vui.chroma_sample_loc_type_top_field =
402 sps->vui.chroma_sample_loc_type_bottom_field =
403 avctx->chroma_sample_location - 1;
406 sps->vui.timing_info_present_flag = 1;
407 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
408 sps->vui.num_units_in_tick = avctx->framerate.den;
409 sps->vui.time_scale = 2 * avctx->framerate.num;
410 sps->vui.fixed_frame_rate_flag = 1;
412 sps->vui.num_units_in_tick = avctx->time_base.num;
413 sps->vui.time_scale = 2 * avctx->time_base.den;
414 sps->vui.fixed_frame_rate_flag = 0;
417 if (priv->sei & SEI_TIMING) {
418 H264RawHRD *hrd = &sps->vui.nal_hrd_parameters;
419 H264RawSEIBufferingPeriod *bp = &priv->sei_buffering_period;
421 sps->vui.nal_hrd_parameters_present_flag = 1;
423 hrd->cpb_cnt_minus1 = 0;
425 // Try to scale these to a sensible range so that the
426 // golomb encode of the value is not overlong.
427 hrd->bit_rate_scale =
428 av_clip_uintp2(av_log2(avctx->bit_rate) - 15 - 6, 4);
429 hrd->bit_rate_value_minus1[0] =
430 (avctx->bit_rate >> hrd->bit_rate_scale + 6) - 1;
432 hrd->cpb_size_scale =
433 av_clip_uintp2(av_log2(ctx->hrd_params.hrd.buffer_size) - 15 - 4, 4);
434 hrd->cpb_size_value_minus1[0] =
435 (ctx->hrd_params.hrd.buffer_size >> hrd->cpb_size_scale + 4) - 1;
437 // CBR mode as defined for the HRD cannot be achieved without filler
438 // data, so this flag cannot be set even with VAAPI CBR modes.
439 hrd->cbr_flag[0] = 0;
441 hrd->initial_cpb_removal_delay_length_minus1 = 23;
442 hrd->cpb_removal_delay_length_minus1 = 23;
443 hrd->dpb_output_delay_length_minus1 = 7;
444 hrd->time_offset_length = 0;
446 bp->seq_parameter_set_id = sps->seq_parameter_set_id;
448 // This calculation can easily overflow 32 bits.
449 bp->nal.initial_cpb_removal_delay[0] = 90000 *
450 (uint64_t)ctx->hrd_params.hrd.initial_buffer_fullness /
451 ctx->hrd_params.hrd.buffer_size;
452 bp->nal.initial_cpb_removal_delay_offset[0] = 0;
454 sps->vui.nal_hrd_parameters_present_flag = 0;
455 sps->vui.low_delay_hrd_flag = 1 - sps->vui.fixed_frame_rate_flag;
458 sps->vui.bitstream_restriction_flag = 1;
459 sps->vui.motion_vectors_over_pic_boundaries_flag = 1;
460 sps->vui.log2_max_mv_length_horizontal = 16;
461 sps->vui.log2_max_mv_length_vertical = 16;
462 sps->vui.max_num_reorder_frames = (ctx->b_per_p > 0);
463 sps->vui.max_dec_frame_buffering = sps->max_num_ref_frames;
465 pps->nal_unit_header.nal_ref_idc = 3;
466 pps->nal_unit_header.nal_unit_type = H264_NAL_PPS;
468 pps->pic_parameter_set_id = 0;
469 pps->seq_parameter_set_id = 0;
471 pps->entropy_coding_mode_flag =
472 !(sps->profile_idc == FF_PROFILE_H264_BASELINE ||
473 sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
474 sps->profile_idc == FF_PROFILE_H264_CAVLC_444);
475 if (!priv->coder && pps->entropy_coding_mode_flag)
476 pps->entropy_coding_mode_flag = 0;
478 pps->num_ref_idx_l0_default_active_minus1 = 0;
479 pps->num_ref_idx_l1_default_active_minus1 = 0;
481 pps->pic_init_qp_minus26 = priv->fixed_qp_idr - 26;
483 if (sps->profile_idc == FF_PROFILE_H264_BASELINE ||
484 sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
485 sps->profile_idc == FF_PROFILE_H264_MAIN) {
486 pps->more_rbsp_data = 0;
488 pps->more_rbsp_data = 1;
490 pps->transform_8x8_mode_flag = 1;
493 *vseq = (VAEncSequenceParameterBufferH264) {
494 .seq_parameter_set_id = sps->seq_parameter_set_id,
495 .level_idc = sps->level_idc,
496 .intra_period = avctx->gop_size,
497 .intra_idr_period = avctx->gop_size,
498 .ip_period = ctx->b_per_p + 1,
500 .bits_per_second = avctx->bit_rate,
501 .max_num_ref_frames = sps->max_num_ref_frames,
502 .picture_width_in_mbs = sps->pic_width_in_mbs_minus1 + 1,
503 .picture_height_in_mbs = sps->pic_height_in_map_units_minus1 + 1,
506 .chroma_format_idc = sps->chroma_format_idc,
507 .frame_mbs_only_flag = sps->frame_mbs_only_flag,
508 .mb_adaptive_frame_field_flag = sps->mb_adaptive_frame_field_flag,
509 .seq_scaling_matrix_present_flag = sps->seq_scaling_matrix_present_flag,
510 .direct_8x8_inference_flag = sps->direct_8x8_inference_flag,
511 .log2_max_frame_num_minus4 = sps->log2_max_frame_num_minus4,
512 .pic_order_cnt_type = sps->pic_order_cnt_type,
513 .log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_pic_order_cnt_lsb_minus4,
514 .delta_pic_order_always_zero_flag = sps->delta_pic_order_always_zero_flag,
517 .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
518 .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
520 .frame_cropping_flag = sps->frame_cropping_flag,
521 .frame_crop_left_offset = sps->frame_crop_left_offset,
522 .frame_crop_right_offset = sps->frame_crop_right_offset,
523 .frame_crop_top_offset = sps->frame_crop_top_offset,
524 .frame_crop_bottom_offset = sps->frame_crop_bottom_offset,
526 .vui_parameters_present_flag = sps->vui_parameters_present_flag,
529 .aspect_ratio_info_present_flag = sps->vui.aspect_ratio_info_present_flag,
530 .timing_info_present_flag = sps->vui.timing_info_present_flag,
531 .bitstream_restriction_flag = sps->vui.bitstream_restriction_flag,
532 .log2_max_mv_length_horizontal = sps->vui.log2_max_mv_length_horizontal,
533 .log2_max_mv_length_vertical = sps->vui.log2_max_mv_length_vertical,
536 .aspect_ratio_idc = sps->vui.aspect_ratio_idc,
537 .sar_width = sps->vui.sar_width,
538 .sar_height = sps->vui.sar_height,
539 .num_units_in_tick = sps->vui.num_units_in_tick,
540 .time_scale = sps->vui.time_scale,
543 *vpic = (VAEncPictureParameterBufferH264) {
545 .picture_id = VA_INVALID_ID,
546 .flags = VA_PICTURE_H264_INVALID,
549 .coded_buf = VA_INVALID_ID,
551 .pic_parameter_set_id = pps->pic_parameter_set_id,
552 .seq_parameter_set_id = pps->seq_parameter_set_id,
554 .pic_init_qp = pps->pic_init_qp_minus26 + 26,
555 .num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1,
556 .num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1,
558 .chroma_qp_index_offset = pps->chroma_qp_index_offset,
559 .second_chroma_qp_index_offset = pps->second_chroma_qp_index_offset,
562 .entropy_coding_mode_flag = pps->entropy_coding_mode_flag,
563 .weighted_pred_flag = pps->weighted_pred_flag,
564 .weighted_bipred_idc = pps->weighted_bipred_idc,
565 .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
566 .transform_8x8_mode_flag = pps->transform_8x8_mode_flag,
567 .deblocking_filter_control_present_flag =
568 pps->deblocking_filter_control_present_flag,
569 .redundant_pic_cnt_present_flag = pps->redundant_pic_cnt_present_flag,
570 .pic_order_present_flag =
571 pps->bottom_field_pic_order_in_frame_present_flag,
572 .pic_scaling_matrix_present_flag = pps->pic_scaling_matrix_present_flag,
579 static int vaapi_encode_h264_init_picture_params(AVCodecContext *avctx,
580 VAAPIEncodePicture *pic)
582 VAAPIEncodeContext *ctx = avctx->priv_data;
583 VAAPIEncodeH264Context *priv = avctx->priv_data;
584 H264RawSPS *sps = &priv->raw_sps;
585 VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
588 memset(&priv->current_access_unit, 0,
589 sizeof(priv->current_access_unit));
591 if (pic->type == PICTURE_TYPE_IDR) {
592 av_assert0(pic->display_order == pic->encode_order);
594 priv->next_frame_num = 1;
596 priv->last_idr_frame = pic->display_order;
597 ++priv->idr_pic_count;
599 priv->slice_type = 7;
600 priv->primary_pic_type = 0;
602 priv->frame_num = priv->next_frame_num;
604 if (pic->type != PICTURE_TYPE_B) {
605 // Reference picture, so frame_num advances.
606 priv->next_frame_num = (priv->frame_num + 1) &
607 ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
611 if (pic->type == PICTURE_TYPE_I) {
612 priv->slice_type = 7;
613 priv->primary_pic_type = 0;
614 } else if (pic->type == PICTURE_TYPE_P) {
615 priv->slice_type = 5;
616 priv->primary_pic_type = 1;
618 priv->slice_type = 6;
619 priv->primary_pic_type = 2;
622 priv->pic_order_cnt = pic->display_order - priv->last_idr_frame;
623 priv->dpb_delay = pic->display_order - pic->encode_order + 1;
626 priv->aud_needed = 1;
627 priv->raw_aud = (H264RawAUD) {
629 .nal_unit_type = H264_NAL_AUD,
631 .primary_pic_type = priv->primary_pic_type,
634 priv->aud_needed = 0;
637 priv->sei_needed = 0;
639 if (priv->sei & SEI_IDENTIFIER && pic->encode_order == 0)
640 priv->sei_needed |= SEI_IDENTIFIER;
642 if (ctx->va_rc_mode == VA_RC_CBR)
643 priv->sei_cbr_workaround_needed = 1;
646 if (priv->sei & SEI_TIMING) {
647 priv->sei_pic_timing = (H264RawSEIPicTiming) {
648 .cpb_removal_delay = 2 * priv->cpb_delay,
649 .dpb_output_delay = 2 * priv->dpb_delay,
652 priv->sei_needed |= SEI_TIMING;
655 if (priv->sei & SEI_RECOVERY_POINT && pic->type == PICTURE_TYPE_I) {
656 priv->sei_recovery_point = (H264RawSEIRecoveryPoint) {
657 .recovery_frame_cnt = 0,
658 .exact_match_flag = 1,
659 .broken_link_flag = ctx->b_per_p > 0,
662 priv->sei_needed |= SEI_RECOVERY_POINT;
665 vpic->CurrPic = (VAPictureH264) {
666 .picture_id = pic->recon_surface,
667 .frame_idx = priv->frame_num,
669 .TopFieldOrderCnt = priv->pic_order_cnt,
670 .BottomFieldOrderCnt = priv->pic_order_cnt,
673 for (i = 0; i < pic->nb_refs; i++) {
674 VAAPIEncodePicture *ref = pic->refs[i];
675 unsigned int frame_num = (ref->encode_order - priv->last_idr_frame) &
676 ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
677 unsigned int pic_order_cnt = ref->display_order - priv->last_idr_frame;
679 av_assert0(ref && ref->encode_order < pic->encode_order);
680 vpic->ReferenceFrames[i] = (VAPictureH264) {
681 .picture_id = ref->recon_surface,
682 .frame_idx = frame_num,
683 .flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE,
684 .TopFieldOrderCnt = pic_order_cnt,
685 .BottomFieldOrderCnt = pic_order_cnt,
688 for (; i < FF_ARRAY_ELEMS(vpic->ReferenceFrames); i++) {
689 vpic->ReferenceFrames[i] = (VAPictureH264) {
690 .picture_id = VA_INVALID_ID,
691 .flags = VA_PICTURE_H264_INVALID,
695 vpic->coded_buf = pic->output_buffer;
697 vpic->frame_num = priv->frame_num;
699 vpic->pic_fields.bits.idr_pic_flag = (pic->type == PICTURE_TYPE_IDR);
700 vpic->pic_fields.bits.reference_pic_flag = (pic->type != PICTURE_TYPE_B);
707 static int vaapi_encode_h264_init_slice_params(AVCodecContext *avctx,
708 VAAPIEncodePicture *pic,
709 VAAPIEncodeSlice *slice)
711 VAAPIEncodeH264Context *priv = avctx->priv_data;
712 H264RawSPS *sps = &priv->raw_sps;
713 H264RawPPS *pps = &priv->raw_pps;
714 H264RawSliceHeader *sh = &priv->raw_slice.header;
715 VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
716 VAEncSliceParameterBufferH264 *vslice = slice->codec_slice_params;
719 if (pic->type == PICTURE_TYPE_IDR) {
720 sh->nal_unit_header.nal_unit_type = H264_NAL_IDR_SLICE;
721 sh->nal_unit_header.nal_ref_idc = 3;
723 sh->nal_unit_header.nal_unit_type = H264_NAL_SLICE;
724 sh->nal_unit_header.nal_ref_idc = pic->type != PICTURE_TYPE_B;
727 // Only one slice per frame.
728 sh->first_mb_in_slice = 0;
729 sh->slice_type = priv->slice_type;
731 sh->pic_parameter_set_id = pps->pic_parameter_set_id;
733 sh->frame_num = priv->frame_num;
734 sh->idr_pic_id = priv->idr_pic_count;
736 sh->pic_order_cnt_lsb = priv->pic_order_cnt &
737 ((1 << (4 + sps->log2_max_pic_order_cnt_lsb_minus4)) - 1);
739 sh->direct_spatial_mv_pred_flag = 1;
741 if (pic->type == PICTURE_TYPE_B)
742 sh->slice_qp_delta = priv->fixed_qp_b - (pps->pic_init_qp_minus26 + 26);
743 else if (pic->type == PICTURE_TYPE_P)
744 sh->slice_qp_delta = priv->fixed_qp_p - (pps->pic_init_qp_minus26 + 26);
746 sh->slice_qp_delta = priv->fixed_qp_idr - (pps->pic_init_qp_minus26 + 26);
749 vslice->macroblock_address = sh->first_mb_in_slice;
750 vslice->num_macroblocks = priv->mb_width * priv->mb_height;
752 vslice->macroblock_info = VA_INVALID_ID;
754 vslice->slice_type = sh->slice_type % 5;
755 vslice->pic_parameter_set_id = sh->pic_parameter_set_id;
756 vslice->idr_pic_id = sh->idr_pic_id;
758 vslice->pic_order_cnt_lsb = sh->pic_order_cnt_lsb;
760 vslice->direct_spatial_mv_pred_flag = sh->direct_spatial_mv_pred_flag;
762 for (i = 0; i < FF_ARRAY_ELEMS(vslice->RefPicList0); i++) {
763 vslice->RefPicList0[i].picture_id = VA_INVALID_ID;
764 vslice->RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
765 vslice->RefPicList1[i].picture_id = VA_INVALID_ID;
766 vslice->RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
769 av_assert0(pic->nb_refs <= 2);
770 if (pic->nb_refs >= 1) {
771 // Backward reference for P- or B-frame.
772 av_assert0(pic->type == PICTURE_TYPE_P ||
773 pic->type == PICTURE_TYPE_B);
774 vslice->RefPicList0[0] = vpic->ReferenceFrames[0];
776 if (pic->nb_refs >= 2) {
777 // Forward reference for B-frame.
778 av_assert0(pic->type == PICTURE_TYPE_B);
779 vslice->RefPicList1[0] = vpic->ReferenceFrames[1];
782 vslice->slice_qp_delta = sh->slice_qp_delta;
787 static av_cold int vaapi_encode_h264_configure(AVCodecContext *avctx)
789 VAAPIEncodeContext *ctx = avctx->priv_data;
790 VAAPIEncodeH264Context *priv = avctx->priv_data;
793 err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_H264, avctx);
797 priv->mb_width = FFALIGN(avctx->width, 16) / 16;
798 priv->mb_height = FFALIGN(avctx->height, 16) / 16;
800 if (ctx->va_rc_mode == VA_RC_CQP) {
801 priv->fixed_qp_p = priv->qp;
802 if (avctx->i_quant_factor > 0.0)
803 priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
804 avctx->i_quant_offset) + 0.5);
806 priv->fixed_qp_idr = priv->fixed_qp_p;
807 if (avctx->b_quant_factor > 0.0)
808 priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
809 avctx->b_quant_offset) + 0.5);
811 priv->fixed_qp_b = priv->fixed_qp_p;
813 priv->sei &= ~SEI_TIMING;
815 av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
816 "%d / %d / %d for IDR- / P- / B-frames.\n",
817 priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
819 } else if (ctx->va_rc_mode == VA_RC_CBR ||
820 ctx->va_rc_mode == VA_RC_VBR) {
821 // These still need to be set for pic_init_qp/slice_qp_delta.
822 priv->fixed_qp_idr = 26;
823 priv->fixed_qp_p = 26;
824 priv->fixed_qp_b = 26;
826 av_log(avctx, AV_LOG_DEBUG, "Using %s-bitrate = %"PRId64" bps.\n",
827 ctx->va_rc_mode == VA_RC_CBR ? "constant" : "variable",
831 av_assert0(0 && "Invalid RC mode.");
834 if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
835 avctx->compression_level = priv->quality;
837 if (priv->sei & SEI_IDENTIFIER) {
838 const char *lavc = LIBAVCODEC_IDENT;
839 const char *vaapi = VA_VERSION_S;
843 memcpy(priv->sei_identifier.uuid_iso_iec_11578,
844 vaapi_encode_h264_sei_identifier_uuid,
845 sizeof(priv->sei_identifier.uuid_iso_iec_11578));
847 driver = vaQueryVendorString(ctx->hwctx->display);
849 driver = "unknown driver";
851 len = snprintf(NULL, 0, "%s / VAAPI %s / %s", lavc, vaapi, driver);
853 priv->sei_identifier_string = av_malloc(len + 1);
854 if (!priv->sei_identifier_string)
855 return AVERROR(ENOMEM);
857 snprintf(priv->sei_identifier_string, len + 1,
858 "%s / VAAPI %s / %s", lavc, vaapi, driver);
860 priv->sei_identifier.data = priv->sei_identifier_string;
861 priv->sei_identifier.data_length = len + 1;
868 static const VAAPIEncodeProfile vaapi_encode_h264_profiles[] = {
869 { FF_PROFILE_H264_HIGH, 8, 3, 1, 1, VAProfileH264High },
870 { FF_PROFILE_H264_MAIN, 8, 3, 1, 1, VAProfileH264Main },
871 { FF_PROFILE_H264_CONSTRAINED_BASELINE,
872 8, 3, 1, 1, VAProfileH264ConstrainedBaseline },
873 { FF_PROFILE_UNKNOWN }
876 static const VAAPIEncodeType vaapi_encode_type_h264 = {
877 .profiles = vaapi_encode_h264_profiles,
879 .configure = &vaapi_encode_h264_configure,
881 .sequence_params_size = sizeof(VAEncSequenceParameterBufferH264),
882 .init_sequence_params = &vaapi_encode_h264_init_sequence_params,
884 .picture_params_size = sizeof(VAEncPictureParameterBufferH264),
885 .init_picture_params = &vaapi_encode_h264_init_picture_params,
887 .slice_params_size = sizeof(VAEncSliceParameterBufferH264),
888 .init_slice_params = &vaapi_encode_h264_init_slice_params,
890 .sequence_header_type = VAEncPackedHeaderSequence,
891 .write_sequence_header = &vaapi_encode_h264_write_sequence_header,
893 .slice_header_type = VAEncPackedHeaderH264_Slice,
894 .write_slice_header = &vaapi_encode_h264_write_slice_header,
896 .write_extra_header = &vaapi_encode_h264_write_extra_header,
899 static av_cold int vaapi_encode_h264_init(AVCodecContext *avctx)
901 VAAPIEncodeContext *ctx = avctx->priv_data;
902 VAAPIEncodeH264Context *priv = avctx->priv_data;
904 ctx->codec = &vaapi_encode_type_h264;
906 if (avctx->profile == FF_PROFILE_UNKNOWN)
907 avctx->profile = priv->profile;
908 if (avctx->level == FF_LEVEL_UNKNOWN)
909 avctx->level = priv->level;
911 // Reject unsupported profiles.
912 switch (avctx->profile) {
913 case FF_PROFILE_H264_BASELINE:
914 av_log(avctx, AV_LOG_WARNING, "H.264 baseline profile is not "
915 "supported, using constrained baseline profile instead.\n");
916 avctx->profile = FF_PROFILE_H264_CONSTRAINED_BASELINE;
918 case FF_PROFILE_H264_EXTENDED:
919 av_log(avctx, AV_LOG_ERROR, "H.264 extended profile "
920 "is not supported.\n");
921 return AVERROR_PATCHWELCOME;
922 case FF_PROFILE_H264_HIGH_10:
923 case FF_PROFILE_H264_HIGH_10_INTRA:
924 av_log(avctx, AV_LOG_ERROR, "H.264 10-bit profiles "
925 "are not supported.\n");
926 return AVERROR_PATCHWELCOME;
927 case FF_PROFILE_H264_HIGH_422:
928 case FF_PROFILE_H264_HIGH_422_INTRA:
929 case FF_PROFILE_H264_HIGH_444:
930 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
931 case FF_PROFILE_H264_HIGH_444_INTRA:
932 case FF_PROFILE_H264_CAVLC_444:
933 av_log(avctx, AV_LOG_ERROR, "H.264 non-4:2:0 profiles "
934 "are not supported.\n");
935 return AVERROR_PATCHWELCOME;
938 if (avctx->bit_rate > 0) {
939 if (avctx->rc_max_rate == avctx->bit_rate)
940 ctx->va_rc_mode = VA_RC_CBR;
942 ctx->va_rc_mode = VA_RC_VBR;
944 ctx->va_rc_mode = VA_RC_CQP;
946 ctx->va_packed_headers =
947 VA_ENC_PACKED_HEADER_SEQUENCE | // SPS and PPS.
948 VA_ENC_PACKED_HEADER_SLICE | // Slice headers.
949 VA_ENC_PACKED_HEADER_MISC; // SEI.
951 ctx->surface_width = FFALIGN(avctx->width, 16);
952 ctx->surface_height = FFALIGN(avctx->height, 16);
954 return ff_vaapi_encode_init(avctx);
957 static av_cold int vaapi_encode_h264_close(AVCodecContext *avctx)
959 VAAPIEncodeH264Context *priv = avctx->priv_data;
961 ff_cbs_close(&priv->cbc);
962 av_freep(&priv->sei_identifier_string);
964 return ff_vaapi_encode_close(avctx);
967 #define OFFSET(x) offsetof(VAAPIEncodeH264Context, x)
968 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
969 static const AVOption vaapi_encode_h264_options[] = {
970 VAAPI_ENCODE_COMMON_OPTIONS,
972 { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
973 OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 20 }, 0, 52, FLAGS },
974 { "quality", "Set encode quality (trades off against speed, higher is faster)",
975 OFFSET(quality), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 8, FLAGS },
976 { "coder", "Entropy coder type",
977 OFFSET(coder), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS, "coder" },
978 { "cavlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
979 { "cabac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
980 { "vlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
981 { "ac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
983 { "aud", "Include AUD",
984 OFFSET(aud), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
986 { "sei", "Set SEI to include",
987 OFFSET(sei), AV_OPT_TYPE_FLAGS,
988 { .i64 = SEI_IDENTIFIER | SEI_TIMING | SEI_RECOVERY_POINT },
989 0, INT_MAX, FLAGS, "sei" },
990 { "identifier", "Include encoder version identifier",
991 0, AV_OPT_TYPE_CONST, { .i64 = SEI_IDENTIFIER },
992 INT_MIN, INT_MAX, FLAGS, "sei" },
993 { "timing", "Include timing parameters (buffering_period and pic_timing)",
994 0, AV_OPT_TYPE_CONST, { .i64 = SEI_TIMING },
995 INT_MIN, INT_MAX, FLAGS, "sei" },
996 { "recovery_point", "Include recovery points where appropriate",
997 0, AV_OPT_TYPE_CONST, { .i64 = SEI_RECOVERY_POINT },
998 INT_MIN, INT_MAX, FLAGS, "sei" },
1000 { "profile", "Set profile (profile_idc and constraint_set*_flag)",
1001 OFFSET(profile), AV_OPT_TYPE_INT,
1002 { .i64 = FF_PROFILE_UNKNOWN }, FF_PROFILE_UNKNOWN, 0xffff, FLAGS, "profile" },
1004 #define PROFILE(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1005 { .i64 = value }, 0, 0, FLAGS, "profile"
1006 { PROFILE("constrained_baseline", FF_PROFILE_H264_CONSTRAINED_BASELINE) },
1007 { PROFILE("main", FF_PROFILE_H264_MAIN) },
1008 { PROFILE("high", FF_PROFILE_H264_HIGH) },
1011 { "level", "Set level (level_idc)",
1012 OFFSET(level), AV_OPT_TYPE_INT,
1013 { .i64 = 51 }, 0x00, 0xff, FLAGS, "level" },
1015 #define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1016 { .i64 = value }, 0, 0, FLAGS, "level"
1018 { LEVEL("1.1", 11) },
1019 { LEVEL("1.2", 12) },
1020 { LEVEL("1.3", 13) },
1022 { LEVEL("2.1", 21) },
1023 { LEVEL("2.2", 22) },
1025 { LEVEL("3.1", 31) },
1026 { LEVEL("3.2", 32) },
1028 { LEVEL("4.1", 41) },
1029 { LEVEL("4.2", 42) },
1031 { LEVEL("5.1", 51) },
1032 { LEVEL("5.2", 52) },
1034 { LEVEL("6.1", 61) },
1035 { LEVEL("6.2", 62) },
1041 static const AVCodecDefault vaapi_encode_h264_defaults[] = {
1045 { "i_qfactor", "1" },
1046 { "i_qoffset", "0" },
1047 { "b_qfactor", "6/5" },
1048 { "b_qoffset", "0" },
1053 static const AVClass vaapi_encode_h264_class = {
1054 .class_name = "h264_vaapi",
1055 .item_name = av_default_item_name,
1056 .option = vaapi_encode_h264_options,
1057 .version = LIBAVUTIL_VERSION_INT,
1060 AVCodec ff_h264_vaapi_encoder = {
1061 .name = "h264_vaapi",
1062 .long_name = NULL_IF_CONFIG_SMALL("H.264/AVC (VAAPI)"),
1063 .type = AVMEDIA_TYPE_VIDEO,
1064 .id = AV_CODEC_ID_H264,
1065 .priv_data_size = sizeof(VAAPIEncodeH264Context),
1066 .init = &vaapi_encode_h264_init,
1067 .encode2 = &ff_vaapi_encode2,
1068 .close = &vaapi_encode_h264_close,
1069 .priv_class = &vaapi_encode_h264_class,
1070 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
1071 .defaults = vaapi_encode_h264_defaults,
1072 .pix_fmts = (const enum AVPixelFormat[]) {
1076 .wrapper_name = "vaapi",