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"
33 #include "h264_levels.h"
36 #include "vaapi_encode.h"
40 SEI_IDENTIFIER = 0x02,
41 SEI_RECOVERY_POINT = 0x04,
44 // Random (version 4) ISO 11578 UUID.
45 static const uint8_t vaapi_encode_h264_sei_identifier_uuid[16] = {
46 0x59, 0x94, 0x8b, 0x28, 0x11, 0xec, 0x45, 0xaf,
47 0x96, 0x75, 0x19, 0xd4, 0x1f, 0xea, 0xa9, 0x4d,
50 typedef struct VAAPIEncodeH264Context {
51 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;
300 memset(&priv->current_access_unit, 0,
301 sizeof(priv->current_access_unit));
303 memset(sps, 0, sizeof(*sps));
304 memset(pps, 0, sizeof(*pps));
306 sps->nal_unit_header.nal_ref_idc = 3;
307 sps->nal_unit_header.nal_unit_type = H264_NAL_SPS;
309 sps->profile_idc = avctx->profile & 0xff;
311 if (avctx->profile == FF_PROFILE_H264_CONSTRAINED_BASELINE ||
312 avctx->profile == FF_PROFILE_H264_MAIN)
313 sps->constraint_set1_flag = 1;
315 if (avctx->profile == FF_PROFILE_H264_HIGH)
316 sps->constraint_set3_flag = ctx->gop_size == 1;
318 if (avctx->profile == FF_PROFILE_H264_MAIN ||
319 avctx->profile == FF_PROFILE_H264_HIGH) {
320 sps->constraint_set4_flag = 1;
321 sps->constraint_set5_flag = ctx->b_per_p == 0;
324 if (ctx->gop_size == 1)
327 dpb_frames = 1 + (ctx->b_per_p > 0);
329 if (avctx->level != FF_LEVEL_UNKNOWN) {
330 sps->level_idc = avctx->level;
332 const H264LevelDescriptor *level;
334 level = ff_h264_guess_level(sps->profile_idc,
337 priv->mb_height * 16,
340 av_log(avctx, AV_LOG_VERBOSE, "Using level %s.\n", level->name);
341 if (level->constraint_set3_flag)
342 sps->constraint_set3_flag = 1;
343 sps->level_idc = level->level_idc;
345 av_log(avctx, AV_LOG_WARNING, "Stream will not conform "
346 "to any level: using level 6.2.\n");
351 sps->seq_parameter_set_id = 0;
352 sps->chroma_format_idc = 1;
354 sps->log2_max_frame_num_minus4 = 4;
355 sps->pic_order_cnt_type = 0;
356 sps->log2_max_pic_order_cnt_lsb_minus4 =
357 av_clip(av_log2(ctx->b_per_p + 1) - 2, 0, 12);
359 sps->max_num_ref_frames = dpb_frames;
361 sps->pic_width_in_mbs_minus1 = priv->mb_width - 1;
362 sps->pic_height_in_map_units_minus1 = priv->mb_height - 1;
364 sps->frame_mbs_only_flag = 1;
365 sps->direct_8x8_inference_flag = 1;
367 if (avctx->width != 16 * priv->mb_width ||
368 avctx->height != 16 * priv->mb_height) {
369 sps->frame_cropping_flag = 1;
371 sps->frame_crop_left_offset = 0;
372 sps->frame_crop_right_offset =
373 (16 * priv->mb_width - avctx->width) / 2;
374 sps->frame_crop_top_offset = 0;
375 sps->frame_crop_bottom_offset =
376 (16 * priv->mb_height - avctx->height) / 2;
378 sps->frame_cropping_flag = 0;
381 sps->vui_parameters_present_flag = 1;
383 if (avctx->sample_aspect_ratio.num != 0 &&
384 avctx->sample_aspect_ratio.den != 0) {
385 static const AVRational sar_idc[] = {
387 { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 },
388 { 40, 33 }, { 24, 11 }, { 20, 11 }, { 32, 11 },
389 { 80, 33 }, { 18, 11 }, { 15, 11 }, { 64, 33 },
390 { 160, 99 }, { 4, 3 }, { 3, 2 }, { 2, 1 },
393 for (i = 0; i < FF_ARRAY_ELEMS(sar_idc); i++) {
394 if (avctx->sample_aspect_ratio.num == sar_idc[i].num &&
395 avctx->sample_aspect_ratio.den == sar_idc[i].den) {
396 sps->vui.aspect_ratio_idc = i;
400 if (i >= FF_ARRAY_ELEMS(sar_idc)) {
401 sps->vui.aspect_ratio_idc = 255;
402 sps->vui.sar_width = avctx->sample_aspect_ratio.num;
403 sps->vui.sar_height = avctx->sample_aspect_ratio.den;
405 sps->vui.aspect_ratio_info_present_flag = 1;
408 if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED ||
409 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
410 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
411 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
412 sps->vui.video_signal_type_present_flag = 1;
413 sps->vui.video_format = 5; // Unspecified.
414 sps->vui.video_full_range_flag =
415 avctx->color_range == AVCOL_RANGE_JPEG;
417 if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
418 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
419 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
420 sps->vui.colour_description_present_flag = 1;
421 sps->vui.colour_primaries = avctx->color_primaries;
422 sps->vui.transfer_characteristics = avctx->color_trc;
423 sps->vui.matrix_coefficients = avctx->colorspace;
426 sps->vui.video_format = 5;
427 sps->vui.video_full_range_flag = 0;
428 sps->vui.colour_primaries = avctx->color_primaries;
429 sps->vui.transfer_characteristics = avctx->color_trc;
430 sps->vui.matrix_coefficients = avctx->colorspace;
433 if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
434 sps->vui.chroma_loc_info_present_flag = 1;
435 sps->vui.chroma_sample_loc_type_top_field =
436 sps->vui.chroma_sample_loc_type_bottom_field =
437 avctx->chroma_sample_location - 1;
440 sps->vui.timing_info_present_flag = 1;
441 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
442 sps->vui.num_units_in_tick = avctx->framerate.den;
443 sps->vui.time_scale = 2 * avctx->framerate.num;
444 sps->vui.fixed_frame_rate_flag = 1;
446 sps->vui.num_units_in_tick = avctx->time_base.num;
447 sps->vui.time_scale = 2 * avctx->time_base.den;
448 sps->vui.fixed_frame_rate_flag = 0;
451 if (priv->sei & SEI_TIMING) {
452 H264RawHRD *hrd = &sps->vui.nal_hrd_parameters;
453 H264RawSEIBufferingPeriod *bp = &priv->sei_buffering_period;
455 sps->vui.nal_hrd_parameters_present_flag = 1;
457 hrd->cpb_cnt_minus1 = 0;
459 // Try to scale these to a sensible range so that the
460 // golomb encode of the value is not overlong.
461 hrd->bit_rate_scale =
462 av_clip_uintp2(av_log2(ctx->va_bit_rate) - 15 - 6, 4);
463 hrd->bit_rate_value_minus1[0] =
464 (ctx->va_bit_rate >> hrd->bit_rate_scale + 6) - 1;
466 hrd->cpb_size_scale =
467 av_clip_uintp2(av_log2(ctx->hrd_params.hrd.buffer_size) - 15 - 4, 4);
468 hrd->cpb_size_value_minus1[0] =
469 (ctx->hrd_params.hrd.buffer_size >> hrd->cpb_size_scale + 4) - 1;
471 // CBR mode as defined for the HRD cannot be achieved without filler
472 // data, so this flag cannot be set even with VAAPI CBR modes.
473 hrd->cbr_flag[0] = 0;
475 hrd->initial_cpb_removal_delay_length_minus1 = 23;
476 hrd->cpb_removal_delay_length_minus1 = 23;
477 hrd->dpb_output_delay_length_minus1 = 7;
478 hrd->time_offset_length = 0;
480 bp->seq_parameter_set_id = sps->seq_parameter_set_id;
482 // This calculation can easily overflow 32 bits.
483 bp->nal.initial_cpb_removal_delay[0] = 90000 *
484 (uint64_t)ctx->hrd_params.hrd.initial_buffer_fullness /
485 ctx->hrd_params.hrd.buffer_size;
486 bp->nal.initial_cpb_removal_delay_offset[0] = 0;
488 sps->vui.nal_hrd_parameters_present_flag = 0;
489 sps->vui.low_delay_hrd_flag = 1 - sps->vui.fixed_frame_rate_flag;
492 sps->vui.bitstream_restriction_flag = 1;
493 sps->vui.motion_vectors_over_pic_boundaries_flag = 1;
494 sps->vui.log2_max_mv_length_horizontal = 15;
495 sps->vui.log2_max_mv_length_vertical = 15;
496 sps->vui.max_num_reorder_frames = (ctx->b_per_p > 0);
497 sps->vui.max_dec_frame_buffering = sps->max_num_ref_frames;
499 pps->nal_unit_header.nal_ref_idc = 3;
500 pps->nal_unit_header.nal_unit_type = H264_NAL_PPS;
502 pps->pic_parameter_set_id = 0;
503 pps->seq_parameter_set_id = 0;
505 pps->entropy_coding_mode_flag =
506 !(sps->profile_idc == FF_PROFILE_H264_BASELINE ||
507 sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
508 sps->profile_idc == FF_PROFILE_H264_CAVLC_444);
509 if (!priv->coder && pps->entropy_coding_mode_flag)
510 pps->entropy_coding_mode_flag = 0;
512 pps->num_ref_idx_l0_default_active_minus1 = 0;
513 pps->num_ref_idx_l1_default_active_minus1 = 0;
515 pps->pic_init_qp_minus26 = priv->fixed_qp_idr - 26;
517 if (sps->profile_idc == FF_PROFILE_H264_BASELINE ||
518 sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
519 sps->profile_idc == FF_PROFILE_H264_MAIN) {
520 pps->more_rbsp_data = 0;
522 pps->more_rbsp_data = 1;
524 pps->transform_8x8_mode_flag = 1;
527 *vseq = (VAEncSequenceParameterBufferH264) {
528 .seq_parameter_set_id = sps->seq_parameter_set_id,
529 .level_idc = sps->level_idc,
530 .intra_period = ctx->gop_size,
531 .intra_idr_period = ctx->gop_size,
532 .ip_period = ctx->b_per_p + 1,
534 .bits_per_second = ctx->va_bit_rate,
535 .max_num_ref_frames = sps->max_num_ref_frames,
536 .picture_width_in_mbs = sps->pic_width_in_mbs_minus1 + 1,
537 .picture_height_in_mbs = sps->pic_height_in_map_units_minus1 + 1,
540 .chroma_format_idc = sps->chroma_format_idc,
541 .frame_mbs_only_flag = sps->frame_mbs_only_flag,
542 .mb_adaptive_frame_field_flag = sps->mb_adaptive_frame_field_flag,
543 .seq_scaling_matrix_present_flag = sps->seq_scaling_matrix_present_flag,
544 .direct_8x8_inference_flag = sps->direct_8x8_inference_flag,
545 .log2_max_frame_num_minus4 = sps->log2_max_frame_num_minus4,
546 .pic_order_cnt_type = sps->pic_order_cnt_type,
547 .log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_pic_order_cnt_lsb_minus4,
548 .delta_pic_order_always_zero_flag = sps->delta_pic_order_always_zero_flag,
551 .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
552 .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
554 .frame_cropping_flag = sps->frame_cropping_flag,
555 .frame_crop_left_offset = sps->frame_crop_left_offset,
556 .frame_crop_right_offset = sps->frame_crop_right_offset,
557 .frame_crop_top_offset = sps->frame_crop_top_offset,
558 .frame_crop_bottom_offset = sps->frame_crop_bottom_offset,
560 .vui_parameters_present_flag = sps->vui_parameters_present_flag,
563 .aspect_ratio_info_present_flag = sps->vui.aspect_ratio_info_present_flag,
564 .timing_info_present_flag = sps->vui.timing_info_present_flag,
565 .bitstream_restriction_flag = sps->vui.bitstream_restriction_flag,
566 .log2_max_mv_length_horizontal = sps->vui.log2_max_mv_length_horizontal,
567 .log2_max_mv_length_vertical = sps->vui.log2_max_mv_length_vertical,
570 .aspect_ratio_idc = sps->vui.aspect_ratio_idc,
571 .sar_width = sps->vui.sar_width,
572 .sar_height = sps->vui.sar_height,
573 .num_units_in_tick = sps->vui.num_units_in_tick,
574 .time_scale = sps->vui.time_scale,
577 *vpic = (VAEncPictureParameterBufferH264) {
579 .picture_id = VA_INVALID_ID,
580 .flags = VA_PICTURE_H264_INVALID,
583 .coded_buf = VA_INVALID_ID,
585 .pic_parameter_set_id = pps->pic_parameter_set_id,
586 .seq_parameter_set_id = pps->seq_parameter_set_id,
588 .pic_init_qp = pps->pic_init_qp_minus26 + 26,
589 .num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1,
590 .num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1,
592 .chroma_qp_index_offset = pps->chroma_qp_index_offset,
593 .second_chroma_qp_index_offset = pps->second_chroma_qp_index_offset,
596 .entropy_coding_mode_flag = pps->entropy_coding_mode_flag,
597 .weighted_pred_flag = pps->weighted_pred_flag,
598 .weighted_bipred_idc = pps->weighted_bipred_idc,
599 .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
600 .transform_8x8_mode_flag = pps->transform_8x8_mode_flag,
601 .deblocking_filter_control_present_flag =
602 pps->deblocking_filter_control_present_flag,
603 .redundant_pic_cnt_present_flag = pps->redundant_pic_cnt_present_flag,
604 .pic_order_present_flag =
605 pps->bottom_field_pic_order_in_frame_present_flag,
606 .pic_scaling_matrix_present_flag = pps->pic_scaling_matrix_present_flag,
613 static int vaapi_encode_h264_init_picture_params(AVCodecContext *avctx,
614 VAAPIEncodePicture *pic)
616 VAAPIEncodeContext *ctx = avctx->priv_data;
617 VAAPIEncodeH264Context *priv = avctx->priv_data;
618 H264RawSPS *sps = &priv->raw_sps;
619 VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
622 memset(&priv->current_access_unit, 0,
623 sizeof(priv->current_access_unit));
625 if (pic->type == PICTURE_TYPE_IDR) {
626 av_assert0(pic->display_order == pic->encode_order);
628 priv->next_frame_num = 1;
630 priv->last_idr_frame = pic->display_order;
631 ++priv->idr_pic_count;
633 priv->slice_type = 7;
634 priv->primary_pic_type = 0;
636 priv->frame_num = priv->next_frame_num;
638 if (pic->type != PICTURE_TYPE_B) {
639 // Reference picture, so frame_num advances.
640 priv->next_frame_num = (priv->frame_num + 1) &
641 ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
645 if (pic->type == PICTURE_TYPE_I) {
646 priv->slice_type = 7;
647 priv->primary_pic_type = 0;
648 } else if (pic->type == PICTURE_TYPE_P) {
649 priv->slice_type = 5;
650 priv->primary_pic_type = 1;
652 priv->slice_type = 6;
653 priv->primary_pic_type = 2;
656 priv->pic_order_cnt = pic->display_order - priv->last_idr_frame;
657 priv->dpb_delay = pic->display_order - pic->encode_order + 1;
660 priv->aud_needed = 1;
661 priv->raw_aud = (H264RawAUD) {
663 .nal_unit_type = H264_NAL_AUD,
665 .primary_pic_type = priv->primary_pic_type,
668 priv->aud_needed = 0;
671 priv->sei_needed = 0;
673 if (priv->sei & SEI_IDENTIFIER && pic->encode_order == 0)
674 priv->sei_needed |= SEI_IDENTIFIER;
676 if (ctx->va_rc_mode == VA_RC_CBR)
677 priv->sei_cbr_workaround_needed = 1;
680 if (priv->sei & SEI_TIMING) {
681 priv->sei_pic_timing = (H264RawSEIPicTiming) {
682 .cpb_removal_delay = 2 * priv->cpb_delay,
683 .dpb_output_delay = 2 * priv->dpb_delay,
686 priv->sei_needed |= SEI_TIMING;
689 if (priv->sei & SEI_RECOVERY_POINT && pic->type == PICTURE_TYPE_I) {
690 priv->sei_recovery_point = (H264RawSEIRecoveryPoint) {
691 .recovery_frame_cnt = 0,
692 .exact_match_flag = 1,
693 .broken_link_flag = ctx->b_per_p > 0,
696 priv->sei_needed |= SEI_RECOVERY_POINT;
699 vpic->CurrPic = (VAPictureH264) {
700 .picture_id = pic->recon_surface,
701 .frame_idx = priv->frame_num,
703 .TopFieldOrderCnt = priv->pic_order_cnt,
704 .BottomFieldOrderCnt = priv->pic_order_cnt,
707 for (i = 0; i < pic->nb_refs; i++) {
708 VAAPIEncodePicture *ref = pic->refs[i];
709 unsigned int frame_num = (ref->encode_order - priv->last_idr_frame) &
710 ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
711 unsigned int pic_order_cnt = ref->display_order - priv->last_idr_frame;
713 av_assert0(ref && ref->encode_order < pic->encode_order);
714 vpic->ReferenceFrames[i] = (VAPictureH264) {
715 .picture_id = ref->recon_surface,
716 .frame_idx = frame_num,
717 .flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE,
718 .TopFieldOrderCnt = pic_order_cnt,
719 .BottomFieldOrderCnt = pic_order_cnt,
722 for (; i < FF_ARRAY_ELEMS(vpic->ReferenceFrames); i++) {
723 vpic->ReferenceFrames[i] = (VAPictureH264) {
724 .picture_id = VA_INVALID_ID,
725 .flags = VA_PICTURE_H264_INVALID,
729 vpic->coded_buf = pic->output_buffer;
731 vpic->frame_num = priv->frame_num;
733 vpic->pic_fields.bits.idr_pic_flag = (pic->type == PICTURE_TYPE_IDR);
734 vpic->pic_fields.bits.reference_pic_flag = (pic->type != PICTURE_TYPE_B);
741 static int vaapi_encode_h264_init_slice_params(AVCodecContext *avctx,
742 VAAPIEncodePicture *pic,
743 VAAPIEncodeSlice *slice)
745 VAAPIEncodeH264Context *priv = avctx->priv_data;
746 H264RawSPS *sps = &priv->raw_sps;
747 H264RawPPS *pps = &priv->raw_pps;
748 H264RawSliceHeader *sh = &priv->raw_slice.header;
749 VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
750 VAEncSliceParameterBufferH264 *vslice = slice->codec_slice_params;
753 if (pic->type == PICTURE_TYPE_IDR) {
754 sh->nal_unit_header.nal_unit_type = H264_NAL_IDR_SLICE;
755 sh->nal_unit_header.nal_ref_idc = 3;
757 sh->nal_unit_header.nal_unit_type = H264_NAL_SLICE;
758 sh->nal_unit_header.nal_ref_idc = pic->type != PICTURE_TYPE_B;
761 // Only one slice per frame.
762 sh->first_mb_in_slice = 0;
763 sh->slice_type = priv->slice_type;
765 sh->pic_parameter_set_id = pps->pic_parameter_set_id;
767 sh->frame_num = priv->frame_num;
768 sh->idr_pic_id = priv->idr_pic_count;
770 sh->pic_order_cnt_lsb = priv->pic_order_cnt &
771 ((1 << (4 + sps->log2_max_pic_order_cnt_lsb_minus4)) - 1);
773 sh->direct_spatial_mv_pred_flag = 1;
775 if (pic->type == PICTURE_TYPE_B)
776 sh->slice_qp_delta = priv->fixed_qp_b - (pps->pic_init_qp_minus26 + 26);
777 else if (pic->type == PICTURE_TYPE_P)
778 sh->slice_qp_delta = priv->fixed_qp_p - (pps->pic_init_qp_minus26 + 26);
780 sh->slice_qp_delta = priv->fixed_qp_idr - (pps->pic_init_qp_minus26 + 26);
783 vslice->macroblock_address = sh->first_mb_in_slice;
784 vslice->num_macroblocks = priv->mb_width * priv->mb_height;
786 vslice->macroblock_info = VA_INVALID_ID;
788 vslice->slice_type = sh->slice_type % 5;
789 vslice->pic_parameter_set_id = sh->pic_parameter_set_id;
790 vslice->idr_pic_id = sh->idr_pic_id;
792 vslice->pic_order_cnt_lsb = sh->pic_order_cnt_lsb;
794 vslice->direct_spatial_mv_pred_flag = sh->direct_spatial_mv_pred_flag;
796 for (i = 0; i < FF_ARRAY_ELEMS(vslice->RefPicList0); i++) {
797 vslice->RefPicList0[i].picture_id = VA_INVALID_ID;
798 vslice->RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
799 vslice->RefPicList1[i].picture_id = VA_INVALID_ID;
800 vslice->RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
803 av_assert0(pic->nb_refs <= 2);
804 if (pic->nb_refs >= 1) {
805 // Backward reference for P- or B-frame.
806 av_assert0(pic->type == PICTURE_TYPE_P ||
807 pic->type == PICTURE_TYPE_B);
808 vslice->RefPicList0[0] = vpic->ReferenceFrames[0];
810 if (pic->nb_refs >= 2) {
811 // Forward reference for B-frame.
812 av_assert0(pic->type == PICTURE_TYPE_B);
813 vslice->RefPicList1[0] = vpic->ReferenceFrames[1];
816 vslice->slice_qp_delta = sh->slice_qp_delta;
821 static av_cold int vaapi_encode_h264_configure(AVCodecContext *avctx)
823 VAAPIEncodeContext *ctx = avctx->priv_data;
824 VAAPIEncodeH264Context *priv = avctx->priv_data;
827 err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_H264, avctx);
831 priv->mb_width = FFALIGN(avctx->width, 16) / 16;
832 priv->mb_height = FFALIGN(avctx->height, 16) / 16;
834 if (ctx->va_rc_mode == VA_RC_CQP) {
835 priv->fixed_qp_p = priv->qp;
836 if (avctx->i_quant_factor > 0.0)
837 priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
838 avctx->i_quant_offset) + 0.5);
840 priv->fixed_qp_idr = priv->fixed_qp_p;
841 if (avctx->b_quant_factor > 0.0)
842 priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
843 avctx->b_quant_offset) + 0.5);
845 priv->fixed_qp_b = priv->fixed_qp_p;
847 priv->sei &= ~SEI_TIMING;
849 av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
850 "%d / %d / %d for IDR- / P- / B-frames.\n",
851 priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
853 } else if (ctx->va_rc_mode == VA_RC_CBR ||
854 ctx->va_rc_mode == VA_RC_VBR) {
855 // These still need to be set for pic_init_qp/slice_qp_delta.
856 priv->fixed_qp_idr = 26;
857 priv->fixed_qp_p = 26;
858 priv->fixed_qp_b = 26;
861 av_assert0(0 && "Invalid RC mode.");
864 if (priv->sei & SEI_IDENTIFIER) {
865 const char *lavc = LIBAVCODEC_IDENT;
866 const char *vaapi = VA_VERSION_S;
870 memcpy(priv->sei_identifier.uuid_iso_iec_11578,
871 vaapi_encode_h264_sei_identifier_uuid,
872 sizeof(priv->sei_identifier.uuid_iso_iec_11578));
874 driver = vaQueryVendorString(ctx->hwctx->display);
876 driver = "unknown driver";
878 len = snprintf(NULL, 0, "%s / VAAPI %s / %s", lavc, vaapi, driver);
880 priv->sei_identifier_string = av_malloc(len + 1);
881 if (!priv->sei_identifier_string)
882 return AVERROR(ENOMEM);
884 snprintf(priv->sei_identifier_string, len + 1,
885 "%s / VAAPI %s / %s", lavc, vaapi, driver);
887 priv->sei_identifier.data = priv->sei_identifier_string;
888 priv->sei_identifier.data_length = len + 1;
895 static const VAAPIEncodeProfile vaapi_encode_h264_profiles[] = {
896 { FF_PROFILE_H264_HIGH, 8, 3, 1, 1, VAProfileH264High },
897 { FF_PROFILE_H264_MAIN, 8, 3, 1, 1, VAProfileH264Main },
898 { FF_PROFILE_H264_CONSTRAINED_BASELINE,
899 8, 3, 1, 1, VAProfileH264ConstrainedBaseline },
900 { FF_PROFILE_UNKNOWN }
903 static const VAAPIEncodeType vaapi_encode_type_h264 = {
904 .profiles = vaapi_encode_h264_profiles,
906 .configure = &vaapi_encode_h264_configure,
908 .sequence_params_size = sizeof(VAEncSequenceParameterBufferH264),
909 .init_sequence_params = &vaapi_encode_h264_init_sequence_params,
911 .picture_params_size = sizeof(VAEncPictureParameterBufferH264),
912 .init_picture_params = &vaapi_encode_h264_init_picture_params,
914 .slice_params_size = sizeof(VAEncSliceParameterBufferH264),
915 .init_slice_params = &vaapi_encode_h264_init_slice_params,
917 .sequence_header_type = VAEncPackedHeaderSequence,
918 .write_sequence_header = &vaapi_encode_h264_write_sequence_header,
920 .slice_header_type = VAEncPackedHeaderH264_Slice,
921 .write_slice_header = &vaapi_encode_h264_write_slice_header,
923 .write_extra_header = &vaapi_encode_h264_write_extra_header,
926 static av_cold int vaapi_encode_h264_init(AVCodecContext *avctx)
928 VAAPIEncodeContext *ctx = avctx->priv_data;
929 VAAPIEncodeH264Context *priv = avctx->priv_data;
931 ctx->codec = &vaapi_encode_type_h264;
933 if (avctx->profile == FF_PROFILE_UNKNOWN)
934 avctx->profile = priv->profile;
935 if (avctx->level == FF_LEVEL_UNKNOWN)
936 avctx->level = priv->level;
937 if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
938 avctx->compression_level = priv->quality;
940 // Reject unsupported profiles.
941 switch (avctx->profile) {
942 case FF_PROFILE_H264_BASELINE:
943 av_log(avctx, AV_LOG_WARNING, "H.264 baseline profile is not "
944 "supported, using constrained baseline profile instead.\n");
945 avctx->profile = FF_PROFILE_H264_CONSTRAINED_BASELINE;
947 case FF_PROFILE_H264_EXTENDED:
948 av_log(avctx, AV_LOG_ERROR, "H.264 extended profile "
949 "is not supported.\n");
950 return AVERROR_PATCHWELCOME;
951 case FF_PROFILE_H264_HIGH_10:
952 case FF_PROFILE_H264_HIGH_10_INTRA:
953 av_log(avctx, AV_LOG_ERROR, "H.264 10-bit profiles "
954 "are not supported.\n");
955 return AVERROR_PATCHWELCOME;
956 case FF_PROFILE_H264_HIGH_422:
957 case FF_PROFILE_H264_HIGH_422_INTRA:
958 case FF_PROFILE_H264_HIGH_444:
959 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
960 case FF_PROFILE_H264_HIGH_444_INTRA:
961 case FF_PROFILE_H264_CAVLC_444:
962 av_log(avctx, AV_LOG_ERROR, "H.264 non-4:2:0 profiles "
963 "are not supported.\n");
964 return AVERROR_PATCHWELCOME;
967 if (avctx->level != FF_LEVEL_UNKNOWN && avctx->level & ~0xff) {
968 av_log(avctx, AV_LOG_ERROR, "Invalid level %d: must fit "
969 "in 8-bit unsigned integer.\n", avctx->level);
970 return AVERROR(EINVAL);
973 ctx->desired_packed_headers =
974 VA_ENC_PACKED_HEADER_SEQUENCE | // SPS and PPS.
975 VA_ENC_PACKED_HEADER_SLICE | // Slice headers.
976 VA_ENC_PACKED_HEADER_MISC; // SEI.
978 ctx->surface_width = FFALIGN(avctx->width, 16);
979 ctx->surface_height = FFALIGN(avctx->height, 16);
981 return ff_vaapi_encode_init(avctx);
984 static av_cold int vaapi_encode_h264_close(AVCodecContext *avctx)
986 VAAPIEncodeH264Context *priv = avctx->priv_data;
988 ff_cbs_close(&priv->cbc);
989 av_freep(&priv->sei_identifier_string);
991 return ff_vaapi_encode_close(avctx);
994 #define OFFSET(x) offsetof(VAAPIEncodeH264Context, x)
995 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
996 static const AVOption vaapi_encode_h264_options[] = {
997 VAAPI_ENCODE_COMMON_OPTIONS,
999 { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
1000 OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 20 }, 0, 52, FLAGS },
1001 { "quality", "Set encode quality (trades off against speed, higher is faster)",
1002 OFFSET(quality), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS },
1003 { "coder", "Entropy coder type",
1004 OFFSET(coder), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS, "coder" },
1005 { "cavlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
1006 { "cabac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
1007 { "vlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
1008 { "ac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
1010 { "aud", "Include AUD",
1011 OFFSET(aud), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
1013 { "sei", "Set SEI to include",
1014 OFFSET(sei), AV_OPT_TYPE_FLAGS,
1015 { .i64 = SEI_IDENTIFIER | SEI_TIMING | SEI_RECOVERY_POINT },
1016 0, INT_MAX, FLAGS, "sei" },
1017 { "identifier", "Include encoder version identifier",
1018 0, AV_OPT_TYPE_CONST, { .i64 = SEI_IDENTIFIER },
1019 INT_MIN, INT_MAX, FLAGS, "sei" },
1020 { "timing", "Include timing parameters (buffering_period and pic_timing)",
1021 0, AV_OPT_TYPE_CONST, { .i64 = SEI_TIMING },
1022 INT_MIN, INT_MAX, FLAGS, "sei" },
1023 { "recovery_point", "Include recovery points where appropriate",
1024 0, AV_OPT_TYPE_CONST, { .i64 = SEI_RECOVERY_POINT },
1025 INT_MIN, INT_MAX, FLAGS, "sei" },
1027 { "profile", "Set profile (profile_idc and constraint_set*_flag)",
1028 OFFSET(profile), AV_OPT_TYPE_INT,
1029 { .i64 = FF_PROFILE_UNKNOWN }, FF_PROFILE_UNKNOWN, 0xffff, FLAGS, "profile" },
1031 #define PROFILE(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1032 { .i64 = value }, 0, 0, FLAGS, "profile"
1033 { PROFILE("constrained_baseline", FF_PROFILE_H264_CONSTRAINED_BASELINE) },
1034 { PROFILE("main", FF_PROFILE_H264_MAIN) },
1035 { PROFILE("high", FF_PROFILE_H264_HIGH) },
1038 { "level", "Set level (level_idc)",
1039 OFFSET(level), AV_OPT_TYPE_INT,
1040 { .i64 = FF_LEVEL_UNKNOWN }, FF_LEVEL_UNKNOWN, 0xff, FLAGS, "level" },
1042 #define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1043 { .i64 = value }, 0, 0, FLAGS, "level"
1045 { LEVEL("1.1", 11) },
1046 { LEVEL("1.2", 12) },
1047 { LEVEL("1.3", 13) },
1049 { LEVEL("2.1", 21) },
1050 { LEVEL("2.2", 22) },
1052 { LEVEL("3.1", 31) },
1053 { LEVEL("3.2", 32) },
1055 { LEVEL("4.1", 41) },
1056 { LEVEL("4.2", 42) },
1058 { LEVEL("5.1", 51) },
1059 { LEVEL("5.2", 52) },
1061 { LEVEL("6.1", 61) },
1062 { LEVEL("6.2", 62) },
1068 static const AVCodecDefault vaapi_encode_h264_defaults[] = {
1072 { "i_qfactor", "1" },
1073 { "i_qoffset", "0" },
1074 { "b_qfactor", "6/5" },
1075 { "b_qoffset", "0" },
1081 static const AVClass vaapi_encode_h264_class = {
1082 .class_name = "h264_vaapi",
1083 .item_name = av_default_item_name,
1084 .option = vaapi_encode_h264_options,
1085 .version = LIBAVUTIL_VERSION_INT,
1088 AVCodec ff_h264_vaapi_encoder = {
1089 .name = "h264_vaapi",
1090 .long_name = NULL_IF_CONFIG_SMALL("H.264/AVC (VAAPI)"),
1091 .type = AVMEDIA_TYPE_VIDEO,
1092 .id = AV_CODEC_ID_H264,
1093 .priv_data_size = sizeof(VAAPIEncodeH264Context),
1094 .init = &vaapi_encode_h264_init,
1095 .encode2 = &ff_vaapi_encode2,
1096 .close = &vaapi_encode_h264_close,
1097 .priv_class = &vaapi_encode_h264_class,
1098 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
1099 .defaults = vaapi_encode_h264_defaults,
1100 .pix_fmts = (const enum AVPixelFormat[]) {
1104 .wrapper_name = "vaapi",