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.
96 } VAAPIEncodeH264Options;
99 static int vaapi_encode_h264_write_access_unit(AVCodecContext *avctx,
100 char *data, size_t *data_len,
101 CodedBitstreamFragment *au)
103 VAAPIEncodeContext *ctx = avctx->priv_data;
104 VAAPIEncodeH264Context *priv = ctx->priv_data;
107 err = ff_cbs_write_fragment_data(priv->cbc, au);
109 av_log(avctx, AV_LOG_ERROR, "Failed to write packed header.\n");
113 if (*data_len < 8 * au->data_size - au->data_bit_padding) {
114 av_log(avctx, AV_LOG_ERROR, "Access unit too large: "
115 "%zu < %zu.\n", *data_len,
116 8 * au->data_size - au->data_bit_padding);
117 return AVERROR(ENOSPC);
120 memcpy(data, au->data, au->data_size);
121 *data_len = 8 * au->data_size - au->data_bit_padding;
126 static int vaapi_encode_h264_add_nal(AVCodecContext *avctx,
127 CodedBitstreamFragment *au,
130 VAAPIEncodeContext *ctx = avctx->priv_data;
131 VAAPIEncodeH264Context *priv = ctx->priv_data;
132 H264RawNALUnitHeader *header = nal_unit;
135 err = ff_cbs_insert_unit_content(priv->cbc, au, -1,
136 header->nal_unit_type, nal_unit);
138 av_log(avctx, AV_LOG_ERROR, "Failed to add NAL unit: "
139 "type = %d.\n", header->nal_unit_type);
146 static int vaapi_encode_h264_write_sequence_header(AVCodecContext *avctx,
147 char *data, size_t *data_len)
149 VAAPIEncodeContext *ctx = avctx->priv_data;
150 VAAPIEncodeH264Context *priv = ctx->priv_data;
151 CodedBitstreamFragment *au = &priv->current_access_unit;
154 if (priv->aud_needed) {
155 err = vaapi_encode_h264_add_nal(avctx, au, &priv->aud);
158 priv->aud_needed = 0;
161 err = vaapi_encode_h264_add_nal(avctx, au, &priv->sps);
165 err = vaapi_encode_h264_add_nal(avctx, au, &priv->pps);
169 err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
171 ff_cbs_fragment_uninit(priv->cbc, au);
175 static int vaapi_encode_h264_write_slice_header(AVCodecContext *avctx,
176 VAAPIEncodePicture *pic,
177 VAAPIEncodeSlice *slice,
178 char *data, size_t *data_len)
180 VAAPIEncodeContext *ctx = avctx->priv_data;
181 VAAPIEncodeH264Context *priv = ctx->priv_data;
182 CodedBitstreamFragment *au = &priv->current_access_unit;
185 if (priv->aud_needed) {
186 err = vaapi_encode_h264_add_nal(avctx, au, &priv->aud);
189 priv->aud_needed = 0;
192 err = vaapi_encode_h264_add_nal(avctx, au, &priv->slice);
196 err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
198 ff_cbs_fragment_uninit(priv->cbc, au);
202 static int vaapi_encode_h264_write_extra_header(AVCodecContext *avctx,
203 VAAPIEncodePicture *pic,
204 int index, int *type,
205 char *data, size_t *data_len)
207 VAAPIEncodeContext *ctx = avctx->priv_data;
208 VAAPIEncodeH264Context *priv = ctx->priv_data;
209 VAAPIEncodeH264Options *opt = ctx->codec_options;
210 CodedBitstreamFragment *au = &priv->current_access_unit;
213 if (priv->sei_needed) {
214 if (priv->aud_needed) {
215 err = vaapi_encode_h264_add_nal(avctx, au, &priv->aud);
218 priv->aud_needed = 0;
221 memset(&priv->sei, 0, sizeof(priv->sei));
222 priv->sei.nal_unit_header.nal_unit_type = H264_NAL_SEI;
225 if (pic->encode_order == 0 && opt->sei & SEI_IDENTIFIER) {
226 priv->sei.payload[i].payload_type = H264_SEI_TYPE_USER_DATA_UNREGISTERED;
227 priv->sei.payload[i].payload.user_data_unregistered = priv->identifier;
230 if (opt->sei & SEI_TIMING) {
231 if (pic->type == PICTURE_TYPE_IDR) {
232 priv->sei.payload[i].payload_type = H264_SEI_TYPE_BUFFERING_PERIOD;
233 priv->sei.payload[i].payload.buffering_period = priv->buffering_period;
236 priv->sei.payload[i].payload_type = H264_SEI_TYPE_PIC_TIMING;
237 priv->sei.payload[i].payload.pic_timing = priv->pic_timing;
240 if (opt->sei & SEI_RECOVERY_POINT && pic->type == PICTURE_TYPE_I) {
241 priv->sei.payload[i].payload_type = H264_SEI_TYPE_RECOVERY_POINT;
242 priv->sei.payload[i].payload.recovery_point = priv->recovery_point;
246 priv->sei.payload_count = i;
247 av_assert0(priv->sei.payload_count > 0);
249 err = vaapi_encode_h264_add_nal(avctx, au, &priv->sei);
252 priv->sei_needed = 0;
254 err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
258 ff_cbs_fragment_uninit(priv->cbc, au);
260 *type = VAEncPackedHeaderRawData;
264 } else if (priv->sei_cbr_workaround_needed) {
265 // Insert a zero-length header using the old SEI type. This is
266 // required to avoid triggering broken behaviour on Intel platforms
267 // in CBR mode where an invalid SEI message is generated by the
268 // driver and inserted into the stream.
270 *type = VAEncPackedHeaderH264_SEI;
271 priv->sei_cbr_workaround_needed = 0;
280 ff_cbs_fragment_uninit(priv->cbc, au);
284 static int vaapi_encode_h264_init_sequence_params(AVCodecContext *avctx)
286 VAAPIEncodeContext *ctx = avctx->priv_data;
287 VAAPIEncodeH264Context *priv = ctx->priv_data;
288 VAAPIEncodeH264Options *opt = ctx->codec_options;
289 H264RawSPS *sps = &priv->sps;
290 H264RawPPS *pps = &priv->pps;
291 VAEncSequenceParameterBufferH264 *vseq = ctx->codec_sequence_params;
292 VAEncPictureParameterBufferH264 *vpic = ctx->codec_picture_params;
294 memset(&priv->current_access_unit, 0,
295 sizeof(priv->current_access_unit));
297 memset(sps, 0, sizeof(*sps));
298 memset(pps, 0, sizeof(*pps));
300 sps->nal_unit_header.nal_ref_idc = 3;
301 sps->nal_unit_header.nal_unit_type = H264_NAL_SPS;
303 sps->profile_idc = avctx->profile & 0xff;
304 sps->constraint_set1_flag =
305 !!(avctx->profile & FF_PROFILE_H264_CONSTRAINED);
306 sps->constraint_set3_flag =
307 !!(avctx->profile & FF_PROFILE_H264_INTRA);
309 sps->level_idc = avctx->level;
311 sps->seq_parameter_set_id = 0;
312 sps->chroma_format_idc = 1;
314 sps->log2_max_frame_num_minus4 = 4;
315 sps->pic_order_cnt_type = 0;
316 sps->log2_max_pic_order_cnt_lsb_minus4 =
317 av_clip(av_log2(ctx->b_per_p + 1) - 2, 0, 12);
319 sps->max_num_ref_frames =
320 (avctx->profile & FF_PROFILE_H264_INTRA) ? 0 :
321 1 + (ctx->b_per_p > 0);
323 sps->pic_width_in_mbs_minus1 = priv->mb_width - 1;
324 sps->pic_height_in_map_units_minus1 = priv->mb_height - 1;
326 sps->frame_mbs_only_flag = 1;
327 sps->direct_8x8_inference_flag = 1;
329 if (avctx->width != 16 * priv->mb_width ||
330 avctx->height != 16 * priv->mb_height) {
331 sps->frame_cropping_flag = 1;
333 sps->frame_crop_left_offset = 0;
334 sps->frame_crop_right_offset =
335 (16 * priv->mb_width - avctx->width) / 2;
336 sps->frame_crop_top_offset = 0;
337 sps->frame_crop_bottom_offset =
338 (16 * priv->mb_height - avctx->height) / 2;
340 sps->frame_cropping_flag = 0;
343 sps->vui_parameters_present_flag = 1;
345 if (avctx->sample_aspect_ratio.num != 0 &&
346 avctx->sample_aspect_ratio.den != 0) {
347 static const AVRational sar_idc[] = {
349 { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 },
350 { 40, 33 }, { 24, 11 }, { 20, 11 }, { 32, 11 },
351 { 80, 33 }, { 18, 11 }, { 15, 11 }, { 64, 33 },
352 { 160, 99 }, { 4, 3 }, { 3, 2 }, { 2, 1 },
355 for (i = 0; i < FF_ARRAY_ELEMS(sar_idc); i++) {
356 if (avctx->sample_aspect_ratio.num == sar_idc[i].num &&
357 avctx->sample_aspect_ratio.den == sar_idc[i].den) {
358 sps->vui.aspect_ratio_idc = i;
362 if (i >= FF_ARRAY_ELEMS(sar_idc)) {
363 sps->vui.aspect_ratio_idc = 255;
364 sps->vui.sar_width = avctx->sample_aspect_ratio.num;
365 sps->vui.sar_height = avctx->sample_aspect_ratio.den;
367 sps->vui.aspect_ratio_info_present_flag = 1;
370 if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED ||
371 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
372 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
373 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
374 sps->vui.video_signal_type_present_flag = 1;
375 sps->vui.video_format = 5; // Unspecified.
376 sps->vui.video_full_range_flag =
377 avctx->color_range == AVCOL_RANGE_JPEG;
379 if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
380 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
381 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
382 sps->vui.colour_description_present_flag = 1;
383 sps->vui.colour_primaries = avctx->color_primaries;
384 sps->vui.transfer_characteristics = avctx->color_trc;
385 sps->vui.matrix_coefficients = avctx->colorspace;
388 sps->vui.video_format = 5;
389 sps->vui.video_full_range_flag = 0;
390 sps->vui.colour_primaries = avctx->color_primaries;
391 sps->vui.transfer_characteristics = avctx->color_trc;
392 sps->vui.matrix_coefficients = avctx->colorspace;
395 if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
396 sps->vui.chroma_loc_info_present_flag = 1;
397 sps->vui.chroma_sample_loc_type_top_field =
398 sps->vui.chroma_sample_loc_type_bottom_field =
399 avctx->chroma_sample_location - 1;
402 sps->vui.timing_info_present_flag = 1;
403 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
404 sps->vui.num_units_in_tick = avctx->framerate.den;
405 sps->vui.time_scale = 2 * avctx->framerate.num;
406 sps->vui.fixed_frame_rate_flag = 1;
408 sps->vui.num_units_in_tick = avctx->time_base.num;
409 sps->vui.time_scale = 2 * avctx->time_base.den;
410 sps->vui.fixed_frame_rate_flag = 0;
413 if (opt->sei & SEI_TIMING) {
414 H264RawHRD *hrd = &sps->vui.nal_hrd_parameters;
416 sps->vui.nal_hrd_parameters_present_flag = 1;
418 hrd->cpb_cnt_minus1 = 0;
420 // Try to scale these to a sensible range so that the
421 // golomb encode of the value is not overlong.
422 hrd->bit_rate_scale =
423 av_clip_uintp2(av_log2(avctx->bit_rate) - 15 - 6, 4);
424 hrd->bit_rate_value_minus1[0] =
425 (avctx->bit_rate >> hrd->bit_rate_scale + 6) - 1;
427 hrd->cpb_size_scale =
428 av_clip_uintp2(av_log2(ctx->hrd_params.hrd.buffer_size) - 15 - 4, 4);
429 hrd->cpb_size_value_minus1[0] =
430 (ctx->hrd_params.hrd.buffer_size >> hrd->cpb_size_scale + 4) - 1;
432 // CBR mode as defined for the HRD cannot be achieved without filler
433 // data, so this flag cannot be set even with VAAPI CBR modes.
434 hrd->cbr_flag[0] = 0;
436 hrd->initial_cpb_removal_delay_length_minus1 = 23;
437 hrd->cpb_removal_delay_length_minus1 = 23;
438 hrd->dpb_output_delay_length_minus1 = 7;
439 hrd->time_offset_length = 0;
441 priv->buffering_period.seq_parameter_set_id = sps->seq_parameter_set_id;
443 // This calculation can easily overflow 32 bits.
444 priv->buffering_period.nal.initial_cpb_removal_delay[0] = 90000 *
445 (uint64_t)ctx->hrd_params.hrd.initial_buffer_fullness /
446 ctx->hrd_params.hrd.buffer_size;
447 priv->buffering_period.nal.initial_cpb_removal_delay_offset[0] = 0;
449 sps->vui.nal_hrd_parameters_present_flag = 0;
450 sps->vui.low_delay_hrd_flag = 1 - sps->vui.fixed_frame_rate_flag;
453 sps->vui.bitstream_restriction_flag = 1;
454 sps->vui.motion_vectors_over_pic_boundaries_flag = 1;
455 sps->vui.log2_max_mv_length_horizontal = 16;
456 sps->vui.log2_max_mv_length_vertical = 16;
457 sps->vui.max_num_reorder_frames = (ctx->b_per_p > 0);
458 sps->vui.max_dec_frame_buffering = sps->max_num_ref_frames;
460 pps->nal_unit_header.nal_ref_idc = 3;
461 pps->nal_unit_header.nal_unit_type = H264_NAL_PPS;
463 pps->pic_parameter_set_id = 0;
464 pps->seq_parameter_set_id = 0;
466 pps->entropy_coding_mode_flag =
467 !(sps->profile_idc == FF_PROFILE_H264_BASELINE ||
468 sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
469 sps->profile_idc == FF_PROFILE_H264_CAVLC_444);
470 if (!opt->coder && pps->entropy_coding_mode_flag)
471 pps->entropy_coding_mode_flag = 0;
473 pps->num_ref_idx_l0_default_active_minus1 = 0;
474 pps->num_ref_idx_l1_default_active_minus1 = 0;
476 pps->pic_init_qp_minus26 = priv->fixed_qp_idr - 26;
478 if (sps->profile_idc == FF_PROFILE_H264_BASELINE ||
479 sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
480 sps->profile_idc == FF_PROFILE_H264_MAIN) {
481 pps->more_rbsp_data = 0;
483 pps->more_rbsp_data = 1;
485 pps->transform_8x8_mode_flag = 1;
488 *vseq = (VAEncSequenceParameterBufferH264) {
489 .seq_parameter_set_id = sps->seq_parameter_set_id,
490 .level_idc = sps->level_idc,
491 .intra_period = avctx->gop_size,
492 .intra_idr_period = avctx->gop_size,
493 .ip_period = ctx->b_per_p + 1,
495 .bits_per_second = avctx->bit_rate,
496 .max_num_ref_frames = sps->max_num_ref_frames,
497 .picture_width_in_mbs = sps->pic_width_in_mbs_minus1 + 1,
498 .picture_height_in_mbs = sps->pic_height_in_map_units_minus1 + 1,
501 .chroma_format_idc = sps->chroma_format_idc,
502 .frame_mbs_only_flag = sps->frame_mbs_only_flag,
503 .mb_adaptive_frame_field_flag = sps->mb_adaptive_frame_field_flag,
504 .seq_scaling_matrix_present_flag = sps->seq_scaling_matrix_present_flag,
505 .direct_8x8_inference_flag = sps->direct_8x8_inference_flag,
506 .log2_max_frame_num_minus4 = sps->log2_max_frame_num_minus4,
507 .pic_order_cnt_type = sps->pic_order_cnt_type,
508 .log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_pic_order_cnt_lsb_minus4,
509 .delta_pic_order_always_zero_flag = sps->delta_pic_order_always_zero_flag,
512 .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
513 .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
515 .frame_cropping_flag = sps->frame_cropping_flag,
516 .frame_crop_left_offset = sps->frame_crop_left_offset,
517 .frame_crop_right_offset = sps->frame_crop_right_offset,
518 .frame_crop_top_offset = sps->frame_crop_top_offset,
519 .frame_crop_bottom_offset = sps->frame_crop_bottom_offset,
521 .vui_parameters_present_flag = sps->vui_parameters_present_flag,
524 .aspect_ratio_info_present_flag = sps->vui.aspect_ratio_info_present_flag,
525 .timing_info_present_flag = sps->vui.timing_info_present_flag,
526 .bitstream_restriction_flag = sps->vui.bitstream_restriction_flag,
527 .log2_max_mv_length_horizontal = sps->vui.log2_max_mv_length_horizontal,
528 .log2_max_mv_length_vertical = sps->vui.log2_max_mv_length_vertical,
531 .aspect_ratio_idc = sps->vui.aspect_ratio_idc,
532 .sar_width = sps->vui.sar_width,
533 .sar_height = sps->vui.sar_height,
534 .num_units_in_tick = sps->vui.num_units_in_tick,
535 .time_scale = sps->vui.time_scale,
538 *vpic = (VAEncPictureParameterBufferH264) {
540 .picture_id = VA_INVALID_ID,
541 .flags = VA_PICTURE_H264_INVALID,
544 .coded_buf = VA_INVALID_ID,
546 .pic_parameter_set_id = pps->pic_parameter_set_id,
547 .seq_parameter_set_id = pps->seq_parameter_set_id,
549 .pic_init_qp = pps->pic_init_qp_minus26 + 26,
550 .num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1,
551 .num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1,
553 .chroma_qp_index_offset = pps->chroma_qp_index_offset,
554 .second_chroma_qp_index_offset = pps->second_chroma_qp_index_offset,
557 .entropy_coding_mode_flag = pps->entropy_coding_mode_flag,
558 .weighted_pred_flag = pps->weighted_pred_flag,
559 .weighted_bipred_idc = pps->weighted_bipred_idc,
560 .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
561 .transform_8x8_mode_flag = pps->transform_8x8_mode_flag,
562 .deblocking_filter_control_present_flag =
563 pps->deblocking_filter_control_present_flag,
564 .redundant_pic_cnt_present_flag = pps->redundant_pic_cnt_present_flag,
565 .pic_order_present_flag =
566 pps->bottom_field_pic_order_in_frame_present_flag,
567 .pic_scaling_matrix_present_flag = pps->pic_scaling_matrix_present_flag,
574 static int vaapi_encode_h264_init_picture_params(AVCodecContext *avctx,
575 VAAPIEncodePicture *pic)
577 VAAPIEncodeContext *ctx = avctx->priv_data;
578 VAAPIEncodeH264Context *priv = ctx->priv_data;
579 VAAPIEncodeH264Options *opt = ctx->codec_options;
580 H264RawSPS *sps = &priv->sps;
581 VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
584 memset(&priv->current_access_unit, 0,
585 sizeof(priv->current_access_unit));
587 if (pic->type == PICTURE_TYPE_IDR) {
588 av_assert0(pic->display_order == pic->encode_order);
590 priv->next_frame_num = 1;
592 priv->last_idr_frame = pic->display_order;
593 ++priv->idr_pic_count;
595 priv->slice_type = 7;
596 priv->primary_pic_type = 0;
598 priv->frame_num = priv->next_frame_num;
600 if (pic->type != PICTURE_TYPE_B) {
601 // Reference picture, so frame_num advances.
602 priv->next_frame_num = (priv->frame_num + 1) &
603 ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
607 if (pic->type == PICTURE_TYPE_I) {
608 priv->slice_type = 7;
609 priv->primary_pic_type = 0;
610 } else if (pic->type == PICTURE_TYPE_P) {
611 priv->slice_type = 5;
612 priv->primary_pic_type = 1;
614 priv->slice_type = 6;
615 priv->primary_pic_type = 2;
618 priv->pic_order_cnt = pic->display_order - priv->last_idr_frame;
619 priv->dpb_delay = pic->display_order - pic->encode_order + 1;
622 priv->aud_needed = 1;
623 priv->aud.nal_unit_header.nal_unit_type = H264_NAL_AUD;
624 priv->aud.primary_pic_type = priv->primary_pic_type;
626 priv->aud_needed = 0;
629 if (opt->sei & SEI_IDENTIFIER && pic->encode_order == 0)
630 priv->sei_needed = 1;
632 if (ctx->va_rc_mode == VA_RC_CBR)
633 priv->sei_cbr_workaround_needed = 1;
636 if (opt->sei & SEI_TIMING) {
637 memset(&priv->pic_timing, 0, sizeof(priv->pic_timing));
639 priv->pic_timing.cpb_removal_delay = 2 * priv->cpb_delay;
640 priv->pic_timing.dpb_output_delay = 2 * priv->dpb_delay;
642 priv->sei_needed = 1;
645 if (opt->sei & SEI_RECOVERY_POINT && pic->type == PICTURE_TYPE_I) {
646 priv->recovery_point.recovery_frame_cnt = 0;
647 priv->recovery_point.exact_match_flag = 1;
648 priv->recovery_point.broken_link_flag = ctx->b_per_p > 0;
650 priv->sei_needed = 1;
653 vpic->CurrPic = (VAPictureH264) {
654 .picture_id = pic->recon_surface,
655 .frame_idx = priv->frame_num,
657 .TopFieldOrderCnt = priv->pic_order_cnt,
658 .BottomFieldOrderCnt = priv->pic_order_cnt,
661 for (i = 0; i < pic->nb_refs; i++) {
662 VAAPIEncodePicture *ref = pic->refs[i];
663 unsigned int frame_num = (ref->encode_order - priv->last_idr_frame) &
664 ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
665 unsigned int pic_order_cnt = ref->display_order - priv->last_idr_frame;
667 av_assert0(ref && ref->encode_order < pic->encode_order);
668 vpic->ReferenceFrames[i] = (VAPictureH264) {
669 .picture_id = ref->recon_surface,
670 .frame_idx = frame_num,
671 .flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE,
672 .TopFieldOrderCnt = pic_order_cnt,
673 .BottomFieldOrderCnt = pic_order_cnt,
676 for (; i < FF_ARRAY_ELEMS(vpic->ReferenceFrames); i++) {
677 vpic->ReferenceFrames[i] = (VAPictureH264) {
678 .picture_id = VA_INVALID_ID,
679 .flags = VA_PICTURE_H264_INVALID,
683 vpic->coded_buf = pic->output_buffer;
685 vpic->frame_num = priv->frame_num;
687 vpic->pic_fields.bits.idr_pic_flag = (pic->type == PICTURE_TYPE_IDR);
688 vpic->pic_fields.bits.reference_pic_flag = (pic->type != PICTURE_TYPE_B);
695 static int vaapi_encode_h264_init_slice_params(AVCodecContext *avctx,
696 VAAPIEncodePicture *pic,
697 VAAPIEncodeSlice *slice)
699 VAAPIEncodeContext *ctx = avctx->priv_data;
700 VAAPIEncodeH264Context *priv = ctx->priv_data;
701 H264RawSPS *sps = &priv->sps;
702 H264RawPPS *pps = &priv->pps;
703 H264RawSliceHeader *sh = &priv->slice.header;
704 VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
705 VAEncSliceParameterBufferH264 *vslice = slice->codec_slice_params;
708 if (pic->type == PICTURE_TYPE_IDR) {
709 sh->nal_unit_header.nal_unit_type = H264_NAL_IDR_SLICE;
710 sh->nal_unit_header.nal_ref_idc = 3;
712 sh->nal_unit_header.nal_unit_type = H264_NAL_SLICE;
713 sh->nal_unit_header.nal_ref_idc = pic->type != PICTURE_TYPE_B;
716 // Only one slice per frame.
717 sh->first_mb_in_slice = 0;
718 sh->slice_type = priv->slice_type;
720 sh->pic_parameter_set_id = pps->pic_parameter_set_id;
722 sh->frame_num = priv->frame_num;
723 sh->idr_pic_id = priv->idr_pic_count;
725 sh->pic_order_cnt_lsb = priv->pic_order_cnt &
726 ((1 << (4 + sps->log2_max_pic_order_cnt_lsb_minus4)) - 1);
728 sh->direct_spatial_mv_pred_flag = 1;
730 if (pic->type == PICTURE_TYPE_B)
731 sh->slice_qp_delta = priv->fixed_qp_b - (pps->pic_init_qp_minus26 + 26);
732 else if (pic->type == PICTURE_TYPE_P)
733 sh->slice_qp_delta = priv->fixed_qp_p - (pps->pic_init_qp_minus26 + 26);
735 sh->slice_qp_delta = priv->fixed_qp_idr - (pps->pic_init_qp_minus26 + 26);
738 vslice->macroblock_address = sh->first_mb_in_slice;
739 vslice->num_macroblocks = priv->mb_width * priv->mb_height;
741 vslice->macroblock_info = VA_INVALID_ID;
743 vslice->slice_type = sh->slice_type % 5;
744 vslice->pic_parameter_set_id = sh->pic_parameter_set_id;
745 vslice->idr_pic_id = sh->idr_pic_id;
747 vslice->pic_order_cnt_lsb = sh->pic_order_cnt_lsb;
749 vslice->direct_spatial_mv_pred_flag = sh->direct_spatial_mv_pred_flag;
751 for (i = 0; i < FF_ARRAY_ELEMS(vslice->RefPicList0); i++) {
752 vslice->RefPicList0[i].picture_id = VA_INVALID_ID;
753 vslice->RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
754 vslice->RefPicList1[i].picture_id = VA_INVALID_ID;
755 vslice->RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
758 av_assert0(pic->nb_refs <= 2);
759 if (pic->nb_refs >= 1) {
760 // Backward reference for P- or B-frame.
761 av_assert0(pic->type == PICTURE_TYPE_P ||
762 pic->type == PICTURE_TYPE_B);
763 vslice->RefPicList0[0] = vpic->ReferenceFrames[0];
765 if (pic->nb_refs >= 2) {
766 // Forward reference for B-frame.
767 av_assert0(pic->type == PICTURE_TYPE_B);
768 vslice->RefPicList1[0] = vpic->ReferenceFrames[1];
771 vslice->slice_qp_delta = sh->slice_qp_delta;
776 static av_cold int vaapi_encode_h264_configure(AVCodecContext *avctx)
778 VAAPIEncodeContext *ctx = avctx->priv_data;
779 VAAPIEncodeH264Context *priv = ctx->priv_data;
780 VAAPIEncodeH264Options *opt = ctx->codec_options;
783 err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_H264, avctx);
787 priv->mb_width = FFALIGN(avctx->width, 16) / 16;
788 priv->mb_height = FFALIGN(avctx->height, 16) / 16;
790 if (ctx->va_rc_mode == VA_RC_CQP) {
791 priv->fixed_qp_p = opt->qp;
792 if (avctx->i_quant_factor > 0.0)
793 priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
794 avctx->i_quant_offset) + 0.5);
796 priv->fixed_qp_idr = priv->fixed_qp_p;
797 if (avctx->b_quant_factor > 0.0)
798 priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
799 avctx->b_quant_offset) + 0.5);
801 priv->fixed_qp_b = priv->fixed_qp_p;
803 opt->sei &= ~SEI_TIMING;
805 av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
806 "%d / %d / %d for IDR- / P- / B-frames.\n",
807 priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
809 } else if (ctx->va_rc_mode == VA_RC_CBR ||
810 ctx->va_rc_mode == VA_RC_VBR) {
811 // These still need to be set for pic_init_qp/slice_qp_delta.
812 priv->fixed_qp_idr = 26;
813 priv->fixed_qp_p = 26;
814 priv->fixed_qp_b = 26;
816 av_log(avctx, AV_LOG_DEBUG, "Using %s-bitrate = %"PRId64" bps.\n",
817 ctx->va_rc_mode == VA_RC_CBR ? "constant" : "variable",
821 av_assert0(0 && "Invalid RC mode.");
824 if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
825 avctx->compression_level = opt->quality;
827 if (opt->sei & SEI_IDENTIFIER) {
828 const char *lavc = LIBAVCODEC_IDENT;
829 const char *vaapi = VA_VERSION_S;
833 memcpy(priv->identifier.uuid_iso_iec_11578,
834 vaapi_encode_h264_sei_identifier_uuid,
835 sizeof(priv->identifier.uuid_iso_iec_11578));
837 driver = vaQueryVendorString(ctx->hwctx->display);
839 driver = "unknown driver";
841 len = snprintf(NULL, 0, "%s / VAAPI %s / %s", lavc, vaapi, driver);
843 priv->identifier_string = av_malloc(len + 1);
844 if (!priv->identifier_string)
845 return AVERROR(ENOMEM);
847 snprintf(priv->identifier_string, len + 1,
848 "%s / VAAPI %s / %s", lavc, vaapi, driver);
850 priv->identifier.data = priv->identifier_string;
851 priv->identifier.data_length = len + 1;
858 static const VAAPIEncodeType vaapi_encode_type_h264 = {
859 .priv_data_size = sizeof(VAAPIEncodeH264Context),
861 .configure = &vaapi_encode_h264_configure,
863 .sequence_params_size = sizeof(VAEncSequenceParameterBufferH264),
864 .init_sequence_params = &vaapi_encode_h264_init_sequence_params,
866 .picture_params_size = sizeof(VAEncPictureParameterBufferH264),
867 .init_picture_params = &vaapi_encode_h264_init_picture_params,
869 .slice_params_size = sizeof(VAEncSliceParameterBufferH264),
870 .init_slice_params = &vaapi_encode_h264_init_slice_params,
872 .sequence_header_type = VAEncPackedHeaderSequence,
873 .write_sequence_header = &vaapi_encode_h264_write_sequence_header,
875 .slice_header_type = VAEncPackedHeaderH264_Slice,
876 .write_slice_header = &vaapi_encode_h264_write_slice_header,
878 .write_extra_header = &vaapi_encode_h264_write_extra_header,
881 static av_cold int vaapi_encode_h264_init(AVCodecContext *avctx)
883 VAAPIEncodeContext *ctx = avctx->priv_data;
884 VAAPIEncodeH264Options *opt =
885 (VAAPIEncodeH264Options*)ctx->codec_options_data;
887 ctx->codec = &vaapi_encode_type_h264;
889 switch (avctx->profile) {
890 case FF_PROFILE_H264_BASELINE:
891 av_log(avctx, AV_LOG_WARNING, "H.264 baseline profile is not "
892 "supported, using constrained baseline profile instead.\n");
893 avctx->profile = FF_PROFILE_H264_CONSTRAINED_BASELINE;
894 case FF_PROFILE_H264_CONSTRAINED_BASELINE:
895 ctx->va_profile = VAProfileH264ConstrainedBaseline;
896 if (avctx->max_b_frames != 0) {
897 avctx->max_b_frames = 0;
898 av_log(avctx, AV_LOG_WARNING, "H.264 constrained baseline profile "
899 "doesn't support encoding with B frames, disabling them.\n");
902 case FF_PROFILE_H264_MAIN:
903 ctx->va_profile = VAProfileH264Main;
905 case FF_PROFILE_H264_EXTENDED:
906 av_log(avctx, AV_LOG_ERROR, "H.264 extended profile "
907 "is not supported.\n");
908 return AVERROR_PATCHWELCOME;
909 case FF_PROFILE_UNKNOWN:
910 case FF_PROFILE_H264_HIGH:
911 ctx->va_profile = VAProfileH264High;
913 case FF_PROFILE_H264_HIGH_10:
914 case FF_PROFILE_H264_HIGH_10_INTRA:
915 av_log(avctx, AV_LOG_ERROR, "H.264 10-bit profiles "
916 "are not supported.\n");
917 return AVERROR_PATCHWELCOME;
918 case FF_PROFILE_H264_HIGH_422:
919 case FF_PROFILE_H264_HIGH_422_INTRA:
920 case FF_PROFILE_H264_HIGH_444:
921 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
922 case FF_PROFILE_H264_HIGH_444_INTRA:
923 case FF_PROFILE_H264_CAVLC_444:
924 av_log(avctx, AV_LOG_ERROR, "H.264 non-4:2:0 profiles "
925 "are not supported.\n");
926 return AVERROR_PATCHWELCOME;
928 av_log(avctx, AV_LOG_ERROR, "Unknown H.264 profile %d.\n",
930 return AVERROR(EINVAL);
932 if (opt->low_power) {
933 #if VA_CHECK_VERSION(0, 39, 2)
934 ctx->va_entrypoint = VAEntrypointEncSliceLP;
936 av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
937 "supported with this VAAPI version.\n");
938 return AVERROR(EINVAL);
941 ctx->va_entrypoint = VAEntrypointEncSlice;
944 // Only 8-bit encode is supported.
945 ctx->va_rt_format = VA_RT_FORMAT_YUV420;
947 if (avctx->bit_rate > 0) {
948 if (avctx->rc_max_rate == avctx->bit_rate)
949 ctx->va_rc_mode = VA_RC_CBR;
951 ctx->va_rc_mode = VA_RC_VBR;
953 ctx->va_rc_mode = VA_RC_CQP;
955 ctx->va_packed_headers =
956 VA_ENC_PACKED_HEADER_SEQUENCE | // SPS and PPS.
957 VA_ENC_PACKED_HEADER_SLICE | // Slice headers.
958 VA_ENC_PACKED_HEADER_MISC; // SEI.
960 ctx->surface_width = FFALIGN(avctx->width, 16);
961 ctx->surface_height = FFALIGN(avctx->height, 16);
963 return ff_vaapi_encode_init(avctx);
966 static av_cold int vaapi_encode_h264_close(AVCodecContext *avctx)
968 VAAPIEncodeContext *ctx = avctx->priv_data;
969 VAAPIEncodeH264Context *priv = ctx->priv_data;
972 ff_cbs_close(&priv->cbc);
973 av_freep(&priv->identifier_string);
976 return ff_vaapi_encode_close(avctx);
979 #define OFFSET(x) (offsetof(VAAPIEncodeContext, codec_options_data) + \
980 offsetof(VAAPIEncodeH264Options, x))
981 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
982 static const AVOption vaapi_encode_h264_options[] = {
983 { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
984 OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 20 }, 0, 52, FLAGS },
985 { "quality", "Set encode quality (trades off against speed, higher is faster)",
986 OFFSET(quality), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 8, FLAGS },
987 { "low_power", "Use low-power encoding mode (experimental: only supported "
988 "on some platforms, does not support all features)",
989 OFFSET(low_power), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
990 { "coder", "Entropy coder type",
991 OFFSET(coder), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS, "coder" },
992 { "cavlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
993 { "cabac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
994 { "vlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
995 { "ac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
997 { "aud", "Include AUD",
998 OFFSET(aud), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
1000 { "sei", "Set SEI to include",
1001 OFFSET(sei), AV_OPT_TYPE_FLAGS,
1002 { .i64 = SEI_IDENTIFIER | SEI_TIMING | SEI_RECOVERY_POINT },
1003 0, INT_MAX, FLAGS, "sei" },
1004 { "identifier", "Include encoder version identifier",
1005 0, AV_OPT_TYPE_CONST, { .i64 = SEI_IDENTIFIER },
1006 INT_MIN, INT_MAX, FLAGS, "sei" },
1007 { "timing", "Include timing parameters (buffering_period and pic_timing)",
1008 0, AV_OPT_TYPE_CONST, { .i64 = SEI_TIMING },
1009 INT_MIN, INT_MAX, FLAGS, "sei" },
1010 { "recovery_point", "Include recovery points where appropriate",
1011 0, AV_OPT_TYPE_CONST, { .i64 = SEI_RECOVERY_POINT },
1012 INT_MIN, INT_MAX, FLAGS, "sei" },
1016 static const AVCodecDefault vaapi_encode_h264_defaults[] = {
1017 { "profile", "100" },
1022 { "i_qfactor", "1" },
1023 { "i_qoffset", "0" },
1024 { "b_qfactor", "6/5" },
1025 { "b_qoffset", "0" },
1030 static const AVClass vaapi_encode_h264_class = {
1031 .class_name = "h264_vaapi",
1032 .item_name = av_default_item_name,
1033 .option = vaapi_encode_h264_options,
1034 .version = LIBAVUTIL_VERSION_INT,
1037 AVCodec ff_h264_vaapi_encoder = {
1038 .name = "h264_vaapi",
1039 .long_name = NULL_IF_CONFIG_SMALL("H.264/AVC (VAAPI)"),
1040 .type = AVMEDIA_TYPE_VIDEO,
1041 .id = AV_CODEC_ID_H264,
1042 .priv_data_size = (sizeof(VAAPIEncodeContext) +
1043 sizeof(VAAPIEncodeH264Options)),
1044 .init = &vaapi_encode_h264_init,
1045 .encode2 = &ff_vaapi_encode2,
1046 .close = &vaapi_encode_h264_close,
1047 .priv_class = &vaapi_encode_h264_class,
1048 .capabilities = AV_CODEC_CAP_DELAY,
1049 .defaults = vaapi_encode_h264_defaults,
1050 .pix_fmts = (const enum AVPixelFormat[]) {