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.

1350 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. if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED ||
  406. avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
  407. avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
  408. avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
  409. vui->video_signal_type_present_flag = 1;
  410. vui->video_format = 5; // Unspecified.
  411. vui->video_full_range_flag =
  412. avctx->color_range == AVCOL_RANGE_JPEG;
  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. vui->colour_primaries = avctx->color_primaries;
  418. vui->transfer_characteristics = avctx->color_trc;
  419. vui->matrix_coefficients = avctx->colorspace;
  420. }
  421. } else {
  422. vui->video_format = 5;
  423. vui->video_full_range_flag = 0;
  424. vui->colour_primaries = avctx->color_primaries;
  425. vui->transfer_characteristics = avctx->color_trc;
  426. vui->matrix_coefficients = avctx->colorspace;
  427. }
  428. if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
  429. vui->chroma_loc_info_present_flag = 1;
  430. vui->chroma_sample_loc_type_top_field =
  431. vui->chroma_sample_loc_type_bottom_field =
  432. avctx->chroma_sample_location - 1;
  433. }
  434. vui->vui_timing_info_present_flag = 1;
  435. vui->vui_num_units_in_tick = vps->vps_num_units_in_tick;
  436. vui->vui_time_scale = vps->vps_time_scale;
  437. vui->vui_poc_proportional_to_timing_flag = vps->vps_poc_proportional_to_timing_flag;
  438. vui->vui_num_ticks_poc_diff_one_minus1 = vps->vps_num_ticks_poc_diff_one_minus1;
  439. vui->vui_hrd_parameters_present_flag = 0;
  440. vui->bitstream_restriction_flag = 1;
  441. vui->motion_vectors_over_pic_boundaries_flag = 1;
  442. vui->restricted_ref_pic_lists_flag = 1;
  443. vui->max_bytes_per_pic_denom = 0;
  444. vui->max_bits_per_min_cu_denom = 0;
  445. vui->log2_max_mv_length_horizontal = 15;
  446. vui->log2_max_mv_length_vertical = 15;
  447. // PPS
  448. pps->nal_unit_header = (H265RawNALUnitHeader) {
  449. .nal_unit_type = HEVC_NAL_PPS,
  450. .nuh_layer_id = 0,
  451. .nuh_temporal_id_plus1 = 1,
  452. };
  453. pps->pps_pic_parameter_set_id = 0;
  454. pps->pps_seq_parameter_set_id = sps->sps_seq_parameter_set_id;
  455. pps->num_ref_idx_l0_default_active_minus1 = 0;
  456. pps->num_ref_idx_l1_default_active_minus1 = 0;
  457. pps->init_qp_minus26 = priv->fixed_qp_idr - 26;
  458. pps->cu_qp_delta_enabled_flag = (ctx->va_rc_mode != VA_RC_CQP);
  459. pps->diff_cu_qp_delta_depth = 0;
  460. if (ctx->tile_rows && ctx->tile_cols) {
  461. int uniform_spacing;
  462. pps->tiles_enabled_flag = 1;
  463. pps->num_tile_columns_minus1 = ctx->tile_cols - 1;
  464. pps->num_tile_rows_minus1 = ctx->tile_rows - 1;
  465. // Test whether the spacing provided matches the H.265 uniform
  466. // spacing, and set the flag if it does.
  467. uniform_spacing = 1;
  468. for (i = 0; i <= pps->num_tile_columns_minus1 &&
  469. uniform_spacing; i++) {
  470. if (ctx->col_width[i] !=
  471. (i + 1) * ctx->slice_block_cols / ctx->tile_cols -
  472. i * ctx->slice_block_cols / ctx->tile_cols)
  473. uniform_spacing = 0;
  474. }
  475. for (i = 0; i <= pps->num_tile_rows_minus1 &&
  476. uniform_spacing; i++) {
  477. if (ctx->row_height[i] !=
  478. (i + 1) * ctx->slice_block_rows / ctx->tile_rows -
  479. i * ctx->slice_block_rows / ctx->tile_rows)
  480. uniform_spacing = 0;
  481. }
  482. pps->uniform_spacing_flag = uniform_spacing;
  483. for (i = 0; i <= pps->num_tile_columns_minus1; i++)
  484. pps->column_width_minus1[i] = ctx->col_width[i] - 1;
  485. for (i = 0; i <= pps->num_tile_rows_minus1; i++)
  486. pps->row_height_minus1[i] = ctx->row_height[i] - 1;
  487. pps->loop_filter_across_tiles_enabled_flag = 1;
  488. }
  489. pps->pps_loop_filter_across_slices_enabled_flag = 1;
  490. // Fill VAAPI parameter buffers.
  491. *vseq = (VAEncSequenceParameterBufferHEVC) {
  492. .general_profile_idc = vps->profile_tier_level.general_profile_idc,
  493. .general_level_idc = vps->profile_tier_level.general_level_idc,
  494. .general_tier_flag = vps->profile_tier_level.general_tier_flag,
  495. .intra_period = ctx->gop_size,
  496. .intra_idr_period = ctx->gop_size,
  497. .ip_period = ctx->b_per_p + 1,
  498. .bits_per_second = ctx->va_bit_rate,
  499. .pic_width_in_luma_samples = sps->pic_width_in_luma_samples,
  500. .pic_height_in_luma_samples = sps->pic_height_in_luma_samples,
  501. .seq_fields.bits = {
  502. .chroma_format_idc = sps->chroma_format_idc,
  503. .separate_colour_plane_flag = sps->separate_colour_plane_flag,
  504. .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
  505. .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
  506. .scaling_list_enabled_flag = sps->scaling_list_enabled_flag,
  507. .strong_intra_smoothing_enabled_flag =
  508. sps->strong_intra_smoothing_enabled_flag,
  509. .amp_enabled_flag = sps->amp_enabled_flag,
  510. .sample_adaptive_offset_enabled_flag =
  511. sps->sample_adaptive_offset_enabled_flag,
  512. .pcm_enabled_flag = sps->pcm_enabled_flag,
  513. .pcm_loop_filter_disabled_flag = sps->pcm_loop_filter_disabled_flag,
  514. .sps_temporal_mvp_enabled_flag = sps->sps_temporal_mvp_enabled_flag,
  515. },
  516. .log2_min_luma_coding_block_size_minus3 =
  517. sps->log2_min_luma_coding_block_size_minus3,
  518. .log2_diff_max_min_luma_coding_block_size =
  519. sps->log2_diff_max_min_luma_coding_block_size,
  520. .log2_min_transform_block_size_minus2 =
  521. sps->log2_min_luma_transform_block_size_minus2,
  522. .log2_diff_max_min_transform_block_size =
  523. sps->log2_diff_max_min_luma_transform_block_size,
  524. .max_transform_hierarchy_depth_inter =
  525. sps->max_transform_hierarchy_depth_inter,
  526. .max_transform_hierarchy_depth_intra =
  527. sps->max_transform_hierarchy_depth_intra,
  528. .pcm_sample_bit_depth_luma_minus1 =
  529. sps->pcm_sample_bit_depth_luma_minus1,
  530. .pcm_sample_bit_depth_chroma_minus1 =
  531. sps->pcm_sample_bit_depth_chroma_minus1,
  532. .log2_min_pcm_luma_coding_block_size_minus3 =
  533. sps->log2_min_pcm_luma_coding_block_size_minus3,
  534. .log2_max_pcm_luma_coding_block_size_minus3 =
  535. sps->log2_min_pcm_luma_coding_block_size_minus3 +
  536. sps->log2_diff_max_min_pcm_luma_coding_block_size,
  537. .vui_parameters_present_flag = 0,
  538. };
  539. *vpic = (VAEncPictureParameterBufferHEVC) {
  540. .decoded_curr_pic = {
  541. .picture_id = VA_INVALID_ID,
  542. .flags = VA_PICTURE_HEVC_INVALID,
  543. },
  544. .coded_buf = VA_INVALID_ID,
  545. .collocated_ref_pic_index = 0xff,
  546. .last_picture = 0,
  547. .pic_init_qp = pps->init_qp_minus26 + 26,
  548. .diff_cu_qp_delta_depth = pps->diff_cu_qp_delta_depth,
  549. .pps_cb_qp_offset = pps->pps_cb_qp_offset,
  550. .pps_cr_qp_offset = pps->pps_cr_qp_offset,
  551. .num_tile_columns_minus1 = pps->num_tile_columns_minus1,
  552. .num_tile_rows_minus1 = pps->num_tile_rows_minus1,
  553. .log2_parallel_merge_level_minus2 = pps->log2_parallel_merge_level_minus2,
  554. .ctu_max_bitsize_allowed = 0,
  555. .num_ref_idx_l0_default_active_minus1 =
  556. pps->num_ref_idx_l0_default_active_minus1,
  557. .num_ref_idx_l1_default_active_minus1 =
  558. pps->num_ref_idx_l1_default_active_minus1,
  559. .slice_pic_parameter_set_id = pps->pps_pic_parameter_set_id,
  560. .pic_fields.bits = {
  561. .sign_data_hiding_enabled_flag = pps->sign_data_hiding_enabled_flag,
  562. .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
  563. .transform_skip_enabled_flag = pps->transform_skip_enabled_flag,
  564. .cu_qp_delta_enabled_flag = pps->cu_qp_delta_enabled_flag,
  565. .weighted_pred_flag = pps->weighted_pred_flag,
  566. .weighted_bipred_flag = pps->weighted_bipred_flag,
  567. .transquant_bypass_enabled_flag = pps->transquant_bypass_enabled_flag,
  568. .tiles_enabled_flag = pps->tiles_enabled_flag,
  569. .entropy_coding_sync_enabled_flag = pps->entropy_coding_sync_enabled_flag,
  570. .loop_filter_across_tiles_enabled_flag =
  571. pps->loop_filter_across_tiles_enabled_flag,
  572. .scaling_list_data_present_flag = (sps->sps_scaling_list_data_present_flag |
  573. pps->pps_scaling_list_data_present_flag),
  574. .screen_content_flag = 0,
  575. .enable_gpu_weighted_prediction = 0,
  576. .no_output_of_prior_pics_flag = 0,
  577. },
  578. };
  579. if (pps->tiles_enabled_flag) {
  580. for (i = 0; i <= vpic->num_tile_rows_minus1; i++)
  581. vpic->row_height_minus1[i] = pps->row_height_minus1[i];
  582. for (i = 0; i <= vpic->num_tile_columns_minus1; i++)
  583. vpic->column_width_minus1[i] = pps->column_width_minus1[i];
  584. }
  585. return 0;
  586. }
  587. static int vaapi_encode_h265_init_picture_params(AVCodecContext *avctx,
  588. VAAPIEncodePicture *pic)
  589. {
  590. VAAPIEncodeContext *ctx = avctx->priv_data;
  591. VAAPIEncodeH265Context *priv = avctx->priv_data;
  592. VAAPIEncodeH265Picture *hpic = pic->priv_data;
  593. VAAPIEncodePicture *prev = pic->prev;
  594. VAAPIEncodeH265Picture *hprev = prev ? prev->priv_data : NULL;
  595. VAEncPictureParameterBufferHEVC *vpic = pic->codec_picture_params;
  596. int i;
  597. if (pic->type == PICTURE_TYPE_IDR) {
  598. av_assert0(pic->display_order == pic->encode_order);
  599. hpic->last_idr_frame = pic->display_order;
  600. hpic->slice_nal_unit = HEVC_NAL_IDR_W_RADL;
  601. hpic->slice_type = HEVC_SLICE_I;
  602. hpic->pic_type = 0;
  603. } else {
  604. av_assert0(prev);
  605. hpic->last_idr_frame = hprev->last_idr_frame;
  606. if (pic->type == PICTURE_TYPE_I) {
  607. hpic->slice_nal_unit = HEVC_NAL_CRA_NUT;
  608. hpic->slice_type = HEVC_SLICE_I;
  609. hpic->pic_type = 0;
  610. } else if (pic->type == PICTURE_TYPE_P) {
  611. av_assert0(pic->refs[0]);
  612. hpic->slice_nal_unit = HEVC_NAL_TRAIL_R;
  613. hpic->slice_type = HEVC_SLICE_P;
  614. hpic->pic_type = 1;
  615. } else {
  616. VAAPIEncodePicture *irap_ref;
  617. av_assert0(pic->refs[0] && pic->refs[1]);
  618. for (irap_ref = pic; irap_ref; irap_ref = irap_ref->refs[1]) {
  619. if (irap_ref->type == PICTURE_TYPE_I)
  620. break;
  621. }
  622. if (pic->b_depth == ctx->max_b_depth) {
  623. hpic->slice_nal_unit = irap_ref ? HEVC_NAL_RASL_N
  624. : HEVC_NAL_TRAIL_N;
  625. } else {
  626. hpic->slice_nal_unit = irap_ref ? HEVC_NAL_RASL_R
  627. : HEVC_NAL_TRAIL_R;
  628. }
  629. hpic->slice_type = HEVC_SLICE_B;
  630. hpic->pic_type = 2;
  631. }
  632. }
  633. hpic->pic_order_cnt = pic->display_order - hpic->last_idr_frame;
  634. if (priv->aud) {
  635. priv->aud_needed = 1;
  636. priv->raw_aud = (H265RawAUD) {
  637. .nal_unit_header = {
  638. .nal_unit_type = HEVC_NAL_AUD,
  639. .nuh_layer_id = 0,
  640. .nuh_temporal_id_plus1 = 1,
  641. },
  642. .pic_type = hpic->pic_type,
  643. };
  644. } else {
  645. priv->aud_needed = 0;
  646. }
  647. priv->sei_needed = 0;
  648. // Only look for the metadata on I/IDR frame on the output. We
  649. // may force an IDR frame on the output where the medadata gets
  650. // changed on the input frame.
  651. if ((priv->sei & SEI_MASTERING_DISPLAY) &&
  652. (pic->type == PICTURE_TYPE_I || pic->type == PICTURE_TYPE_IDR)) {
  653. AVFrameSideData *sd =
  654. av_frame_get_side_data(pic->input_image,
  655. AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
  656. if (sd) {
  657. AVMasteringDisplayMetadata *mdm =
  658. (AVMasteringDisplayMetadata *)sd->data;
  659. // SEI is needed when both the primaries and luminance are set
  660. if (mdm->has_primaries && mdm->has_luminance) {
  661. H265RawSEIMasteringDisplayColourVolume *mdcv =
  662. &priv->sei_mastering_display;
  663. const int mapping[3] = {1, 2, 0};
  664. const int chroma_den = 50000;
  665. const int luma_den = 10000;
  666. for (i = 0; i < 3; i++) {
  667. const int j = mapping[i];
  668. mdcv->display_primaries_x[i] =
  669. FFMIN(lrint(chroma_den *
  670. av_q2d(mdm->display_primaries[j][0])),
  671. chroma_den);
  672. mdcv->display_primaries_y[i] =
  673. FFMIN(lrint(chroma_den *
  674. av_q2d(mdm->display_primaries[j][1])),
  675. chroma_den);
  676. }
  677. mdcv->white_point_x =
  678. FFMIN(lrint(chroma_den * av_q2d(mdm->white_point[0])),
  679. chroma_den);
  680. mdcv->white_point_y =
  681. FFMIN(lrint(chroma_den * av_q2d(mdm->white_point[1])),
  682. chroma_den);
  683. mdcv->max_display_mastering_luminance =
  684. lrint(luma_den * av_q2d(mdm->max_luminance));
  685. mdcv->min_display_mastering_luminance =
  686. FFMIN(lrint(luma_den * av_q2d(mdm->min_luminance)),
  687. mdcv->max_display_mastering_luminance);
  688. priv->sei_needed |= SEI_MASTERING_DISPLAY;
  689. }
  690. }
  691. }
  692. if ((priv->sei & SEI_CONTENT_LIGHT_LEVEL) &&
  693. (pic->type == PICTURE_TYPE_I || pic->type == PICTURE_TYPE_IDR)) {
  694. AVFrameSideData *sd =
  695. av_frame_get_side_data(pic->input_image,
  696. AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
  697. if (sd) {
  698. AVContentLightMetadata *clm =
  699. (AVContentLightMetadata *)sd->data;
  700. H265RawSEIContentLightLevelInfo *clli =
  701. &priv->sei_content_light_level;
  702. clli->max_content_light_level = FFMIN(clm->MaxCLL, 65535);
  703. clli->max_pic_average_light_level = FFMIN(clm->MaxFALL, 65535);
  704. priv->sei_needed |= SEI_CONTENT_LIGHT_LEVEL;
  705. }
  706. }
  707. vpic->decoded_curr_pic = (VAPictureHEVC) {
  708. .picture_id = pic->recon_surface,
  709. .pic_order_cnt = hpic->pic_order_cnt,
  710. .flags = 0,
  711. };
  712. for (i = 0; i < pic->nb_refs; i++) {
  713. VAAPIEncodePicture *ref = pic->refs[i];
  714. VAAPIEncodeH265Picture *href;
  715. av_assert0(ref && ref->encode_order < pic->encode_order);
  716. href = ref->priv_data;
  717. vpic->reference_frames[i] = (VAPictureHEVC) {
  718. .picture_id = ref->recon_surface,
  719. .pic_order_cnt = href->pic_order_cnt,
  720. .flags = (ref->display_order < pic->display_order ?
  721. VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE : 0) |
  722. (ref->display_order > pic->display_order ?
  723. VA_PICTURE_HEVC_RPS_ST_CURR_AFTER : 0),
  724. };
  725. }
  726. for (; i < FF_ARRAY_ELEMS(vpic->reference_frames); i++) {
  727. vpic->reference_frames[i] = (VAPictureHEVC) {
  728. .picture_id = VA_INVALID_ID,
  729. .flags = VA_PICTURE_HEVC_INVALID,
  730. };
  731. }
  732. vpic->coded_buf = pic->output_buffer;
  733. vpic->nal_unit_type = hpic->slice_nal_unit;
  734. switch (pic->type) {
  735. case PICTURE_TYPE_IDR:
  736. vpic->pic_fields.bits.idr_pic_flag = 1;
  737. vpic->pic_fields.bits.coding_type = 1;
  738. vpic->pic_fields.bits.reference_pic_flag = 1;
  739. break;
  740. case PICTURE_TYPE_I:
  741. vpic->pic_fields.bits.idr_pic_flag = 0;
  742. vpic->pic_fields.bits.coding_type = 1;
  743. vpic->pic_fields.bits.reference_pic_flag = 1;
  744. break;
  745. case PICTURE_TYPE_P:
  746. vpic->pic_fields.bits.idr_pic_flag = 0;
  747. vpic->pic_fields.bits.coding_type = 2;
  748. vpic->pic_fields.bits.reference_pic_flag = 1;
  749. break;
  750. case PICTURE_TYPE_B:
  751. vpic->pic_fields.bits.idr_pic_flag = 0;
  752. vpic->pic_fields.bits.coding_type = 3;
  753. vpic->pic_fields.bits.reference_pic_flag = 0;
  754. break;
  755. default:
  756. av_assert0(0 && "invalid picture type");
  757. }
  758. return 0;
  759. }
  760. static int vaapi_encode_h265_init_slice_params(AVCodecContext *avctx,
  761. VAAPIEncodePicture *pic,
  762. VAAPIEncodeSlice *slice)
  763. {
  764. VAAPIEncodeH265Context *priv = avctx->priv_data;
  765. VAAPIEncodeH265Picture *hpic = pic->priv_data;
  766. const H265RawSPS *sps = &priv->raw_sps;
  767. const H265RawPPS *pps = &priv->raw_pps;
  768. H265RawSliceHeader *sh = &priv->raw_slice.header;
  769. VAEncPictureParameterBufferHEVC *vpic = pic->codec_picture_params;
  770. VAEncSliceParameterBufferHEVC *vslice = slice->codec_slice_params;
  771. int i;
  772. sh->nal_unit_header = (H265RawNALUnitHeader) {
  773. .nal_unit_type = hpic->slice_nal_unit,
  774. .nuh_layer_id = 0,
  775. .nuh_temporal_id_plus1 = 1,
  776. };
  777. sh->slice_pic_parameter_set_id = pps->pps_pic_parameter_set_id;
  778. sh->first_slice_segment_in_pic_flag = slice->index == 0;
  779. sh->slice_segment_address = slice->block_start;
  780. sh->slice_type = hpic->slice_type;
  781. sh->slice_pic_order_cnt_lsb = hpic->pic_order_cnt &
  782. (1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4)) - 1;
  783. if (pic->type != PICTURE_TYPE_IDR) {
  784. H265RawSTRefPicSet *rps;
  785. const VAAPIEncodeH265Picture *strp;
  786. int rps_poc[MAX_DPB_SIZE];
  787. int rps_used[MAX_DPB_SIZE];
  788. int i, j, poc, rps_pics;
  789. sh->short_term_ref_pic_set_sps_flag = 0;
  790. rps = &sh->short_term_ref_pic_set;
  791. memset(rps, 0, sizeof(*rps));
  792. rps_pics = 0;
  793. for (i = 0; i < pic->nb_refs; i++) {
  794. strp = pic->refs[i]->priv_data;
  795. rps_poc[rps_pics] = strp->pic_order_cnt;
  796. rps_used[rps_pics] = 1;
  797. ++rps_pics;
  798. }
  799. for (i = 0; i < pic->nb_dpb_pics; i++) {
  800. if (pic->dpb[i] == pic)
  801. continue;
  802. for (j = 0; j < pic->nb_refs; j++) {
  803. if (pic->dpb[i] == pic->refs[j])
  804. break;
  805. }
  806. if (j < pic->nb_refs)
  807. continue;
  808. strp = pic->dpb[i]->priv_data;
  809. rps_poc[rps_pics] = strp->pic_order_cnt;
  810. rps_used[rps_pics] = 0;
  811. ++rps_pics;
  812. }
  813. for (i = 1; i < rps_pics; i++) {
  814. for (j = i; j > 0; j--) {
  815. if (rps_poc[j] > rps_poc[j - 1])
  816. break;
  817. av_assert0(rps_poc[j] != rps_poc[j - 1]);
  818. FFSWAP(int, rps_poc[j], rps_poc[j - 1]);
  819. FFSWAP(int, rps_used[j], rps_used[j - 1]);
  820. }
  821. }
  822. av_log(avctx, AV_LOG_DEBUG, "RPS for POC %d:",
  823. hpic->pic_order_cnt);
  824. for (i = 0; i < rps_pics; i++) {
  825. av_log(avctx, AV_LOG_DEBUG, " (%d,%d)",
  826. rps_poc[i], rps_used[i]);
  827. }
  828. av_log(avctx, AV_LOG_DEBUG, "\n");
  829. for (i = 0; i < rps_pics; i++) {
  830. av_assert0(rps_poc[i] != hpic->pic_order_cnt);
  831. if (rps_poc[i] > hpic->pic_order_cnt)
  832. break;
  833. }
  834. rps->num_negative_pics = i;
  835. poc = hpic->pic_order_cnt;
  836. for (j = i - 1; j >= 0; j--) {
  837. rps->delta_poc_s0_minus1[i - 1 - j] = poc - rps_poc[j] - 1;
  838. rps->used_by_curr_pic_s0_flag[i - 1 - j] = rps_used[j];
  839. poc = rps_poc[j];
  840. }
  841. rps->num_positive_pics = rps_pics - i;
  842. poc = hpic->pic_order_cnt;
  843. for (j = i; j < rps_pics; j++) {
  844. rps->delta_poc_s1_minus1[j - i] = rps_poc[j] - poc - 1;
  845. rps->used_by_curr_pic_s1_flag[j - i] = rps_used[j];
  846. poc = rps_poc[j];
  847. }
  848. sh->num_long_term_sps = 0;
  849. sh->num_long_term_pics = 0;
  850. sh->slice_temporal_mvp_enabled_flag =
  851. sps->sps_temporal_mvp_enabled_flag;
  852. if (sh->slice_temporal_mvp_enabled_flag) {
  853. sh->collocated_from_l0_flag = sh->slice_type == HEVC_SLICE_B;
  854. sh->collocated_ref_idx = 0;
  855. }
  856. sh->num_ref_idx_active_override_flag = 0;
  857. sh->num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1;
  858. sh->num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1;
  859. }
  860. sh->slice_sao_luma_flag = sh->slice_sao_chroma_flag =
  861. sps->sample_adaptive_offset_enabled_flag;
  862. if (pic->type == PICTURE_TYPE_B)
  863. sh->slice_qp_delta = priv->fixed_qp_b - (pps->init_qp_minus26 + 26);
  864. else if (pic->type == PICTURE_TYPE_P)
  865. sh->slice_qp_delta = priv->fixed_qp_p - (pps->init_qp_minus26 + 26);
  866. else
  867. sh->slice_qp_delta = priv->fixed_qp_idr - (pps->init_qp_minus26 + 26);
  868. *vslice = (VAEncSliceParameterBufferHEVC) {
  869. .slice_segment_address = sh->slice_segment_address,
  870. .num_ctu_in_slice = slice->block_size,
  871. .slice_type = sh->slice_type,
  872. .slice_pic_parameter_set_id = sh->slice_pic_parameter_set_id,
  873. .num_ref_idx_l0_active_minus1 = sh->num_ref_idx_l0_active_minus1,
  874. .num_ref_idx_l1_active_minus1 = sh->num_ref_idx_l1_active_minus1,
  875. .luma_log2_weight_denom = sh->luma_log2_weight_denom,
  876. .delta_chroma_log2_weight_denom = sh->delta_chroma_log2_weight_denom,
  877. .max_num_merge_cand = 5 - sh->five_minus_max_num_merge_cand,
  878. .slice_qp_delta = sh->slice_qp_delta,
  879. .slice_cb_qp_offset = sh->slice_cb_qp_offset,
  880. .slice_cr_qp_offset = sh->slice_cr_qp_offset,
  881. .slice_beta_offset_div2 = sh->slice_beta_offset_div2,
  882. .slice_tc_offset_div2 = sh->slice_tc_offset_div2,
  883. .slice_fields.bits = {
  884. .last_slice_of_pic_flag = slice->index == pic->nb_slices - 1,
  885. .dependent_slice_segment_flag = sh->dependent_slice_segment_flag,
  886. .colour_plane_id = sh->colour_plane_id,
  887. .slice_temporal_mvp_enabled_flag =
  888. sh->slice_temporal_mvp_enabled_flag,
  889. .slice_sao_luma_flag = sh->slice_sao_luma_flag,
  890. .slice_sao_chroma_flag = sh->slice_sao_chroma_flag,
  891. .num_ref_idx_active_override_flag =
  892. sh->num_ref_idx_active_override_flag,
  893. .mvd_l1_zero_flag = sh->mvd_l1_zero_flag,
  894. .cabac_init_flag = sh->cabac_init_flag,
  895. .slice_deblocking_filter_disabled_flag =
  896. sh->slice_deblocking_filter_disabled_flag,
  897. .slice_loop_filter_across_slices_enabled_flag =
  898. sh->slice_loop_filter_across_slices_enabled_flag,
  899. .collocated_from_l0_flag = sh->collocated_from_l0_flag,
  900. },
  901. };
  902. for (i = 0; i < FF_ARRAY_ELEMS(vslice->ref_pic_list0); i++) {
  903. vslice->ref_pic_list0[i].picture_id = VA_INVALID_ID;
  904. vslice->ref_pic_list0[i].flags = VA_PICTURE_HEVC_INVALID;
  905. vslice->ref_pic_list1[i].picture_id = VA_INVALID_ID;
  906. vslice->ref_pic_list1[i].flags = VA_PICTURE_HEVC_INVALID;
  907. }
  908. av_assert0(pic->nb_refs <= 2);
  909. if (pic->nb_refs >= 1) {
  910. // Backward reference for P- or B-frame.
  911. av_assert0(pic->type == PICTURE_TYPE_P ||
  912. pic->type == PICTURE_TYPE_B);
  913. vslice->ref_pic_list0[0] = vpic->reference_frames[0];
  914. }
  915. if (pic->nb_refs >= 2) {
  916. // Forward reference for B-frame.
  917. av_assert0(pic->type == PICTURE_TYPE_B);
  918. vslice->ref_pic_list1[0] = vpic->reference_frames[1];
  919. }
  920. return 0;
  921. }
  922. static av_cold int vaapi_encode_h265_configure(AVCodecContext *avctx)
  923. {
  924. VAAPIEncodeContext *ctx = avctx->priv_data;
  925. VAAPIEncodeH265Context *priv = avctx->priv_data;
  926. int err;
  927. err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_HEVC, avctx);
  928. if (err < 0)
  929. return err;
  930. if (ctx->va_rc_mode == VA_RC_CQP) {
  931. // Note that VAAPI only supports positive QP values - the range is
  932. // therefore always bounded below by 1, even in 10-bit mode where
  933. // it should go down to -12.
  934. priv->fixed_qp_p = av_clip(ctx->rc_quality, 1, 51);
  935. if (avctx->i_quant_factor > 0.0)
  936. priv->fixed_qp_idr =
  937. av_clip((avctx->i_quant_factor * priv->fixed_qp_p +
  938. avctx->i_quant_offset) + 0.5, 1, 51);
  939. else
  940. priv->fixed_qp_idr = priv->fixed_qp_p;
  941. if (avctx->b_quant_factor > 0.0)
  942. priv->fixed_qp_b =
  943. av_clip((avctx->b_quant_factor * priv->fixed_qp_p +
  944. avctx->b_quant_offset) + 0.5, 1, 51);
  945. else
  946. priv->fixed_qp_b = priv->fixed_qp_p;
  947. av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
  948. "%d / %d / %d for IDR- / P- / B-frames.\n",
  949. priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
  950. } else {
  951. // These still need to be set for init_qp/slice_qp_delta.
  952. priv->fixed_qp_idr = 30;
  953. priv->fixed_qp_p = 30;
  954. priv->fixed_qp_b = 30;
  955. }
  956. ctx->roi_quant_range = 51 + 6 * (ctx->profile->depth - 8);
  957. return 0;
  958. }
  959. static const VAAPIEncodeProfile vaapi_encode_h265_profiles[] = {
  960. { FF_PROFILE_HEVC_MAIN, 8, 3, 1, 1, VAProfileHEVCMain },
  961. { FF_PROFILE_HEVC_REXT, 8, 3, 1, 1, VAProfileHEVCMain },
  962. #if VA_CHECK_VERSION(0, 37, 0)
  963. { FF_PROFILE_HEVC_MAIN_10, 10, 3, 1, 1, VAProfileHEVCMain10 },
  964. { FF_PROFILE_HEVC_REXT, 10, 3, 1, 1, VAProfileHEVCMain10 },
  965. #endif
  966. #if VA_CHECK_VERSION(1, 2, 0)
  967. { FF_PROFILE_HEVC_REXT, 8, 3, 1, 0, VAProfileHEVCMain422_10 },
  968. { FF_PROFILE_HEVC_REXT, 10, 3, 1, 0, VAProfileHEVCMain422_10 },
  969. #endif
  970. { FF_PROFILE_UNKNOWN }
  971. };
  972. static const VAAPIEncodeType vaapi_encode_type_h265 = {
  973. .profiles = vaapi_encode_h265_profiles,
  974. .flags = FLAG_SLICE_CONTROL |
  975. FLAG_B_PICTURES |
  976. FLAG_B_PICTURE_REFERENCES |
  977. FLAG_NON_IDR_KEY_PICTURES,
  978. .default_quality = 25,
  979. .configure = &vaapi_encode_h265_configure,
  980. .picture_priv_data_size = sizeof(VAAPIEncodeH265Picture),
  981. .sequence_params_size = sizeof(VAEncSequenceParameterBufferHEVC),
  982. .init_sequence_params = &vaapi_encode_h265_init_sequence_params,
  983. .picture_params_size = sizeof(VAEncPictureParameterBufferHEVC),
  984. .init_picture_params = &vaapi_encode_h265_init_picture_params,
  985. .slice_params_size = sizeof(VAEncSliceParameterBufferHEVC),
  986. .init_slice_params = &vaapi_encode_h265_init_slice_params,
  987. .sequence_header_type = VAEncPackedHeaderSequence,
  988. .write_sequence_header = &vaapi_encode_h265_write_sequence_header,
  989. .slice_header_type = VAEncPackedHeaderHEVC_Slice,
  990. .write_slice_header = &vaapi_encode_h265_write_slice_header,
  991. .write_extra_header = &vaapi_encode_h265_write_extra_header,
  992. };
  993. static av_cold int vaapi_encode_h265_init(AVCodecContext *avctx)
  994. {
  995. VAAPIEncodeContext *ctx = avctx->priv_data;
  996. VAAPIEncodeH265Context *priv = avctx->priv_data;
  997. ctx->codec = &vaapi_encode_type_h265;
  998. if (avctx->profile == FF_PROFILE_UNKNOWN)
  999. avctx->profile = priv->profile;
  1000. if (avctx->level == FF_LEVEL_UNKNOWN)
  1001. avctx->level = priv->level;
  1002. if (avctx->level != FF_LEVEL_UNKNOWN && avctx->level & ~0xff) {
  1003. av_log(avctx, AV_LOG_ERROR, "Invalid level %d: must fit "
  1004. "in 8-bit unsigned integer.\n", avctx->level);
  1005. return AVERROR(EINVAL);
  1006. }
  1007. ctx->desired_packed_headers =
  1008. VA_ENC_PACKED_HEADER_SEQUENCE | // VPS, SPS and PPS.
  1009. VA_ENC_PACKED_HEADER_SLICE | // Slice headers.
  1010. VA_ENC_PACKED_HEADER_MISC; // SEI
  1011. ctx->surface_width = FFALIGN(avctx->width, 16);
  1012. ctx->surface_height = FFALIGN(avctx->height, 16);
  1013. // CTU size is currently hard-coded to 32.
  1014. ctx->slice_block_width = ctx->slice_block_height = 32;
  1015. if (priv->qp > 0)
  1016. ctx->explicit_qp = priv->qp;
  1017. return ff_vaapi_encode_init(avctx);
  1018. }
  1019. static av_cold int vaapi_encode_h265_close(AVCodecContext *avctx)
  1020. {
  1021. VAAPIEncodeH265Context *priv = avctx->priv_data;
  1022. ff_cbs_fragment_free(&priv->current_access_unit);
  1023. ff_cbs_close(&priv->cbc);
  1024. return ff_vaapi_encode_close(avctx);
  1025. }
  1026. #define OFFSET(x) offsetof(VAAPIEncodeH265Context, x)
  1027. #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
  1028. static const AVOption vaapi_encode_h265_options[] = {
  1029. VAAPI_ENCODE_COMMON_OPTIONS,
  1030. VAAPI_ENCODE_RC_OPTIONS,
  1031. { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
  1032. OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 52, FLAGS },
  1033. { "aud", "Include AUD",
  1034. OFFSET(aud), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
  1035. { "profile", "Set profile (general_profile_idc)",
  1036. OFFSET(profile), AV_OPT_TYPE_INT,
  1037. { .i64 = FF_PROFILE_UNKNOWN }, FF_PROFILE_UNKNOWN, 0xff, FLAGS, "profile" },
  1038. #define PROFILE(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
  1039. { .i64 = value }, 0, 0, FLAGS, "profile"
  1040. { PROFILE("main", FF_PROFILE_HEVC_MAIN) },
  1041. { PROFILE("main10", FF_PROFILE_HEVC_MAIN_10) },
  1042. { PROFILE("rext", FF_PROFILE_HEVC_REXT) },
  1043. #undef PROFILE
  1044. { "tier", "Set tier (general_tier_flag)",
  1045. OFFSET(tier), AV_OPT_TYPE_INT,
  1046. { .i64 = 0 }, 0, 1, FLAGS, "tier" },
  1047. { "main", NULL, 0, AV_OPT_TYPE_CONST,
  1048. { .i64 = 0 }, 0, 0, FLAGS, "tier" },
  1049. { "high", NULL, 0, AV_OPT_TYPE_CONST,
  1050. { .i64 = 1 }, 0, 0, FLAGS, "tier" },
  1051. { "level", "Set level (general_level_idc)",
  1052. OFFSET(level), AV_OPT_TYPE_INT,
  1053. { .i64 = FF_LEVEL_UNKNOWN }, FF_LEVEL_UNKNOWN, 0xff, FLAGS, "level" },
  1054. #define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
  1055. { .i64 = value }, 0, 0, FLAGS, "level"
  1056. { LEVEL("1", 30) },
  1057. { LEVEL("2", 60) },
  1058. { LEVEL("2.1", 63) },
  1059. { LEVEL("3", 90) },
  1060. { LEVEL("3.1", 93) },
  1061. { LEVEL("4", 120) },
  1062. { LEVEL("4.1", 123) },
  1063. { LEVEL("5", 150) },
  1064. { LEVEL("5.1", 153) },
  1065. { LEVEL("5.2", 156) },
  1066. { LEVEL("6", 180) },
  1067. { LEVEL("6.1", 183) },
  1068. { LEVEL("6.2", 186) },
  1069. #undef LEVEL
  1070. { "sei", "Set SEI to include",
  1071. OFFSET(sei), AV_OPT_TYPE_FLAGS,
  1072. { .i64 = SEI_MASTERING_DISPLAY | SEI_CONTENT_LIGHT_LEVEL },
  1073. 0, INT_MAX, FLAGS, "sei" },
  1074. { "hdr",
  1075. "Include HDR metadata for mastering display colour volume "
  1076. "and content light level information",
  1077. 0, AV_OPT_TYPE_CONST,
  1078. { .i64 = SEI_MASTERING_DISPLAY | SEI_CONTENT_LIGHT_LEVEL },
  1079. INT_MIN, INT_MAX, FLAGS, "sei" },
  1080. { "tiles", "Tile columns x rows",
  1081. OFFSET(common.tile_cols), AV_OPT_TYPE_IMAGE_SIZE,
  1082. { .str = NULL }, 0, 0, FLAGS },
  1083. { NULL },
  1084. };
  1085. static const AVCodecDefault vaapi_encode_h265_defaults[] = {
  1086. { "b", "0" },
  1087. { "bf", "2" },
  1088. { "g", "120" },
  1089. { "i_qfactor", "1" },
  1090. { "i_qoffset", "0" },
  1091. { "b_qfactor", "6/5" },
  1092. { "b_qoffset", "0" },
  1093. { "qmin", "-1" },
  1094. { "qmax", "-1" },
  1095. { NULL },
  1096. };
  1097. static const AVClass vaapi_encode_h265_class = {
  1098. .class_name = "h265_vaapi",
  1099. .item_name = av_default_item_name,
  1100. .option = vaapi_encode_h265_options,
  1101. .version = LIBAVUTIL_VERSION_INT,
  1102. };
  1103. AVCodec ff_hevc_vaapi_encoder = {
  1104. .name = "hevc_vaapi",
  1105. .long_name = NULL_IF_CONFIG_SMALL("H.265/HEVC (VAAPI)"),
  1106. .type = AVMEDIA_TYPE_VIDEO,
  1107. .id = AV_CODEC_ID_HEVC,
  1108. .priv_data_size = sizeof(VAAPIEncodeH265Context),
  1109. .init = &vaapi_encode_h265_init,
  1110. .receive_packet = &ff_vaapi_encode_receive_packet,
  1111. .close = &vaapi_encode_h265_close,
  1112. .priv_class = &vaapi_encode_h265_class,
  1113. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
  1114. .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
  1115. .defaults = vaapi_encode_h265_defaults,
  1116. .pix_fmts = (const enum AVPixelFormat[]) {
  1117. AV_PIX_FMT_VAAPI,
  1118. AV_PIX_FMT_NONE,
  1119. },
  1120. .hw_configs = ff_vaapi_encode_hw_configs,
  1121. .wrapper_name = "vaapi",
  1122. };