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.

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