vaapi_h265: Add support for AUD NAL units
[libav.git] / libavcodec / vaapi_encode_h265.c
CommitLineData
31fe1f25
MT
1/*
2 * This file is part of Libav.
3 *
4 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18
ac124867
MT
19#include <string.h>
20
31fe1f25
MT
21#include <va/va.h>
22#include <va/va_enc_hevc.h>
23
24#include "libavutil/avassert.h"
ac124867 25#include "libavutil/common.h"
31fe1f25 26#include "libavutil/opt.h"
31fe1f25
MT
27
28#include "avcodec.h"
ac124867
MT
29#include "cbs.h"
30#include "cbs_h265.h"
0bfdcce4 31#include "hevc.h"
31fe1f25
MT
32#include "internal.h"
33#include "put_bits.h"
34#include "vaapi_encode.h"
31fe1f25 35
31fe1f25 36
ac124867 37typedef struct VAAPIEncodeH265Context {
31fe1f25
MT
38 unsigned int ctu_width;
39 unsigned int ctu_height;
40
41 int fixed_qp_idr;
42 int fixed_qp_p;
43 int fixed_qp_b;
44
e3e8eab3 45 H265RawAUD aud;
ac124867
MT
46 H265RawVPS vps;
47 H265RawSPS sps;
48 H265RawPPS pps;
49 H265RawSlice slice;
50
31fe1f25 51 int64_t last_idr_frame;
ac124867 52 int pic_order_cnt;
f70e4627 53
ac124867
MT
54 int slice_nal_unit;
55 int slice_type;
e3e8eab3 56 int pic_type;
ac124867
MT
57
58 CodedBitstreamContext cbc;
59 CodedBitstreamFragment current_access_unit;
e3e8eab3 60 int aud_needed;
31fe1f25
MT
61} VAAPIEncodeH265Context;
62
92fdea37
MT
63typedef struct VAAPIEncodeH265Options {
64 int qp;
e3e8eab3 65 int aud;
92fdea37
MT
66} VAAPIEncodeH265Options;
67
31fe1f25 68
ac124867
MT
69static int vaapi_encode_h265_write_access_unit(AVCodecContext *avctx,
70 char *data, size_t *data_len,
71 CodedBitstreamFragment *au)
31fe1f25 72{
ac124867
MT
73 VAAPIEncodeContext *ctx = avctx->priv_data;
74 VAAPIEncodeH265Context *priv = ctx->priv_data;
75 int err;
31fe1f25 76
ac124867
MT
77 err = ff_cbs_write_fragment_data(&priv->cbc, au);
78 if (err < 0) {
79 av_log(avctx, AV_LOG_ERROR, "Failed to write packed header.\n");
80 return err;
31fe1f25
MT
81 }
82
ac124867
MT
83 if (*data_len < 8 * au->data_size - au->data_bit_padding) {
84 av_log(avctx, AV_LOG_ERROR, "Access unit too large: "
85 "%zu < %zu.\n", *data_len,
86 8 * au->data_size - au->data_bit_padding);
87 return AVERROR(ENOSPC);
31fe1f25
MT
88 }
89
ac124867
MT
90 memcpy(data, au->data, au->data_size);
91 *data_len = 8 * au->data_size - au->data_bit_padding;
31fe1f25 92
ac124867 93 return 0;
31fe1f25
MT
94}
95
ac124867
MT
96static int vaapi_encode_h265_add_nal(AVCodecContext *avctx,
97 CodedBitstreamFragment *au,
98 void *nal_unit)
31fe1f25 99{
ac124867
MT
100 VAAPIEncodeContext *ctx = avctx->priv_data;
101 VAAPIEncodeH265Context *priv = ctx->priv_data;
102 H265RawNALUnitHeader *header = nal_unit;
103 int err;
31fe1f25 104
ac124867
MT
105 err = ff_cbs_insert_unit_content(&priv->cbc, au, -1,
106 header->nal_unit_type, nal_unit);
107 if (err < 0) {
108 av_log(avctx, AV_LOG_ERROR, "Failed to add NAL unit: "
109 "type = %d.\n", header->nal_unit_type);
110 return err;
31fe1f25
MT
111 }
112
ac124867 113 return 0;
31fe1f25
MT
114}
115
116static int vaapi_encode_h265_write_sequence_header(AVCodecContext *avctx,
117 char *data, size_t *data_len)
118{
ac124867
MT
119 VAAPIEncodeContext *ctx = avctx->priv_data;
120 VAAPIEncodeH265Context *priv = ctx->priv_data;
121 CodedBitstreamFragment *au = &priv->current_access_unit;
31fe1f25 122 int err;
31fe1f25 123
e3e8eab3
MT
124 if (priv->aud_needed) {
125 err = vaapi_encode_h265_add_nal(avctx, au, &priv->aud);
126 if (err < 0)
127 goto fail;
128 priv->aud_needed = 0;
129 }
130
ac124867 131 err = vaapi_encode_h265_add_nal(avctx, au, &priv->vps);
31fe1f25 132 if (err < 0)
ac124867 133 goto fail;
31fe1f25 134
ac124867 135 err = vaapi_encode_h265_add_nal(avctx, au, &priv->sps);
31fe1f25 136 if (err < 0)
ac124867 137 goto fail;
31fe1f25 138
ac124867 139 err = vaapi_encode_h265_add_nal(avctx, au, &priv->pps);
31fe1f25 140 if (err < 0)
ac124867 141 goto fail;
31fe1f25 142
ac124867
MT
143 err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
144fail:
145 ff_cbs_fragment_uninit(&priv->cbc, au);
146 return err;
31fe1f25
MT
147}
148
149static int vaapi_encode_h265_write_slice_header(AVCodecContext *avctx,
150 VAAPIEncodePicture *pic,
151 VAAPIEncodeSlice *slice,
152 char *data, size_t *data_len)
153{
ac124867
MT
154 VAAPIEncodeContext *ctx = avctx->priv_data;
155 VAAPIEncodeH265Context *priv = ctx->priv_data;
156 CodedBitstreamFragment *au = &priv->current_access_unit;
157 int err;
31fe1f25 158
e3e8eab3
MT
159 if (priv->aud_needed) {
160 err = vaapi_encode_h265_add_nal(avctx, au, &priv->aud);
161 if (err < 0)
162 goto fail;
163 priv->aud_needed = 0;
164 }
165
ac124867
MT
166 err = vaapi_encode_h265_add_nal(avctx, au, &priv->slice);
167 if (err < 0)
168 goto fail;
31fe1f25 169
ac124867
MT
170 err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
171fail:
172 ff_cbs_fragment_uninit(&priv->cbc, au);
173 return err;
31fe1f25
MT
174}
175
176static int vaapi_encode_h265_init_sequence_params(AVCodecContext *avctx)
177{
ac124867
MT
178 VAAPIEncodeContext *ctx = avctx->priv_data;
179 VAAPIEncodeH265Context *priv = ctx->priv_data;
180 H265RawVPS *vps = &priv->vps;
181 H265RawSPS *sps = &priv->sps;
182 H265RawPPS *pps = &priv->pps;
183 H265RawVUI *vui = &sps->vui;
184 VAEncSequenceParameterBufferHEVC *vseq = ctx->codec_sequence_params;
185 VAEncPictureParameterBufferHEVC *vpic = ctx->codec_picture_params;
31fe1f25
MT
186 int i;
187
ac124867
MT
188 memset(&priv->current_access_unit, 0,
189 sizeof(priv->current_access_unit));
f70e4627 190
ac124867
MT
191 memset(vps, 0, sizeof(*vps));
192 memset(sps, 0, sizeof(*sps));
193 memset(pps, 0, sizeof(*pps));
31fe1f25 194
31fe1f25 195
ac124867 196 // VPS
31fe1f25 197
ac124867
MT
198 vps->nal_unit_header = (H265RawNALUnitHeader) {
199 .nal_unit_type = HEVC_NAL_VPS,
200 .nuh_layer_id = 0,
201 .nuh_temporal_id_plus1 = 1,
202 };
31fe1f25 203
ac124867 204 vps->vps_video_parameter_set_id = 0;
31fe1f25 205
ac124867
MT
206 vps->vps_base_layer_internal_flag = 1;
207 vps->vps_base_layer_available_flag = 1;
208 vps->vps_max_layers_minus1 = 0;
209 vps->vps_max_sub_layers_minus1 = 0;
210 vps->vps_temporal_id_nesting_flag = 1;
31fe1f25 211
ac124867
MT
212 vps->profile_tier_level = (H265RawProfileTierLevel) {
213 .general_profile_space = 0,
214 .general_profile_idc = avctx->profile,
215 .general_tier_flag = 0,
31fe1f25 216
ac124867
MT
217 .general_progressive_source_flag = 1,
218 .general_interlaced_source_flag = 0,
219 .general_non_packed_constraint_flag = 1,
220 .general_frame_only_constraint_flag = 1,
31fe1f25 221
ac124867
MT
222 .general_level_idc = avctx->level,
223 };
224 vps->profile_tier_level.general_profile_compatibility_flag[avctx->profile & 31] = 1;
31fe1f25 225
ac124867
MT
226 vps->vps_sub_layer_ordering_info_present_flag = 0;
227 vps->vps_max_dec_pic_buffering_minus1[0] = (ctx->b_per_p > 0) + 1;
228 vps->vps_max_num_reorder_pics[0] = (ctx->b_per_p > 0);
229 vps->vps_max_latency_increase_plus1[0] = 0;
31fe1f25 230
ac124867
MT
231 vps->vps_max_layer_id = 0;
232 vps->vps_num_layer_sets_minus1 = 0;
233 vps->layer_id_included_flag[0][0] = 1;
31fe1f25 234
ac124867
MT
235 vps->vps_timing_info_present_flag = 1;
236 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
237 vps->vps_num_units_in_tick = avctx->framerate.den;
238 vps->vps_time_scale = avctx->framerate.num;
239 vps->vps_poc_proportional_to_timing_flag = 1;
240 vps->vps_num_ticks_poc_diff_one_minus1 = 0;
241 } else {
242 vps->vps_num_units_in_tick = avctx->time_base.num;
243 vps->vps_time_scale = avctx->time_base.den;
244 vps->vps_poc_proportional_to_timing_flag = 0;
245 }
246 vps->vps_num_hrd_parameters = 0;
31fe1f25 247
2940e196 248
ac124867 249 // SPS
31fe1f25 250
ac124867
MT
251 sps->nal_unit_header = (H265RawNALUnitHeader) {
252 .nal_unit_type = HEVC_NAL_SPS,
253 .nuh_layer_id = 0,
254 .nuh_temporal_id_plus1 = 1,
255 };
31fe1f25 256
ac124867 257 sps->sps_video_parameter_set_id = vps->vps_video_parameter_set_id;
31fe1f25 258
ac124867
MT
259 sps->sps_max_sub_layers_minus1 = vps->vps_max_sub_layers_minus1;
260 sps->sps_temporal_id_nesting_flag = vps->vps_temporal_id_nesting_flag;
31fe1f25 261
ac124867 262 sps->profile_tier_level = vps->profile_tier_level;
31fe1f25 263
ac124867 264 sps->sps_seq_parameter_set_id = 0;
31fe1f25 265
ac124867
MT
266 sps->chroma_format_idc = 1; // YUV 4:2:0.
267 sps->separate_colour_plane_flag = 0;
268
269 sps->pic_width_in_luma_samples = ctx->surface_width;
270 sps->pic_height_in_luma_samples = ctx->surface_height;
271
272 if (avctx->width != ctx->surface_width ||
273 avctx->height != ctx->surface_height) {
274 sps->conformance_window_flag = 1;
275 sps->conf_win_left_offset = 0;
276 sps->conf_win_right_offset =
277 (ctx->surface_width - avctx->width) / 2;
278 sps->conf_win_top_offset = 0;
279 sps->conf_win_bottom_offset =
280 (ctx->surface_height - avctx->height) / 2;
281 } else {
282 sps->conformance_window_flag = 0;
283 }
284
285 sps->bit_depth_luma_minus8 =
286 avctx->profile == FF_PROFILE_HEVC_MAIN_10 ? 2 : 0;
287 sps->bit_depth_chroma_minus8 = sps->bit_depth_luma_minus8;
288
289 sps->log2_max_pic_order_cnt_lsb_minus4 = 8;
290
291 sps->sps_sub_layer_ordering_info_present_flag =
292 vps->vps_sub_layer_ordering_info_present_flag;
293 for (i = 0; i <= sps->sps_max_sub_layers_minus1; i++) {
294 sps->sps_max_dec_pic_buffering_minus1[i] =
295 vps->vps_max_dec_pic_buffering_minus1[i];
296 sps->sps_max_num_reorder_pics[i] =
297 vps->vps_max_num_reorder_pics[i];
298 sps->sps_max_latency_increase_plus1[i] =
299 vps->vps_max_latency_increase_plus1[i];
300 }
301
302 // These have to come from the capabilities of the encoder. We have no
303 // way to query them, so just hardcode parameters which work on the Intel
304 // driver.
305 // CTB size from 8x8 to 32x32.
306 sps->log2_min_luma_coding_block_size_minus3 = 0;
307 sps->log2_diff_max_min_luma_coding_block_size = 2;
308 // Transform size from 4x4 to 32x32.
309 sps->log2_min_luma_transform_block_size_minus2 = 0;
310 sps->log2_diff_max_min_luma_transform_block_size = 3;
311 // Full transform hierarchy allowed (2-5).
312 sps->max_transform_hierarchy_depth_inter = 3;
313 sps->max_transform_hierarchy_depth_intra = 3;
314 // AMP works.
315 sps->amp_enabled_flag = 1;
316 // SAO and temporal MVP do not work.
317 sps->sample_adaptive_offset_enabled_flag = 0;
318 sps->sps_temporal_mvp_enabled_flag = 0;
319
320 sps->pcm_enabled_flag = 0;
321
322 // STRPSs should ideally be here rather than defined individually in
323 // each slice, but the structure isn't completely fixed so for now
324 // don't bother.
325 sps->num_short_term_ref_pic_sets = 0;
326 sps->long_term_ref_pics_present_flag = 0;
327
328 sps->vui_parameters_present_flag = 1;
329
330 if (avctx->sample_aspect_ratio.num != 0 &&
331 avctx->sample_aspect_ratio.den != 0) {
332 static const AVRational sar_idc[] = {
333 { 0, 0 },
334 { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 },
335 { 40, 33 }, { 24, 11 }, { 20, 11 }, { 32, 11 },
336 { 80, 33 }, { 18, 11 }, { 15, 11 }, { 64, 33 },
337 { 160, 99 }, { 4, 3 }, { 3, 2 }, { 2, 1 },
338 };
339 int i;
340 for (i = 0; i < FF_ARRAY_ELEMS(sar_idc); i++) {
341 if (avctx->sample_aspect_ratio.num == sar_idc[i].num &&
342 avctx->sample_aspect_ratio.den == sar_idc[i].den) {
343 vui->aspect_ratio_idc = i;
344 break;
31fe1f25
MT
345 }
346 }
ac124867
MT
347 if (i >= FF_ARRAY_ELEMS(sar_idc)) {
348 vui->aspect_ratio_idc = 255;
349 vui->sar_width = avctx->sample_aspect_ratio.num;
350 vui->sar_height = avctx->sample_aspect_ratio.den;
351 }
352 vui->aspect_ratio_info_present_flag = 1;
353 }
354
355 if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED ||
356 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
357 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
358 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
359 vui->video_signal_type_present_flag = 1;
360 vui->video_format = 5; // Unspecified.
361 vui->video_full_range_flag =
362 avctx->color_range == AVCOL_RANGE_JPEG;
363
364 if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
365 avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
366 avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
367 vui->colour_description_present_flag = 1;
368 vui->colour_primaries = avctx->color_primaries;
369 vui->transfer_characteristics = avctx->color_trc;
370 vui->matrix_coefficients = avctx->colorspace;
31fe1f25 371 }
ac124867
MT
372 } else {
373 vui->video_format = 5;
374 vui->video_full_range_flag = 0;
375 vui->colour_primaries = avctx->color_primaries;
376 vui->transfer_characteristics = avctx->color_trc;
377 vui->matrix_coefficients = avctx->colorspace;
378 }
379
380 if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
381 vui->chroma_loc_info_present_flag = 1;
382 vui->chroma_sample_loc_type_top_field =
383 vui->chroma_sample_loc_type_bottom_field =
384 avctx->chroma_sample_location - 1;
31fe1f25
MT
385 }
386
ac124867
MT
387 vui->vui_timing_info_present_flag = 1;
388 vui->vui_num_units_in_tick = vps->vps_num_units_in_tick;
389 vui->vui_time_scale = vps->vps_time_scale;
390 vui->vui_poc_proportional_to_timing_flag = vps->vps_poc_proportional_to_timing_flag;
391 vui->vui_num_ticks_poc_diff_one_minus1 = vps->vps_num_ticks_poc_diff_one_minus1;
392 vui->vui_hrd_parameters_present_flag = 0;
393
394 vui->bitstream_restriction_flag = 1;
395 vui->motion_vectors_over_pic_boundaries_flag = 1;
396 vui->restricted_ref_pic_lists_flag = 1;
397 vui->max_bytes_per_pic_denom = 0;
398 vui->max_bits_per_min_cu_denom = 0;
399 vui->log2_max_mv_length_horizontal = 15;
400 vui->log2_max_mv_length_vertical = 15;
401
402
403 // PPS
404
405 pps->nal_unit_header = (H265RawNALUnitHeader) {
406 .nal_unit_type = HEVC_NAL_PPS,
407 .nuh_layer_id = 0,
408 .nuh_temporal_id_plus1 = 1,
409 };
410
411 pps->pps_pic_parameter_set_id = 0;
412 pps->pps_seq_parameter_set_id = sps->sps_seq_parameter_set_id;
413
414 pps->num_ref_idx_l0_default_active_minus1 = 0;
415 pps->num_ref_idx_l1_default_active_minus1 = 0;
416
417 pps->init_qp_minus26 = priv->fixed_qp_idr - 26;
418
419 pps->cu_qp_delta_enabled_flag = (ctx->va_rc_mode != VA_RC_CQP);
420 pps->diff_cu_qp_delta_depth = 0;
421
422 pps->pps_loop_filter_across_slices_enabled_flag = 1;
423
424
425 // Fill VAAPI parameter buffers.
426
427 *vseq = (VAEncSequenceParameterBufferHEVC) {
428 .general_profile_idc = vps->profile_tier_level.general_profile_idc,
429 .general_level_idc = vps->profile_tier_level.general_level_idc,
430 .general_tier_flag = vps->profile_tier_level.general_tier_flag,
431
432 .intra_period = avctx->gop_size,
433 .intra_idr_period = avctx->gop_size,
434 .ip_period = ctx->b_per_p + 1,
435 .bits_per_second = avctx->bit_rate,
436
437 .pic_width_in_luma_samples = sps->pic_width_in_luma_samples,
438 .pic_height_in_luma_samples = sps->pic_height_in_luma_samples,
439
440 .seq_fields.bits = {
441 .chroma_format_idc = sps->chroma_format_idc,
442 .separate_colour_plane_flag = sps->separate_colour_plane_flag,
443 .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
444 .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
445 .scaling_list_enabled_flag = sps->scaling_list_enabled_flag,
446 .strong_intra_smoothing_enabled_flag =
447 sps->strong_intra_smoothing_enabled_flag,
448 .amp_enabled_flag = sps->amp_enabled_flag,
449 .sample_adaptive_offset_enabled_flag =
450 sps->sample_adaptive_offset_enabled_flag,
451 .pcm_enabled_flag = sps->pcm_enabled_flag,
452 .pcm_loop_filter_disabled_flag = sps->pcm_loop_filter_disabled_flag,
453 .sps_temporal_mvp_enabled_flag = sps->sps_temporal_mvp_enabled_flag,
454 },
455
456 .log2_min_luma_coding_block_size_minus3 =
457 sps->log2_min_luma_coding_block_size_minus3,
458 .log2_diff_max_min_luma_coding_block_size =
459 sps->log2_diff_max_min_luma_coding_block_size,
460 .log2_min_transform_block_size_minus2 =
461 sps->log2_min_luma_transform_block_size_minus2,
462 .log2_diff_max_min_transform_block_size =
463 sps->log2_diff_max_min_luma_transform_block_size,
464 .max_transform_hierarchy_depth_inter =
465 sps->max_transform_hierarchy_depth_inter,
466 .max_transform_hierarchy_depth_intra =
467 sps->max_transform_hierarchy_depth_intra,
468
469 .pcm_sample_bit_depth_luma_minus1 =
470 sps->pcm_sample_bit_depth_luma_minus1,
471 .pcm_sample_bit_depth_chroma_minus1 =
472 sps->pcm_sample_bit_depth_chroma_minus1,
473 .log2_min_pcm_luma_coding_block_size_minus3 =
474 sps->log2_min_pcm_luma_coding_block_size_minus3,
475 .log2_max_pcm_luma_coding_block_size_minus3 =
476 sps->log2_min_pcm_luma_coding_block_size_minus3 +
477 sps->log2_diff_max_min_pcm_luma_coding_block_size,
478
479 .vui_parameters_present_flag = 0,
480 };
481
482 *vpic = (VAEncPictureParameterBufferHEVC) {
483 .decoded_curr_pic = {
484 .picture_id = VA_INVALID_ID,
485 .flags = VA_PICTURE_HEVC_INVALID,
486 },
487
488 .coded_buf = VA_INVALID_ID,
489
490 .collocated_ref_pic_index = 0xff,
491
492 .last_picture = 0,
493
494 .pic_init_qp = pps->init_qp_minus26 + 26,
495 .diff_cu_qp_delta_depth = pps->diff_cu_qp_delta_depth,
496 .pps_cb_qp_offset = pps->pps_cb_qp_offset,
497 .pps_cr_qp_offset = pps->pps_cr_qp_offset,
498
499 .num_tile_columns_minus1 = pps->num_tile_columns_minus1,
500 .num_tile_rows_minus1 = pps->num_tile_rows_minus1,
501
502 .log2_parallel_merge_level_minus2 = pps->log2_parallel_merge_level_minus2,
503 .ctu_max_bitsize_allowed = 0,
504
505 .num_ref_idx_l0_default_active_minus1 =
506 pps->num_ref_idx_l0_default_active_minus1,
507 .num_ref_idx_l1_default_active_minus1 =
508 pps->num_ref_idx_l1_default_active_minus1,
509
510 .slice_pic_parameter_set_id = pps->pps_pic_parameter_set_id,
511
512 .pic_fields.bits = {
513 .sign_data_hiding_enabled_flag = pps->sign_data_hiding_enabled_flag,
514 .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
515 .transform_skip_enabled_flag = pps->transform_skip_enabled_flag,
516 .cu_qp_delta_enabled_flag = pps->cu_qp_delta_enabled_flag,
517 .weighted_pred_flag = pps->weighted_pred_flag,
518 .weighted_bipred_flag = pps->weighted_bipred_flag,
519 .transquant_bypass_enabled_flag = pps->transquant_bypass_enabled_flag,
520 .tiles_enabled_flag = pps->tiles_enabled_flag,
521 .entropy_coding_sync_enabled_flag = pps->entropy_coding_sync_enabled_flag,
522 .loop_filter_across_tiles_enabled_flag =
523 pps->loop_filter_across_tiles_enabled_flag,
524 .scaling_list_data_present_flag = (sps->sps_scaling_list_data_present_flag |
525 pps->pps_scaling_list_data_present_flag),
526 .screen_content_flag = 0,
527 .enable_gpu_weighted_prediction = 0,
528 .no_output_of_prior_pics_flag = 0,
529 },
530 };
531
31fe1f25
MT
532 return 0;
533}
534
535static int vaapi_encode_h265_init_picture_params(AVCodecContext *avctx,
536 VAAPIEncodePicture *pic)
537{
538 VAAPIEncodeContext *ctx = avctx->priv_data;
31fe1f25 539 VAAPIEncodeH265Context *priv = ctx->priv_data;
e3e8eab3 540 VAAPIEncodeH265Options *opt = ctx->codec_options;
ac124867 541 VAEncPictureParameterBufferHEVC *vpic = pic->codec_picture_params;
31fe1f25
MT
542 int i;
543
544 if (pic->type == PICTURE_TYPE_IDR) {
545 av_assert0(pic->display_order == pic->encode_order);
ac124867 546
31fe1f25 547 priv->last_idr_frame = pic->display_order;
ac124867
MT
548
549 priv->slice_nal_unit = HEVC_NAL_IDR_W_RADL;
550 priv->slice_type = HEVC_SLICE_I;
e3e8eab3 551 priv->pic_type = 0;
31fe1f25
MT
552 } else {
553 av_assert0(pic->encode_order > priv->last_idr_frame);
ac124867
MT
554
555 if (pic->type == PICTURE_TYPE_I) {
556 priv->slice_nal_unit = HEVC_NAL_CRA_NUT;
557 priv->slice_type = HEVC_SLICE_I;
e3e8eab3 558 priv->pic_type = 0;
ac124867
MT
559 } else if (pic->type == PICTURE_TYPE_P) {
560 av_assert0(pic->refs[0]);
561 priv->slice_nal_unit = HEVC_NAL_TRAIL_R;
562 priv->slice_type = HEVC_SLICE_P;
e3e8eab3 563 priv->pic_type = 1;
ac124867
MT
564 } else {
565 av_assert0(pic->refs[0] && pic->refs[1]);
566 if (pic->refs[1]->type == PICTURE_TYPE_I)
567 priv->slice_nal_unit = HEVC_NAL_RASL_N;
568 else
569 priv->slice_nal_unit = HEVC_NAL_TRAIL_N;
570 priv->slice_type = HEVC_SLICE_B;
e3e8eab3 571 priv->pic_type = 2;
ac124867 572 }
31fe1f25 573 }
ac124867 574 priv->pic_order_cnt = pic->display_order - priv->last_idr_frame;
31fe1f25 575
e3e8eab3
MT
576 if (opt->aud) {
577 priv->aud_needed = 1;
578 priv->aud.nal_unit_header = (H265RawNALUnitHeader) {
579 .nal_unit_type = HEVC_NAL_AUD,
580 .nuh_layer_id = 0,
581 .nuh_temporal_id_plus1 = 1,
582 };
583 priv->aud.pic_type = priv->pic_type;
584 } else {
585 priv->aud_needed = 0;
586 }
587
ac124867
MT
588 vpic->decoded_curr_pic = (VAPictureHEVC) {
589 .picture_id = pic->recon_surface,
590 .pic_order_cnt = priv->pic_order_cnt,
591 .flags = 0,
592 };
31fe1f25
MT
593
594 for (i = 0; i < pic->nb_refs; i++) {
595 VAAPIEncodePicture *ref = pic->refs[i];
ac124867
MT
596 av_assert0(ref && ref->encode_order < pic->encode_order);
597
598 vpic->reference_frames[i] = (VAPictureHEVC) {
599 .picture_id = ref->recon_surface,
600 .pic_order_cnt = ref->display_order - priv->last_idr_frame,
601 .flags = (ref->display_order < pic->display_order ?
602 VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE : 0) |
603 (ref->display_order > pic->display_order ?
604 VA_PICTURE_HEVC_RPS_ST_CURR_AFTER : 0),
605 };
31fe1f25
MT
606 }
607 for (; i < FF_ARRAY_ELEMS(vpic->reference_frames); i++) {
ac124867
MT
608 vpic->reference_frames[i] = (VAPictureHEVC) {
609 .picture_id = VA_INVALID_ID,
610 .flags = VA_PICTURE_HEVC_INVALID,
611 };
31fe1f25
MT
612 }
613
614 vpic->coded_buf = pic->output_buffer;
615
ac124867
MT
616 vpic->nal_unit_type = priv->slice_nal_unit;
617
31fe1f25
MT
618 switch (pic->type) {
619 case PICTURE_TYPE_IDR:
ac124867
MT
620 vpic->pic_fields.bits.idr_pic_flag = 1;
621 vpic->pic_fields.bits.coding_type = 1;
31fe1f25
MT
622 vpic->pic_fields.bits.reference_pic_flag = 1;
623 break;
624 case PICTURE_TYPE_I:
ac124867
MT
625 vpic->pic_fields.bits.idr_pic_flag = 0;
626 vpic->pic_fields.bits.coding_type = 1;
31fe1f25
MT
627 vpic->pic_fields.bits.reference_pic_flag = 1;
628 break;
629 case PICTURE_TYPE_P:
ac124867
MT
630 vpic->pic_fields.bits.idr_pic_flag = 0;
631 vpic->pic_fields.bits.coding_type = 2;
31fe1f25
MT
632 vpic->pic_fields.bits.reference_pic_flag = 1;
633 break;
634 case PICTURE_TYPE_B:
ac124867
MT
635 vpic->pic_fields.bits.idr_pic_flag = 0;
636 vpic->pic_fields.bits.coding_type = 3;
31fe1f25
MT
637 vpic->pic_fields.bits.reference_pic_flag = 0;
638 break;
639 default:
640 av_assert0(0 && "invalid picture type");
641 }
642
643 pic->nb_slices = 1;
644
645 return 0;
646}
647
648static int vaapi_encode_h265_init_slice_params(AVCodecContext *avctx,
649 VAAPIEncodePicture *pic,
650 VAAPIEncodeSlice *slice)
651{
652 VAAPIEncodeContext *ctx = avctx->priv_data;
ac124867
MT
653 VAAPIEncodeH265Context *priv = ctx->priv_data;
654 const H265RawSPS *sps = &priv->sps;
655 const H265RawPPS *pps = &priv->pps;
656 H265RawSliceHeader *sh = &priv->slice.header;
31fe1f25
MT
657 VAEncPictureParameterBufferHEVC *vpic = pic->codec_picture_params;
658 VAEncSliceParameterBufferHEVC *vslice = slice->codec_slice_params;
31fe1f25
MT
659 int i;
660
ac124867
MT
661 sh->nal_unit_header = (H265RawNALUnitHeader) {
662 .nal_unit_type = priv->slice_nal_unit,
663 .nuh_layer_id = 0,
664 .nuh_temporal_id_plus1 = 1,
665 };
31fe1f25 666
ac124867 667 sh->slice_pic_parameter_set_id = pps->pps_pic_parameter_set_id;
31fe1f25 668
ac124867
MT
669 // Currently we only support one slice per frame.
670 sh->first_slice_segment_in_pic_flag = 1;
671 sh->slice_segment_address = 0;
31fe1f25 672
ac124867 673 sh->slice_type = priv->slice_type;
31fe1f25 674
ac124867
MT
675 sh->slice_pic_order_cnt_lsb = priv->pic_order_cnt &
676 (1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4)) - 1;
31fe1f25 677
ac124867
MT
678 if (pic->type != PICTURE_TYPE_IDR) {
679 H265RawSTRefPicSet *rps;
31fe1f25
MT
680 VAAPIEncodePicture *st;
681 int used;
682
ac124867
MT
683 sh->short_term_ref_pic_set_sps_flag = 0;
684
685 rps = &sh->short_term_ref_pic_set;
686 memset(rps, 0, sizeof(*rps));
31fe1f25
MT
687
688 for (st = ctx->pic_start; st; st = st->next) {
689 if (st->encode_order >= pic->encode_order) {
690 // Not yet in DPB.
691 continue;
692 }
693 used = 0;
694 for (i = 0; i < pic->nb_refs; i++) {
695 if (pic->refs[i] == st)
696 used = 1;
697 }
698 if (!used) {
ac124867
MT
699 // Usually each picture always uses all of the others in the
700 // DPB as references. The one case we have to treat here is
701 // a non-IDR IRAP picture, which may need to hold unused
702 // references across itself to be used for the decoding of
703 // following RASL pictures. This looks for such an RASL
704 // picture, and keeps the reference if there is one.
705 VAAPIEncodePicture *rp;
706 for (rp = ctx->pic_start; rp; rp = rp->next) {
707 if (rp->encode_order < pic->encode_order)
708 continue;
709 if (rp->type != PICTURE_TYPE_B)
710 continue;
711 if (rp->refs[0] == st && rp->refs[1] == pic)
712 break;
713 }
714 if (!rp)
715 continue;
31fe1f25
MT
716 }
717 // This only works for one instance of each (delta_poc_sN_minus1
718 // is relative to the previous frame in the list, not relative to
719 // the current frame directly).
720 if (st->display_order < pic->display_order) {
ac124867 721 rps->delta_poc_s0_minus1[rps->num_negative_pics] =
31fe1f25 722 pic->display_order - st->display_order - 1;
ac124867
MT
723 rps->used_by_curr_pic_s0_flag[rps->num_negative_pics] = used;
724 ++rps->num_negative_pics;
31fe1f25 725 } else {
ac124867 726 rps->delta_poc_s1_minus1[rps->num_positive_pics] =
31fe1f25 727 st->display_order - pic->display_order - 1;
ac124867
MT
728 rps->used_by_curr_pic_s1_flag[rps->num_positive_pics] = used;
729 ++rps->num_positive_pics;
31fe1f25
MT
730 }
731 }
ac124867
MT
732
733 sh->num_long_term_sps = 0;
734 sh->num_long_term_pics = 0;
735
736 sh->slice_temporal_mvp_enabled_flag =
737 sps->sps_temporal_mvp_enabled_flag;
738 if (sh->slice_temporal_mvp_enabled_flag) {
739 sh->collocated_from_l0_flag = sh->slice_type == HEVC_SLICE_B;
740 sh->collocated_ref_idx = 0;
741 }
742
743 sh->num_ref_idx_active_override_flag = 0;
744 sh->num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1;
745 sh->num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1;
31fe1f25
MT
746 }
747
ac124867
MT
748 sh->slice_sao_luma_flag = sh->slice_sao_chroma_flag =
749 sps->sample_adaptive_offset_enabled_flag;
750
751 if (pic->type == PICTURE_TYPE_B)
752 sh->slice_qp_delta = priv->fixed_qp_b - (pps->init_qp_minus26 + 26);
753 else if (pic->type == PICTURE_TYPE_P)
754 sh->slice_qp_delta = priv->fixed_qp_p - (pps->init_qp_minus26 + 26);
755 else
756 sh->slice_qp_delta = priv->fixed_qp_idr - (pps->init_qp_minus26 + 26);
757
758
759 *vslice = (VAEncSliceParameterBufferHEVC) {
760 .slice_segment_address = sh->slice_segment_address,
761 .num_ctu_in_slice = priv->ctu_width * priv->ctu_height,
762
763 .slice_type = sh->slice_type,
764 .slice_pic_parameter_set_id = sh->slice_pic_parameter_set_id,
765
766 .num_ref_idx_l0_active_minus1 = sh->num_ref_idx_l0_active_minus1,
767 .num_ref_idx_l1_active_minus1 = sh->num_ref_idx_l1_active_minus1,
768 .ref_pic_list0[0] = vpic->reference_frames[0],
769 .ref_pic_list1[0] = vpic->reference_frames[1],
770
771 .luma_log2_weight_denom = sh->luma_log2_weight_denom,
772 .delta_chroma_log2_weight_denom = sh->delta_chroma_log2_weight_denom,
773
774 .max_num_merge_cand = 5 - sh->five_minus_max_num_merge_cand,
775
776 .slice_qp_delta = sh->slice_qp_delta,
777 .slice_cb_qp_offset = sh->slice_cb_qp_offset,
778 .slice_cr_qp_offset = sh->slice_cr_qp_offset,
779
780 .slice_beta_offset_div2 = sh->slice_beta_offset_div2,
781 .slice_tc_offset_div2 = sh->slice_tc_offset_div2,
782
783 .slice_fields.bits = {
784 .last_slice_of_pic_flag = 1,
785 .dependent_slice_segment_flag = sh->dependent_slice_segment_flag,
786 .colour_plane_id = sh->colour_plane_id,
787 .slice_temporal_mvp_enabled_flag =
788 sh->slice_temporal_mvp_enabled_flag,
789 .slice_sao_luma_flag = sh->slice_sao_luma_flag,
790 .slice_sao_chroma_flag = sh->slice_sao_chroma_flag,
791 .num_ref_idx_active_override_flag =
792 sh->num_ref_idx_active_override_flag,
793 .mvd_l1_zero_flag = sh->mvd_l1_zero_flag,
794 .cabac_init_flag = sh->cabac_init_flag,
795 .slice_deblocking_filter_disabled_flag =
796 sh->slice_deblocking_filter_disabled_flag,
797 .slice_loop_filter_across_slices_enabled_flag =
798 sh->slice_loop_filter_across_slices_enabled_flag,
799 .collocated_from_l0_flag = sh->collocated_from_l0_flag,
800 },
801 };
802
803
31fe1f25
MT
804 return 0;
805}
806
80a5d051 807static av_cold int vaapi_encode_h265_configure(AVCodecContext *avctx)
f70e4627
MT
808{
809 VAAPIEncodeContext *ctx = avctx->priv_data;
810 VAAPIEncodeH265Context *priv = ctx->priv_data;
80a5d051 811 VAAPIEncodeH265Options *opt = ctx->codec_options;
ac124867
MT
812 int err;
813
814 err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_HEVC, avctx);
815 if (err < 0)
816 return err;
80a5d051
MT
817
818 priv->ctu_width = FFALIGN(ctx->surface_width, 32) / 32;
819 priv->ctu_height = FFALIGN(ctx->surface_height, 32) / 32;
820
821 av_log(avctx, AV_LOG_VERBOSE, "Input %ux%u -> Surface %ux%u -> CTU %ux%u.\n",
822 avctx->width, avctx->height, ctx->surface_width,
823 ctx->surface_height, priv->ctu_width, priv->ctu_height);
824
825 if (ctx->va_rc_mode == VA_RC_CQP) {
826 priv->fixed_qp_p = opt->qp;
827 if (avctx->i_quant_factor > 0.0)
828 priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
829 avctx->i_quant_offset) + 0.5);
830 else
831 priv->fixed_qp_idr = priv->fixed_qp_p;
832 if (avctx->b_quant_factor > 0.0)
833 priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
834 avctx->b_quant_offset) + 0.5);
835 else
836 priv->fixed_qp_b = priv->fixed_qp_p;
837
838 av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
839 "%d / %d / %d for IDR- / P- / B-frames.\n",
840 priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
841
842 } else if (ctx->va_rc_mode == VA_RC_CBR) {
843 // These still need to be set for pic_init_qp/slice_qp_delta.
844 priv->fixed_qp_idr = 30;
845 priv->fixed_qp_p = 30;
846 priv->fixed_qp_b = 30;
847
848 av_log(avctx, AV_LOG_DEBUG, "Using constant-bitrate = %d bps.\n",
849 avctx->bit_rate);
850
851 } else {
852 av_assert0(0 && "Invalid RC mode.");
853 }
f70e4627 854
f70e4627
MT
855 return 0;
856}
857
80a5d051
MT
858static const VAAPIEncodeType vaapi_encode_type_h265 = {
859 .priv_data_size = sizeof(VAAPIEncodeH265Context),
f70e4627 860
80a5d051 861 .configure = &vaapi_encode_h265_configure,
f70e4627 862
80a5d051
MT
863 .sequence_params_size = sizeof(VAEncSequenceParameterBufferHEVC),
864 .init_sequence_params = &vaapi_encode_h265_init_sequence_params,
f70e4627 865
80a5d051
MT
866 .picture_params_size = sizeof(VAEncPictureParameterBufferHEVC),
867 .init_picture_params = &vaapi_encode_h265_init_picture_params,
868
869 .slice_params_size = sizeof(VAEncSliceParameterBufferHEVC),
870 .init_slice_params = &vaapi_encode_h265_init_slice_params,
871
872 .sequence_header_type = VAEncPackedHeaderSequence,
873 .write_sequence_header = &vaapi_encode_h265_write_sequence_header,
874
875 .slice_header_type = VAEncPackedHeaderHEVC_Slice,
876 .write_slice_header = &vaapi_encode_h265_write_slice_header,
877};
878
879static av_cold int vaapi_encode_h265_init(AVCodecContext *avctx)
31fe1f25 880{
80a5d051 881 VAAPIEncodeContext *ctx = avctx->priv_data;
f6b85523 882
80a5d051 883 ctx->codec = &vaapi_encode_type_h265;
31fe1f25
MT
884
885 switch (avctx->profile) {
886 case FF_PROFILE_HEVC_MAIN:
887 case FF_PROFILE_UNKNOWN:
888 ctx->va_profile = VAProfileHEVCMain;
5a5df90d 889 ctx->va_rt_format = VA_RT_FORMAT_YUV420;
31fe1f25
MT
890 break;
891 case FF_PROFILE_HEVC_MAIN_10:
d08e02d9 892#ifdef VA_RT_FORMAT_YUV420_10BPP
5a5df90d
MT
893 ctx->va_profile = VAProfileHEVCMain10;
894 ctx->va_rt_format = VA_RT_FORMAT_YUV420_10BPP;
895 break;
d08e02d9
MT
896#else
897 av_log(avctx, AV_LOG_ERROR, "10-bit encoding is not "
898 "supported with this VAAPI version.\n");
899 return AVERROR(ENOSYS);
900#endif
31fe1f25
MT
901 default:
902 av_log(avctx, AV_LOG_ERROR, "Unknown H.265 profile %d.\n",
903 avctx->profile);
904 return AVERROR(EINVAL);
905 }
906 ctx->va_entrypoint = VAEntrypointEncSlice;
907
80a5d051 908 if (avctx->bit_rate > 0)
f70e4627 909 ctx->va_rc_mode = VA_RC_CBR;
80a5d051 910 else
f70e4627 911 ctx->va_rc_mode = VA_RC_CQP;
f6b85523 912
892bbbcd
MT
913 ctx->va_packed_headers =
914 VA_ENC_PACKED_HEADER_SEQUENCE | // VPS, SPS and PPS.
915 VA_ENC_PACKED_HEADER_SLICE; // Slice headers.
31fe1f25 916
80a5d051
MT
917 ctx->surface_width = FFALIGN(avctx->width, 16);
918 ctx->surface_height = FFALIGN(avctx->height, 16);
31fe1f25 919
80a5d051 920 return ff_vaapi_encode_init(avctx);
31fe1f25
MT
921}
922
ac124867
MT
923static av_cold int vaapi_encode_h265_close(AVCodecContext *avctx)
924{
925 VAAPIEncodeContext *ctx = avctx->priv_data;
926 VAAPIEncodeH265Context *priv = ctx->priv_data;
927
928 if (priv)
929 ff_cbs_close(&priv->cbc);
930
931 return ff_vaapi_encode_close(avctx);
932}
933
92fdea37
MT
934#define OFFSET(x) (offsetof(VAAPIEncodeContext, codec_options_data) + \
935 offsetof(VAAPIEncodeH265Options, x))
936#define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
937static const AVOption vaapi_encode_h265_options[] = {
41ed7ab4 938 { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
92fdea37 939 OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 25 }, 0, 52, FLAGS },
e3e8eab3
MT
940
941 { "aud", "Include AUD",
942 OFFSET(aud), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
943
92fdea37
MT
944 { NULL },
945};
946
31fe1f25
MT
947static const AVCodecDefault vaapi_encode_h265_defaults[] = {
948 { "profile", "1" },
949 { "level", "51" },
950 { "b", "0" },
951 { "bf", "2" },
952 { "g", "120" },
31fe1f25
MT
953 { "i_qfactor", "1.0" },
954 { "i_qoffset", "0.0" },
955 { "b_qfactor", "1.2" },
956 { "b_qoffset", "0.0" },
957 { NULL },
958};
959
960static const AVClass vaapi_encode_h265_class = {
961 .class_name = "h265_vaapi",
962 .item_name = av_default_item_name,
92fdea37 963 .option = vaapi_encode_h265_options,
31fe1f25
MT
964 .version = LIBAVUTIL_VERSION_INT,
965};
966
967AVCodec ff_hevc_vaapi_encoder = {
968 .name = "hevc_vaapi",
969 .long_name = NULL_IF_CONFIG_SMALL("H.265/HEVC (VAAPI)"),
970 .type = AVMEDIA_TYPE_VIDEO,
971 .id = AV_CODEC_ID_HEVC,
92fdea37
MT
972 .priv_data_size = (sizeof(VAAPIEncodeContext) +
973 sizeof(VAAPIEncodeH265Options)),
31fe1f25
MT
974 .init = &vaapi_encode_h265_init,
975 .encode2 = &ff_vaapi_encode2,
ac124867 976 .close = &vaapi_encode_h265_close,
31fe1f25
MT
977 .priv_class = &vaapi_encode_h265_class,
978 .capabilities = AV_CODEC_CAP_DELAY,
979 .defaults = vaapi_encode_h265_defaults,
980 .pix_fmts = (const enum AVPixelFormat[]) {
981 AV_PIX_FMT_VAAPI,
982 AV_PIX_FMT_NONE,
983 },
984};