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 {
63 H264RawSEIBufferingPeriod buffering_period;
64 H264RawSEIPicTiming pic_timing;
65 H264RawSEIRecoveryPoint recovery_point;
66 H264RawSEIUserDataUnregistered identifier;
67 char *identifier_string;
72 int64_t last_idr_frame;
73 int64_t idr_pic_count;
81 CodedBitstreamContext *cbc;
82 CodedBitstreamFragment current_access_unit;
85 int sei_cbr_workaround_needed;
86 } VAAPIEncodeH264Context;
88 typedef struct VAAPIEncodeH264Options {
92 // Entropy encoder type.
98 } VAAPIEncodeH264Options;
101 static int vaapi_encode_h264_write_access_unit(AVCodecContext *avctx,
102 char *data, size_t *data_len,
103 CodedBitstreamFragment *au)
105 VAAPIEncodeContext *ctx = avctx->priv_data;
106 VAAPIEncodeH264Context *priv = ctx->priv_data;
109 err = ff_cbs_write_fragment_data(priv->cbc, au);
111 av_log(avctx, AV_LOG_ERROR, "Failed to write packed header.\n");
115 if (*data_len < 8 * au->data_size - au->data_bit_padding) {
116 av_log(avctx, AV_LOG_ERROR, "Access unit too large: "
117 "%zu < %zu.\n", *data_len,
118 8 * au->data_size - au->data_bit_padding);
119 return AVERROR(ENOSPC);
122 memcpy(data, au->data, au->data_size);
123 *data_len = 8 * au->data_size - au->data_bit_padding;
128 static int vaapi_encode_h264_add_nal(AVCodecContext *avctx,
129 CodedBitstreamFragment *au,
132 VAAPIEncodeContext *ctx = avctx->priv_data;
133 VAAPIEncodeH264Context *priv = ctx->priv_data;
134 H264RawNALUnitHeader *header = nal_unit;
137 err = ff_cbs_insert_unit_content(priv->cbc, au, -1,
138 header->nal_unit_type, nal_unit, NULL);
140 av_log(avctx, AV_LOG_ERROR, "Failed to add NAL unit: "
141 "type = %d.\n", header->nal_unit_type);
148 static int vaapi_encode_h264_write_sequence_header(AVCodecContext *avctx,
149 char *data, size_t *data_len)
151 VAAPIEncodeContext *ctx = avctx->priv_data;
152 VAAPIEncodeH264Context *priv = ctx->priv_data;
153 CodedBitstreamFragment *au = &priv->current_access_unit;
156 if (priv->aud_needed) {
157 err = vaapi_encode_h264_add_nal(avctx, au, &priv->aud);
160 priv->aud_needed = 0;
163 err = vaapi_encode_h264_add_nal(avctx, au, &priv->sps);
167 err = vaapi_encode_h264_add_nal(avctx, au, &priv->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 VAAPIEncodeContext *ctx = avctx->priv_data;
183 VAAPIEncodeH264Context *priv = ctx->priv_data;
184 CodedBitstreamFragment *au = &priv->current_access_unit;
187 if (priv->aud_needed) {
188 err = vaapi_encode_h264_add_nal(avctx, au, &priv->aud);
191 priv->aud_needed = 0;
194 err = vaapi_encode_h264_add_nal(avctx, au, &priv->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 VAAPIEncodeContext *ctx = avctx->priv_data;
210 VAAPIEncodeH264Context *priv = ctx->priv_data;
211 VAAPIEncodeH264Options *opt = ctx->codec_options;
212 CodedBitstreamFragment *au = &priv->current_access_unit;
215 if (priv->sei_needed) {
216 if (priv->aud_needed) {
217 err = vaapi_encode_h264_add_nal(avctx, au, &priv->aud);
220 priv->aud_needed = 0;
223 memset(&priv->sei, 0, sizeof(priv->sei));
224 priv->sei.nal_unit_header.nal_unit_type = H264_NAL_SEI;
227 if (pic->encode_order == 0 && opt->sei & SEI_IDENTIFIER) {
228 priv->sei.payload[i].payload_type = H264_SEI_TYPE_USER_DATA_UNREGISTERED;
229 priv->sei.payload[i].payload.user_data_unregistered = priv->identifier;
232 if (opt->sei & SEI_TIMING) {
233 if (pic->type == PICTURE_TYPE_IDR) {
234 priv->sei.payload[i].payload_type = H264_SEI_TYPE_BUFFERING_PERIOD;
235 priv->sei.payload[i].payload.buffering_period = priv->buffering_period;
238 priv->sei.payload[i].payload_type = H264_SEI_TYPE_PIC_TIMING;
239 priv->sei.payload[i].payload.pic_timing = priv->pic_timing;
242 if (opt->sei & SEI_RECOVERY_POINT && pic->type == PICTURE_TYPE_I) {
243 priv->sei.payload[i].payload_type = H264_SEI_TYPE_RECOVERY_POINT;
244 priv->sei.payload[i].payload.recovery_point = priv->recovery_point;
248 priv->sei.payload_count = i;
249 av_assert0(priv->sei.payload_count > 0);
251 err = vaapi_encode_h264_add_nal(avctx, au, &priv->sei);
254 priv->sei_needed = 0;
256 err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
260 ff_cbs_fragment_uninit(priv->cbc, au);
262 *type = VAEncPackedHeaderRawData;
266 } else if (priv->sei_cbr_workaround_needed) {
267 // Insert a zero-length header using the old SEI type. This is
268 // required to avoid triggering broken behaviour on Intel platforms
269 // in CBR mode where an invalid SEI message is generated by the
270 // driver and inserted into the stream.
272 *type = VAEncPackedHeaderH264_SEI;
273 priv->sei_cbr_workaround_needed = 0;
282 ff_cbs_fragment_uninit(priv->cbc, au);
286 static int vaapi_encode_h264_init_sequence_params(AVCodecContext *avctx)
288 VAAPIEncodeContext *ctx = avctx->priv_data;
289 VAAPIEncodeH264Context *priv = ctx->priv_data;
290 VAAPIEncodeH264Options *opt = ctx->codec_options;
291 H264RawSPS *sps = &priv->sps;
292 H264RawPPS *pps = &priv->pps;
293 VAEncSequenceParameterBufferH264 *vseq = ctx->codec_sequence_params;
294 VAEncPictureParameterBufferH264 *vpic = ctx->codec_picture_params;
296 memset(&priv->current_access_unit, 0,
297 sizeof(priv->current_access_unit));
299 memset(sps, 0, sizeof(*sps));
300 memset(pps, 0, sizeof(*pps));
302 sps->nal_unit_header.nal_ref_idc = 3;
303 sps->nal_unit_header.nal_unit_type = H264_NAL_SPS;
305 sps->profile_idc = avctx->profile & 0xff;
306 sps->constraint_set1_flag =
307 !!(avctx->profile & FF_PROFILE_H264_CONSTRAINED);
308 sps->constraint_set3_flag =
309 !!(avctx->profile & FF_PROFILE_H264_INTRA);
311 sps->level_idc = avctx->level;
313 sps->seq_parameter_set_id = 0;
314 sps->chroma_format_idc = 1;
316 sps->log2_max_frame_num_minus4 = 4;
317 sps->pic_order_cnt_type = 0;
318 sps->log2_max_pic_order_cnt_lsb_minus4 =
319 av_clip(av_log2(ctx->b_per_p + 1) - 2, 0, 12);
321 sps->max_num_ref_frames =
322 (avctx->profile & FF_PROFILE_H264_INTRA) ? 0 :
323 1 + (ctx->b_per_p > 0);
325 sps->pic_width_in_mbs_minus1 = priv->mb_width - 1;
326 sps->pic_height_in_map_units_minus1 = priv->mb_height - 1;
328 sps->frame_mbs_only_flag = 1;
329 sps->direct_8x8_inference_flag = 1;
331 if (avctx->width != 16 * priv->mb_width ||
332 avctx->height != 16 * priv->mb_height) {
333 sps->frame_cropping_flag = 1;
335 sps->frame_crop_left_offset = 0;
336 sps->frame_crop_right_offset =
337 (16 * priv->mb_width - avctx->width) / 2;
338 sps->frame_crop_top_offset = 0;
339 sps->frame_crop_bottom_offset =
340 (16 * priv->mb_height - avctx->height) / 2;
342 sps->frame_cropping_flag = 0;
345 sps->vui_parameters_present_flag = 1;
347 if (avctx->sample_aspect_ratio.num != 0 &&
348 avctx->sample_aspect_ratio.den != 0) {
349 static const AVRational sar_idc[] = {
351 { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 },
352 { 40, 33 }, { 24, 11 }, { 20, 11 }, { 32, 11 },
353 { 80, 33 }, { 18, 11 }, { 15, 11 }, { 64, 33 },
354 { 160, 99 }, { 4, 3 }, { 3, 2 }, { 2, 1 },
357 for (i = 0; i < FF_ARRAY_ELEMS(sar_idc); i++) {
358 if (avctx->sample_aspect_ratio.num == sar_idc[i].num &&
359 avctx->sample_aspect_ratio.den == sar_idc[i].den) {
360 sps->vui.aspect_ratio_idc = i;
364 if (i >= FF_ARRAY_ELEMS(sar_idc)) {
365 sps->vui.aspect_ratio_idc = 255;
366 sps->vui.sar_width = avctx->sample_aspect_ratio.num;
367 sps->vui.sar_height = avctx->sample_aspect_ratio.den;
369 sps->vui.aspect_ratio_info_present_flag = 1;
372 if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED ||
373 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
374 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
375 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
376 sps->vui.video_signal_type_present_flag = 1;
377 sps->vui.video_format = 5; // Unspecified.
378 sps->vui.video_full_range_flag =
379 avctx->color_range == AVCOL_RANGE_JPEG;
381 if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
382 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
383 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
384 sps->vui.colour_description_present_flag = 1;
385 sps->vui.colour_primaries = avctx->color_primaries;
386 sps->vui.transfer_characteristics = avctx->color_trc;
387 sps->vui.matrix_coefficients = avctx->colorspace;
390 sps->vui.video_format = 5;
391 sps->vui.video_full_range_flag = 0;
392 sps->vui.colour_primaries = avctx->color_primaries;
393 sps->vui.transfer_characteristics = avctx->color_trc;
394 sps->vui.matrix_coefficients = avctx->colorspace;
397 if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
398 sps->vui.chroma_loc_info_present_flag = 1;
399 sps->vui.chroma_sample_loc_type_top_field =
400 sps->vui.chroma_sample_loc_type_bottom_field =
401 avctx->chroma_sample_location - 1;
404 sps->vui.timing_info_present_flag = 1;
405 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
406 sps->vui.num_units_in_tick = avctx->framerate.den;
407 sps->vui.time_scale = 2 * avctx->framerate.num;
408 sps->vui.fixed_frame_rate_flag = 1;
410 sps->vui.num_units_in_tick = avctx->time_base.num;
411 sps->vui.time_scale = 2 * avctx->time_base.den;
412 sps->vui.fixed_frame_rate_flag = 0;
415 if (opt->sei & SEI_TIMING) {
416 H264RawHRD *hrd = &sps->vui.nal_hrd_parameters;
418 sps->vui.nal_hrd_parameters_present_flag = 1;
420 hrd->cpb_cnt_minus1 = 0;
422 // Try to scale these to a sensible range so that the
423 // golomb encode of the value is not overlong.
424 hrd->bit_rate_scale =
425 av_clip_uintp2(av_log2(avctx->bit_rate) - 15 - 6, 4);
426 hrd->bit_rate_value_minus1[0] =
427 (avctx->bit_rate >> hrd->bit_rate_scale + 6) - 1;
429 hrd->cpb_size_scale =
430 av_clip_uintp2(av_log2(ctx->hrd_params.hrd.buffer_size) - 15 - 4, 4);
431 hrd->cpb_size_value_minus1[0] =
432 (ctx->hrd_params.hrd.buffer_size >> hrd->cpb_size_scale + 4) - 1;
434 // CBR mode as defined for the HRD cannot be achieved without filler
435 // data, so this flag cannot be set even with VAAPI CBR modes.
436 hrd->cbr_flag[0] = 0;
438 hrd->initial_cpb_removal_delay_length_minus1 = 23;
439 hrd->cpb_removal_delay_length_minus1 = 23;
440 hrd->dpb_output_delay_length_minus1 = 7;
441 hrd->time_offset_length = 0;
443 priv->buffering_period.seq_parameter_set_id = sps->seq_parameter_set_id;
445 // This calculation can easily overflow 32 bits.
446 priv->buffering_period.nal.initial_cpb_removal_delay[0] = 90000 *
447 (uint64_t)ctx->hrd_params.hrd.initial_buffer_fullness /
448 ctx->hrd_params.hrd.buffer_size;
449 priv->buffering_period.nal.initial_cpb_removal_delay_offset[0] = 0;
451 sps->vui.nal_hrd_parameters_present_flag = 0;
452 sps->vui.low_delay_hrd_flag = 1 - sps->vui.fixed_frame_rate_flag;
455 sps->vui.bitstream_restriction_flag = 1;
456 sps->vui.motion_vectors_over_pic_boundaries_flag = 1;
457 sps->vui.log2_max_mv_length_horizontal = 16;
458 sps->vui.log2_max_mv_length_vertical = 16;
459 sps->vui.max_num_reorder_frames = (ctx->b_per_p > 0);
460 sps->vui.max_dec_frame_buffering = sps->max_num_ref_frames;
462 pps->nal_unit_header.nal_ref_idc = 3;
463 pps->nal_unit_header.nal_unit_type = H264_NAL_PPS;
465 pps->pic_parameter_set_id = 0;
466 pps->seq_parameter_set_id = 0;
468 pps->entropy_coding_mode_flag =
469 !(sps->profile_idc == FF_PROFILE_H264_BASELINE ||
470 sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
471 sps->profile_idc == FF_PROFILE_H264_CAVLC_444);
472 if (!opt->coder && pps->entropy_coding_mode_flag)
473 pps->entropy_coding_mode_flag = 0;
475 pps->num_ref_idx_l0_default_active_minus1 = 0;
476 pps->num_ref_idx_l1_default_active_minus1 = 0;
478 pps->pic_init_qp_minus26 = priv->fixed_qp_idr - 26;
480 if (sps->profile_idc == FF_PROFILE_H264_BASELINE ||
481 sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
482 sps->profile_idc == FF_PROFILE_H264_MAIN) {
483 pps->more_rbsp_data = 0;
485 pps->more_rbsp_data = 1;
487 pps->transform_8x8_mode_flag = 1;
490 *vseq = (VAEncSequenceParameterBufferH264) {
491 .seq_parameter_set_id = sps->seq_parameter_set_id,
492 .level_idc = sps->level_idc,
493 .intra_period = avctx->gop_size,
494 .intra_idr_period = avctx->gop_size,
495 .ip_period = ctx->b_per_p + 1,
497 .bits_per_second = avctx->bit_rate,
498 .max_num_ref_frames = sps->max_num_ref_frames,
499 .picture_width_in_mbs = sps->pic_width_in_mbs_minus1 + 1,
500 .picture_height_in_mbs = sps->pic_height_in_map_units_minus1 + 1,
503 .chroma_format_idc = sps->chroma_format_idc,
504 .frame_mbs_only_flag = sps->frame_mbs_only_flag,
505 .mb_adaptive_frame_field_flag = sps->mb_adaptive_frame_field_flag,
506 .seq_scaling_matrix_present_flag = sps->seq_scaling_matrix_present_flag,
507 .direct_8x8_inference_flag = sps->direct_8x8_inference_flag,
508 .log2_max_frame_num_minus4 = sps->log2_max_frame_num_minus4,
509 .pic_order_cnt_type = sps->pic_order_cnt_type,
510 .log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_pic_order_cnt_lsb_minus4,
511 .delta_pic_order_always_zero_flag = sps->delta_pic_order_always_zero_flag,
514 .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
515 .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
517 .frame_cropping_flag = sps->frame_cropping_flag,
518 .frame_crop_left_offset = sps->frame_crop_left_offset,
519 .frame_crop_right_offset = sps->frame_crop_right_offset,
520 .frame_crop_top_offset = sps->frame_crop_top_offset,
521 .frame_crop_bottom_offset = sps->frame_crop_bottom_offset,
523 .vui_parameters_present_flag = sps->vui_parameters_present_flag,
526 .aspect_ratio_info_present_flag = sps->vui.aspect_ratio_info_present_flag,
527 .timing_info_present_flag = sps->vui.timing_info_present_flag,
528 .bitstream_restriction_flag = sps->vui.bitstream_restriction_flag,
529 .log2_max_mv_length_horizontal = sps->vui.log2_max_mv_length_horizontal,
530 .log2_max_mv_length_vertical = sps->vui.log2_max_mv_length_vertical,
533 .aspect_ratio_idc = sps->vui.aspect_ratio_idc,
534 .sar_width = sps->vui.sar_width,
535 .sar_height = sps->vui.sar_height,
536 .num_units_in_tick = sps->vui.num_units_in_tick,
537 .time_scale = sps->vui.time_scale,
540 *vpic = (VAEncPictureParameterBufferH264) {
542 .picture_id = VA_INVALID_ID,
543 .flags = VA_PICTURE_H264_INVALID,
546 .coded_buf = VA_INVALID_ID,
548 .pic_parameter_set_id = pps->pic_parameter_set_id,
549 .seq_parameter_set_id = pps->seq_parameter_set_id,
551 .pic_init_qp = pps->pic_init_qp_minus26 + 26,
552 .num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1,
553 .num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1,
555 .chroma_qp_index_offset = pps->chroma_qp_index_offset,
556 .second_chroma_qp_index_offset = pps->second_chroma_qp_index_offset,
559 .entropy_coding_mode_flag = pps->entropy_coding_mode_flag,
560 .weighted_pred_flag = pps->weighted_pred_flag,
561 .weighted_bipred_idc = pps->weighted_bipred_idc,
562 .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
563 .transform_8x8_mode_flag = pps->transform_8x8_mode_flag,
564 .deblocking_filter_control_present_flag =
565 pps->deblocking_filter_control_present_flag,
566 .redundant_pic_cnt_present_flag = pps->redundant_pic_cnt_present_flag,
567 .pic_order_present_flag =
568 pps->bottom_field_pic_order_in_frame_present_flag,
569 .pic_scaling_matrix_present_flag = pps->pic_scaling_matrix_present_flag,
576 static int vaapi_encode_h264_init_picture_params(AVCodecContext *avctx,
577 VAAPIEncodePicture *pic)
579 VAAPIEncodeContext *ctx = avctx->priv_data;
580 VAAPIEncodeH264Context *priv = ctx->priv_data;
581 VAAPIEncodeH264Options *opt = ctx->codec_options;
582 H264RawSPS *sps = &priv->sps;
583 VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
586 memset(&priv->current_access_unit, 0,
587 sizeof(priv->current_access_unit));
589 if (pic->type == PICTURE_TYPE_IDR) {
590 av_assert0(pic->display_order == pic->encode_order);
592 priv->next_frame_num = 1;
594 priv->last_idr_frame = pic->display_order;
595 ++priv->idr_pic_count;
597 priv->slice_type = 7;
598 priv->primary_pic_type = 0;
600 priv->frame_num = priv->next_frame_num;
602 if (pic->type != PICTURE_TYPE_B) {
603 // Reference picture, so frame_num advances.
604 priv->next_frame_num = (priv->frame_num + 1) &
605 ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
609 if (pic->type == PICTURE_TYPE_I) {
610 priv->slice_type = 7;
611 priv->primary_pic_type = 0;
612 } else if (pic->type == PICTURE_TYPE_P) {
613 priv->slice_type = 5;
614 priv->primary_pic_type = 1;
616 priv->slice_type = 6;
617 priv->primary_pic_type = 2;
620 priv->pic_order_cnt = pic->display_order - priv->last_idr_frame;
621 priv->dpb_delay = pic->display_order - pic->encode_order + 1;
624 priv->aud_needed = 1;
625 priv->aud.nal_unit_header.nal_unit_type = H264_NAL_AUD;
626 priv->aud.primary_pic_type = priv->primary_pic_type;
628 priv->aud_needed = 0;
631 if (opt->sei & SEI_IDENTIFIER && pic->encode_order == 0)
632 priv->sei_needed = 1;
634 if (ctx->va_rc_mode == VA_RC_CBR)
635 priv->sei_cbr_workaround_needed = 1;
638 if (opt->sei & SEI_TIMING) {
639 memset(&priv->pic_timing, 0, sizeof(priv->pic_timing));
641 priv->pic_timing.cpb_removal_delay = 2 * priv->cpb_delay;
642 priv->pic_timing.dpb_output_delay = 2 * priv->dpb_delay;
644 priv->sei_needed = 1;
647 if (opt->sei & SEI_RECOVERY_POINT && pic->type == PICTURE_TYPE_I) {
648 priv->recovery_point.recovery_frame_cnt = 0;
649 priv->recovery_point.exact_match_flag = 1;
650 priv->recovery_point.broken_link_flag = ctx->b_per_p > 0;
652 priv->sei_needed = 1;
655 vpic->CurrPic = (VAPictureH264) {
656 .picture_id = pic->recon_surface,
657 .frame_idx = priv->frame_num,
659 .TopFieldOrderCnt = priv->pic_order_cnt,
660 .BottomFieldOrderCnt = priv->pic_order_cnt,
663 for (i = 0; i < pic->nb_refs; i++) {
664 VAAPIEncodePicture *ref = pic->refs[i];
665 unsigned int frame_num = (ref->encode_order - priv->last_idr_frame) &
666 ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
667 unsigned int pic_order_cnt = ref->display_order - priv->last_idr_frame;
669 av_assert0(ref && ref->encode_order < pic->encode_order);
670 vpic->ReferenceFrames[i] = (VAPictureH264) {
671 .picture_id = ref->recon_surface,
672 .frame_idx = frame_num,
673 .flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE,
674 .TopFieldOrderCnt = pic_order_cnt,
675 .BottomFieldOrderCnt = pic_order_cnt,
678 for (; i < FF_ARRAY_ELEMS(vpic->ReferenceFrames); i++) {
679 vpic->ReferenceFrames[i] = (VAPictureH264) {
680 .picture_id = VA_INVALID_ID,
681 .flags = VA_PICTURE_H264_INVALID,
685 vpic->coded_buf = pic->output_buffer;
687 vpic->frame_num = priv->frame_num;
689 vpic->pic_fields.bits.idr_pic_flag = (pic->type == PICTURE_TYPE_IDR);
690 vpic->pic_fields.bits.reference_pic_flag = (pic->type != PICTURE_TYPE_B);
697 static int vaapi_encode_h264_init_slice_params(AVCodecContext *avctx,
698 VAAPIEncodePicture *pic,
699 VAAPIEncodeSlice *slice)
701 VAAPIEncodeContext *ctx = avctx->priv_data;
702 VAAPIEncodeH264Context *priv = ctx->priv_data;
703 H264RawSPS *sps = &priv->sps;
704 H264RawPPS *pps = &priv->pps;
705 H264RawSliceHeader *sh = &priv->slice.header;
706 VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
707 VAEncSliceParameterBufferH264 *vslice = slice->codec_slice_params;
710 if (pic->type == PICTURE_TYPE_IDR) {
711 sh->nal_unit_header.nal_unit_type = H264_NAL_IDR_SLICE;
712 sh->nal_unit_header.nal_ref_idc = 3;
714 sh->nal_unit_header.nal_unit_type = H264_NAL_SLICE;
715 sh->nal_unit_header.nal_ref_idc = pic->type != PICTURE_TYPE_B;
718 // Only one slice per frame.
719 sh->first_mb_in_slice = 0;
720 sh->slice_type = priv->slice_type;
722 sh->pic_parameter_set_id = pps->pic_parameter_set_id;
724 sh->frame_num = priv->frame_num;
725 sh->idr_pic_id = priv->idr_pic_count;
727 sh->pic_order_cnt_lsb = priv->pic_order_cnt &
728 ((1 << (4 + sps->log2_max_pic_order_cnt_lsb_minus4)) - 1);
730 sh->direct_spatial_mv_pred_flag = 1;
732 if (pic->type == PICTURE_TYPE_B)
733 sh->slice_qp_delta = priv->fixed_qp_b - (pps->pic_init_qp_minus26 + 26);
734 else if (pic->type == PICTURE_TYPE_P)
735 sh->slice_qp_delta = priv->fixed_qp_p - (pps->pic_init_qp_minus26 + 26);
737 sh->slice_qp_delta = priv->fixed_qp_idr - (pps->pic_init_qp_minus26 + 26);
740 vslice->macroblock_address = sh->first_mb_in_slice;
741 vslice->num_macroblocks = priv->mb_width * priv->mb_height;
743 vslice->macroblock_info = VA_INVALID_ID;
745 vslice->slice_type = sh->slice_type % 5;
746 vslice->pic_parameter_set_id = sh->pic_parameter_set_id;
747 vslice->idr_pic_id = sh->idr_pic_id;
749 vslice->pic_order_cnt_lsb = sh->pic_order_cnt_lsb;
751 vslice->direct_spatial_mv_pred_flag = sh->direct_spatial_mv_pred_flag;
753 for (i = 0; i < FF_ARRAY_ELEMS(vslice->RefPicList0); i++) {
754 vslice->RefPicList0[i].picture_id = VA_INVALID_ID;
755 vslice->RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
756 vslice->RefPicList1[i].picture_id = VA_INVALID_ID;
757 vslice->RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
760 av_assert0(pic->nb_refs <= 2);
761 if (pic->nb_refs >= 1) {
762 // Backward reference for P- or B-frame.
763 av_assert0(pic->type == PICTURE_TYPE_P ||
764 pic->type == PICTURE_TYPE_B);
765 vslice->RefPicList0[0] = vpic->ReferenceFrames[0];
767 if (pic->nb_refs >= 2) {
768 // Forward reference for B-frame.
769 av_assert0(pic->type == PICTURE_TYPE_B);
770 vslice->RefPicList1[0] = vpic->ReferenceFrames[1];
773 vslice->slice_qp_delta = sh->slice_qp_delta;
778 static av_cold int vaapi_encode_h264_configure(AVCodecContext *avctx)
780 VAAPIEncodeContext *ctx = avctx->priv_data;
781 VAAPIEncodeH264Context *priv = ctx->priv_data;
782 VAAPIEncodeH264Options *opt = ctx->codec_options;
785 err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_H264, avctx);
789 priv->mb_width = FFALIGN(avctx->width, 16) / 16;
790 priv->mb_height = FFALIGN(avctx->height, 16) / 16;
792 if (ctx->va_rc_mode == VA_RC_CQP) {
793 priv->fixed_qp_p = opt->qp;
794 if (avctx->i_quant_factor > 0.0)
795 priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
796 avctx->i_quant_offset) + 0.5);
798 priv->fixed_qp_idr = priv->fixed_qp_p;
799 if (avctx->b_quant_factor > 0.0)
800 priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
801 avctx->b_quant_offset) + 0.5);
803 priv->fixed_qp_b = priv->fixed_qp_p;
805 opt->sei &= ~SEI_TIMING;
807 av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
808 "%d / %d / %d for IDR- / P- / B-frames.\n",
809 priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
811 } else if (ctx->va_rc_mode == VA_RC_CBR ||
812 ctx->va_rc_mode == VA_RC_VBR) {
813 // These still need to be set for pic_init_qp/slice_qp_delta.
814 priv->fixed_qp_idr = 26;
815 priv->fixed_qp_p = 26;
816 priv->fixed_qp_b = 26;
818 av_log(avctx, AV_LOG_DEBUG, "Using %s-bitrate = %"PRId64" bps.\n",
819 ctx->va_rc_mode == VA_RC_CBR ? "constant" : "variable",
823 av_assert0(0 && "Invalid RC mode.");
826 if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
827 avctx->compression_level = opt->quality;
829 if (opt->sei & SEI_IDENTIFIER) {
830 const char *lavc = LIBAVCODEC_IDENT;
831 const char *vaapi = VA_VERSION_S;
835 memcpy(priv->identifier.uuid_iso_iec_11578,
836 vaapi_encode_h264_sei_identifier_uuid,
837 sizeof(priv->identifier.uuid_iso_iec_11578));
839 driver = vaQueryVendorString(ctx->hwctx->display);
841 driver = "unknown driver";
843 len = snprintf(NULL, 0, "%s / VAAPI %s / %s", lavc, vaapi, driver);
845 priv->identifier_string = av_malloc(len + 1);
846 if (!priv->identifier_string)
847 return AVERROR(ENOMEM);
849 snprintf(priv->identifier_string, len + 1,
850 "%s / VAAPI %s / %s", lavc, vaapi, driver);
852 priv->identifier.data = priv->identifier_string;
853 priv->identifier.data_length = len + 1;
860 static const VAAPIEncodeType vaapi_encode_type_h264 = {
861 .priv_data_size = sizeof(VAAPIEncodeH264Context),
863 .configure = &vaapi_encode_h264_configure,
865 .sequence_params_size = sizeof(VAEncSequenceParameterBufferH264),
866 .init_sequence_params = &vaapi_encode_h264_init_sequence_params,
868 .picture_params_size = sizeof(VAEncPictureParameterBufferH264),
869 .init_picture_params = &vaapi_encode_h264_init_picture_params,
871 .slice_params_size = sizeof(VAEncSliceParameterBufferH264),
872 .init_slice_params = &vaapi_encode_h264_init_slice_params,
874 .sequence_header_type = VAEncPackedHeaderSequence,
875 .write_sequence_header = &vaapi_encode_h264_write_sequence_header,
877 .slice_header_type = VAEncPackedHeaderH264_Slice,
878 .write_slice_header = &vaapi_encode_h264_write_slice_header,
880 .write_extra_header = &vaapi_encode_h264_write_extra_header,
883 static av_cold int vaapi_encode_h264_init(AVCodecContext *avctx)
885 VAAPIEncodeContext *ctx = avctx->priv_data;
886 VAAPIEncodeH264Options *opt =
887 (VAAPIEncodeH264Options*)ctx->codec_options_data;
889 ctx->codec = &vaapi_encode_type_h264;
891 if (avctx->profile == FF_PROFILE_UNKNOWN)
892 avctx->profile = opt->profile;
893 if (avctx->level == FF_LEVEL_UNKNOWN)
894 avctx->level = opt->level;
896 switch (avctx->profile) {
897 case FF_PROFILE_H264_BASELINE:
898 av_log(avctx, AV_LOG_WARNING, "H.264 baseline profile is not "
899 "supported, using constrained baseline profile instead.\n");
900 avctx->profile = FF_PROFILE_H264_CONSTRAINED_BASELINE;
901 case FF_PROFILE_H264_CONSTRAINED_BASELINE:
902 ctx->va_profile = VAProfileH264ConstrainedBaseline;
903 if (avctx->max_b_frames != 0) {
904 avctx->max_b_frames = 0;
905 av_log(avctx, AV_LOG_WARNING, "H.264 constrained baseline profile "
906 "doesn't support encoding with B frames, disabling them.\n");
909 case FF_PROFILE_H264_MAIN:
910 ctx->va_profile = VAProfileH264Main;
912 case FF_PROFILE_H264_EXTENDED:
913 av_log(avctx, AV_LOG_ERROR, "H.264 extended profile "
914 "is not supported.\n");
915 return AVERROR_PATCHWELCOME;
916 case FF_PROFILE_UNKNOWN:
917 case FF_PROFILE_H264_HIGH:
918 ctx->va_profile = VAProfileH264High;
920 case FF_PROFILE_H264_HIGH_10:
921 case FF_PROFILE_H264_HIGH_10_INTRA:
922 av_log(avctx, AV_LOG_ERROR, "H.264 10-bit profiles "
923 "are not supported.\n");
924 return AVERROR_PATCHWELCOME;
925 case FF_PROFILE_H264_HIGH_422:
926 case FF_PROFILE_H264_HIGH_422_INTRA:
927 case FF_PROFILE_H264_HIGH_444:
928 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
929 case FF_PROFILE_H264_HIGH_444_INTRA:
930 case FF_PROFILE_H264_CAVLC_444:
931 av_log(avctx, AV_LOG_ERROR, "H.264 non-4:2:0 profiles "
932 "are not supported.\n");
933 return AVERROR_PATCHWELCOME;
935 av_log(avctx, AV_LOG_ERROR, "Unknown H.264 profile %d.\n",
937 return AVERROR(EINVAL);
939 if (opt->low_power) {
940 #if VA_CHECK_VERSION(0, 39, 2)
941 ctx->va_entrypoint = VAEntrypointEncSliceLP;
943 av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
944 "supported with this VAAPI version.\n");
945 return AVERROR(EINVAL);
948 ctx->va_entrypoint = VAEntrypointEncSlice;
951 // Only 8-bit encode is supported.
952 ctx->va_rt_format = VA_RT_FORMAT_YUV420;
954 if (avctx->bit_rate > 0) {
955 if (avctx->rc_max_rate == avctx->bit_rate)
956 ctx->va_rc_mode = VA_RC_CBR;
958 ctx->va_rc_mode = VA_RC_VBR;
960 ctx->va_rc_mode = VA_RC_CQP;
962 ctx->va_packed_headers =
963 VA_ENC_PACKED_HEADER_SEQUENCE | // SPS and PPS.
964 VA_ENC_PACKED_HEADER_SLICE | // Slice headers.
965 VA_ENC_PACKED_HEADER_MISC; // SEI.
967 ctx->surface_width = FFALIGN(avctx->width, 16);
968 ctx->surface_height = FFALIGN(avctx->height, 16);
970 return ff_vaapi_encode_init(avctx);
973 static av_cold int vaapi_encode_h264_close(AVCodecContext *avctx)
975 VAAPIEncodeContext *ctx = avctx->priv_data;
976 VAAPIEncodeH264Context *priv = ctx->priv_data;
979 ff_cbs_close(&priv->cbc);
980 av_freep(&priv->identifier_string);
983 return ff_vaapi_encode_close(avctx);
986 #define OFFSET(x) (offsetof(VAAPIEncodeContext, codec_options_data) + \
987 offsetof(VAAPIEncodeH264Options, x))
988 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
989 static const AVOption vaapi_encode_h264_options[] = {
990 { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
991 OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 20 }, 0, 52, FLAGS },
992 { "quality", "Set encode quality (trades off against speed, higher is faster)",
993 OFFSET(quality), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 8, FLAGS },
994 { "low_power", "Use low-power encoding mode (experimental: only supported "
995 "on some platforms, does not support all features)",
996 OFFSET(low_power), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
997 { "coder", "Entropy coder type",
998 OFFSET(coder), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS, "coder" },
999 { "cavlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
1000 { "cabac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
1001 { "vlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
1002 { "ac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
1004 { "aud", "Include AUD",
1005 OFFSET(aud), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
1007 { "sei", "Set SEI to include",
1008 OFFSET(sei), AV_OPT_TYPE_FLAGS,
1009 { .i64 = SEI_IDENTIFIER | SEI_TIMING | SEI_RECOVERY_POINT },
1010 0, INT_MAX, FLAGS, "sei" },
1011 { "identifier", "Include encoder version identifier",
1012 0, AV_OPT_TYPE_CONST, { .i64 = SEI_IDENTIFIER },
1013 INT_MIN, INT_MAX, FLAGS, "sei" },
1014 { "timing", "Include timing parameters (buffering_period and pic_timing)",
1015 0, AV_OPT_TYPE_CONST, { .i64 = SEI_TIMING },
1016 INT_MIN, INT_MAX, FLAGS, "sei" },
1017 { "recovery_point", "Include recovery points where appropriate",
1018 0, AV_OPT_TYPE_CONST, { .i64 = SEI_RECOVERY_POINT },
1019 INT_MIN, INT_MAX, FLAGS, "sei" },
1021 { "profile", "Set profile (profile_idc and constraint_set*_flag)",
1022 OFFSET(profile), AV_OPT_TYPE_INT,
1023 { .i64 = FF_PROFILE_H264_HIGH }, 0x0000, 0xffff, FLAGS, "profile" },
1025 #define PROFILE(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1026 { .i64 = value }, 0, 0, FLAGS, "profile"
1027 { PROFILE("constrained_baseline", FF_PROFILE_H264_CONSTRAINED_BASELINE) },
1028 { PROFILE("main", FF_PROFILE_H264_MAIN) },
1029 { PROFILE("high", FF_PROFILE_H264_HIGH) },
1032 { "level", "Set level (level_idc)",
1033 OFFSET(level), AV_OPT_TYPE_INT,
1034 { .i64 = 51 }, 0x00, 0xff, FLAGS, "level" },
1036 #define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1037 { .i64 = value }, 0, 0, FLAGS, "level"
1039 { LEVEL("1.1", 11) },
1040 { LEVEL("1.2", 12) },
1041 { LEVEL("1.3", 13) },
1043 { LEVEL("2.1", 21) },
1044 { LEVEL("2.2", 22) },
1046 { LEVEL("3.1", 31) },
1047 { LEVEL("3.2", 32) },
1049 { LEVEL("4.1", 41) },
1050 { LEVEL("4.2", 42) },
1052 { LEVEL("5.1", 51) },
1053 { LEVEL("5.2", 52) },
1055 { LEVEL("6.1", 61) },
1056 { LEVEL("6.2", 62) },
1062 static const AVCodecDefault vaapi_encode_h264_defaults[] = {
1066 { "i_qfactor", "1" },
1067 { "i_qoffset", "0" },
1068 { "b_qfactor", "6/5" },
1069 { "b_qoffset", "0" },
1074 static const AVClass vaapi_encode_h264_class = {
1075 .class_name = "h264_vaapi",
1076 .item_name = av_default_item_name,
1077 .option = vaapi_encode_h264_options,
1078 .version = LIBAVUTIL_VERSION_INT,
1081 AVCodec ff_h264_vaapi_encoder = {
1082 .name = "h264_vaapi",
1083 .long_name = NULL_IF_CONFIG_SMALL("H.264/AVC (VAAPI)"),
1084 .type = AVMEDIA_TYPE_VIDEO,
1085 .id = AV_CODEC_ID_H264,
1086 .priv_data_size = (sizeof(VAAPIEncodeContext) +
1087 sizeof(VAAPIEncodeH264Options)),
1088 .init = &vaapi_encode_h264_init,
1089 .encode2 = &ff_vaapi_encode2,
1090 .close = &vaapi_encode_h264_close,
1091 .priv_class = &vaapi_encode_h264_class,
1092 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
1093 .defaults = vaapi_encode_h264_defaults,
1094 .pix_fmts = (const enum AVPixelFormat[]) {
1098 .wrapper_name = "vaapi",