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.

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