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;
74 int64_t last_idr_frame;
75 int64_t idr_pic_count;
84 CodedBitstreamContext *cbc;
85 CodedBitstreamFragment current_access_unit;
91 H264RawSlice raw_slice;
93 H264RawSEIBufferingPeriod sei_buffering_period;
94 H264RawSEIPicTiming sei_pic_timing;
95 H264RawSEIRecoveryPoint sei_recovery_point;
96 H264RawSEIUserDataUnregistered sei_identifier;
97 char *sei_identifier_string;
101 int sei_cbr_workaround_needed;
102 } VAAPIEncodeH264Context;
105 static int vaapi_encode_h264_write_access_unit(AVCodecContext *avctx,
106 char *data, size_t *data_len,
107 CodedBitstreamFragment *au)
109 VAAPIEncodeH264Context *priv = avctx->priv_data;
112 err = ff_cbs_write_fragment_data(priv->cbc, au);
114 av_log(avctx, AV_LOG_ERROR, "Failed to write packed header.\n");
118 if (*data_len < 8 * au->data_size - au->data_bit_padding) {
119 av_log(avctx, AV_LOG_ERROR, "Access unit too large: "
120 "%zu < %zu.\n", *data_len,
121 8 * au->data_size - au->data_bit_padding);
122 return AVERROR(ENOSPC);
125 memcpy(data, au->data, au->data_size);
126 *data_len = 8 * au->data_size - au->data_bit_padding;
131 static int vaapi_encode_h264_add_nal(AVCodecContext *avctx,
132 CodedBitstreamFragment *au,
135 VAAPIEncodeH264Context *priv = avctx->priv_data;
136 H264RawNALUnitHeader *header = nal_unit;
139 err = ff_cbs_insert_unit_content(priv->cbc, au, -1,
140 header->nal_unit_type, nal_unit, NULL);
142 av_log(avctx, AV_LOG_ERROR, "Failed to add NAL unit: "
143 "type = %d.\n", header->nal_unit_type);
150 static int vaapi_encode_h264_write_sequence_header(AVCodecContext *avctx,
151 char *data, size_t *data_len)
153 VAAPIEncodeH264Context *priv = avctx->priv_data;
154 CodedBitstreamFragment *au = &priv->current_access_unit;
157 if (priv->aud_needed) {
158 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_aud);
161 priv->aud_needed = 0;
164 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_sps);
168 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_pps);
172 err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
174 ff_cbs_fragment_uninit(priv->cbc, au);
178 static int vaapi_encode_h264_write_slice_header(AVCodecContext *avctx,
179 VAAPIEncodePicture *pic,
180 VAAPIEncodeSlice *slice,
181 char *data, size_t *data_len)
183 VAAPIEncodeH264Context *priv = avctx->priv_data;
184 CodedBitstreamFragment *au = &priv->current_access_unit;
187 if (priv->aud_needed) {
188 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_aud);
191 priv->aud_needed = 0;
194 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_slice);
198 err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
200 ff_cbs_fragment_uninit(priv->cbc, au);
204 static int vaapi_encode_h264_write_extra_header(AVCodecContext *avctx,
205 VAAPIEncodePicture *pic,
206 int index, int *type,
207 char *data, size_t *data_len)
209 VAAPIEncodeH264Context *priv = avctx->priv_data;
210 CodedBitstreamFragment *au = &priv->current_access_unit;
213 if (priv->sei_needed) {
214 H264RawSEI *sei = &priv->raw_sei;
216 if (priv->aud_needed) {
217 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_aud);
220 priv->aud_needed = 0;
223 *sei = (H264RawSEI) {
225 .nal_unit_type = H264_NAL_SEI,
231 if (priv->sei_needed & SEI_IDENTIFIER) {
232 sei->payload[i].payload_type = H264_SEI_TYPE_USER_DATA_UNREGISTERED;
233 sei->payload[i].payload.user_data_unregistered = priv->sei_identifier;
236 if (priv->sei_needed & SEI_TIMING) {
237 if (pic->type == PICTURE_TYPE_IDR) {
238 sei->payload[i].payload_type = H264_SEI_TYPE_BUFFERING_PERIOD;
239 sei->payload[i].payload.buffering_period = priv->sei_buffering_period;
242 sei->payload[i].payload_type = H264_SEI_TYPE_PIC_TIMING;
243 sei->payload[i].payload.pic_timing = priv->sei_pic_timing;
246 if (priv->sei_needed & SEI_RECOVERY_POINT) {
247 sei->payload[i].payload_type = H264_SEI_TYPE_RECOVERY_POINT;
248 sei->payload[i].payload.recovery_point = priv->sei_recovery_point;
252 sei->payload_count = i;
253 av_assert0(sei->payload_count > 0);
255 err = vaapi_encode_h264_add_nal(avctx, au, sei);
258 priv->sei_needed = 0;
260 err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
264 ff_cbs_fragment_uninit(priv->cbc, au);
266 *type = VAEncPackedHeaderRawData;
270 } else if (priv->sei_cbr_workaround_needed) {
271 // Insert a zero-length header using the old SEI type. This is
272 // required to avoid triggering broken behaviour on Intel platforms
273 // in CBR mode where an invalid SEI message is generated by the
274 // driver and inserted into the stream.
276 *type = VAEncPackedHeaderH264_SEI;
277 priv->sei_cbr_workaround_needed = 0;
286 ff_cbs_fragment_uninit(priv->cbc, au);
290 static int vaapi_encode_h264_init_sequence_params(AVCodecContext *avctx)
292 VAAPIEncodeContext *ctx = avctx->priv_data;
293 VAAPIEncodeH264Context *priv = avctx->priv_data;
294 H264RawSPS *sps = &priv->raw_sps;
295 H264RawPPS *pps = &priv->raw_pps;
296 VAEncSequenceParameterBufferH264 *vseq = ctx->codec_sequence_params;
297 VAEncPictureParameterBufferH264 *vpic = ctx->codec_picture_params;
299 memset(&priv->current_access_unit, 0,
300 sizeof(priv->current_access_unit));
302 memset(sps, 0, sizeof(*sps));
303 memset(pps, 0, sizeof(*pps));
305 sps->nal_unit_header.nal_ref_idc = 3;
306 sps->nal_unit_header.nal_unit_type = H264_NAL_SPS;
308 sps->profile_idc = avctx->profile & 0xff;
309 sps->constraint_set1_flag =
310 !!(avctx->profile & FF_PROFILE_H264_CONSTRAINED);
311 sps->constraint_set3_flag =
312 !!(avctx->profile & FF_PROFILE_H264_INTRA);
314 sps->level_idc = avctx->level;
316 sps->seq_parameter_set_id = 0;
317 sps->chroma_format_idc = 1;
319 sps->log2_max_frame_num_minus4 = 4;
320 sps->pic_order_cnt_type = 0;
321 sps->log2_max_pic_order_cnt_lsb_minus4 =
322 av_clip(av_log2(ctx->b_per_p + 1) - 2, 0, 12);
324 sps->max_num_ref_frames =
325 (avctx->profile & FF_PROFILE_H264_INTRA) ? 0 :
326 1 + (ctx->b_per_p > 0);
328 sps->pic_width_in_mbs_minus1 = priv->mb_width - 1;
329 sps->pic_height_in_map_units_minus1 = priv->mb_height - 1;
331 sps->frame_mbs_only_flag = 1;
332 sps->direct_8x8_inference_flag = 1;
334 if (avctx->width != 16 * priv->mb_width ||
335 avctx->height != 16 * priv->mb_height) {
336 sps->frame_cropping_flag = 1;
338 sps->frame_crop_left_offset = 0;
339 sps->frame_crop_right_offset =
340 (16 * priv->mb_width - avctx->width) / 2;
341 sps->frame_crop_top_offset = 0;
342 sps->frame_crop_bottom_offset =
343 (16 * priv->mb_height - avctx->height) / 2;
345 sps->frame_cropping_flag = 0;
348 sps->vui_parameters_present_flag = 1;
350 if (avctx->sample_aspect_ratio.num != 0 &&
351 avctx->sample_aspect_ratio.den != 0) {
352 static const AVRational sar_idc[] = {
354 { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 },
355 { 40, 33 }, { 24, 11 }, { 20, 11 }, { 32, 11 },
356 { 80, 33 }, { 18, 11 }, { 15, 11 }, { 64, 33 },
357 { 160, 99 }, { 4, 3 }, { 3, 2 }, { 2, 1 },
360 for (i = 0; i < FF_ARRAY_ELEMS(sar_idc); i++) {
361 if (avctx->sample_aspect_ratio.num == sar_idc[i].num &&
362 avctx->sample_aspect_ratio.den == sar_idc[i].den) {
363 sps->vui.aspect_ratio_idc = i;
367 if (i >= FF_ARRAY_ELEMS(sar_idc)) {
368 sps->vui.aspect_ratio_idc = 255;
369 sps->vui.sar_width = avctx->sample_aspect_ratio.num;
370 sps->vui.sar_height = avctx->sample_aspect_ratio.den;
372 sps->vui.aspect_ratio_info_present_flag = 1;
375 if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED ||
376 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
377 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
378 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
379 sps->vui.video_signal_type_present_flag = 1;
380 sps->vui.video_format = 5; // Unspecified.
381 sps->vui.video_full_range_flag =
382 avctx->color_range == AVCOL_RANGE_JPEG;
384 if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
385 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
386 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
387 sps->vui.colour_description_present_flag = 1;
388 sps->vui.colour_primaries = avctx->color_primaries;
389 sps->vui.transfer_characteristics = avctx->color_trc;
390 sps->vui.matrix_coefficients = avctx->colorspace;
393 sps->vui.video_format = 5;
394 sps->vui.video_full_range_flag = 0;
395 sps->vui.colour_primaries = avctx->color_primaries;
396 sps->vui.transfer_characteristics = avctx->color_trc;
397 sps->vui.matrix_coefficients = avctx->colorspace;
400 if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
401 sps->vui.chroma_loc_info_present_flag = 1;
402 sps->vui.chroma_sample_loc_type_top_field =
403 sps->vui.chroma_sample_loc_type_bottom_field =
404 avctx->chroma_sample_location - 1;
407 sps->vui.timing_info_present_flag = 1;
408 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
409 sps->vui.num_units_in_tick = avctx->framerate.den;
410 sps->vui.time_scale = 2 * avctx->framerate.num;
411 sps->vui.fixed_frame_rate_flag = 1;
413 sps->vui.num_units_in_tick = avctx->time_base.num;
414 sps->vui.time_scale = 2 * avctx->time_base.den;
415 sps->vui.fixed_frame_rate_flag = 0;
418 if (priv->sei & SEI_TIMING) {
419 H264RawHRD *hrd = &sps->vui.nal_hrd_parameters;
420 H264RawSEIBufferingPeriod *bp = &priv->sei_buffering_period;
422 sps->vui.nal_hrd_parameters_present_flag = 1;
424 hrd->cpb_cnt_minus1 = 0;
426 // Try to scale these to a sensible range so that the
427 // golomb encode of the value is not overlong.
428 hrd->bit_rate_scale =
429 av_clip_uintp2(av_log2(avctx->bit_rate) - 15 - 6, 4);
430 hrd->bit_rate_value_minus1[0] =
431 (avctx->bit_rate >> hrd->bit_rate_scale + 6) - 1;
433 hrd->cpb_size_scale =
434 av_clip_uintp2(av_log2(ctx->hrd_params.hrd.buffer_size) - 15 - 4, 4);
435 hrd->cpb_size_value_minus1[0] =
436 (ctx->hrd_params.hrd.buffer_size >> hrd->cpb_size_scale + 4) - 1;
438 // CBR mode as defined for the HRD cannot be achieved without filler
439 // data, so this flag cannot be set even with VAAPI CBR modes.
440 hrd->cbr_flag[0] = 0;
442 hrd->initial_cpb_removal_delay_length_minus1 = 23;
443 hrd->cpb_removal_delay_length_minus1 = 23;
444 hrd->dpb_output_delay_length_minus1 = 7;
445 hrd->time_offset_length = 0;
447 bp->seq_parameter_set_id = sps->seq_parameter_set_id;
449 // This calculation can easily overflow 32 bits.
450 bp->nal.initial_cpb_removal_delay[0] = 90000 *
451 (uint64_t)ctx->hrd_params.hrd.initial_buffer_fullness /
452 ctx->hrd_params.hrd.buffer_size;
453 bp->nal.initial_cpb_removal_delay_offset[0] = 0;
455 sps->vui.nal_hrd_parameters_present_flag = 0;
456 sps->vui.low_delay_hrd_flag = 1 - sps->vui.fixed_frame_rate_flag;
459 sps->vui.bitstream_restriction_flag = 1;
460 sps->vui.motion_vectors_over_pic_boundaries_flag = 1;
461 sps->vui.log2_max_mv_length_horizontal = 16;
462 sps->vui.log2_max_mv_length_vertical = 16;
463 sps->vui.max_num_reorder_frames = (ctx->b_per_p > 0);
464 sps->vui.max_dec_frame_buffering = sps->max_num_ref_frames;
466 pps->nal_unit_header.nal_ref_idc = 3;
467 pps->nal_unit_header.nal_unit_type = H264_NAL_PPS;
469 pps->pic_parameter_set_id = 0;
470 pps->seq_parameter_set_id = 0;
472 pps->entropy_coding_mode_flag =
473 !(sps->profile_idc == FF_PROFILE_H264_BASELINE ||
474 sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
475 sps->profile_idc == FF_PROFILE_H264_CAVLC_444);
476 if (!priv->coder && pps->entropy_coding_mode_flag)
477 pps->entropy_coding_mode_flag = 0;
479 pps->num_ref_idx_l0_default_active_minus1 = 0;
480 pps->num_ref_idx_l1_default_active_minus1 = 0;
482 pps->pic_init_qp_minus26 = priv->fixed_qp_idr - 26;
484 if (sps->profile_idc == FF_PROFILE_H264_BASELINE ||
485 sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
486 sps->profile_idc == FF_PROFILE_H264_MAIN) {
487 pps->more_rbsp_data = 0;
489 pps->more_rbsp_data = 1;
491 pps->transform_8x8_mode_flag = 1;
494 *vseq = (VAEncSequenceParameterBufferH264) {
495 .seq_parameter_set_id = sps->seq_parameter_set_id,
496 .level_idc = sps->level_idc,
497 .intra_period = avctx->gop_size,
498 .intra_idr_period = avctx->gop_size,
499 .ip_period = ctx->b_per_p + 1,
501 .bits_per_second = avctx->bit_rate,
502 .max_num_ref_frames = sps->max_num_ref_frames,
503 .picture_width_in_mbs = sps->pic_width_in_mbs_minus1 + 1,
504 .picture_height_in_mbs = sps->pic_height_in_map_units_minus1 + 1,
507 .chroma_format_idc = sps->chroma_format_idc,
508 .frame_mbs_only_flag = sps->frame_mbs_only_flag,
509 .mb_adaptive_frame_field_flag = sps->mb_adaptive_frame_field_flag,
510 .seq_scaling_matrix_present_flag = sps->seq_scaling_matrix_present_flag,
511 .direct_8x8_inference_flag = sps->direct_8x8_inference_flag,
512 .log2_max_frame_num_minus4 = sps->log2_max_frame_num_minus4,
513 .pic_order_cnt_type = sps->pic_order_cnt_type,
514 .log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_pic_order_cnt_lsb_minus4,
515 .delta_pic_order_always_zero_flag = sps->delta_pic_order_always_zero_flag,
518 .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
519 .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
521 .frame_cropping_flag = sps->frame_cropping_flag,
522 .frame_crop_left_offset = sps->frame_crop_left_offset,
523 .frame_crop_right_offset = sps->frame_crop_right_offset,
524 .frame_crop_top_offset = sps->frame_crop_top_offset,
525 .frame_crop_bottom_offset = sps->frame_crop_bottom_offset,
527 .vui_parameters_present_flag = sps->vui_parameters_present_flag,
530 .aspect_ratio_info_present_flag = sps->vui.aspect_ratio_info_present_flag,
531 .timing_info_present_flag = sps->vui.timing_info_present_flag,
532 .bitstream_restriction_flag = sps->vui.bitstream_restriction_flag,
533 .log2_max_mv_length_horizontal = sps->vui.log2_max_mv_length_horizontal,
534 .log2_max_mv_length_vertical = sps->vui.log2_max_mv_length_vertical,
537 .aspect_ratio_idc = sps->vui.aspect_ratio_idc,
538 .sar_width = sps->vui.sar_width,
539 .sar_height = sps->vui.sar_height,
540 .num_units_in_tick = sps->vui.num_units_in_tick,
541 .time_scale = sps->vui.time_scale,
544 *vpic = (VAEncPictureParameterBufferH264) {
546 .picture_id = VA_INVALID_ID,
547 .flags = VA_PICTURE_H264_INVALID,
550 .coded_buf = VA_INVALID_ID,
552 .pic_parameter_set_id = pps->pic_parameter_set_id,
553 .seq_parameter_set_id = pps->seq_parameter_set_id,
555 .pic_init_qp = pps->pic_init_qp_minus26 + 26,
556 .num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1,
557 .num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1,
559 .chroma_qp_index_offset = pps->chroma_qp_index_offset,
560 .second_chroma_qp_index_offset = pps->second_chroma_qp_index_offset,
563 .entropy_coding_mode_flag = pps->entropy_coding_mode_flag,
564 .weighted_pred_flag = pps->weighted_pred_flag,
565 .weighted_bipred_idc = pps->weighted_bipred_idc,
566 .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
567 .transform_8x8_mode_flag = pps->transform_8x8_mode_flag,
568 .deblocking_filter_control_present_flag =
569 pps->deblocking_filter_control_present_flag,
570 .redundant_pic_cnt_present_flag = pps->redundant_pic_cnt_present_flag,
571 .pic_order_present_flag =
572 pps->bottom_field_pic_order_in_frame_present_flag,
573 .pic_scaling_matrix_present_flag = pps->pic_scaling_matrix_present_flag,
580 static int vaapi_encode_h264_init_picture_params(AVCodecContext *avctx,
581 VAAPIEncodePicture *pic)
583 VAAPIEncodeContext *ctx = avctx->priv_data;
584 VAAPIEncodeH264Context *priv = avctx->priv_data;
585 H264RawSPS *sps = &priv->raw_sps;
586 VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
589 memset(&priv->current_access_unit, 0,
590 sizeof(priv->current_access_unit));
592 if (pic->type == PICTURE_TYPE_IDR) {
593 av_assert0(pic->display_order == pic->encode_order);
595 priv->next_frame_num = 1;
597 priv->last_idr_frame = pic->display_order;
598 ++priv->idr_pic_count;
600 priv->slice_type = 7;
601 priv->primary_pic_type = 0;
603 priv->frame_num = priv->next_frame_num;
605 if (pic->type != PICTURE_TYPE_B) {
606 // Reference picture, so frame_num advances.
607 priv->next_frame_num = (priv->frame_num + 1) &
608 ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
612 if (pic->type == PICTURE_TYPE_I) {
613 priv->slice_type = 7;
614 priv->primary_pic_type = 0;
615 } else if (pic->type == PICTURE_TYPE_P) {
616 priv->slice_type = 5;
617 priv->primary_pic_type = 1;
619 priv->slice_type = 6;
620 priv->primary_pic_type = 2;
623 priv->pic_order_cnt = pic->display_order - priv->last_idr_frame;
624 priv->dpb_delay = pic->display_order - pic->encode_order + 1;
627 priv->aud_needed = 1;
628 priv->raw_aud = (H264RawAUD) {
630 .nal_unit_type = H264_NAL_AUD,
632 .primary_pic_type = priv->primary_pic_type,
635 priv->aud_needed = 0;
638 priv->sei_needed = 0;
640 if (priv->sei & SEI_IDENTIFIER && pic->encode_order == 0)
641 priv->sei_needed |= SEI_IDENTIFIER;
643 if (ctx->va_rc_mode == VA_RC_CBR)
644 priv->sei_cbr_workaround_needed = 1;
647 if (priv->sei & SEI_TIMING) {
648 priv->sei_pic_timing = (H264RawSEIPicTiming) {
649 .cpb_removal_delay = 2 * priv->cpb_delay,
650 .dpb_output_delay = 2 * priv->dpb_delay,
653 priv->sei_needed |= SEI_TIMING;
656 if (priv->sei & SEI_RECOVERY_POINT && pic->type == PICTURE_TYPE_I) {
657 priv->sei_recovery_point = (H264RawSEIRecoveryPoint) {
658 .recovery_frame_cnt = 0,
659 .exact_match_flag = 1,
660 .broken_link_flag = ctx->b_per_p > 0,
663 priv->sei_needed |= SEI_RECOVERY_POINT;
666 vpic->CurrPic = (VAPictureH264) {
667 .picture_id = pic->recon_surface,
668 .frame_idx = priv->frame_num,
670 .TopFieldOrderCnt = priv->pic_order_cnt,
671 .BottomFieldOrderCnt = priv->pic_order_cnt,
674 for (i = 0; i < pic->nb_refs; i++) {
675 VAAPIEncodePicture *ref = pic->refs[i];
676 unsigned int frame_num = (ref->encode_order - priv->last_idr_frame) &
677 ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
678 unsigned int pic_order_cnt = ref->display_order - priv->last_idr_frame;
680 av_assert0(ref && ref->encode_order < pic->encode_order);
681 vpic->ReferenceFrames[i] = (VAPictureH264) {
682 .picture_id = ref->recon_surface,
683 .frame_idx = frame_num,
684 .flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE,
685 .TopFieldOrderCnt = pic_order_cnt,
686 .BottomFieldOrderCnt = pic_order_cnt,
689 for (; i < FF_ARRAY_ELEMS(vpic->ReferenceFrames); i++) {
690 vpic->ReferenceFrames[i] = (VAPictureH264) {
691 .picture_id = VA_INVALID_ID,
692 .flags = VA_PICTURE_H264_INVALID,
696 vpic->coded_buf = pic->output_buffer;
698 vpic->frame_num = priv->frame_num;
700 vpic->pic_fields.bits.idr_pic_flag = (pic->type == PICTURE_TYPE_IDR);
701 vpic->pic_fields.bits.reference_pic_flag = (pic->type != PICTURE_TYPE_B);
708 static int vaapi_encode_h264_init_slice_params(AVCodecContext *avctx,
709 VAAPIEncodePicture *pic,
710 VAAPIEncodeSlice *slice)
712 VAAPIEncodeH264Context *priv = avctx->priv_data;
713 H264RawSPS *sps = &priv->raw_sps;
714 H264RawPPS *pps = &priv->raw_pps;
715 H264RawSliceHeader *sh = &priv->raw_slice.header;
716 VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
717 VAEncSliceParameterBufferH264 *vslice = slice->codec_slice_params;
720 if (pic->type == PICTURE_TYPE_IDR) {
721 sh->nal_unit_header.nal_unit_type = H264_NAL_IDR_SLICE;
722 sh->nal_unit_header.nal_ref_idc = 3;
724 sh->nal_unit_header.nal_unit_type = H264_NAL_SLICE;
725 sh->nal_unit_header.nal_ref_idc = pic->type != PICTURE_TYPE_B;
728 // Only one slice per frame.
729 sh->first_mb_in_slice = 0;
730 sh->slice_type = priv->slice_type;
732 sh->pic_parameter_set_id = pps->pic_parameter_set_id;
734 sh->frame_num = priv->frame_num;
735 sh->idr_pic_id = priv->idr_pic_count;
737 sh->pic_order_cnt_lsb = priv->pic_order_cnt &
738 ((1 << (4 + sps->log2_max_pic_order_cnt_lsb_minus4)) - 1);
740 sh->direct_spatial_mv_pred_flag = 1;
742 if (pic->type == PICTURE_TYPE_B)
743 sh->slice_qp_delta = priv->fixed_qp_b - (pps->pic_init_qp_minus26 + 26);
744 else if (pic->type == PICTURE_TYPE_P)
745 sh->slice_qp_delta = priv->fixed_qp_p - (pps->pic_init_qp_minus26 + 26);
747 sh->slice_qp_delta = priv->fixed_qp_idr - (pps->pic_init_qp_minus26 + 26);
750 vslice->macroblock_address = sh->first_mb_in_slice;
751 vslice->num_macroblocks = priv->mb_width * priv->mb_height;
753 vslice->macroblock_info = VA_INVALID_ID;
755 vslice->slice_type = sh->slice_type % 5;
756 vslice->pic_parameter_set_id = sh->pic_parameter_set_id;
757 vslice->idr_pic_id = sh->idr_pic_id;
759 vslice->pic_order_cnt_lsb = sh->pic_order_cnt_lsb;
761 vslice->direct_spatial_mv_pred_flag = sh->direct_spatial_mv_pred_flag;
763 for (i = 0; i < FF_ARRAY_ELEMS(vslice->RefPicList0); i++) {
764 vslice->RefPicList0[i].picture_id = VA_INVALID_ID;
765 vslice->RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
766 vslice->RefPicList1[i].picture_id = VA_INVALID_ID;
767 vslice->RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
770 av_assert0(pic->nb_refs <= 2);
771 if (pic->nb_refs >= 1) {
772 // Backward reference for P- or B-frame.
773 av_assert0(pic->type == PICTURE_TYPE_P ||
774 pic->type == PICTURE_TYPE_B);
775 vslice->RefPicList0[0] = vpic->ReferenceFrames[0];
777 if (pic->nb_refs >= 2) {
778 // Forward reference for B-frame.
779 av_assert0(pic->type == PICTURE_TYPE_B);
780 vslice->RefPicList1[0] = vpic->ReferenceFrames[1];
783 vslice->slice_qp_delta = sh->slice_qp_delta;
788 static av_cold int vaapi_encode_h264_configure(AVCodecContext *avctx)
790 VAAPIEncodeContext *ctx = avctx->priv_data;
791 VAAPIEncodeH264Context *priv = avctx->priv_data;
794 err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_H264, avctx);
798 priv->mb_width = FFALIGN(avctx->width, 16) / 16;
799 priv->mb_height = FFALIGN(avctx->height, 16) / 16;
801 if (ctx->va_rc_mode == VA_RC_CQP) {
802 priv->fixed_qp_p = priv->qp;
803 if (avctx->i_quant_factor > 0.0)
804 priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
805 avctx->i_quant_offset) + 0.5);
807 priv->fixed_qp_idr = priv->fixed_qp_p;
808 if (avctx->b_quant_factor > 0.0)
809 priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
810 avctx->b_quant_offset) + 0.5);
812 priv->fixed_qp_b = priv->fixed_qp_p;
814 priv->sei &= ~SEI_TIMING;
816 av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
817 "%d / %d / %d for IDR- / P- / B-frames.\n",
818 priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
820 } else if (ctx->va_rc_mode == VA_RC_CBR ||
821 ctx->va_rc_mode == VA_RC_VBR) {
822 // These still need to be set for pic_init_qp/slice_qp_delta.
823 priv->fixed_qp_idr = 26;
824 priv->fixed_qp_p = 26;
825 priv->fixed_qp_b = 26;
827 av_log(avctx, AV_LOG_DEBUG, "Using %s-bitrate = %"PRId64" bps.\n",
828 ctx->va_rc_mode == VA_RC_CBR ? "constant" : "variable",
832 av_assert0(0 && "Invalid RC mode.");
835 if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
836 avctx->compression_level = priv->quality;
838 if (priv->sei & SEI_IDENTIFIER) {
839 const char *lavc = LIBAVCODEC_IDENT;
840 const char *vaapi = VA_VERSION_S;
844 memcpy(priv->sei_identifier.uuid_iso_iec_11578,
845 vaapi_encode_h264_sei_identifier_uuid,
846 sizeof(priv->sei_identifier.uuid_iso_iec_11578));
848 driver = vaQueryVendorString(ctx->hwctx->display);
850 driver = "unknown driver";
852 len = snprintf(NULL, 0, "%s / VAAPI %s / %s", lavc, vaapi, driver);
854 priv->sei_identifier_string = av_malloc(len + 1);
855 if (!priv->sei_identifier_string)
856 return AVERROR(ENOMEM);
858 snprintf(priv->sei_identifier_string, len + 1,
859 "%s / VAAPI %s / %s", lavc, vaapi, driver);
861 priv->sei_identifier.data = priv->sei_identifier_string;
862 priv->sei_identifier.data_length = len + 1;
869 static const VAAPIEncodeType vaapi_encode_type_h264 = {
870 .configure = &vaapi_encode_h264_configure,
872 .sequence_params_size = sizeof(VAEncSequenceParameterBufferH264),
873 .init_sequence_params = &vaapi_encode_h264_init_sequence_params,
875 .picture_params_size = sizeof(VAEncPictureParameterBufferH264),
876 .init_picture_params = &vaapi_encode_h264_init_picture_params,
878 .slice_params_size = sizeof(VAEncSliceParameterBufferH264),
879 .init_slice_params = &vaapi_encode_h264_init_slice_params,
881 .sequence_header_type = VAEncPackedHeaderSequence,
882 .write_sequence_header = &vaapi_encode_h264_write_sequence_header,
884 .slice_header_type = VAEncPackedHeaderH264_Slice,
885 .write_slice_header = &vaapi_encode_h264_write_slice_header,
887 .write_extra_header = &vaapi_encode_h264_write_extra_header,
890 static av_cold int vaapi_encode_h264_init(AVCodecContext *avctx)
892 VAAPIEncodeContext *ctx = avctx->priv_data;
893 VAAPIEncodeH264Context *priv = avctx->priv_data;
895 ctx->codec = &vaapi_encode_type_h264;
897 if (avctx->profile == FF_PROFILE_UNKNOWN)
898 avctx->profile = priv->profile;
899 if (avctx->level == FF_LEVEL_UNKNOWN)
900 avctx->level = priv->level;
902 switch (avctx->profile) {
903 case FF_PROFILE_H264_BASELINE:
904 av_log(avctx, AV_LOG_WARNING, "H.264 baseline profile is not "
905 "supported, using constrained baseline profile instead.\n");
906 avctx->profile = FF_PROFILE_H264_CONSTRAINED_BASELINE;
907 case FF_PROFILE_H264_CONSTRAINED_BASELINE:
908 ctx->va_profile = VAProfileH264ConstrainedBaseline;
909 if (avctx->max_b_frames != 0) {
910 avctx->max_b_frames = 0;
911 av_log(avctx, AV_LOG_WARNING, "H.264 constrained baseline profile "
912 "doesn't support encoding with B frames, disabling them.\n");
915 case FF_PROFILE_H264_MAIN:
916 ctx->va_profile = VAProfileH264Main;
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_UNKNOWN:
923 case FF_PROFILE_H264_HIGH:
924 ctx->va_profile = VAProfileH264High;
926 case FF_PROFILE_H264_HIGH_10:
927 case FF_PROFILE_H264_HIGH_10_INTRA:
928 av_log(avctx, AV_LOG_ERROR, "H.264 10-bit profiles "
929 "are not supported.\n");
930 return AVERROR_PATCHWELCOME;
931 case FF_PROFILE_H264_HIGH_422:
932 case FF_PROFILE_H264_HIGH_422_INTRA:
933 case FF_PROFILE_H264_HIGH_444:
934 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
935 case FF_PROFILE_H264_HIGH_444_INTRA:
936 case FF_PROFILE_H264_CAVLC_444:
937 av_log(avctx, AV_LOG_ERROR, "H.264 non-4:2:0 profiles "
938 "are not supported.\n");
939 return AVERROR_PATCHWELCOME;
941 av_log(avctx, AV_LOG_ERROR, "Unknown H.264 profile %d.\n",
943 return AVERROR(EINVAL);
945 if (priv->low_power) {
946 #if VA_CHECK_VERSION(0, 39, 2)
947 ctx->va_entrypoint = VAEntrypointEncSliceLP;
949 av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
950 "supported with this VAAPI version.\n");
951 return AVERROR(EINVAL);
954 ctx->va_entrypoint = VAEntrypointEncSlice;
957 // Only 8-bit encode is supported.
958 ctx->va_rt_format = VA_RT_FORMAT_YUV420;
960 if (avctx->bit_rate > 0) {
961 if (avctx->rc_max_rate == avctx->bit_rate)
962 ctx->va_rc_mode = VA_RC_CBR;
964 ctx->va_rc_mode = VA_RC_VBR;
966 ctx->va_rc_mode = VA_RC_CQP;
968 ctx->va_packed_headers =
969 VA_ENC_PACKED_HEADER_SEQUENCE | // SPS and PPS.
970 VA_ENC_PACKED_HEADER_SLICE | // Slice headers.
971 VA_ENC_PACKED_HEADER_MISC; // SEI.
973 ctx->surface_width = FFALIGN(avctx->width, 16);
974 ctx->surface_height = FFALIGN(avctx->height, 16);
976 return ff_vaapi_encode_init(avctx);
979 static av_cold int vaapi_encode_h264_close(AVCodecContext *avctx)
981 VAAPIEncodeH264Context *priv = avctx->priv_data;
983 ff_cbs_close(&priv->cbc);
984 av_freep(&priv->sei_identifier_string);
986 return ff_vaapi_encode_close(avctx);
989 #define OFFSET(x) offsetof(VAAPIEncodeH264Context, x)
990 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
991 static const AVOption vaapi_encode_h264_options[] = {
992 { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
993 OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 20 }, 0, 52, FLAGS },
994 { "quality", "Set encode quality (trades off against speed, higher is faster)",
995 OFFSET(quality), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 8, FLAGS },
996 { "low_power", "Use low-power encoding mode (experimental: only supported "
997 "on some platforms, does not support all features)",
998 OFFSET(low_power), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
999 { "coder", "Entropy coder type",
1000 OFFSET(coder), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS, "coder" },
1001 { "cavlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
1002 { "cabac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
1003 { "vlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
1004 { "ac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
1006 { "aud", "Include AUD",
1007 OFFSET(aud), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
1009 { "sei", "Set SEI to include",
1010 OFFSET(sei), AV_OPT_TYPE_FLAGS,
1011 { .i64 = SEI_IDENTIFIER | SEI_TIMING | SEI_RECOVERY_POINT },
1012 0, INT_MAX, FLAGS, "sei" },
1013 { "identifier", "Include encoder version identifier",
1014 0, AV_OPT_TYPE_CONST, { .i64 = SEI_IDENTIFIER },
1015 INT_MIN, INT_MAX, FLAGS, "sei" },
1016 { "timing", "Include timing parameters (buffering_period and pic_timing)",
1017 0, AV_OPT_TYPE_CONST, { .i64 = SEI_TIMING },
1018 INT_MIN, INT_MAX, FLAGS, "sei" },
1019 { "recovery_point", "Include recovery points where appropriate",
1020 0, AV_OPT_TYPE_CONST, { .i64 = SEI_RECOVERY_POINT },
1021 INT_MIN, INT_MAX, FLAGS, "sei" },
1023 { "profile", "Set profile (profile_idc and constraint_set*_flag)",
1024 OFFSET(profile), AV_OPT_TYPE_INT,
1025 { .i64 = FF_PROFILE_H264_HIGH }, 0x0000, 0xffff, FLAGS, "profile" },
1027 #define PROFILE(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1028 { .i64 = value }, 0, 0, FLAGS, "profile"
1029 { PROFILE("constrained_baseline", FF_PROFILE_H264_CONSTRAINED_BASELINE) },
1030 { PROFILE("main", FF_PROFILE_H264_MAIN) },
1031 { PROFILE("high", FF_PROFILE_H264_HIGH) },
1034 { "level", "Set level (level_idc)",
1035 OFFSET(level), AV_OPT_TYPE_INT,
1036 { .i64 = 51 }, 0x00, 0xff, FLAGS, "level" },
1038 #define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1039 { .i64 = value }, 0, 0, FLAGS, "level"
1041 { LEVEL("1.1", 11) },
1042 { LEVEL("1.2", 12) },
1043 { LEVEL("1.3", 13) },
1045 { LEVEL("2.1", 21) },
1046 { LEVEL("2.2", 22) },
1048 { LEVEL("3.1", 31) },
1049 { LEVEL("3.2", 32) },
1051 { LEVEL("4.1", 41) },
1052 { LEVEL("4.2", 42) },
1054 { LEVEL("5.1", 51) },
1055 { LEVEL("5.2", 52) },
1057 { LEVEL("6.1", 61) },
1058 { LEVEL("6.2", 62) },
1064 static const AVCodecDefault vaapi_encode_h264_defaults[] = {
1068 { "i_qfactor", "1" },
1069 { "i_qoffset", "0" },
1070 { "b_qfactor", "6/5" },
1071 { "b_qoffset", "0" },
1076 static const AVClass vaapi_encode_h264_class = {
1077 .class_name = "h264_vaapi",
1078 .item_name = av_default_item_name,
1079 .option = vaapi_encode_h264_options,
1080 .version = LIBAVUTIL_VERSION_INT,
1083 AVCodec ff_h264_vaapi_encoder = {
1084 .name = "h264_vaapi",
1085 .long_name = NULL_IF_CONFIG_SMALL("H.264/AVC (VAAPI)"),
1086 .type = AVMEDIA_TYPE_VIDEO,
1087 .id = AV_CODEC_ID_H264,
1088 .priv_data_size = sizeof(VAAPIEncodeH264Context),
1089 .init = &vaapi_encode_h264_init,
1090 .encode2 = &ff_vaapi_encode2,
1091 .close = &vaapi_encode_h264_close,
1092 .priv_class = &vaapi_encode_h264_class,
1093 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
1094 .defaults = vaapi_encode_h264_defaults,
1095 .pix_fmts = (const enum AVPixelFormat[]) {
1099 .wrapper_name = "vaapi",