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.

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