FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavcodec/vaapi_encode_h264.c
Date: 2024-07-26 21:54:09
Exec Total Coverage
Lines: 0 687 0.0%
Functions: 0 12 0.0%
Branches: 0 367 0.0%

Line Branch Exec Source
1 /*
2 * This file is part of FFmpeg.
3 *
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.
8 *
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.
13 *
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
17 */
18
19 #include <string.h>
20
21 #include <va/va.h>
22 #include <va/va_enc_h264.h>
23
24 #include "libavutil/avassert.h"
25 #include "libavutil/common.h"
26 #include "libavutil/mem.h"
27 #include "libavutil/pixdesc.h"
28 #include "libavutil/opt.h"
29
30 #include "atsc_a53.h"
31 #include "avcodec.h"
32 #include "cbs.h"
33 #include "cbs_h264.h"
34 #include "codec_internal.h"
35 #include "h264.h"
36 #include "h264_levels.h"
37 #include "h2645data.h"
38 #include "vaapi_encode.h"
39 #include "version.h"
40
41 enum {
42 SEI_TIMING = 0x01,
43 SEI_IDENTIFIER = 0x02,
44 SEI_RECOVERY_POINT = 0x04,
45 SEI_A53_CC = 0x08,
46 };
47
48 // Random (version 4) ISO 11578 UUID.
49 static const uint8_t vaapi_encode_h264_sei_identifier_uuid[16] = {
50 0x59, 0x94, 0x8b, 0x28, 0x11, 0xec, 0x45, 0xaf,
51 0x96, 0x75, 0x19, 0xd4, 0x1f, 0xea, 0xa9, 0x4d,
52 };
53
54 typedef struct VAAPIEncodeH264Picture {
55 int frame_num;
56 int pic_order_cnt;
57
58 int64_t last_idr_frame;
59 uint16_t idr_pic_id;
60
61 int primary_pic_type;
62 int slice_type;
63
64 int cpb_delay;
65 int dpb_delay;
66 } VAAPIEncodeH264Picture;
67
68 typedef struct VAAPIEncodeH264Context {
69 VAAPIEncodeContext common;
70
71 // User options.
72 int qp;
73 int quality;
74 int coder;
75 int aud;
76 int sei;
77 int profile;
78 int level;
79
80 // Derived settings.
81 int mb_width;
82 int mb_height;
83
84 int fixed_qp_idr;
85 int fixed_qp_p;
86 int fixed_qp_b;
87
88 int dpb_frames;
89
90 // Writer structures.
91 CodedBitstreamContext *cbc;
92 CodedBitstreamFragment current_access_unit;
93
94 H264RawAUD raw_aud;
95 H264RawSPS raw_sps;
96 H264RawPPS raw_pps;
97 H264RawSlice raw_slice;
98
99 H264RawSEIBufferingPeriod sei_buffering_period;
100 H264RawSEIPicTiming sei_pic_timing;
101 H264RawSEIRecoveryPoint sei_recovery_point;
102 SEIRawUserDataUnregistered sei_identifier;
103 char *sei_identifier_string;
104 SEIRawUserDataRegistered sei_a53cc;
105 void *sei_a53cc_data;
106
107 int aud_needed;
108 int sei_needed;
109 int sei_cbr_workaround_needed;
110 } VAAPIEncodeH264Context;
111
112
113 static int vaapi_encode_h264_write_access_unit(AVCodecContext *avctx,
114 char *data, size_t *data_len,
115 CodedBitstreamFragment *au)
116 {
117 VAAPIEncodeH264Context *priv = avctx->priv_data;
118 int err;
119
120 err = ff_cbs_write_fragment_data(priv->cbc, au);
121 if (err < 0) {
122 av_log(avctx, AV_LOG_ERROR, "Failed to write packed header.\n");
123 return err;
124 }
125
126 if (*data_len < 8 * au->data_size - au->data_bit_padding) {
127 av_log(avctx, AV_LOG_ERROR, "Access unit too large: "
128 "%zu < %zu.\n", *data_len,
129 8 * au->data_size - au->data_bit_padding);
130 return AVERROR(ENOSPC);
131 }
132
133 memcpy(data, au->data, au->data_size);
134 *data_len = 8 * au->data_size - au->data_bit_padding;
135
136 return 0;
137 }
138
139 static int vaapi_encode_h264_add_nal(AVCodecContext *avctx,
140 CodedBitstreamFragment *au,
141 void *nal_unit)
142 {
143 H264RawNALUnitHeader *header = nal_unit;
144 int err;
145
146 err = ff_cbs_insert_unit_content(au, -1,
147 header->nal_unit_type, nal_unit, NULL);
148 if (err < 0) {
149 av_log(avctx, AV_LOG_ERROR, "Failed to add NAL unit: "
150 "type = %d.\n", header->nal_unit_type);
151 return err;
152 }
153
154 return 0;
155 }
156
157 static int vaapi_encode_h264_write_sequence_header(AVCodecContext *avctx,
158 char *data, size_t *data_len)
159 {
160 VAAPIEncodeH264Context *priv = avctx->priv_data;
161 CodedBitstreamFragment *au = &priv->current_access_unit;
162 int err;
163
164 if (priv->aud_needed) {
165 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_aud);
166 if (err < 0)
167 goto fail;
168 priv->aud_needed = 0;
169 }
170
171 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_sps);
172 if (err < 0)
173 goto fail;
174
175 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_pps);
176 if (err < 0)
177 goto fail;
178
179 err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
180 fail:
181 ff_cbs_fragment_reset(au);
182 return err;
183 }
184
185 static int vaapi_encode_h264_write_slice_header(AVCodecContext *avctx,
186 VAAPIEncodePicture *pic,
187 VAAPIEncodeSlice *slice,
188 char *data, size_t *data_len)
189 {
190 VAAPIEncodeH264Context *priv = avctx->priv_data;
191 CodedBitstreamFragment *au = &priv->current_access_unit;
192 int err;
193
194 if (priv->aud_needed) {
195 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_aud);
196 if (err < 0)
197 goto fail;
198 priv->aud_needed = 0;
199 }
200
201 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_slice);
202 if (err < 0)
203 goto fail;
204
205 err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
206 fail:
207 ff_cbs_fragment_reset(au);
208 return err;
209 }
210
211 static int vaapi_encode_h264_write_extra_header(AVCodecContext *avctx,
212 VAAPIEncodePicture *pic,
213 int index, int *type,
214 char *data, size_t *data_len)
215 {
216 VAAPIEncodeH264Context *priv = avctx->priv_data;
217 CodedBitstreamFragment *au = &priv->current_access_unit;
218 int err;
219
220 if (priv->sei_needed) {
221 if (priv->aud_needed) {
222 err = vaapi_encode_h264_add_nal(avctx, au, &priv->raw_aud);
223 if (err < 0)
224 goto fail;
225 priv->aud_needed = 0;
226 }
227
228 if (priv->sei_needed & SEI_IDENTIFIER) {
229 err = ff_cbs_sei_add_message(priv->cbc, au, 1,
230 SEI_TYPE_USER_DATA_UNREGISTERED,
231 &priv->sei_identifier, NULL);
232 if (err < 0)
233 goto fail;
234 }
235 if (priv->sei_needed & SEI_TIMING) {
236 if (pic->base.type == FF_HW_PICTURE_TYPE_IDR) {
237 err = ff_cbs_sei_add_message(priv->cbc, au, 1,
238 SEI_TYPE_BUFFERING_PERIOD,
239 &priv->sei_buffering_period, NULL);
240 if (err < 0)
241 goto fail;
242 }
243 err = ff_cbs_sei_add_message(priv->cbc, au, 1,
244 SEI_TYPE_PIC_TIMING,
245 &priv->sei_pic_timing, NULL);
246 if (err < 0)
247 goto fail;
248 }
249 if (priv->sei_needed & SEI_RECOVERY_POINT) {
250 err = ff_cbs_sei_add_message(priv->cbc, au, 1,
251 SEI_TYPE_RECOVERY_POINT,
252 &priv->sei_recovery_point, NULL);
253 if (err < 0)
254 goto fail;
255 }
256 if (priv->sei_needed & SEI_A53_CC) {
257 err = ff_cbs_sei_add_message(priv->cbc, au, 1,
258 SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35,
259 &priv->sei_a53cc, NULL);
260 if (err < 0)
261 goto fail;
262 }
263
264 priv->sei_needed = 0;
265
266 err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
267 if (err < 0)
268 goto fail;
269
270 ff_cbs_fragment_reset(au);
271
272 *type = VAEncPackedHeaderRawData;
273 return 0;
274
275 #if !CONFIG_VAAPI_1
276 } else if (priv->sei_cbr_workaround_needed) {
277 // Insert a zero-length header using the old SEI type. This is
278 // required to avoid triggering broken behaviour on Intel platforms
279 // in CBR mode where an invalid SEI message is generated by the
280 // driver and inserted into the stream.
281 *data_len = 0;
282 *type = VAEncPackedHeaderH264_SEI;
283 priv->sei_cbr_workaround_needed = 0;
284 return 0;
285 #endif
286
287 } else {
288 return AVERROR_EOF;
289 }
290
291 fail:
292 ff_cbs_fragment_reset(au);
293 return err;
294 }
295
296 static int vaapi_encode_h264_init_sequence_params(AVCodecContext *avctx)
297 {
298 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
299 VAAPIEncodeContext *ctx = avctx->priv_data;
300 VAAPIEncodeH264Context *priv = avctx->priv_data;
301 H264RawSPS *sps = &priv->raw_sps;
302 H264RawPPS *pps = &priv->raw_pps;
303 VAEncSequenceParameterBufferH264 *vseq = ctx->codec_sequence_params;
304 VAEncPictureParameterBufferH264 *vpic = ctx->codec_picture_params;
305 const AVPixFmtDescriptor *desc;
306 int bit_depth;
307
308 memset(sps, 0, sizeof(*sps));
309 memset(pps, 0, sizeof(*pps));
310
311 desc = av_pix_fmt_desc_get(base_ctx->input_frames->sw_format);
312 av_assert0(desc);
313 if (desc->nb_components == 1 || desc->log2_chroma_w != 1 || desc->log2_chroma_h != 1) {
314 av_log(avctx, AV_LOG_ERROR, "Chroma format of input pixel format "
315 "%s is not supported.\n", desc->name);
316 return AVERROR(EINVAL);
317 }
318 bit_depth = desc->comp[0].depth;
319
320 sps->nal_unit_header.nal_ref_idc = 3;
321 sps->nal_unit_header.nal_unit_type = H264_NAL_SPS;
322
323 sps->profile_idc = avctx->profile & 0xff;
324
325 if (avctx->profile == AV_PROFILE_H264_CONSTRAINED_BASELINE ||
326 avctx->profile == AV_PROFILE_H264_MAIN)
327 sps->constraint_set1_flag = 1;
328
329 if (avctx->profile == AV_PROFILE_H264_HIGH || avctx->profile == AV_PROFILE_H264_HIGH_10)
330 sps->constraint_set3_flag = base_ctx->gop_size == 1;
331
332 if (avctx->profile == AV_PROFILE_H264_MAIN ||
333 avctx->profile == AV_PROFILE_H264_HIGH || avctx->profile == AV_PROFILE_H264_HIGH_10) {
334 sps->constraint_set4_flag = 1;
335 sps->constraint_set5_flag = base_ctx->b_per_p == 0;
336 }
337
338 if (base_ctx->gop_size == 1)
339 priv->dpb_frames = 0;
340 else
341 priv->dpb_frames = 1 + base_ctx->max_b_depth;
342
343 if (avctx->level != AV_LEVEL_UNKNOWN) {
344 sps->level_idc = avctx->level;
345 } else {
346 const H264LevelDescriptor *level;
347 int framerate;
348
349 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
350 framerate = avctx->framerate.num / avctx->framerate.den;
351 else
352 framerate = 0;
353
354 level = ff_h264_guess_level(sps->profile_idc,
355 avctx->bit_rate,
356 framerate,
357 priv->mb_width * 16,
358 priv->mb_height * 16,
359 priv->dpb_frames);
360 if (level) {
361 av_log(avctx, AV_LOG_VERBOSE, "Using level %s.\n", level->name);
362 if (level->constraint_set3_flag)
363 sps->constraint_set3_flag = 1;
364 sps->level_idc = level->level_idc;
365 } else {
366 av_log(avctx, AV_LOG_WARNING, "Stream will not conform "
367 "to any level: using level 6.2.\n");
368 sps->level_idc = 62;
369 }
370 }
371
372 sps->seq_parameter_set_id = 0;
373 sps->chroma_format_idc = 1;
374 sps->bit_depth_luma_minus8 = bit_depth - 8;
375 sps->bit_depth_chroma_minus8 = bit_depth - 8;
376
377 sps->log2_max_frame_num_minus4 = 4;
378 sps->pic_order_cnt_type = base_ctx->max_b_depth ? 0 : 2;
379 if (sps->pic_order_cnt_type == 0) {
380 sps->log2_max_pic_order_cnt_lsb_minus4 = 4;
381 }
382
383 sps->max_num_ref_frames = priv->dpb_frames;
384
385 sps->pic_width_in_mbs_minus1 = priv->mb_width - 1;
386 sps->pic_height_in_map_units_minus1 = priv->mb_height - 1;
387
388 sps->frame_mbs_only_flag = 1;
389 sps->direct_8x8_inference_flag = 1;
390
391 if (avctx->width != 16 * priv->mb_width ||
392 avctx->height != 16 * priv->mb_height) {
393 sps->frame_cropping_flag = 1;
394
395 sps->frame_crop_left_offset = 0;
396 sps->frame_crop_right_offset =
397 (16 * priv->mb_width - avctx->width) / 2;
398 sps->frame_crop_top_offset = 0;
399 sps->frame_crop_bottom_offset =
400 (16 * priv->mb_height - avctx->height) / 2;
401 } else {
402 sps->frame_cropping_flag = 0;
403 }
404
405 sps->vui_parameters_present_flag = 1;
406
407 if (avctx->sample_aspect_ratio.num != 0 &&
408 avctx->sample_aspect_ratio.den != 0) {
409 int num, den, i;
410 av_reduce(&num, &den, avctx->sample_aspect_ratio.num,
411 avctx->sample_aspect_ratio.den, 65535);
412 for (i = 0; i < FF_ARRAY_ELEMS(ff_h2645_pixel_aspect); i++) {
413 if (num == ff_h2645_pixel_aspect[i].num &&
414 den == ff_h2645_pixel_aspect[i].den) {
415 sps->vui.aspect_ratio_idc = i;
416 break;
417 }
418 }
419 if (i >= FF_ARRAY_ELEMS(ff_h2645_pixel_aspect)) {
420 sps->vui.aspect_ratio_idc = 255;
421 sps->vui.sar_width = num;
422 sps->vui.sar_height = den;
423 }
424 sps->vui.aspect_ratio_info_present_flag = 1;
425 }
426
427 // Unspecified video format, from table E-2.
428 sps->vui.video_format = 5;
429 sps->vui.video_full_range_flag =
430 avctx->color_range == AVCOL_RANGE_JPEG;
431 sps->vui.colour_primaries = avctx->color_primaries;
432 sps->vui.transfer_characteristics = avctx->color_trc;
433 sps->vui.matrix_coefficients = avctx->colorspace;
434 if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
435 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
436 avctx->colorspace != AVCOL_SPC_UNSPECIFIED)
437 sps->vui.colour_description_present_flag = 1;
438 if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED ||
439 sps->vui.colour_description_present_flag)
440 sps->vui.video_signal_type_present_flag = 1;
441
442 if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
443 sps->vui.chroma_loc_info_present_flag = 1;
444 sps->vui.chroma_sample_loc_type_top_field =
445 sps->vui.chroma_sample_loc_type_bottom_field =
446 avctx->chroma_sample_location - 1;
447 }
448
449 sps->vui.timing_info_present_flag = 1;
450 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
451 sps->vui.num_units_in_tick = avctx->framerate.den;
452 sps->vui.time_scale = 2 * avctx->framerate.num;
453 sps->vui.fixed_frame_rate_flag = 1;
454 } else {
455 sps->vui.num_units_in_tick = avctx->time_base.num;
456 sps->vui.time_scale = 2 * avctx->time_base.den;
457 sps->vui.fixed_frame_rate_flag = 0;
458 }
459
460 if (priv->sei & SEI_TIMING) {
461 H264RawHRD *hrd = &sps->vui.nal_hrd_parameters;
462 H264RawSEIBufferingPeriod *bp = &priv->sei_buffering_period;
463
464 sps->vui.nal_hrd_parameters_present_flag = 1;
465
466 hrd->cpb_cnt_minus1 = 0;
467
468 // Try to scale these to a sensible range so that the
469 // golomb encode of the value is not overlong.
470 hrd->bit_rate_scale =
471 av_clip_uintp2(av_log2(ctx->va_bit_rate) - 15 - 6, 4);
472 hrd->bit_rate_value_minus1[0] =
473 (ctx->va_bit_rate >> hrd->bit_rate_scale + 6) - 1;
474
475 hrd->cpb_size_scale =
476 av_clip_uintp2(av_log2(ctx->hrd_params.buffer_size) - 15 - 4, 4);
477 hrd->cpb_size_value_minus1[0] =
478 (ctx->hrd_params.buffer_size >> hrd->cpb_size_scale + 4) - 1;
479
480 // CBR mode as defined for the HRD cannot be achieved without filler
481 // data, so this flag cannot be set even with VAAPI CBR modes.
482 hrd->cbr_flag[0] = 0;
483
484 hrd->initial_cpb_removal_delay_length_minus1 = 23;
485 hrd->cpb_removal_delay_length_minus1 = 23;
486 hrd->dpb_output_delay_length_minus1 = 7;
487 hrd->time_offset_length = 0;
488
489 bp->seq_parameter_set_id = sps->seq_parameter_set_id;
490
491 // This calculation can easily overflow 32 bits.
492 bp->nal.initial_cpb_removal_delay[0] = 90000 *
493 (uint64_t)ctx->hrd_params.initial_buffer_fullness /
494 ctx->hrd_params.buffer_size;
495 bp->nal.initial_cpb_removal_delay_offset[0] = 0;
496 } else {
497 sps->vui.nal_hrd_parameters_present_flag = 0;
498 sps->vui.low_delay_hrd_flag = 1 - sps->vui.fixed_frame_rate_flag;
499 }
500
501 sps->vui.bitstream_restriction_flag = 1;
502 sps->vui.motion_vectors_over_pic_boundaries_flag = 1;
503 sps->vui.log2_max_mv_length_horizontal = 15;
504 sps->vui.log2_max_mv_length_vertical = 15;
505 sps->vui.max_num_reorder_frames = base_ctx->max_b_depth;
506 sps->vui.max_dec_frame_buffering = base_ctx->max_b_depth + 1;
507
508 pps->nal_unit_header.nal_ref_idc = 3;
509 pps->nal_unit_header.nal_unit_type = H264_NAL_PPS;
510
511 pps->pic_parameter_set_id = 0;
512 pps->seq_parameter_set_id = 0;
513
514 pps->entropy_coding_mode_flag =
515 !(sps->profile_idc == AV_PROFILE_H264_BASELINE ||
516 sps->profile_idc == AV_PROFILE_H264_EXTENDED ||
517 sps->profile_idc == AV_PROFILE_H264_CAVLC_444);
518 if (!priv->coder && pps->entropy_coding_mode_flag)
519 pps->entropy_coding_mode_flag = 0;
520
521 pps->num_ref_idx_l0_default_active_minus1 = 0;
522 pps->num_ref_idx_l1_default_active_minus1 = 0;
523
524 pps->pic_init_qp_minus26 = priv->fixed_qp_idr - 26;
525
526 if (sps->profile_idc == AV_PROFILE_H264_BASELINE ||
527 sps->profile_idc == AV_PROFILE_H264_EXTENDED ||
528 sps->profile_idc == AV_PROFILE_H264_MAIN) {
529 pps->more_rbsp_data = 0;
530 } else {
531 pps->more_rbsp_data = 1;
532
533 pps->transform_8x8_mode_flag = 1;
534 }
535
536 *vseq = (VAEncSequenceParameterBufferH264) {
537 .seq_parameter_set_id = sps->seq_parameter_set_id,
538 .level_idc = sps->level_idc,
539 .intra_period = base_ctx->gop_size,
540 .intra_idr_period = base_ctx->gop_size,
541 .ip_period = base_ctx->b_per_p + 1,
542
543 .bits_per_second = ctx->va_bit_rate,
544 .max_num_ref_frames = sps->max_num_ref_frames,
545 .picture_width_in_mbs = sps->pic_width_in_mbs_minus1 + 1,
546 .picture_height_in_mbs = sps->pic_height_in_map_units_minus1 + 1,
547
548 .seq_fields.bits = {
549 .chroma_format_idc = sps->chroma_format_idc,
550 .frame_mbs_only_flag = sps->frame_mbs_only_flag,
551 .mb_adaptive_frame_field_flag = sps->mb_adaptive_frame_field_flag,
552 .seq_scaling_matrix_present_flag = sps->seq_scaling_matrix_present_flag,
553 .direct_8x8_inference_flag = sps->direct_8x8_inference_flag,
554 .log2_max_frame_num_minus4 = sps->log2_max_frame_num_minus4,
555 .pic_order_cnt_type = sps->pic_order_cnt_type,
556 .log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_pic_order_cnt_lsb_minus4,
557 .delta_pic_order_always_zero_flag = sps->delta_pic_order_always_zero_flag,
558 },
559
560 .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
561 .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
562
563 .frame_cropping_flag = sps->frame_cropping_flag,
564 .frame_crop_left_offset = sps->frame_crop_left_offset,
565 .frame_crop_right_offset = sps->frame_crop_right_offset,
566 .frame_crop_top_offset = sps->frame_crop_top_offset,
567 .frame_crop_bottom_offset = sps->frame_crop_bottom_offset,
568
569 .vui_parameters_present_flag = sps->vui_parameters_present_flag,
570
571 .vui_fields.bits = {
572 .aspect_ratio_info_present_flag = sps->vui.aspect_ratio_info_present_flag,
573 .timing_info_present_flag = sps->vui.timing_info_present_flag,
574 .bitstream_restriction_flag = sps->vui.bitstream_restriction_flag,
575 .log2_max_mv_length_horizontal = sps->vui.log2_max_mv_length_horizontal,
576 .log2_max_mv_length_vertical = sps->vui.log2_max_mv_length_vertical,
577 },
578
579 .aspect_ratio_idc = sps->vui.aspect_ratio_idc,
580 .sar_width = sps->vui.sar_width,
581 .sar_height = sps->vui.sar_height,
582 .num_units_in_tick = sps->vui.num_units_in_tick,
583 .time_scale = sps->vui.time_scale,
584 };
585
586 *vpic = (VAEncPictureParameterBufferH264) {
587 .CurrPic = {
588 .picture_id = VA_INVALID_ID,
589 .flags = VA_PICTURE_H264_INVALID,
590 },
591
592 .coded_buf = VA_INVALID_ID,
593
594 .pic_parameter_set_id = pps->pic_parameter_set_id,
595 .seq_parameter_set_id = pps->seq_parameter_set_id,
596
597 .pic_init_qp = pps->pic_init_qp_minus26 + 26,
598 .num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1,
599 .num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1,
600
601 .chroma_qp_index_offset = pps->chroma_qp_index_offset,
602 .second_chroma_qp_index_offset = pps->second_chroma_qp_index_offset,
603
604 .pic_fields.bits = {
605 .entropy_coding_mode_flag = pps->entropy_coding_mode_flag,
606 .weighted_pred_flag = pps->weighted_pred_flag,
607 .weighted_bipred_idc = pps->weighted_bipred_idc,
608 .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
609 .transform_8x8_mode_flag = pps->transform_8x8_mode_flag,
610 .deblocking_filter_control_present_flag =
611 pps->deblocking_filter_control_present_flag,
612 .redundant_pic_cnt_present_flag = pps->redundant_pic_cnt_present_flag,
613 .pic_order_present_flag =
614 pps->bottom_field_pic_order_in_frame_present_flag,
615 .pic_scaling_matrix_present_flag = pps->pic_scaling_matrix_present_flag,
616 },
617 };
618
619 return 0;
620 }
621
622 static int vaapi_encode_h264_init_picture_params(AVCodecContext *avctx,
623 VAAPIEncodePicture *vaapi_pic)
624 {
625 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
626 VAAPIEncodeH264Context *priv = avctx->priv_data;
627 const FFHWBaseEncodePicture *pic = &vaapi_pic->base;
628 VAAPIEncodeH264Picture *hpic = pic->priv_data;
629 FFHWBaseEncodePicture *prev = pic->prev;
630 VAAPIEncodeH264Picture *hprev = prev ? prev->priv_data : NULL;
631 VAEncPictureParameterBufferH264 *vpic = vaapi_pic->codec_picture_params;
632 int i, j = 0;
633
634 if (pic->type == FF_HW_PICTURE_TYPE_IDR) {
635 av_assert0(pic->display_order == pic->encode_order);
636
637 hpic->frame_num = 0;
638 hpic->last_idr_frame = pic->display_order;
639 hpic->idr_pic_id = hprev ? hprev->idr_pic_id + 1 : 0;
640
641 hpic->primary_pic_type = 0;
642 hpic->slice_type = 7;
643 } else {
644 av_assert0(prev);
645
646 hpic->frame_num = hprev->frame_num + prev->is_reference;
647
648 hpic->last_idr_frame = hprev->last_idr_frame;
649 hpic->idr_pic_id = hprev->idr_pic_id;
650
651 if (pic->type == FF_HW_PICTURE_TYPE_I) {
652 hpic->slice_type = 7;
653 hpic->primary_pic_type = 0;
654 } else if (pic->type == FF_HW_PICTURE_TYPE_P) {
655 hpic->slice_type = 5;
656 hpic->primary_pic_type = 1;
657 } else {
658 hpic->slice_type = 6;
659 hpic->primary_pic_type = 2;
660 }
661 }
662 hpic->pic_order_cnt = pic->display_order - hpic->last_idr_frame;
663 if (priv->raw_sps.pic_order_cnt_type == 2) {
664 hpic->pic_order_cnt *= 2;
665 }
666
667 hpic->dpb_delay = pic->display_order - pic->encode_order + base_ctx->max_b_depth;
668 hpic->cpb_delay = pic->encode_order - hpic->last_idr_frame;
669
670 if (priv->aud) {
671 priv->aud_needed = 1;
672 priv->raw_aud = (H264RawAUD) {
673 .nal_unit_header = {
674 .nal_unit_type = H264_NAL_AUD,
675 },
676 .primary_pic_type = hpic->primary_pic_type,
677 };
678 } else {
679 priv->aud_needed = 0;
680 }
681
682 priv->sei_needed = 0;
683
684 if (priv->sei & SEI_IDENTIFIER && pic->encode_order == 0)
685 priv->sei_needed |= SEI_IDENTIFIER;
686 #if !CONFIG_VAAPI_1
687 if (ctx->va_rc_mode == VA_RC_CBR)
688 priv->sei_cbr_workaround_needed = 1;
689 #endif
690
691 if (priv->sei & SEI_TIMING) {
692 priv->sei_pic_timing = (H264RawSEIPicTiming) {
693 .cpb_removal_delay = 2 * hpic->cpb_delay,
694 .dpb_output_delay = 2 * hpic->dpb_delay,
695 };
696
697 priv->sei_needed |= SEI_TIMING;
698 }
699
700 if (priv->sei & SEI_RECOVERY_POINT && pic->type == FF_HW_PICTURE_TYPE_I) {
701 priv->sei_recovery_point = (H264RawSEIRecoveryPoint) {
702 .recovery_frame_cnt = 0,
703 .exact_match_flag = 1,
704 .broken_link_flag = base_ctx->b_per_p > 0,
705 };
706
707 priv->sei_needed |= SEI_RECOVERY_POINT;
708 }
709
710 if (priv->sei & SEI_A53_CC) {
711 int err;
712 size_t sei_a53cc_len;
713 av_freep(&priv->sei_a53cc_data);
714 err = ff_alloc_a53_sei(pic->input_image, 0, &priv->sei_a53cc_data, &sei_a53cc_len);
715 if (err < 0)
716 return err;
717 if (priv->sei_a53cc_data != NULL) {
718 priv->sei_a53cc.itu_t_t35_country_code = 181;
719 priv->sei_a53cc.data = (uint8_t *)priv->sei_a53cc_data + 1;
720 priv->sei_a53cc.data_length = sei_a53cc_len - 1;
721
722 priv->sei_needed |= SEI_A53_CC;
723 }
724 }
725
726 vpic->CurrPic = (VAPictureH264) {
727 .picture_id = vaapi_pic->recon_surface,
728 .frame_idx = hpic->frame_num,
729 .flags = 0,
730 .TopFieldOrderCnt = hpic->pic_order_cnt,
731 .BottomFieldOrderCnt = hpic->pic_order_cnt,
732 };
733 for (int k = 0; k < MAX_REFERENCE_LIST_NUM; k++) {
734 for (i = 0; i < pic->nb_refs[k]; i++) {
735 FFHWBaseEncodePicture *ref = pic->refs[k][i];
736 VAAPIEncodeH264Picture *href;
737
738 av_assert0(ref && ref->encode_order < pic->encode_order);
739 href = ref->priv_data;
740
741 vpic->ReferenceFrames[j++] = (VAPictureH264) {
742 .picture_id = ((VAAPIEncodePicture *)ref)->recon_surface,
743 .frame_idx = href->frame_num,
744 .flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE,
745 .TopFieldOrderCnt = href->pic_order_cnt,
746 .BottomFieldOrderCnt = href->pic_order_cnt,
747 };
748 }
749 }
750
751 for (; j < FF_ARRAY_ELEMS(vpic->ReferenceFrames); j++) {
752 vpic->ReferenceFrames[j] = (VAPictureH264) {
753 .picture_id = VA_INVALID_ID,
754 .flags = VA_PICTURE_H264_INVALID,
755 };
756 }
757
758 vpic->coded_buf = vaapi_pic->output_buffer;
759
760 vpic->frame_num = hpic->frame_num;
761
762 vpic->pic_fields.bits.idr_pic_flag = (pic->type == FF_HW_PICTURE_TYPE_IDR);
763 vpic->pic_fields.bits.reference_pic_flag = pic->is_reference;
764
765 return 0;
766 }
767
768 static void vaapi_encode_h264_default_ref_pic_list(AVCodecContext *avctx,
769 VAAPIEncodePicture *vaapi_pic,
770 VAAPIEncodePicture **rpl0,
771 VAAPIEncodePicture **rpl1,
772 int *rpl_size)
773 {
774 FFHWBaseEncodePicture *pic = &vaapi_pic->base;
775 FFHWBaseEncodePicture *prev;
776 VAAPIEncodeH264Picture *hp, *hn, *hc;
777 int i, j, n = 0;
778
779 prev = pic->prev;
780 av_assert0(prev);
781 hp = pic->priv_data;
782
783 for (i = 0; i < pic->prev->nb_dpb_pics; i++) {
784 hn = prev->dpb[i]->priv_data;
785 av_assert0(hn->frame_num < hp->frame_num);
786
787 if (pic->type == FF_HW_PICTURE_TYPE_P) {
788 for (j = n; j > 0; j--) {
789 hc = rpl0[j - 1]->base.priv_data;
790 av_assert0(hc->frame_num != hn->frame_num);
791 if (hc->frame_num > hn->frame_num)
792 break;
793 rpl0[j] = rpl0[j - 1];
794 }
795 rpl0[j] = (VAAPIEncodePicture *)prev->dpb[i];
796
797 } else if (pic->type == FF_HW_PICTURE_TYPE_B) {
798 for (j = n; j > 0; j--) {
799 hc = rpl0[j - 1]->base.priv_data;
800 av_assert0(hc->pic_order_cnt != hp->pic_order_cnt);
801 if (hc->pic_order_cnt < hp->pic_order_cnt) {
802 if (hn->pic_order_cnt > hp->pic_order_cnt ||
803 hn->pic_order_cnt < hc->pic_order_cnt)
804 break;
805 } else {
806 if (hn->pic_order_cnt > hc->pic_order_cnt)
807 break;
808 }
809 rpl0[j] = rpl0[j - 1];
810 }
811 rpl0[j] = (VAAPIEncodePicture *)prev->dpb[i];
812
813 for (j = n; j > 0; j--) {
814 hc = rpl1[j - 1]->base.priv_data;
815 av_assert0(hc->pic_order_cnt != hp->pic_order_cnt);
816 if (hc->pic_order_cnt > hp->pic_order_cnt) {
817 if (hn->pic_order_cnt < hp->pic_order_cnt ||
818 hn->pic_order_cnt > hc->pic_order_cnt)
819 break;
820 } else {
821 if (hn->pic_order_cnt < hc->pic_order_cnt)
822 break;
823 }
824 rpl1[j] = rpl1[j - 1];
825 }
826 rpl1[j] = (VAAPIEncodePicture *)prev->dpb[i];
827 }
828
829 ++n;
830 }
831
832 if (pic->type == FF_HW_PICTURE_TYPE_B) {
833 for (i = 0; i < n; i++) {
834 if (rpl0[i] != rpl1[i])
835 break;
836 }
837 if (i == n)
838 FFSWAP(VAAPIEncodePicture*, rpl1[0], rpl1[1]);
839 }
840
841 if (pic->type == FF_HW_PICTURE_TYPE_P ||
842 pic->type == FF_HW_PICTURE_TYPE_B) {
843 av_log(avctx, AV_LOG_DEBUG, "Default RefPicList0 for fn=%d/poc=%d:",
844 hp->frame_num, hp->pic_order_cnt);
845 for (i = 0; i < n; i++) {
846 hn = rpl0[i]->base.priv_data;
847 av_log(avctx, AV_LOG_DEBUG, " fn=%d/poc=%d",
848 hn->frame_num, hn->pic_order_cnt);
849 }
850 av_log(avctx, AV_LOG_DEBUG, "\n");
851 }
852 if (pic->type == FF_HW_PICTURE_TYPE_B) {
853 av_log(avctx, AV_LOG_DEBUG, "Default RefPicList1 for fn=%d/poc=%d:",
854 hp->frame_num, hp->pic_order_cnt);
855 for (i = 0; i < n; i++) {
856 hn = rpl1[i]->base.priv_data;
857 av_log(avctx, AV_LOG_DEBUG, " fn=%d/poc=%d",
858 hn->frame_num, hn->pic_order_cnt);
859 }
860 av_log(avctx, AV_LOG_DEBUG, "\n");
861 }
862
863 *rpl_size = n;
864 }
865
866 static int vaapi_encode_h264_init_slice_params(AVCodecContext *avctx,
867 VAAPIEncodePicture *vaapi_pic,
868 VAAPIEncodeSlice *slice)
869 {
870 VAAPIEncodeH264Context *priv = avctx->priv_data;
871 const FFHWBaseEncodePicture *pic = &vaapi_pic->base;
872 VAAPIEncodeH264Picture *hpic = pic->priv_data;
873 FFHWBaseEncodePicture *prev = pic->prev;
874 H264RawSPS *sps = &priv->raw_sps;
875 H264RawPPS *pps = &priv->raw_pps;
876 H264RawSliceHeader *sh = &priv->raw_slice.header;
877 VAEncPictureParameterBufferH264 *vpic = vaapi_pic->codec_picture_params;
878 VAEncSliceParameterBufferH264 *vslice = slice->codec_slice_params;
879 int i, j;
880
881 if (pic->type == FF_HW_PICTURE_TYPE_IDR) {
882 sh->nal_unit_header.nal_unit_type = H264_NAL_IDR_SLICE;
883 sh->nal_unit_header.nal_ref_idc = 3;
884 } else {
885 sh->nal_unit_header.nal_unit_type = H264_NAL_SLICE;
886 sh->nal_unit_header.nal_ref_idc = pic->is_reference;
887 }
888
889 sh->first_mb_in_slice = slice->block_start;
890 sh->slice_type = hpic->slice_type;
891
892 sh->pic_parameter_set_id = pps->pic_parameter_set_id;
893
894 sh->frame_num = hpic->frame_num &
895 ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
896 sh->idr_pic_id = hpic->idr_pic_id;
897 sh->pic_order_cnt_lsb = hpic->pic_order_cnt &
898 ((1 << (4 + sps->log2_max_pic_order_cnt_lsb_minus4)) - 1);
899
900 sh->direct_spatial_mv_pred_flag = 1;
901
902 if (pic->type == FF_HW_PICTURE_TYPE_B)
903 sh->slice_qp_delta = priv->fixed_qp_b - (pps->pic_init_qp_minus26 + 26);
904 else if (pic->type == FF_HW_PICTURE_TYPE_P)
905 sh->slice_qp_delta = priv->fixed_qp_p - (pps->pic_init_qp_minus26 + 26);
906 else
907 sh->slice_qp_delta = priv->fixed_qp_idr - (pps->pic_init_qp_minus26 + 26);
908
909 if (pic->is_reference && pic->type != FF_HW_PICTURE_TYPE_IDR) {
910 FFHWBaseEncodePicture *discard_list[MAX_DPB_SIZE];
911 int discard = 0, keep = 0;
912
913 // Discard everything which is in the DPB of the previous frame but
914 // not in the DPB of this one.
915 for (i = 0; i < prev->nb_dpb_pics; i++) {
916 for (j = 0; j < pic->nb_dpb_pics; j++) {
917 if (prev->dpb[i] == pic->dpb[j])
918 break;
919 }
920 if (j == pic->nb_dpb_pics) {
921 discard_list[discard] = prev->dpb[i];
922 ++discard;
923 } else {
924 ++keep;
925 }
926 }
927 av_assert0(keep <= priv->dpb_frames);
928
929 if (discard == 0) {
930 sh->adaptive_ref_pic_marking_mode_flag = 0;
931 } else {
932 sh->adaptive_ref_pic_marking_mode_flag = 1;
933 for (i = 0; i < discard; i++) {
934 VAAPIEncodeH264Picture *old = discard_list[i]->priv_data;
935 av_assert0(old->frame_num < hpic->frame_num);
936 sh->mmco[i].memory_management_control_operation = 1;
937 sh->mmco[i].difference_of_pic_nums_minus1 =
938 hpic->frame_num - old->frame_num - 1;
939 }
940 sh->mmco[i].memory_management_control_operation = 0;
941 }
942 }
943
944 // If the intended references are not the first entries of RefPicListN
945 // by default, use ref-pic-list-modification to move them there.
946 if (pic->type == FF_HW_PICTURE_TYPE_P || pic->type == FF_HW_PICTURE_TYPE_B) {
947 VAAPIEncodePicture *def_l0[MAX_DPB_SIZE], *def_l1[MAX_DPB_SIZE];
948 VAAPIEncodeH264Picture *href;
949 int n;
950
951 vaapi_encode_h264_default_ref_pic_list(avctx, vaapi_pic,
952 def_l0, def_l1, &n);
953
954 if (pic->type == FF_HW_PICTURE_TYPE_P) {
955 int need_rplm = 0;
956 for (i = 0; i < pic->nb_refs[0]; i++) {
957 av_assert0(pic->refs[0][i]);
958 if (pic->refs[0][i] != (FFHWBaseEncodePicture *)def_l0[i])
959 need_rplm = 1;
960 }
961
962 sh->ref_pic_list_modification_flag_l0 = need_rplm;
963 if (need_rplm) {
964 int pic_num = hpic->frame_num;
965 for (i = 0; i < pic->nb_refs[0]; i++) {
966 href = pic->refs[0][i]->priv_data;
967 av_assert0(href->frame_num != pic_num);
968 if (href->frame_num < pic_num) {
969 sh->rplm_l0[i].modification_of_pic_nums_idc = 0;
970 sh->rplm_l0[i].abs_diff_pic_num_minus1 =
971 pic_num - href->frame_num - 1;
972 } else {
973 sh->rplm_l0[i].modification_of_pic_nums_idc = 1;
974 sh->rplm_l0[i].abs_diff_pic_num_minus1 =
975 href->frame_num - pic_num - 1;
976 }
977 pic_num = href->frame_num;
978 }
979 sh->rplm_l0[i].modification_of_pic_nums_idc = 3;
980 }
981
982 } else {
983 int need_rplm_l0 = 0, need_rplm_l1 = 0;
984 int n0 = 0, n1 = 0;
985 for (i = 0; i < pic->nb_refs[0]; i++) {
986 av_assert0(pic->refs[0][i]);
987 href = pic->refs[0][i]->priv_data;
988 av_assert0(href->pic_order_cnt < hpic->pic_order_cnt);
989 if (pic->refs[0][i] != (FFHWBaseEncodePicture *)def_l0[n0])
990 need_rplm_l0 = 1;
991 ++n0;
992 }
993
994 for (i = 0; i < pic->nb_refs[1]; i++) {
995 av_assert0(pic->refs[1][i]);
996 href = pic->refs[1][i]->priv_data;
997 av_assert0(href->pic_order_cnt > hpic->pic_order_cnt);
998 if (pic->refs[1][i] != (FFHWBaseEncodePicture *)def_l1[n1])
999 need_rplm_l1 = 1;
1000 ++n1;
1001 }
1002
1003 sh->ref_pic_list_modification_flag_l0 = need_rplm_l0;
1004 if (need_rplm_l0) {
1005 int pic_num = hpic->frame_num;
1006 for (i = j = 0; i < pic->nb_refs[0]; i++) {
1007 href = pic->refs[0][i]->priv_data;
1008 av_assert0(href->frame_num != pic_num);
1009 if (href->frame_num < pic_num) {
1010 sh->rplm_l0[j].modification_of_pic_nums_idc = 0;
1011 sh->rplm_l0[j].abs_diff_pic_num_minus1 =
1012 pic_num - href->frame_num - 1;
1013 } else {
1014 sh->rplm_l0[j].modification_of_pic_nums_idc = 1;
1015 sh->rplm_l0[j].abs_diff_pic_num_minus1 =
1016 href->frame_num - pic_num - 1;
1017 }
1018 pic_num = href->frame_num;
1019 ++j;
1020 }
1021 av_assert0(j == n0);
1022 sh->rplm_l0[j].modification_of_pic_nums_idc = 3;
1023 }
1024
1025 sh->ref_pic_list_modification_flag_l1 = need_rplm_l1;
1026 if (need_rplm_l1) {
1027 int pic_num = hpic->frame_num;
1028 for (i = j = 0; i < pic->nb_refs[1]; i++) {
1029 href = pic->refs[1][i]->priv_data;
1030 av_assert0(href->frame_num != pic_num);
1031 if (href->frame_num < pic_num) {
1032 sh->rplm_l1[j].modification_of_pic_nums_idc = 0;
1033 sh->rplm_l1[j].abs_diff_pic_num_minus1 =
1034 pic_num - href->frame_num - 1;
1035 } else {
1036 sh->rplm_l1[j].modification_of_pic_nums_idc = 1;
1037 sh->rplm_l1[j].abs_diff_pic_num_minus1 =
1038 href->frame_num - pic_num - 1;
1039 }
1040 pic_num = href->frame_num;
1041 ++j;
1042 }
1043 av_assert0(j == n1);
1044 sh->rplm_l1[j].modification_of_pic_nums_idc = 3;
1045 }
1046 }
1047 }
1048
1049 vslice->macroblock_address = slice->block_start;
1050 vslice->num_macroblocks = slice->block_size;
1051
1052 vslice->macroblock_info = VA_INVALID_ID;
1053
1054 vslice->slice_type = sh->slice_type % 5;
1055 vslice->pic_parameter_set_id = sh->pic_parameter_set_id;
1056 vslice->idr_pic_id = sh->idr_pic_id;
1057
1058 vslice->pic_order_cnt_lsb = sh->pic_order_cnt_lsb;
1059
1060 vslice->direct_spatial_mv_pred_flag = sh->direct_spatial_mv_pred_flag;
1061
1062 for (i = 0; i < FF_ARRAY_ELEMS(vslice->RefPicList0); i++) {
1063 vslice->RefPicList0[i].picture_id = VA_INVALID_ID;
1064 vslice->RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
1065 vslice->RefPicList1[i].picture_id = VA_INVALID_ID;
1066 vslice->RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
1067 }
1068
1069 if (pic->nb_refs[0]) {
1070 // Backward reference for P- or B-frame.
1071 av_assert0(pic->type == FF_HW_PICTURE_TYPE_P ||
1072 pic->type == FF_HW_PICTURE_TYPE_B);
1073 vslice->RefPicList0[0] = vpic->ReferenceFrames[0];
1074 }
1075 if (pic->nb_refs[1]) {
1076 // Forward reference for B-frame.
1077 av_assert0(pic->type == FF_HW_PICTURE_TYPE_B);
1078 vslice->RefPicList1[0] = vpic->ReferenceFrames[1];
1079 }
1080
1081 vslice->slice_qp_delta = sh->slice_qp_delta;
1082
1083 return 0;
1084 }
1085
1086 static av_cold int vaapi_encode_h264_configure(AVCodecContext *avctx)
1087 {
1088 VAAPIEncodeContext *ctx = avctx->priv_data;
1089 VAAPIEncodeH264Context *priv = avctx->priv_data;
1090 int err;
1091
1092 err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_H264, avctx);
1093 if (err < 0)
1094 return err;
1095
1096 priv->mb_width = FFALIGN(avctx->width, 16) / 16;
1097 priv->mb_height = FFALIGN(avctx->height, 16) / 16;
1098
1099 if (ctx->va_rc_mode == VA_RC_CQP) {
1100 priv->fixed_qp_p = av_clip(ctx->rc_quality, 1, 51);
1101 if (avctx->i_quant_factor > 0.0)
1102 priv->fixed_qp_idr =
1103 av_clip((avctx->i_quant_factor * priv->fixed_qp_p +
1104 avctx->i_quant_offset) + 0.5, 1, 51);
1105 else
1106 priv->fixed_qp_idr = priv->fixed_qp_p;
1107 if (avctx->b_quant_factor > 0.0)
1108 priv->fixed_qp_b =
1109 av_clip((avctx->b_quant_factor * priv->fixed_qp_p +
1110 avctx->b_quant_offset) + 0.5, 1, 51);
1111 else
1112 priv->fixed_qp_b = priv->fixed_qp_p;
1113
1114 av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
1115 "%d / %d / %d for IDR- / P- / B-frames.\n",
1116 priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
1117
1118 } else {
1119 // These still need to be set for pic_init_qp/slice_qp_delta.
1120 priv->fixed_qp_idr = 26;
1121 priv->fixed_qp_p = 26;
1122 priv->fixed_qp_b = 26;
1123 }
1124
1125 if (!ctx->rc_mode->hrd) {
1126 // Timing SEI requires a mode respecting HRD parameters.
1127 priv->sei &= ~SEI_TIMING;
1128 }
1129
1130 if (priv->sei & SEI_IDENTIFIER) {
1131 const char *lavc = LIBAVCODEC_IDENT;
1132 const char *vaapi = VA_VERSION_S;
1133 const char *driver;
1134 int len;
1135
1136 memcpy(priv->sei_identifier.uuid_iso_iec_11578,
1137 vaapi_encode_h264_sei_identifier_uuid,
1138 sizeof(priv->sei_identifier.uuid_iso_iec_11578));
1139
1140 driver = vaQueryVendorString(ctx->hwctx->display);
1141 if (!driver)
1142 driver = "unknown driver";
1143
1144 len = snprintf(NULL, 0, "%s / VAAPI %s / %s", lavc, vaapi, driver);
1145 if (len >= 0) {
1146 priv->sei_identifier_string = av_malloc(len + 1);
1147 if (!priv->sei_identifier_string)
1148 return AVERROR(ENOMEM);
1149
1150 snprintf(priv->sei_identifier_string, len + 1,
1151 "%s / VAAPI %s / %s", lavc, vaapi, driver);
1152
1153 priv->sei_identifier.data = priv->sei_identifier_string;
1154 priv->sei_identifier.data_length = len + 1;
1155 }
1156 }
1157
1158 ctx->roi_quant_range = 51 + 6 * (ctx->profile->depth - 8);
1159
1160 return 0;
1161 }
1162
1163 static const VAAPIEncodeProfile vaapi_encode_h264_profiles[] = {
1164 #if VA_CHECK_VERSION(1, 18, 0)
1165 { AV_PROFILE_H264_HIGH_10, 10, 3, 1, 1, VAProfileH264High10 },
1166 #endif
1167 { AV_PROFILE_H264_HIGH, 8, 3, 1, 1, VAProfileH264High },
1168 { AV_PROFILE_H264_MAIN, 8, 3, 1, 1, VAProfileH264Main },
1169 { AV_PROFILE_H264_CONSTRAINED_BASELINE,
1170 8, 3, 1, 1, VAProfileH264ConstrainedBaseline },
1171 { AV_PROFILE_UNKNOWN }
1172 };
1173
1174 static const VAAPIEncodeType vaapi_encode_type_h264 = {
1175 .profiles = vaapi_encode_h264_profiles,
1176
1177 .flags = FF_HW_FLAG_SLICE_CONTROL |
1178 FF_HW_FLAG_B_PICTURES |
1179 FF_HW_FLAG_B_PICTURE_REFERENCES |
1180 FF_HW_FLAG_NON_IDR_KEY_PICTURES,
1181
1182 .default_quality = 20,
1183
1184 .configure = &vaapi_encode_h264_configure,
1185
1186 .picture_priv_data_size = sizeof(VAAPIEncodeH264Picture),
1187
1188 .sequence_params_size = sizeof(VAEncSequenceParameterBufferH264),
1189 .init_sequence_params = &vaapi_encode_h264_init_sequence_params,
1190
1191 .picture_params_size = sizeof(VAEncPictureParameterBufferH264),
1192 .init_picture_params = &vaapi_encode_h264_init_picture_params,
1193
1194 .slice_params_size = sizeof(VAEncSliceParameterBufferH264),
1195 .init_slice_params = &vaapi_encode_h264_init_slice_params,
1196
1197 .sequence_header_type = VAEncPackedHeaderSequence,
1198 .write_sequence_header = &vaapi_encode_h264_write_sequence_header,
1199
1200 .slice_header_type = VAEncPackedHeaderH264_Slice,
1201 .write_slice_header = &vaapi_encode_h264_write_slice_header,
1202
1203 .write_extra_header = &vaapi_encode_h264_write_extra_header,
1204 };
1205
1206 static av_cold int vaapi_encode_h264_init(AVCodecContext *avctx)
1207 {
1208 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
1209 VAAPIEncodeContext *ctx = avctx->priv_data;
1210 VAAPIEncodeH264Context *priv = avctx->priv_data;
1211
1212 ctx->codec = &vaapi_encode_type_h264;
1213
1214 if (avctx->profile == AV_PROFILE_UNKNOWN)
1215 avctx->profile = priv->profile;
1216 if (avctx->level == AV_LEVEL_UNKNOWN)
1217 avctx->level = priv->level;
1218 if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
1219 avctx->compression_level = priv->quality;
1220
1221 // Reject unsupported profiles.
1222 switch (avctx->profile) {
1223 case AV_PROFILE_H264_BASELINE:
1224 av_log(avctx, AV_LOG_WARNING, "H.264 baseline profile is not "
1225 "supported, using constrained baseline profile instead.\n");
1226 avctx->profile = AV_PROFILE_H264_CONSTRAINED_BASELINE;
1227 break;
1228 case AV_PROFILE_H264_EXTENDED:
1229 av_log(avctx, AV_LOG_ERROR, "H.264 extended profile "
1230 "is not supported.\n");
1231 return AVERROR_PATCHWELCOME;
1232 case AV_PROFILE_H264_HIGH_10_INTRA:
1233 av_log(avctx, AV_LOG_ERROR, "H.264 high 10 intra profile "
1234 "is not supported.\n");
1235 return AVERROR_PATCHWELCOME;
1236 case AV_PROFILE_H264_HIGH_422:
1237 case AV_PROFILE_H264_HIGH_422_INTRA:
1238 case AV_PROFILE_H264_HIGH_444:
1239 case AV_PROFILE_H264_HIGH_444_PREDICTIVE:
1240 case AV_PROFILE_H264_HIGH_444_INTRA:
1241 case AV_PROFILE_H264_CAVLC_444:
1242 av_log(avctx, AV_LOG_ERROR, "H.264 non-4:2:0 profiles "
1243 "are not supported.\n");
1244 return AVERROR_PATCHWELCOME;
1245 }
1246
1247 if (avctx->level != AV_LEVEL_UNKNOWN && avctx->level & ~0xff) {
1248 av_log(avctx, AV_LOG_ERROR, "Invalid level %d: must fit "
1249 "in 8-bit unsigned integer.\n", avctx->level);
1250 return AVERROR(EINVAL);
1251 }
1252
1253 ctx->desired_packed_headers =
1254 VA_ENC_PACKED_HEADER_SEQUENCE | // SPS and PPS.
1255 VA_ENC_PACKED_HEADER_SLICE | // Slice headers.
1256 VA_ENC_PACKED_HEADER_MISC; // SEI.
1257
1258 base_ctx->surface_width = FFALIGN(avctx->width, 16);
1259 base_ctx->surface_height = FFALIGN(avctx->height, 16);
1260
1261 base_ctx->slice_block_height = base_ctx->slice_block_width = 16;
1262
1263 if (priv->qp > 0)
1264 ctx->explicit_qp = priv->qp;
1265
1266 return ff_vaapi_encode_init(avctx);
1267 }
1268
1269 static av_cold int vaapi_encode_h264_close(AVCodecContext *avctx)
1270 {
1271 VAAPIEncodeH264Context *priv = avctx->priv_data;
1272
1273 ff_cbs_fragment_free(&priv->current_access_unit);
1274 ff_cbs_close(&priv->cbc);
1275 av_freep(&priv->sei_identifier_string);
1276 av_freep(&priv->sei_a53cc_data);
1277
1278 return ff_vaapi_encode_close(avctx);
1279 }
1280
1281 #define OFFSET(x) offsetof(VAAPIEncodeH264Context, x)
1282 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
1283 static const AVOption vaapi_encode_h264_options[] = {
1284 HW_BASE_ENCODE_COMMON_OPTIONS,
1285 VAAPI_ENCODE_COMMON_OPTIONS,
1286 VAAPI_ENCODE_RC_OPTIONS,
1287
1288 { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
1289 OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 52, FLAGS },
1290 { "quality", "Set encode quality (trades off against speed, higher is faster)",
1291 OFFSET(quality), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS },
1292 { "coder", "Entropy coder type",
1293 OFFSET(coder), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS, .unit = "coder" },
1294 { "cavlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, .unit = "coder" },
1295 { "cabac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, .unit = "coder" },
1296 { "vlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, .unit = "coder" },
1297 { "ac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, .unit = "coder" },
1298
1299 { "aud", "Include AUD",
1300 OFFSET(aud), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
1301
1302 { "sei", "Set SEI to include",
1303 OFFSET(sei), AV_OPT_TYPE_FLAGS,
1304 { .i64 = SEI_IDENTIFIER | SEI_TIMING | SEI_RECOVERY_POINT | SEI_A53_CC },
1305 0, INT_MAX, FLAGS, .unit = "sei" },
1306 { "identifier", "Include encoder version identifier",
1307 0, AV_OPT_TYPE_CONST, { .i64 = SEI_IDENTIFIER },
1308 INT_MIN, INT_MAX, FLAGS, .unit = "sei" },
1309 { "timing", "Include timing parameters (buffering_period and pic_timing)",
1310 0, AV_OPT_TYPE_CONST, { .i64 = SEI_TIMING },
1311 INT_MIN, INT_MAX, FLAGS, .unit = "sei" },
1312 { "recovery_point", "Include recovery points where appropriate",
1313 0, AV_OPT_TYPE_CONST, { .i64 = SEI_RECOVERY_POINT },
1314 INT_MIN, INT_MAX, FLAGS, .unit = "sei" },
1315 { "a53_cc", "Include A/53 caption data",
1316 0, AV_OPT_TYPE_CONST, { .i64 = SEI_A53_CC },
1317 INT_MIN, INT_MAX, FLAGS, .unit = "sei" },
1318
1319 { "profile", "Set profile (profile_idc and constraint_set*_flag)",
1320 OFFSET(profile), AV_OPT_TYPE_INT,
1321 { .i64 = AV_PROFILE_UNKNOWN }, AV_PROFILE_UNKNOWN, 0xffff, FLAGS, .unit = "profile" },
1322
1323 #define PROFILE(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1324 { .i64 = value }, 0, 0, FLAGS, .unit = "profile"
1325 { PROFILE("constrained_baseline", AV_PROFILE_H264_CONSTRAINED_BASELINE) },
1326 { PROFILE("main", AV_PROFILE_H264_MAIN) },
1327 { PROFILE("high", AV_PROFILE_H264_HIGH) },
1328 { PROFILE("high10", AV_PROFILE_H264_HIGH_10) },
1329 #undef PROFILE
1330
1331 { "level", "Set level (level_idc)",
1332 OFFSET(level), AV_OPT_TYPE_INT,
1333 { .i64 = AV_LEVEL_UNKNOWN }, AV_LEVEL_UNKNOWN, 0xff, FLAGS, .unit = "level" },
1334
1335 #define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
1336 { .i64 = value }, 0, 0, FLAGS, .unit = "level"
1337 { LEVEL("1", 10) },
1338 { LEVEL("1.1", 11) },
1339 { LEVEL("1.2", 12) },
1340 { LEVEL("1.3", 13) },
1341 { LEVEL("2", 20) },
1342 { LEVEL("2.1", 21) },
1343 { LEVEL("2.2", 22) },
1344 { LEVEL("3", 30) },
1345 { LEVEL("3.1", 31) },
1346 { LEVEL("3.2", 32) },
1347 { LEVEL("4", 40) },
1348 { LEVEL("4.1", 41) },
1349 { LEVEL("4.2", 42) },
1350 { LEVEL("5", 50) },
1351 { LEVEL("5.1", 51) },
1352 { LEVEL("5.2", 52) },
1353 { LEVEL("6", 60) },
1354 { LEVEL("6.1", 61) },
1355 { LEVEL("6.2", 62) },
1356 #undef LEVEL
1357
1358 { NULL },
1359 };
1360
1361 static const FFCodecDefault vaapi_encode_h264_defaults[] = {
1362 { "b", "0" },
1363 { "bf", "2" },
1364 { "g", "120" },
1365 { "i_qfactor", "1" },
1366 { "i_qoffset", "0" },
1367 { "b_qfactor", "6/5" },
1368 { "b_qoffset", "0" },
1369 { "qmin", "-1" },
1370 { "qmax", "-1" },
1371 { NULL },
1372 };
1373
1374 static const AVClass vaapi_encode_h264_class = {
1375 .class_name = "h264_vaapi",
1376 .item_name = av_default_item_name,
1377 .option = vaapi_encode_h264_options,
1378 .version = LIBAVUTIL_VERSION_INT,
1379 };
1380
1381 const FFCodec ff_h264_vaapi_encoder = {
1382 .p.name = "h264_vaapi",
1383 CODEC_LONG_NAME("H.264/AVC (VAAPI)"),
1384 .p.type = AVMEDIA_TYPE_VIDEO,
1385 .p.id = AV_CODEC_ID_H264,
1386 .priv_data_size = sizeof(VAAPIEncodeH264Context),
1387 .init = &vaapi_encode_h264_init,
1388 FF_CODEC_RECEIVE_PACKET_CB(&ff_vaapi_encode_receive_packet),
1389 .close = &vaapi_encode_h264_close,
1390 .p.priv_class = &vaapi_encode_h264_class,
1391 .p.capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE |
1392 AV_CODEC_CAP_DR1 | AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE,
1393 .caps_internal = FF_CODEC_CAP_NOT_INIT_THREADSAFE |
1394 FF_CODEC_CAP_INIT_CLEANUP,
1395 .defaults = vaapi_encode_h264_defaults,
1396 .p.pix_fmts = (const enum AVPixelFormat[]) {
1397 AV_PIX_FMT_VAAPI,
1398 AV_PIX_FMT_NONE,
1399 },
1400 .hw_configs = ff_vaapi_encode_hw_configs,
1401 .p.wrapper_name = "vaapi",
1402 };
1403