You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1340 lines
48KB

  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. #include <string.h>
  19. #include <va/va.h>
  20. #include <va/va_enc_hevc.h>
  21. #include "libavutil/avassert.h"
  22. #include "libavutil/common.h"
  23. #include "libavutil/pixdesc.h"
  24. #include "libavutil/opt.h"
  25. #include "libavutil/mastering_display_metadata.h"
  26. #include "avcodec.h"
  27. #include "cbs.h"
  28. #include "cbs_h265.h"
  29. #include "h265_profile_level.h"
  30. #include "hevc.h"
  31. #include "hevc_sei.h"
  32. #include "internal.h"
  33. #include "put_bits.h"
  34. #include "vaapi_encode.h"
  35. enum {
  36. SEI_MASTERING_DISPLAY = 0x08,
  37. SEI_CONTENT_LIGHT_LEVEL = 0x10,
  38. };
  39. typedef struct VAAPIEncodeH265Picture {
  40. int pic_order_cnt;
  41. int64_t last_idr_frame;
  42. int slice_nal_unit;
  43. int slice_type;
  44. int pic_type;
  45. } VAAPIEncodeH265Picture;
  46. typedef struct VAAPIEncodeH265Context {
  47. VAAPIEncodeContext common;
  48. // User options.
  49. int qp;
  50. int aud;
  51. int profile;
  52. int tier;
  53. int level;
  54. int sei;
  55. // Derived settings.
  56. int fixed_qp_idr;
  57. int fixed_qp_p;
  58. int fixed_qp_b;
  59. // Writer structures.
  60. H265RawAUD raw_aud;
  61. H265RawVPS raw_vps;
  62. H265RawSPS raw_sps;
  63. H265RawPPS raw_pps;
  64. H265RawSEI raw_sei;
  65. H265RawSlice raw_slice;
  66. H265RawSEIMasteringDisplayColourVolume sei_mastering_display;
  67. H265RawSEIContentLightLevelInfo sei_content_light_level;
  68. CodedBitstreamContext *cbc;
  69. CodedBitstreamFragment current_access_unit;
  70. int aud_needed;
  71. int sei_needed;
  72. } VAAPIEncodeH265Context;
  73. static int vaapi_encode_h265_write_access_unit(AVCodecContext *avctx,
  74. char *data, size_t *data_len,
  75. CodedBitstreamFragment *au)
  76. {
  77. VAAPIEncodeH265Context *priv = avctx->priv_data;
  78. int err;
  79. err = ff_cbs_write_fragment_data(priv->cbc, au);
  80. if (err < 0) {
  81. av_log(avctx, AV_LOG_ERROR, "Failed to write packed header.\n");
  82. return err;
  83. }
  84. if (*data_len < 8 * au->data_size - au->data_bit_padding) {
  85. av_log(avctx, AV_LOG_ERROR, "Access unit too large: "
  86. "%zu < %zu.\n", *data_len,
  87. 8 * au->data_size - au->data_bit_padding);
  88. return AVERROR(ENOSPC);
  89. }
  90. memcpy(data, au->data, au->data_size);
  91. *data_len = 8 * au->data_size - au->data_bit_padding;
  92. return 0;
  93. }
  94. static int vaapi_encode_h265_add_nal(AVCodecContext *avctx,
  95. CodedBitstreamFragment *au,
  96. void *nal_unit)
  97. {
  98. H265RawNALUnitHeader *header = nal_unit;
  99. int err;
  100. err = ff_cbs_insert_unit_content(au, -1,
  101. header->nal_unit_type, nal_unit, NULL);
  102. if (err < 0) {
  103. av_log(avctx, AV_LOG_ERROR, "Failed to add NAL unit: "
  104. "type = %d.\n", header->nal_unit_type);
  105. return err;
  106. }
  107. return 0;
  108. }
  109. static int vaapi_encode_h265_write_sequence_header(AVCodecContext *avctx,
  110. char *data, size_t *data_len)
  111. {
  112. VAAPIEncodeH265Context *priv = avctx->priv_data;
  113. CodedBitstreamFragment *au = &priv->current_access_unit;
  114. int err;
  115. if (priv->aud_needed) {
  116. err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_aud);
  117. if (err < 0)
  118. goto fail;
  119. priv->aud_needed = 0;
  120. }
  121. err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_vps);
  122. if (err < 0)
  123. goto fail;
  124. err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_sps);
  125. if (err < 0)
  126. goto fail;
  127. err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_pps);
  128. if (err < 0)
  129. goto fail;
  130. err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
  131. fail:
  132. ff_cbs_fragment_reset(au);
  133. return err;
  134. }
  135. static int vaapi_encode_h265_write_slice_header(AVCodecContext *avctx,
  136. VAAPIEncodePicture *pic,
  137. VAAPIEncodeSlice *slice,
  138. char *data, size_t *data_len)
  139. {
  140. VAAPIEncodeH265Context *priv = avctx->priv_data;
  141. CodedBitstreamFragment *au = &priv->current_access_unit;
  142. int err;
  143. if (priv->aud_needed) {
  144. err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_aud);
  145. if (err < 0)
  146. goto fail;
  147. priv->aud_needed = 0;
  148. }
  149. err = vaapi_encode_h265_add_nal(avctx, au, &priv->raw_slice);
  150. if (err < 0)
  151. goto fail;
  152. err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
  153. fail:
  154. ff_cbs_fragment_reset(au);
  155. return err;
  156. }
  157. static int vaapi_encode_h265_write_extra_header(AVCodecContext *avctx,
  158. VAAPIEncodePicture *pic,
  159. int index, int *type,
  160. char *data, size_t *data_len)
  161. {
  162. VAAPIEncodeH265Context *priv = avctx->priv_data;
  163. CodedBitstreamFragment *au = &priv->current_access_unit;
  164. int err, i;
  165. if (priv->sei_needed) {
  166. H265RawSEI *sei = &priv->raw_sei;
  167. if (priv->aud_needed) {
  168. err = vaapi_encode_h265_add_nal(avctx, au, &priv->aud);
  169. if (err < 0)
  170. goto fail;
  171. priv->aud_needed = 0;
  172. }
  173. *sei = (H265RawSEI) {
  174. .nal_unit_header = {
  175. .nal_unit_type = HEVC_NAL_SEI_PREFIX,
  176. .nuh_layer_id = 0,
  177. .nuh_temporal_id_plus1 = 1,
  178. },
  179. };
  180. i = 0;
  181. if (priv->sei_needed & SEI_MASTERING_DISPLAY) {
  182. sei->payload[i].payload_type = HEVC_SEI_TYPE_MASTERING_DISPLAY_INFO;
  183. sei->payload[i].payload.mastering_display = priv->sei_mastering_display;
  184. ++i;
  185. }
  186. if (priv->sei_needed & SEI_CONTENT_LIGHT_LEVEL) {
  187. sei->payload[i].payload_type = HEVC_SEI_TYPE_CONTENT_LIGHT_LEVEL_INFO;
  188. sei->payload[i].payload.content_light_level = priv->sei_content_light_level;
  189. ++i;
  190. }
  191. sei->payload_count = i;
  192. av_assert0(sei->payload_count > 0);
  193. err = vaapi_encode_h265_add_nal(avctx, au, sei);
  194. if (err < 0)
  195. goto fail;
  196. priv->sei_needed = 0;
  197. err = vaapi_encode_h265_write_access_unit(avctx, data, data_len, au);
  198. if (err < 0)
  199. goto fail;
  200. ff_cbs_fragment_reset(au);
  201. *type = VAEncPackedHeaderRawData;
  202. return 0;
  203. } else {
  204. return AVERROR_EOF;
  205. }
  206. fail:
  207. ff_cbs_fragment_reset(au);
  208. return err;
  209. }
  210. static int vaapi_encode_h265_init_sequence_params(AVCodecContext *avctx)
  211. {
  212. VAAPIEncodeContext *ctx = avctx->priv_data;
  213. VAAPIEncodeH265Context *priv = avctx->priv_data;
  214. H265RawVPS *vps = &priv->raw_vps;
  215. H265RawSPS *sps = &priv->raw_sps;
  216. H265RawPPS *pps = &priv->raw_pps;
  217. H265RawProfileTierLevel *ptl = &vps->profile_tier_level;
  218. H265RawVUI *vui = &sps->vui;
  219. VAEncSequenceParameterBufferHEVC *vseq = ctx->codec_sequence_params;
  220. VAEncPictureParameterBufferHEVC *vpic = ctx->codec_picture_params;
  221. const AVPixFmtDescriptor *desc;
  222. int chroma_format, bit_depth;
  223. int i;
  224. memset(vps, 0, sizeof(*vps));
  225. memset(sps, 0, sizeof(*sps));
  226. memset(pps, 0, sizeof(*pps));
  227. desc = av_pix_fmt_desc_get(priv->common.input_frames->sw_format);
  228. av_assert0(desc);
  229. if (desc->nb_components == 1) {
  230. chroma_format = 0;
  231. } else {
  232. if (desc->log2_chroma_w == 1 && desc->log2_chroma_h == 1) {
  233. chroma_format = 1;
  234. } else if (desc->log2_chroma_w == 1 && desc->log2_chroma_h == 0) {
  235. chroma_format = 2;
  236. } else if (desc->log2_chroma_w == 0 && desc->log2_chroma_h == 0) {
  237. chroma_format = 3;
  238. } else {
  239. av_log(avctx, AV_LOG_ERROR, "Chroma format of input pixel format "
  240. "%s is not supported.\n", desc->name);
  241. return AVERROR(EINVAL);
  242. }
  243. }
  244. bit_depth = desc->comp[0].depth;
  245. // VPS
  246. vps->nal_unit_header = (H265RawNALUnitHeader) {
  247. .nal_unit_type = HEVC_NAL_VPS,
  248. .nuh_layer_id = 0,
  249. .nuh_temporal_id_plus1 = 1,
  250. };
  251. vps->vps_video_parameter_set_id = 0;
  252. vps->vps_base_layer_internal_flag = 1;
  253. vps->vps_base_layer_available_flag = 1;
  254. vps->vps_max_layers_minus1 = 0;
  255. vps->vps_max_sub_layers_minus1 = 0;
  256. vps->vps_temporal_id_nesting_flag = 1;
  257. ptl->general_profile_space = 0;
  258. ptl->general_profile_idc = avctx->profile;
  259. ptl->general_tier_flag = priv->tier;
  260. if (chroma_format == 1) {
  261. ptl->general_profile_compatibility_flag[1] = bit_depth == 8;
  262. ptl->general_profile_compatibility_flag[2] = bit_depth <= 10;
  263. }
  264. ptl->general_profile_compatibility_flag[4] = 1;
  265. ptl->general_progressive_source_flag = 1;
  266. ptl->general_interlaced_source_flag = 0;
  267. ptl->general_non_packed_constraint_flag = 1;
  268. ptl->general_frame_only_constraint_flag = 1;
  269. ptl->general_max_12bit_constraint_flag = bit_depth <= 12;
  270. ptl->general_max_10bit_constraint_flag = bit_depth <= 10;
  271. ptl->general_max_8bit_constraint_flag = bit_depth == 8;
  272. ptl->general_max_422chroma_constraint_flag = chroma_format <= 2;
  273. ptl->general_max_420chroma_constraint_flag = chroma_format <= 1;
  274. ptl->general_max_monochrome_constraint_flag = chroma_format == 0;
  275. ptl->general_intra_constraint_flag = ctx->gop_size == 1;
  276. ptl->general_lower_bit_rate_constraint_flag = 1;
  277. if (avctx->level != FF_LEVEL_UNKNOWN) {
  278. ptl->general_level_idc = avctx->level;
  279. } else {
  280. const H265LevelDescriptor *level;
  281. level = ff_h265_guess_level(ptl, avctx->bit_rate,
  282. ctx->surface_width, ctx->surface_height,
  283. ctx->nb_slices, ctx->tile_rows, ctx->tile_cols,
  284. (ctx->b_per_p > 0) + 1);
  285. if (level) {
  286. av_log(avctx, AV_LOG_VERBOSE, "Using level %s.\n", level->name);
  287. ptl->general_level_idc = level->level_idc;
  288. } else {
  289. av_log(avctx, AV_LOG_VERBOSE, "Stream will not conform to "
  290. "any normal level; using level 8.5.\n");
  291. ptl->general_level_idc = 255;
  292. // The tier flag must be set in level 8.5.
  293. ptl->general_tier_flag = 1;
  294. }
  295. }
  296. vps->vps_sub_layer_ordering_info_present_flag = 0;
  297. vps->vps_max_dec_pic_buffering_minus1[0] = ctx->max_b_depth + 1;
  298. vps->vps_max_num_reorder_pics[0] = ctx->max_b_depth;
  299. vps->vps_max_latency_increase_plus1[0] = 0;
  300. vps->vps_max_layer_id = 0;
  301. vps->vps_num_layer_sets_minus1 = 0;
  302. vps->layer_id_included_flag[0][0] = 1;
  303. vps->vps_timing_info_present_flag = 1;
  304. if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
  305. vps->vps_num_units_in_tick = avctx->framerate.den;
  306. vps->vps_time_scale = avctx->framerate.num;
  307. vps->vps_poc_proportional_to_timing_flag = 1;
  308. vps->vps_num_ticks_poc_diff_one_minus1 = 0;
  309. } else {
  310. vps->vps_num_units_in_tick = avctx->time_base.num;
  311. vps->vps_time_scale = avctx->time_base.den;
  312. vps->vps_poc_proportional_to_timing_flag = 0;
  313. }
  314. vps->vps_num_hrd_parameters = 0;
  315. // SPS
  316. sps->nal_unit_header = (H265RawNALUnitHeader) {
  317. .nal_unit_type = HEVC_NAL_SPS,
  318. .nuh_layer_id = 0,
  319. .nuh_temporal_id_plus1 = 1,
  320. };
  321. sps->sps_video_parameter_set_id = vps->vps_video_parameter_set_id;
  322. sps->sps_max_sub_layers_minus1 = vps->vps_max_sub_layers_minus1;
  323. sps->sps_temporal_id_nesting_flag = vps->vps_temporal_id_nesting_flag;
  324. sps->profile_tier_level = vps->profile_tier_level;
  325. sps->sps_seq_parameter_set_id = 0;
  326. sps->chroma_format_idc = chroma_format;
  327. sps->separate_colour_plane_flag = 0;
  328. sps->pic_width_in_luma_samples = ctx->surface_width;
  329. sps->pic_height_in_luma_samples = ctx->surface_height;
  330. if (avctx->width != ctx->surface_width ||
  331. avctx->height != ctx->surface_height) {
  332. sps->conformance_window_flag = 1;
  333. sps->conf_win_left_offset = 0;
  334. sps->conf_win_right_offset =
  335. (ctx->surface_width - avctx->width) >> desc->log2_chroma_w;
  336. sps->conf_win_top_offset = 0;
  337. sps->conf_win_bottom_offset =
  338. (ctx->surface_height - avctx->height) >> desc->log2_chroma_h;
  339. } else {
  340. sps->conformance_window_flag = 0;
  341. }
  342. sps->bit_depth_luma_minus8 = bit_depth - 8;
  343. sps->bit_depth_chroma_minus8 = bit_depth - 8;
  344. sps->log2_max_pic_order_cnt_lsb_minus4 = 8;
  345. sps->sps_sub_layer_ordering_info_present_flag =
  346. vps->vps_sub_layer_ordering_info_present_flag;
  347. for (i = 0; i <= sps->sps_max_sub_layers_minus1; i++) {
  348. sps->sps_max_dec_pic_buffering_minus1[i] =
  349. vps->vps_max_dec_pic_buffering_minus1[i];
  350. sps->sps_max_num_reorder_pics[i] =
  351. vps->vps_max_num_reorder_pics[i];
  352. sps->sps_max_latency_increase_plus1[i] =
  353. vps->vps_max_latency_increase_plus1[i];
  354. }
  355. // These have to come from the capabilities of the encoder. We have no
  356. // way to query them, so just hardcode parameters which work on the Intel
  357. // driver.
  358. // CTB size from 8x8 to 32x32.
  359. sps->log2_min_luma_coding_block_size_minus3 = 0;
  360. sps->log2_diff_max_min_luma_coding_block_size = 2;
  361. // Transform size from 4x4 to 32x32.
  362. sps->log2_min_luma_transform_block_size_minus2 = 0;
  363. sps->log2_diff_max_min_luma_transform_block_size = 3;
  364. // Full transform hierarchy allowed (2-5).
  365. sps->max_transform_hierarchy_depth_inter = 3;
  366. sps->max_transform_hierarchy_depth_intra = 3;
  367. // AMP works.
  368. sps->amp_enabled_flag = 1;
  369. // SAO and temporal MVP do not work.
  370. sps->sample_adaptive_offset_enabled_flag = 0;
  371. sps->sps_temporal_mvp_enabled_flag = 0;
  372. sps->pcm_enabled_flag = 0;
  373. // STRPSs should ideally be here rather than defined individually in
  374. // each slice, but the structure isn't completely fixed so for now
  375. // don't bother.
  376. sps->num_short_term_ref_pic_sets = 0;
  377. sps->long_term_ref_pics_present_flag = 0;
  378. sps->vui_parameters_present_flag = 1;
  379. if (avctx->sample_aspect_ratio.num != 0 &&
  380. avctx->sample_aspect_ratio.den != 0) {
  381. static const AVRational sar_idc[] = {
  382. { 0, 0 },
  383. { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 },
  384. { 40, 33 }, { 24, 11 }, { 20, 11 }, { 32, 11 },
  385. { 80, 33 }, { 18, 11 }, { 15, 11 }, { 64, 33 },
  386. { 160, 99 }, { 4, 3 }, { 3, 2 }, { 2, 1 },
  387. };
  388. int num, den, i;
  389. av_reduce(&num, &den, avctx->sample_aspect_ratio.num,
  390. avctx->sample_aspect_ratio.den, 65535);
  391. for (i = 0; i < FF_ARRAY_ELEMS(sar_idc); i++) {
  392. if (num == sar_idc[i].num &&
  393. den == sar_idc[i].den) {
  394. vui->aspect_ratio_idc = i;
  395. break;
  396. }
  397. }
  398. if (i >= FF_ARRAY_ELEMS(sar_idc)) {
  399. vui->aspect_ratio_idc = 255;
  400. vui->sar_width = num;
  401. vui->sar_height = den;
  402. }
  403. vui->aspect_ratio_info_present_flag = 1;
  404. }
  405. // Unspecified video format, from table E-2.
  406. vui->video_format = 5;
  407. vui->video_full_range_flag =
  408. avctx->color_range == AVCOL_RANGE_JPEG;
  409. vui->colour_primaries = avctx->color_primaries;
  410. vui->transfer_characteristics = avctx->color_trc;
  411. vui->matrix_coefficients = avctx->colorspace;
  412. if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
  413. avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
  414. avctx->colorspace != AVCOL_SPC_UNSPECIFIED)
  415. vui->colour_description_present_flag = 1;
  416. if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED ||
  417. vui->colour_description_present_flag)
  418. vui->video_signal_type_present_flag = 1;
  419. if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
  420. vui->chroma_loc_info_present_flag = 1;
  421. vui->chroma_sample_loc_type_top_field =
  422. vui->chroma_sample_loc_type_bottom_field =
  423. avctx->chroma_sample_location - 1;
  424. }
  425. vui->vui_timing_info_present_flag = 1;
  426. vui->vui_num_units_in_tick = vps->vps_num_units_in_tick;
  427. vui->vui_time_scale = vps->vps_time_scale;
  428. vui->vui_poc_proportional_to_timing_flag = vps->vps_poc_proportional_to_timing_flag;
  429. vui->vui_num_ticks_poc_diff_one_minus1 = vps->vps_num_ticks_poc_diff_one_minus1;
  430. vui->vui_hrd_parameters_present_flag = 0;
  431. vui->bitstream_restriction_flag = 1;
  432. vui->motion_vectors_over_pic_boundaries_flag = 1;
  433. vui->restricted_ref_pic_lists_flag = 1;
  434. vui->max_bytes_per_pic_denom = 0;
  435. vui->max_bits_per_min_cu_denom = 0;
  436. vui->log2_max_mv_length_horizontal = 15;
  437. vui->log2_max_mv_length_vertical = 15;
  438. // PPS
  439. pps->nal_unit_header = (H265RawNALUnitHeader) {
  440. .nal_unit_type = HEVC_NAL_PPS,
  441. .nuh_layer_id = 0,
  442. .nuh_temporal_id_plus1 = 1,
  443. };
  444. pps->pps_pic_parameter_set_id = 0;
  445. pps->pps_seq_parameter_set_id = sps->sps_seq_parameter_set_id;
  446. pps->num_ref_idx_l0_default_active_minus1 = 0;
  447. pps->num_ref_idx_l1_default_active_minus1 = 0;
  448. pps->init_qp_minus26 = priv->fixed_qp_idr - 26;
  449. pps->cu_qp_delta_enabled_flag = (ctx->va_rc_mode != VA_RC_CQP);
  450. pps->diff_cu_qp_delta_depth = 0;
  451. if (ctx->tile_rows && ctx->tile_cols) {
  452. int uniform_spacing;
  453. pps->tiles_enabled_flag = 1;
  454. pps->num_tile_columns_minus1 = ctx->tile_cols - 1;
  455. pps->num_tile_rows_minus1 = ctx->tile_rows - 1;
  456. // Test whether the spacing provided matches the H.265 uniform
  457. // spacing, and set the flag if it does.
  458. uniform_spacing = 1;
  459. for (i = 0; i <= pps->num_tile_columns_minus1 &&
  460. uniform_spacing; i++) {
  461. if (ctx->col_width[i] !=
  462. (i + 1) * ctx->slice_block_cols / ctx->tile_cols -
  463. i * ctx->slice_block_cols / ctx->tile_cols)
  464. uniform_spacing = 0;
  465. }
  466. for (i = 0; i <= pps->num_tile_rows_minus1 &&
  467. uniform_spacing; i++) {
  468. if (ctx->row_height[i] !=
  469. (i + 1) * ctx->slice_block_rows / ctx->tile_rows -
  470. i * ctx->slice_block_rows / ctx->tile_rows)
  471. uniform_spacing = 0;
  472. }
  473. pps->uniform_spacing_flag = uniform_spacing;
  474. for (i = 0; i <= pps->num_tile_columns_minus1; i++)
  475. pps->column_width_minus1[i] = ctx->col_width[i] - 1;
  476. for (i = 0; i <= pps->num_tile_rows_minus1; i++)
  477. pps->row_height_minus1[i] = ctx->row_height[i] - 1;
  478. pps->loop_filter_across_tiles_enabled_flag = 1;
  479. }
  480. pps->pps_loop_filter_across_slices_enabled_flag = 1;
  481. // Fill VAAPI parameter buffers.
  482. *vseq = (VAEncSequenceParameterBufferHEVC) {
  483. .general_profile_idc = vps->profile_tier_level.general_profile_idc,
  484. .general_level_idc = vps->profile_tier_level.general_level_idc,
  485. .general_tier_flag = vps->profile_tier_level.general_tier_flag,
  486. .intra_period = ctx->gop_size,
  487. .intra_idr_period = ctx->gop_size,
  488. .ip_period = ctx->b_per_p + 1,
  489. .bits_per_second = ctx->va_bit_rate,
  490. .pic_width_in_luma_samples = sps->pic_width_in_luma_samples,
  491. .pic_height_in_luma_samples = sps->pic_height_in_luma_samples,
  492. .seq_fields.bits = {
  493. .chroma_format_idc = sps->chroma_format_idc,
  494. .separate_colour_plane_flag = sps->separate_colour_plane_flag,
  495. .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
  496. .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
  497. .scaling_list_enabled_flag = sps->scaling_list_enabled_flag,
  498. .strong_intra_smoothing_enabled_flag =
  499. sps->strong_intra_smoothing_enabled_flag,
  500. .amp_enabled_flag = sps->amp_enabled_flag,
  501. .sample_adaptive_offset_enabled_flag =
  502. sps->sample_adaptive_offset_enabled_flag,
  503. .pcm_enabled_flag = sps->pcm_enabled_flag,
  504. .pcm_loop_filter_disabled_flag = sps->pcm_loop_filter_disabled_flag,
  505. .sps_temporal_mvp_enabled_flag = sps->sps_temporal_mvp_enabled_flag,
  506. },
  507. .log2_min_luma_coding_block_size_minus3 =
  508. sps->log2_min_luma_coding_block_size_minus3,
  509. .log2_diff_max_min_luma_coding_block_size =
  510. sps->log2_diff_max_min_luma_coding_block_size,
  511. .log2_min_transform_block_size_minus2 =
  512. sps->log2_min_luma_transform_block_size_minus2,
  513. .log2_diff_max_min_transform_block_size =
  514. sps->log2_diff_max_min_luma_transform_block_size,
  515. .max_transform_hierarchy_depth_inter =
  516. sps->max_transform_hierarchy_depth_inter,
  517. .max_transform_hierarchy_depth_intra =
  518. sps->max_transform_hierarchy_depth_intra,
  519. .pcm_sample_bit_depth_luma_minus1 =
  520. sps->pcm_sample_bit_depth_luma_minus1,
  521. .pcm_sample_bit_depth_chroma_minus1 =
  522. sps->pcm_sample_bit_depth_chroma_minus1,
  523. .log2_min_pcm_luma_coding_block_size_minus3 =
  524. sps->log2_min_pcm_luma_coding_block_size_minus3,
  525. .log2_max_pcm_luma_coding_block_size_minus3 =
  526. sps->log2_min_pcm_luma_coding_block_size_minus3 +
  527. sps->log2_diff_max_min_pcm_luma_coding_block_size,
  528. .vui_parameters_present_flag = 0,
  529. };
  530. *vpic = (VAEncPictureParameterBufferHEVC) {
  531. .decoded_curr_pic = {
  532. .picture_id = VA_INVALID_ID,
  533. .flags = VA_PICTURE_HEVC_INVALID,
  534. },
  535. .coded_buf = VA_INVALID_ID,
  536. .collocated_ref_pic_index = 0xff,
  537. .last_picture = 0,
  538. .pic_init_qp = pps->init_qp_minus26 + 26,
  539. .diff_cu_qp_delta_depth = pps->diff_cu_qp_delta_depth,
  540. .pps_cb_qp_offset = pps->pps_cb_qp_offset,
  541. .pps_cr_qp_offset = pps->pps_cr_qp_offset,
  542. .num_tile_columns_minus1 = pps->num_tile_columns_minus1,
  543. .num_tile_rows_minus1 = pps->num_tile_rows_minus1,
  544. .log2_parallel_merge_level_minus2 = pps->log2_parallel_merge_level_minus2,
  545. .ctu_max_bitsize_allowed = 0,
  546. .num_ref_idx_l0_default_active_minus1 =
  547. pps->num_ref_idx_l0_default_active_minus1,
  548. .num_ref_idx_l1_default_active_minus1 =
  549. pps->num_ref_idx_l1_default_active_minus1,
  550. .slice_pic_parameter_set_id = pps->pps_pic_parameter_set_id,
  551. .pic_fields.bits = {
  552. .sign_data_hiding_enabled_flag = pps->sign_data_hiding_enabled_flag,
  553. .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
  554. .transform_skip_enabled_flag = pps->transform_skip_enabled_flag,
  555. .cu_qp_delta_enabled_flag = pps->cu_qp_delta_enabled_flag,
  556. .weighted_pred_flag = pps->weighted_pred_flag,
  557. .weighted_bipred_flag = pps->weighted_bipred_flag,
  558. .transquant_bypass_enabled_flag = pps->transquant_bypass_enabled_flag,
  559. .tiles_enabled_flag = pps->tiles_enabled_flag,
  560. .entropy_coding_sync_enabled_flag = pps->entropy_coding_sync_enabled_flag,
  561. .loop_filter_across_tiles_enabled_flag =
  562. pps->loop_filter_across_tiles_enabled_flag,
  563. .scaling_list_data_present_flag = (sps->sps_scaling_list_data_present_flag |
  564. pps->pps_scaling_list_data_present_flag),
  565. .screen_content_flag = 0,
  566. .enable_gpu_weighted_prediction = 0,
  567. .no_output_of_prior_pics_flag = 0,
  568. },
  569. };
  570. if (pps->tiles_enabled_flag) {
  571. for (i = 0; i <= vpic->num_tile_rows_minus1; i++)
  572. vpic->row_height_minus1[i] = pps->row_height_minus1[i];
  573. for (i = 0; i <= vpic->num_tile_columns_minus1; i++)
  574. vpic->column_width_minus1[i] = pps->column_width_minus1[i];
  575. }
  576. return 0;
  577. }
  578. static int vaapi_encode_h265_init_picture_params(AVCodecContext *avctx,
  579. VAAPIEncodePicture *pic)
  580. {
  581. VAAPIEncodeContext *ctx = avctx->priv_data;
  582. VAAPIEncodeH265Context *priv = avctx->priv_data;
  583. VAAPIEncodeH265Picture *hpic = pic->priv_data;
  584. VAAPIEncodePicture *prev = pic->prev;
  585. VAAPIEncodeH265Picture *hprev = prev ? prev->priv_data : NULL;
  586. VAEncPictureParameterBufferHEVC *vpic = pic->codec_picture_params;
  587. int i;
  588. if (pic->type == PICTURE_TYPE_IDR) {
  589. av_assert0(pic->display_order == pic->encode_order);
  590. hpic->last_idr_frame = pic->display_order;
  591. hpic->slice_nal_unit = HEVC_NAL_IDR_W_RADL;
  592. hpic->slice_type = HEVC_SLICE_I;
  593. hpic->pic_type = 0;
  594. } else {
  595. av_assert0(prev);
  596. hpic->last_idr_frame = hprev->last_idr_frame;
  597. if (pic->type == PICTURE_TYPE_I) {
  598. hpic->slice_nal_unit = HEVC_NAL_CRA_NUT;
  599. hpic->slice_type = HEVC_SLICE_I;
  600. hpic->pic_type = 0;
  601. } else if (pic->type == PICTURE_TYPE_P) {
  602. av_assert0(pic->refs[0]);
  603. hpic->slice_nal_unit = HEVC_NAL_TRAIL_R;
  604. hpic->slice_type = HEVC_SLICE_P;
  605. hpic->pic_type = 1;
  606. } else {
  607. VAAPIEncodePicture *irap_ref;
  608. av_assert0(pic->refs[0] && pic->refs[1]);
  609. for (irap_ref = pic; irap_ref; irap_ref = irap_ref->refs[1]) {
  610. if (irap_ref->type == PICTURE_TYPE_I)
  611. break;
  612. }
  613. if (pic->b_depth == ctx->max_b_depth) {
  614. hpic->slice_nal_unit = irap_ref ? HEVC_NAL_RASL_N
  615. : HEVC_NAL_TRAIL_N;
  616. } else {
  617. hpic->slice_nal_unit = irap_ref ? HEVC_NAL_RASL_R
  618. : HEVC_NAL_TRAIL_R;
  619. }
  620. hpic->slice_type = HEVC_SLICE_B;
  621. hpic->pic_type = 2;
  622. }
  623. }
  624. hpic->pic_order_cnt = pic->display_order - hpic->last_idr_frame;
  625. if (priv->aud) {
  626. priv->aud_needed = 1;
  627. priv->raw_aud = (H265RawAUD) {
  628. .nal_unit_header = {
  629. .nal_unit_type = HEVC_NAL_AUD,
  630. .nuh_layer_id = 0,
  631. .nuh_temporal_id_plus1 = 1,
  632. },
  633. .pic_type = hpic->pic_type,
  634. };
  635. } else {
  636. priv->aud_needed = 0;
  637. }
  638. priv->sei_needed = 0;
  639. // Only look for the metadata on I/IDR frame on the output. We
  640. // may force an IDR frame on the output where the medadata gets
  641. // changed on the input frame.
  642. if ((priv->sei & SEI_MASTERING_DISPLAY) &&
  643. (pic->type == PICTURE_TYPE_I || pic->type == PICTURE_TYPE_IDR)) {
  644. AVFrameSideData *sd =
  645. av_frame_get_side_data(pic->input_image,
  646. AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
  647. if (sd) {
  648. AVMasteringDisplayMetadata *mdm =
  649. (AVMasteringDisplayMetadata *)sd->data;
  650. // SEI is needed when both the primaries and luminance are set
  651. if (mdm->has_primaries && mdm->has_luminance) {
  652. H265RawSEIMasteringDisplayColourVolume *mdcv =
  653. &priv->sei_mastering_display;
  654. const int mapping[3] = {1, 2, 0};
  655. const int chroma_den = 50000;
  656. const int luma_den = 10000;
  657. for (i = 0; i < 3; i++) {
  658. const int j = mapping[i];
  659. mdcv->display_primaries_x[i] =
  660. FFMIN(lrint(chroma_den *
  661. av_q2d(mdm->display_primaries[j][0])),
  662. chroma_den);
  663. mdcv->display_primaries_y[i] =
  664. FFMIN(lrint(chroma_den *
  665. av_q2d(mdm->display_primaries[j][1])),
  666. chroma_den);
  667. }
  668. mdcv->white_point_x =
  669. FFMIN(lrint(chroma_den * av_q2d(mdm->white_point[0])),
  670. chroma_den);
  671. mdcv->white_point_y =
  672. FFMIN(lrint(chroma_den * av_q2d(mdm->white_point[1])),
  673. chroma_den);
  674. mdcv->max_display_mastering_luminance =
  675. lrint(luma_den * av_q2d(mdm->max_luminance));
  676. mdcv->min_display_mastering_luminance =
  677. FFMIN(lrint(luma_den * av_q2d(mdm->min_luminance)),
  678. mdcv->max_display_mastering_luminance);
  679. priv->sei_needed |= SEI_MASTERING_DISPLAY;
  680. }
  681. }
  682. }
  683. if ((priv->sei & SEI_CONTENT_LIGHT_LEVEL) &&
  684. (pic->type == PICTURE_TYPE_I || pic->type == PICTURE_TYPE_IDR)) {
  685. AVFrameSideData *sd =
  686. av_frame_get_side_data(pic->input_image,
  687. AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
  688. if (sd) {
  689. AVContentLightMetadata *clm =
  690. (AVContentLightMetadata *)sd->data;
  691. H265RawSEIContentLightLevelInfo *clli =
  692. &priv->sei_content_light_level;
  693. clli->max_content_light_level = FFMIN(clm->MaxCLL, 65535);
  694. clli->max_pic_average_light_level = FFMIN(clm->MaxFALL, 65535);
  695. priv->sei_needed |= SEI_CONTENT_LIGHT_LEVEL;
  696. }
  697. }
  698. vpic->decoded_curr_pic = (VAPictureHEVC) {
  699. .picture_id = pic->recon_surface,
  700. .pic_order_cnt = hpic->pic_order_cnt,
  701. .flags = 0,
  702. };
  703. for (i = 0; i < pic->nb_refs; i++) {
  704. VAAPIEncodePicture *ref = pic->refs[i];
  705. VAAPIEncodeH265Picture *href;
  706. av_assert0(ref && ref->encode_order < pic->encode_order);
  707. href = ref->priv_data;
  708. vpic->reference_frames[i] = (VAPictureHEVC) {
  709. .picture_id = ref->recon_surface,
  710. .pic_order_cnt = href->pic_order_cnt,
  711. .flags = (ref->display_order < pic->display_order ?
  712. VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE : 0) |
  713. (ref->display_order > pic->display_order ?
  714. VA_PICTURE_HEVC_RPS_ST_CURR_AFTER : 0),
  715. };
  716. }
  717. for (; i < FF_ARRAY_ELEMS(vpic->reference_frames); i++) {
  718. vpic->reference_frames[i] = (VAPictureHEVC) {
  719. .picture_id = VA_INVALID_ID,
  720. .flags = VA_PICTURE_HEVC_INVALID,
  721. };
  722. }
  723. vpic->coded_buf = pic->output_buffer;
  724. vpic->nal_unit_type = hpic->slice_nal_unit;
  725. switch (pic->type) {
  726. case PICTURE_TYPE_IDR:
  727. vpic->pic_fields.bits.idr_pic_flag = 1;
  728. vpic->pic_fields.bits.coding_type = 1;
  729. vpic->pic_fields.bits.reference_pic_flag = 1;
  730. break;
  731. case PICTURE_TYPE_I:
  732. vpic->pic_fields.bits.idr_pic_flag = 0;
  733. vpic->pic_fields.bits.coding_type = 1;
  734. vpic->pic_fields.bits.reference_pic_flag = 1;
  735. break;
  736. case PICTURE_TYPE_P:
  737. vpic->pic_fields.bits.idr_pic_flag = 0;
  738. vpic->pic_fields.bits.coding_type = 2;
  739. vpic->pic_fields.bits.reference_pic_flag = 1;
  740. break;
  741. case PICTURE_TYPE_B:
  742. vpic->pic_fields.bits.idr_pic_flag = 0;
  743. vpic->pic_fields.bits.coding_type = 3;
  744. vpic->pic_fields.bits.reference_pic_flag = 0;
  745. break;
  746. default:
  747. av_assert0(0 && "invalid picture type");
  748. }
  749. return 0;
  750. }
  751. static int vaapi_encode_h265_init_slice_params(AVCodecContext *avctx,
  752. VAAPIEncodePicture *pic,
  753. VAAPIEncodeSlice *slice)
  754. {
  755. VAAPIEncodeH265Context *priv = avctx->priv_data;
  756. VAAPIEncodeH265Picture *hpic = pic->priv_data;
  757. const H265RawSPS *sps = &priv->raw_sps;
  758. const H265RawPPS *pps = &priv->raw_pps;
  759. H265RawSliceHeader *sh = &priv->raw_slice.header;
  760. VAEncPictureParameterBufferHEVC *vpic = pic->codec_picture_params;
  761. VAEncSliceParameterBufferHEVC *vslice = slice->codec_slice_params;
  762. int i;
  763. sh->nal_unit_header = (H265RawNALUnitHeader) {
  764. .nal_unit_type = hpic->slice_nal_unit,
  765. .nuh_layer_id = 0,
  766. .nuh_temporal_id_plus1 = 1,
  767. };
  768. sh->slice_pic_parameter_set_id = pps->pps_pic_parameter_set_id;
  769. sh->first_slice_segment_in_pic_flag = slice->index == 0;
  770. sh->slice_segment_address = slice->block_start;
  771. sh->slice_type = hpic->slice_type;
  772. sh->slice_pic_order_cnt_lsb = hpic->pic_order_cnt &
  773. (1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4)) - 1;
  774. if (pic->type != PICTURE_TYPE_IDR) {
  775. H265RawSTRefPicSet *rps;
  776. const VAAPIEncodeH265Picture *strp;
  777. int rps_poc[MAX_DPB_SIZE];
  778. int rps_used[MAX_DPB_SIZE];
  779. int i, j, poc, rps_pics;
  780. sh->short_term_ref_pic_set_sps_flag = 0;
  781. rps = &sh->short_term_ref_pic_set;
  782. memset(rps, 0, sizeof(*rps));
  783. rps_pics = 0;
  784. for (i = 0; i < pic->nb_refs; i++) {
  785. strp = pic->refs[i]->priv_data;
  786. rps_poc[rps_pics] = strp->pic_order_cnt;
  787. rps_used[rps_pics] = 1;
  788. ++rps_pics;
  789. }
  790. for (i = 0; i < pic->nb_dpb_pics; i++) {
  791. if (pic->dpb[i] == pic)
  792. continue;
  793. for (j = 0; j < pic->nb_refs; j++) {
  794. if (pic->dpb[i] == pic->refs[j])
  795. break;
  796. }
  797. if (j < pic->nb_refs)
  798. continue;
  799. strp = pic->dpb[i]->priv_data;
  800. rps_poc[rps_pics] = strp->pic_order_cnt;
  801. rps_used[rps_pics] = 0;
  802. ++rps_pics;
  803. }
  804. for (i = 1; i < rps_pics; i++) {
  805. for (j = i; j > 0; j--) {
  806. if (rps_poc[j] > rps_poc[j - 1])
  807. break;
  808. av_assert0(rps_poc[j] != rps_poc[j - 1]);
  809. FFSWAP(int, rps_poc[j], rps_poc[j - 1]);
  810. FFSWAP(int, rps_used[j], rps_used[j - 1]);
  811. }
  812. }
  813. av_log(avctx, AV_LOG_DEBUG, "RPS for POC %d:",
  814. hpic->pic_order_cnt);
  815. for (i = 0; i < rps_pics; i++) {
  816. av_log(avctx, AV_LOG_DEBUG, " (%d,%d)",
  817. rps_poc[i], rps_used[i]);
  818. }
  819. av_log(avctx, AV_LOG_DEBUG, "\n");
  820. for (i = 0; i < rps_pics; i++) {
  821. av_assert0(rps_poc[i] != hpic->pic_order_cnt);
  822. if (rps_poc[i] > hpic->pic_order_cnt)
  823. break;
  824. }
  825. rps->num_negative_pics = i;
  826. poc = hpic->pic_order_cnt;
  827. for (j = i - 1; j >= 0; j--) {
  828. rps->delta_poc_s0_minus1[i - 1 - j] = poc - rps_poc[j] - 1;
  829. rps->used_by_curr_pic_s0_flag[i - 1 - j] = rps_used[j];
  830. poc = rps_poc[j];
  831. }
  832. rps->num_positive_pics = rps_pics - i;
  833. poc = hpic->pic_order_cnt;
  834. for (j = i; j < rps_pics; j++) {
  835. rps->delta_poc_s1_minus1[j - i] = rps_poc[j] - poc - 1;
  836. rps->used_by_curr_pic_s1_flag[j - i] = rps_used[j];
  837. poc = rps_poc[j];
  838. }
  839. sh->num_long_term_sps = 0;
  840. sh->num_long_term_pics = 0;
  841. sh->slice_temporal_mvp_enabled_flag =
  842. sps->sps_temporal_mvp_enabled_flag;
  843. if (sh->slice_temporal_mvp_enabled_flag) {
  844. sh->collocated_from_l0_flag = sh->slice_type == HEVC_SLICE_B;
  845. sh->collocated_ref_idx = 0;
  846. }
  847. sh->num_ref_idx_active_override_flag = 0;
  848. sh->num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1;
  849. sh->num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1;
  850. }
  851. sh->slice_sao_luma_flag = sh->slice_sao_chroma_flag =
  852. sps->sample_adaptive_offset_enabled_flag;
  853. if (pic->type == PICTURE_TYPE_B)
  854. sh->slice_qp_delta = priv->fixed_qp_b - (pps->init_qp_minus26 + 26);
  855. else if (pic->type == PICTURE_TYPE_P)
  856. sh->slice_qp_delta = priv->fixed_qp_p - (pps->init_qp_minus26 + 26);
  857. else
  858. sh->slice_qp_delta = priv->fixed_qp_idr - (pps->init_qp_minus26 + 26);
  859. *vslice = (VAEncSliceParameterBufferHEVC) {
  860. .slice_segment_address = sh->slice_segment_address,
  861. .num_ctu_in_slice = slice->block_size,
  862. .slice_type = sh->slice_type,
  863. .slice_pic_parameter_set_id = sh->slice_pic_parameter_set_id,
  864. .num_ref_idx_l0_active_minus1 = sh->num_ref_idx_l0_active_minus1,
  865. .num_ref_idx_l1_active_minus1 = sh->num_ref_idx_l1_active_minus1,
  866. .luma_log2_weight_denom = sh->luma_log2_weight_denom,
  867. .delta_chroma_log2_weight_denom = sh->delta_chroma_log2_weight_denom,
  868. .max_num_merge_cand = 5 - sh->five_minus_max_num_merge_cand,
  869. .slice_qp_delta = sh->slice_qp_delta,
  870. .slice_cb_qp_offset = sh->slice_cb_qp_offset,
  871. .slice_cr_qp_offset = sh->slice_cr_qp_offset,
  872. .slice_beta_offset_div2 = sh->slice_beta_offset_div2,
  873. .slice_tc_offset_div2 = sh->slice_tc_offset_div2,
  874. .slice_fields.bits = {
  875. .last_slice_of_pic_flag = slice->index == pic->nb_slices - 1,
  876. .dependent_slice_segment_flag = sh->dependent_slice_segment_flag,
  877. .colour_plane_id = sh->colour_plane_id,
  878. .slice_temporal_mvp_enabled_flag =
  879. sh->slice_temporal_mvp_enabled_flag,
  880. .slice_sao_luma_flag = sh->slice_sao_luma_flag,
  881. .slice_sao_chroma_flag = sh->slice_sao_chroma_flag,
  882. .num_ref_idx_active_override_flag =
  883. sh->num_ref_idx_active_override_flag,
  884. .mvd_l1_zero_flag = sh->mvd_l1_zero_flag,
  885. .cabac_init_flag = sh->cabac_init_flag,
  886. .slice_deblocking_filter_disabled_flag =
  887. sh->slice_deblocking_filter_disabled_flag,
  888. .slice_loop_filter_across_slices_enabled_flag =
  889. sh->slice_loop_filter_across_slices_enabled_flag,
  890. .collocated_from_l0_flag = sh->collocated_from_l0_flag,
  891. },
  892. };
  893. for (i = 0; i < FF_ARRAY_ELEMS(vslice->ref_pic_list0); i++) {
  894. vslice->ref_pic_list0[i].picture_id = VA_INVALID_ID;
  895. vslice->ref_pic_list0[i].flags = VA_PICTURE_HEVC_INVALID;
  896. vslice->ref_pic_list1[i].picture_id = VA_INVALID_ID;
  897. vslice->ref_pic_list1[i].flags = VA_PICTURE_HEVC_INVALID;
  898. }
  899. av_assert0(pic->nb_refs <= 2);
  900. if (pic->nb_refs >= 1) {
  901. // Backward reference for P- or B-frame.
  902. av_assert0(pic->type == PICTURE_TYPE_P ||
  903. pic->type == PICTURE_TYPE_B);
  904. vslice->ref_pic_list0[0] = vpic->reference_frames[0];
  905. }
  906. if (pic->nb_refs >= 2) {
  907. // Forward reference for B-frame.
  908. av_assert0(pic->type == PICTURE_TYPE_B);
  909. vslice->ref_pic_list1[0] = vpic->reference_frames[1];
  910. }
  911. return 0;
  912. }
  913. static av_cold int vaapi_encode_h265_configure(AVCodecContext *avctx)
  914. {
  915. VAAPIEncodeContext *ctx = avctx->priv_data;
  916. VAAPIEncodeH265Context *priv = avctx->priv_data;
  917. int err;
  918. err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_HEVC, avctx);
  919. if (err < 0)
  920. return err;
  921. if (ctx->va_rc_mode == VA_RC_CQP) {
  922. // Note that VAAPI only supports positive QP values - the range is
  923. // therefore always bounded below by 1, even in 10-bit mode where
  924. // it should go down to -12.
  925. priv->fixed_qp_p = av_clip(ctx->rc_quality, 1, 51);
  926. if (avctx->i_quant_factor > 0.0)
  927. priv->fixed_qp_idr =
  928. av_clip((avctx->i_quant_factor * priv->fixed_qp_p +
  929. avctx->i_quant_offset) + 0.5, 1, 51);
  930. else
  931. priv->fixed_qp_idr = priv->fixed_qp_p;
  932. if (avctx->b_quant_factor > 0.0)
  933. priv->fixed_qp_b =
  934. av_clip((avctx->b_quant_factor * priv->fixed_qp_p +
  935. avctx->b_quant_offset) + 0.5, 1, 51);
  936. else
  937. priv->fixed_qp_b = priv->fixed_qp_p;
  938. av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
  939. "%d / %d / %d for IDR- / P- / B-frames.\n",
  940. priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
  941. } else {
  942. // These still need to be set for init_qp/slice_qp_delta.
  943. priv->fixed_qp_idr = 30;
  944. priv->fixed_qp_p = 30;
  945. priv->fixed_qp_b = 30;
  946. }
  947. ctx->roi_quant_range = 51 + 6 * (ctx->profile->depth - 8);
  948. return 0;
  949. }
  950. static const VAAPIEncodeProfile vaapi_encode_h265_profiles[] = {
  951. { FF_PROFILE_HEVC_MAIN, 8, 3, 1, 1, VAProfileHEVCMain },
  952. { FF_PROFILE_HEVC_REXT, 8, 3, 1, 1, VAProfileHEVCMain },
  953. #if VA_CHECK_VERSION(0, 37, 0)
  954. { FF_PROFILE_HEVC_MAIN_10, 10, 3, 1, 1, VAProfileHEVCMain10 },
  955. { FF_PROFILE_HEVC_REXT, 10, 3, 1, 1, VAProfileHEVCMain10 },
  956. #endif
  957. #if VA_CHECK_VERSION(1, 2, 0)
  958. { FF_PROFILE_HEVC_REXT, 8, 3, 1, 0, VAProfileHEVCMain422_10 },
  959. { FF_PROFILE_HEVC_REXT, 10, 3, 1, 0, VAProfileHEVCMain422_10 },
  960. #endif
  961. { FF_PROFILE_UNKNOWN }
  962. };
  963. static const VAAPIEncodeType vaapi_encode_type_h265 = {
  964. .profiles = vaapi_encode_h265_profiles,
  965. .flags = FLAG_SLICE_CONTROL |
  966. FLAG_B_PICTURES |
  967. FLAG_B_PICTURE_REFERENCES |
  968. FLAG_NON_IDR_KEY_PICTURES,
  969. .default_quality = 25,
  970. .configure = &vaapi_encode_h265_configure,
  971. .picture_priv_data_size = sizeof(VAAPIEncodeH265Picture),
  972. .sequence_params_size = sizeof(VAEncSequenceParameterBufferHEVC),
  973. .init_sequence_params = &vaapi_encode_h265_init_sequence_params,
  974. .picture_params_size = sizeof(VAEncPictureParameterBufferHEVC),
  975. .init_picture_params = &vaapi_encode_h265_init_picture_params,
  976. .slice_params_size = sizeof(VAEncSliceParameterBufferHEVC),
  977. .init_slice_params = &vaapi_encode_h265_init_slice_params,
  978. .sequence_header_type = VAEncPackedHeaderSequence,
  979. .write_sequence_header = &vaapi_encode_h265_write_sequence_header,
  980. .slice_header_type = VAEncPackedHeaderHEVC_Slice,
  981. .write_slice_header = &vaapi_encode_h265_write_slice_header,
  982. .write_extra_header = &vaapi_encode_h265_write_extra_header,
  983. };
  984. static av_cold int vaapi_encode_h265_init(AVCodecContext *avctx)
  985. {
  986. VAAPIEncodeContext *ctx = avctx->priv_data;
  987. VAAPIEncodeH265Context *priv = avctx->priv_data;
  988. ctx->codec = &vaapi_encode_type_h265;
  989. if (avctx->profile == FF_PROFILE_UNKNOWN)
  990. avctx->profile = priv->profile;
  991. if (avctx->level == FF_LEVEL_UNKNOWN)
  992. avctx->level = priv->level;
  993. if (avctx->level != FF_LEVEL_UNKNOWN && avctx->level & ~0xff) {
  994. av_log(avctx, AV_LOG_ERROR, "Invalid level %d: must fit "
  995. "in 8-bit unsigned integer.\n", avctx->level);
  996. return AVERROR(EINVAL);
  997. }
  998. ctx->desired_packed_headers =
  999. VA_ENC_PACKED_HEADER_SEQUENCE | // VPS, SPS and PPS.
  1000. VA_ENC_PACKED_HEADER_SLICE | // Slice headers.
  1001. VA_ENC_PACKED_HEADER_MISC; // SEI
  1002. ctx->surface_width = FFALIGN(avctx->width, 16);
  1003. ctx->surface_height = FFALIGN(avctx->height, 16);
  1004. // CTU size is currently hard-coded to 32.
  1005. ctx->slice_block_width = ctx->slice_block_height = 32;
  1006. if (priv->qp > 0)
  1007. ctx->explicit_qp = priv->qp;
  1008. return ff_vaapi_encode_init(avctx);
  1009. }
  1010. static av_cold int vaapi_encode_h265_close(AVCodecContext *avctx)
  1011. {
  1012. VAAPIEncodeH265Context *priv = avctx->priv_data;
  1013. ff_cbs_fragment_free(&priv->current_access_unit);
  1014. ff_cbs_close(&priv->cbc);
  1015. return ff_vaapi_encode_close(avctx);
  1016. }
  1017. #define OFFSET(x) offsetof(VAAPIEncodeH265Context, x)
  1018. #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
  1019. static const AVOption vaapi_encode_h265_options[] = {
  1020. VAAPI_ENCODE_COMMON_OPTIONS,
  1021. VAAPI_ENCODE_RC_OPTIONS,
  1022. { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
  1023. OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 52, FLAGS },
  1024. { "aud", "Include AUD",
  1025. OFFSET(aud), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
  1026. { "profile", "Set profile (general_profile_idc)",
  1027. OFFSET(profile), AV_OPT_TYPE_INT,
  1028. { .i64 = FF_PROFILE_UNKNOWN }, FF_PROFILE_UNKNOWN, 0xff, FLAGS, "profile" },
  1029. #define PROFILE(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
  1030. { .i64 = value }, 0, 0, FLAGS, "profile"
  1031. { PROFILE("main", FF_PROFILE_HEVC_MAIN) },
  1032. { PROFILE("main10", FF_PROFILE_HEVC_MAIN_10) },
  1033. { PROFILE("rext", FF_PROFILE_HEVC_REXT) },
  1034. #undef PROFILE
  1035. { "tier", "Set tier (general_tier_flag)",
  1036. OFFSET(tier), AV_OPT_TYPE_INT,
  1037. { .i64 = 0 }, 0, 1, FLAGS, "tier" },
  1038. { "main", NULL, 0, AV_OPT_TYPE_CONST,
  1039. { .i64 = 0 }, 0, 0, FLAGS, "tier" },
  1040. { "high", NULL, 0, AV_OPT_TYPE_CONST,
  1041. { .i64 = 1 }, 0, 0, FLAGS, "tier" },
  1042. { "level", "Set level (general_level_idc)",
  1043. OFFSET(level), AV_OPT_TYPE_INT,
  1044. { .i64 = FF_LEVEL_UNKNOWN }, FF_LEVEL_UNKNOWN, 0xff, FLAGS, "level" },
  1045. #define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
  1046. { .i64 = value }, 0, 0, FLAGS, "level"
  1047. { LEVEL("1", 30) },
  1048. { LEVEL("2", 60) },
  1049. { LEVEL("2.1", 63) },
  1050. { LEVEL("3", 90) },
  1051. { LEVEL("3.1", 93) },
  1052. { LEVEL("4", 120) },
  1053. { LEVEL("4.1", 123) },
  1054. { LEVEL("5", 150) },
  1055. { LEVEL("5.1", 153) },
  1056. { LEVEL("5.2", 156) },
  1057. { LEVEL("6", 180) },
  1058. { LEVEL("6.1", 183) },
  1059. { LEVEL("6.2", 186) },
  1060. #undef LEVEL
  1061. { "sei", "Set SEI to include",
  1062. OFFSET(sei), AV_OPT_TYPE_FLAGS,
  1063. { .i64 = SEI_MASTERING_DISPLAY | SEI_CONTENT_LIGHT_LEVEL },
  1064. 0, INT_MAX, FLAGS, "sei" },
  1065. { "hdr",
  1066. "Include HDR metadata for mastering display colour volume "
  1067. "and content light level information",
  1068. 0, AV_OPT_TYPE_CONST,
  1069. { .i64 = SEI_MASTERING_DISPLAY | SEI_CONTENT_LIGHT_LEVEL },
  1070. INT_MIN, INT_MAX, FLAGS, "sei" },
  1071. { "tiles", "Tile columns x rows",
  1072. OFFSET(common.tile_cols), AV_OPT_TYPE_IMAGE_SIZE,
  1073. { .str = NULL }, 0, 0, FLAGS },
  1074. { NULL },
  1075. };
  1076. static const AVCodecDefault vaapi_encode_h265_defaults[] = {
  1077. { "b", "0" },
  1078. { "bf", "2" },
  1079. { "g", "120" },
  1080. { "i_qfactor", "1" },
  1081. { "i_qoffset", "0" },
  1082. { "b_qfactor", "6/5" },
  1083. { "b_qoffset", "0" },
  1084. { "qmin", "-1" },
  1085. { "qmax", "-1" },
  1086. { NULL },
  1087. };
  1088. static const AVClass vaapi_encode_h265_class = {
  1089. .class_name = "h265_vaapi",
  1090. .item_name = av_default_item_name,
  1091. .option = vaapi_encode_h265_options,
  1092. .version = LIBAVUTIL_VERSION_INT,
  1093. };
  1094. AVCodec ff_hevc_vaapi_encoder = {
  1095. .name = "hevc_vaapi",
  1096. .long_name = NULL_IF_CONFIG_SMALL("H.265/HEVC (VAAPI)"),
  1097. .type = AVMEDIA_TYPE_VIDEO,
  1098. .id = AV_CODEC_ID_HEVC,
  1099. .priv_data_size = sizeof(VAAPIEncodeH265Context),
  1100. .init = &vaapi_encode_h265_init,
  1101. .receive_packet = &ff_vaapi_encode_receive_packet,
  1102. .close = &vaapi_encode_h265_close,
  1103. .priv_class = &vaapi_encode_h265_class,
  1104. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
  1105. .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
  1106. .defaults = vaapi_encode_h265_defaults,
  1107. .pix_fmts = (const enum AVPixelFormat[]) {
  1108. AV_PIX_FMT_VAAPI,
  1109. AV_PIX_FMT_NONE,
  1110. },
  1111. .hw_configs = ff_vaapi_encode_hw_configs,
  1112. .wrapper_name = "vaapi",
  1113. };