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

1350 lines
48KB

  1. /*
  2. * This file is part of FFmpeg.
  3. *
  4. * FFmpeg is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * FFmpeg is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with FFmpeg; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include <string.h>
  19. #include <va/va.h>
  20. #include <va/va_enc_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_reset(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_reset(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_reset(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_reset(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(sps, 0, sizeof(*sps));
  250. memset(pps, 0, sizeof(*pps));
  251. sps->nal_unit_header.nal_ref_idc = 3;
  252. sps->nal_unit_header.nal_unit_type = H264_NAL_SPS;
  253. sps->profile_idc = avctx->profile & 0xff;
  254. if (avctx->profile == FF_PROFILE_H264_CONSTRAINED_BASELINE ||
  255. avctx->profile == FF_PROFILE_H264_MAIN)
  256. sps->constraint_set1_flag = 1;
  257. if (avctx->profile == FF_PROFILE_H264_HIGH)
  258. sps->constraint_set3_flag = ctx->gop_size == 1;
  259. if (avctx->profile == FF_PROFILE_H264_MAIN ||
  260. avctx->profile == FF_PROFILE_H264_HIGH) {
  261. sps->constraint_set4_flag = 1;
  262. sps->constraint_set5_flag = ctx->b_per_p == 0;
  263. }
  264. if (ctx->gop_size == 1)
  265. priv->dpb_frames = 0;
  266. else
  267. priv->dpb_frames = 1 + ctx->max_b_depth;
  268. if (avctx->level != FF_LEVEL_UNKNOWN) {
  269. sps->level_idc = avctx->level;
  270. } else {
  271. const H264LevelDescriptor *level;
  272. level = ff_h264_guess_level(sps->profile_idc,
  273. avctx->bit_rate,
  274. priv->mb_width * 16,
  275. priv->mb_height * 16,
  276. priv->dpb_frames);
  277. if (level) {
  278. av_log(avctx, AV_LOG_VERBOSE, "Using level %s.\n", level->name);
  279. if (level->constraint_set3_flag)
  280. sps->constraint_set3_flag = 1;
  281. sps->level_idc = level->level_idc;
  282. } else {
  283. av_log(avctx, AV_LOG_WARNING, "Stream will not conform "
  284. "to any level: using level 6.2.\n");
  285. sps->level_idc = 62;
  286. }
  287. }
  288. sps->seq_parameter_set_id = 0;
  289. sps->chroma_format_idc = 1;
  290. sps->log2_max_frame_num_minus4 = 4;
  291. sps->pic_order_cnt_type = 0;
  292. sps->log2_max_pic_order_cnt_lsb_minus4 = 4;
  293. sps->max_num_ref_frames = priv->dpb_frames;
  294. sps->pic_width_in_mbs_minus1 = priv->mb_width - 1;
  295. sps->pic_height_in_map_units_minus1 = priv->mb_height - 1;
  296. sps->frame_mbs_only_flag = 1;
  297. sps->direct_8x8_inference_flag = 1;
  298. if (avctx->width != 16 * priv->mb_width ||
  299. avctx->height != 16 * priv->mb_height) {
  300. sps->frame_cropping_flag = 1;
  301. sps->frame_crop_left_offset = 0;
  302. sps->frame_crop_right_offset =
  303. (16 * priv->mb_width - avctx->width) / 2;
  304. sps->frame_crop_top_offset = 0;
  305. sps->frame_crop_bottom_offset =
  306. (16 * priv->mb_height - avctx->height) / 2;
  307. } else {
  308. sps->frame_cropping_flag = 0;
  309. }
  310. sps->vui_parameters_present_flag = 1;
  311. if (avctx->sample_aspect_ratio.num != 0 &&
  312. avctx->sample_aspect_ratio.den != 0) {
  313. static const AVRational sar_idc[] = {
  314. { 0, 0 },
  315. { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 },
  316. { 40, 33 }, { 24, 11 }, { 20, 11 }, { 32, 11 },
  317. { 80, 33 }, { 18, 11 }, { 15, 11 }, { 64, 33 },
  318. { 160, 99 }, { 4, 3 }, { 3, 2 }, { 2, 1 },
  319. };
  320. int num, den, i;
  321. av_reduce(&num, &den, avctx->sample_aspect_ratio.num,
  322. avctx->sample_aspect_ratio.den, 65535);
  323. for (i = 0; i < FF_ARRAY_ELEMS(sar_idc); i++) {
  324. if (num == sar_idc[i].num &&
  325. den == sar_idc[i].den) {
  326. sps->vui.aspect_ratio_idc = i;
  327. break;
  328. }
  329. }
  330. if (i >= FF_ARRAY_ELEMS(sar_idc)) {
  331. sps->vui.aspect_ratio_idc = 255;
  332. sps->vui.sar_width = num;
  333. sps->vui.sar_height = den;
  334. }
  335. sps->vui.aspect_ratio_info_present_flag = 1;
  336. }
  337. if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED ||
  338. avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
  339. avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
  340. avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
  341. sps->vui.video_signal_type_present_flag = 1;
  342. sps->vui.video_format = 5; // Unspecified.
  343. sps->vui.video_full_range_flag =
  344. avctx->color_range == AVCOL_RANGE_JPEG;
  345. if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
  346. avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
  347. avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
  348. sps->vui.colour_description_present_flag = 1;
  349. sps->vui.colour_primaries = avctx->color_primaries;
  350. sps->vui.transfer_characteristics = avctx->color_trc;
  351. sps->vui.matrix_coefficients = avctx->colorspace;
  352. }
  353. } else {
  354. sps->vui.video_format = 5;
  355. sps->vui.video_full_range_flag = 0;
  356. sps->vui.colour_primaries = avctx->color_primaries;
  357. sps->vui.transfer_characteristics = avctx->color_trc;
  358. sps->vui.matrix_coefficients = avctx->colorspace;
  359. }
  360. if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
  361. sps->vui.chroma_loc_info_present_flag = 1;
  362. sps->vui.chroma_sample_loc_type_top_field =
  363. sps->vui.chroma_sample_loc_type_bottom_field =
  364. avctx->chroma_sample_location - 1;
  365. }
  366. sps->vui.timing_info_present_flag = 1;
  367. if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
  368. sps->vui.num_units_in_tick = avctx->framerate.den;
  369. sps->vui.time_scale = 2 * avctx->framerate.num;
  370. sps->vui.fixed_frame_rate_flag = 1;
  371. } else {
  372. sps->vui.num_units_in_tick = avctx->time_base.num;
  373. sps->vui.time_scale = 2 * avctx->time_base.den;
  374. sps->vui.fixed_frame_rate_flag = 0;
  375. }
  376. if (priv->sei & SEI_TIMING) {
  377. H264RawHRD *hrd = &sps->vui.nal_hrd_parameters;
  378. H264RawSEIBufferingPeriod *bp = &priv->sei_buffering_period;
  379. sps->vui.nal_hrd_parameters_present_flag = 1;
  380. hrd->cpb_cnt_minus1 = 0;
  381. // Try to scale these to a sensible range so that the
  382. // golomb encode of the value is not overlong.
  383. hrd->bit_rate_scale =
  384. av_clip_uintp2(av_log2(ctx->va_bit_rate) - 15 - 6, 4);
  385. hrd->bit_rate_value_minus1[0] =
  386. (ctx->va_bit_rate >> hrd->bit_rate_scale + 6) - 1;
  387. hrd->cpb_size_scale =
  388. av_clip_uintp2(av_log2(ctx->hrd_params.hrd.buffer_size) - 15 - 4, 4);
  389. hrd->cpb_size_value_minus1[0] =
  390. (ctx->hrd_params.hrd.buffer_size >> hrd->cpb_size_scale + 4) - 1;
  391. // CBR mode as defined for the HRD cannot be achieved without filler
  392. // data, so this flag cannot be set even with VAAPI CBR modes.
  393. hrd->cbr_flag[0] = 0;
  394. hrd->initial_cpb_removal_delay_length_minus1 = 23;
  395. hrd->cpb_removal_delay_length_minus1 = 23;
  396. hrd->dpb_output_delay_length_minus1 = 7;
  397. hrd->time_offset_length = 0;
  398. bp->seq_parameter_set_id = sps->seq_parameter_set_id;
  399. // This calculation can easily overflow 32 bits.
  400. bp->nal.initial_cpb_removal_delay[0] = 90000 *
  401. (uint64_t)ctx->hrd_params.hrd.initial_buffer_fullness /
  402. ctx->hrd_params.hrd.buffer_size;
  403. bp->nal.initial_cpb_removal_delay_offset[0] = 0;
  404. } else {
  405. sps->vui.nal_hrd_parameters_present_flag = 0;
  406. sps->vui.low_delay_hrd_flag = 1 - sps->vui.fixed_frame_rate_flag;
  407. }
  408. sps->vui.bitstream_restriction_flag = 1;
  409. sps->vui.motion_vectors_over_pic_boundaries_flag = 1;
  410. sps->vui.log2_max_mv_length_horizontal = 15;
  411. sps->vui.log2_max_mv_length_vertical = 15;
  412. sps->vui.max_num_reorder_frames = ctx->max_b_depth;
  413. sps->vui.max_dec_frame_buffering = ctx->max_b_depth + 1;
  414. pps->nal_unit_header.nal_ref_idc = 3;
  415. pps->nal_unit_header.nal_unit_type = H264_NAL_PPS;
  416. pps->pic_parameter_set_id = 0;
  417. pps->seq_parameter_set_id = 0;
  418. pps->entropy_coding_mode_flag =
  419. !(sps->profile_idc == FF_PROFILE_H264_BASELINE ||
  420. sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
  421. sps->profile_idc == FF_PROFILE_H264_CAVLC_444);
  422. if (!priv->coder && pps->entropy_coding_mode_flag)
  423. pps->entropy_coding_mode_flag = 0;
  424. pps->num_ref_idx_l0_default_active_minus1 = 0;
  425. pps->num_ref_idx_l1_default_active_minus1 = 0;
  426. pps->pic_init_qp_minus26 = priv->fixed_qp_idr - 26;
  427. if (sps->profile_idc == FF_PROFILE_H264_BASELINE ||
  428. sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
  429. sps->profile_idc == FF_PROFILE_H264_MAIN) {
  430. pps->more_rbsp_data = 0;
  431. } else {
  432. pps->more_rbsp_data = 1;
  433. pps->transform_8x8_mode_flag = 1;
  434. }
  435. *vseq = (VAEncSequenceParameterBufferH264) {
  436. .seq_parameter_set_id = sps->seq_parameter_set_id,
  437. .level_idc = sps->level_idc,
  438. .intra_period = ctx->gop_size,
  439. .intra_idr_period = ctx->gop_size,
  440. .ip_period = ctx->b_per_p + 1,
  441. .bits_per_second = ctx->va_bit_rate,
  442. .max_num_ref_frames = sps->max_num_ref_frames,
  443. .picture_width_in_mbs = sps->pic_width_in_mbs_minus1 + 1,
  444. .picture_height_in_mbs = sps->pic_height_in_map_units_minus1 + 1,
  445. .seq_fields.bits = {
  446. .chroma_format_idc = sps->chroma_format_idc,
  447. .frame_mbs_only_flag = sps->frame_mbs_only_flag,
  448. .mb_adaptive_frame_field_flag = sps->mb_adaptive_frame_field_flag,
  449. .seq_scaling_matrix_present_flag = sps->seq_scaling_matrix_present_flag,
  450. .direct_8x8_inference_flag = sps->direct_8x8_inference_flag,
  451. .log2_max_frame_num_minus4 = sps->log2_max_frame_num_minus4,
  452. .pic_order_cnt_type = sps->pic_order_cnt_type,
  453. .log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_pic_order_cnt_lsb_minus4,
  454. .delta_pic_order_always_zero_flag = sps->delta_pic_order_always_zero_flag,
  455. },
  456. .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
  457. .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
  458. .frame_cropping_flag = sps->frame_cropping_flag,
  459. .frame_crop_left_offset = sps->frame_crop_left_offset,
  460. .frame_crop_right_offset = sps->frame_crop_right_offset,
  461. .frame_crop_top_offset = sps->frame_crop_top_offset,
  462. .frame_crop_bottom_offset = sps->frame_crop_bottom_offset,
  463. .vui_parameters_present_flag = sps->vui_parameters_present_flag,
  464. .vui_fields.bits = {
  465. .aspect_ratio_info_present_flag = sps->vui.aspect_ratio_info_present_flag,
  466. .timing_info_present_flag = sps->vui.timing_info_present_flag,
  467. .bitstream_restriction_flag = sps->vui.bitstream_restriction_flag,
  468. .log2_max_mv_length_horizontal = sps->vui.log2_max_mv_length_horizontal,
  469. .log2_max_mv_length_vertical = sps->vui.log2_max_mv_length_vertical,
  470. },
  471. .aspect_ratio_idc = sps->vui.aspect_ratio_idc,
  472. .sar_width = sps->vui.sar_width,
  473. .sar_height = sps->vui.sar_height,
  474. .num_units_in_tick = sps->vui.num_units_in_tick,
  475. .time_scale = sps->vui.time_scale,
  476. };
  477. *vpic = (VAEncPictureParameterBufferH264) {
  478. .CurrPic = {
  479. .picture_id = VA_INVALID_ID,
  480. .flags = VA_PICTURE_H264_INVALID,
  481. },
  482. .coded_buf = VA_INVALID_ID,
  483. .pic_parameter_set_id = pps->pic_parameter_set_id,
  484. .seq_parameter_set_id = pps->seq_parameter_set_id,
  485. .pic_init_qp = pps->pic_init_qp_minus26 + 26,
  486. .num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1,
  487. .num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1,
  488. .chroma_qp_index_offset = pps->chroma_qp_index_offset,
  489. .second_chroma_qp_index_offset = pps->second_chroma_qp_index_offset,
  490. .pic_fields.bits = {
  491. .entropy_coding_mode_flag = pps->entropy_coding_mode_flag,
  492. .weighted_pred_flag = pps->weighted_pred_flag,
  493. .weighted_bipred_idc = pps->weighted_bipred_idc,
  494. .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
  495. .transform_8x8_mode_flag = pps->transform_8x8_mode_flag,
  496. .deblocking_filter_control_present_flag =
  497. pps->deblocking_filter_control_present_flag,
  498. .redundant_pic_cnt_present_flag = pps->redundant_pic_cnt_present_flag,
  499. .pic_order_present_flag =
  500. pps->bottom_field_pic_order_in_frame_present_flag,
  501. .pic_scaling_matrix_present_flag = pps->pic_scaling_matrix_present_flag,
  502. },
  503. };
  504. return 0;
  505. }
  506. static int vaapi_encode_h264_init_picture_params(AVCodecContext *avctx,
  507. VAAPIEncodePicture *pic)
  508. {
  509. VAAPIEncodeContext *ctx = avctx->priv_data;
  510. VAAPIEncodeH264Context *priv = avctx->priv_data;
  511. VAAPIEncodeH264Picture *hpic = pic->priv_data;
  512. VAAPIEncodePicture *prev = pic->prev;
  513. VAAPIEncodeH264Picture *hprev = prev ? prev->priv_data : NULL;
  514. VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
  515. int i;
  516. if (pic->type == PICTURE_TYPE_IDR) {
  517. av_assert0(pic->display_order == pic->encode_order);
  518. hpic->frame_num = 0;
  519. hpic->last_idr_frame = pic->display_order;
  520. hpic->idr_pic_id = hprev ? hprev->idr_pic_id + 1 : 0;
  521. hpic->primary_pic_type = 0;
  522. hpic->slice_type = 7;
  523. } else {
  524. av_assert0(prev);
  525. hpic->frame_num = hprev->frame_num + prev->is_reference;
  526. hpic->last_idr_frame = hprev->last_idr_frame;
  527. hpic->idr_pic_id = hprev->idr_pic_id;
  528. if (pic->type == PICTURE_TYPE_I) {
  529. hpic->slice_type = 7;
  530. hpic->primary_pic_type = 0;
  531. } else if (pic->type == PICTURE_TYPE_P) {
  532. hpic->slice_type = 5;
  533. hpic->primary_pic_type = 1;
  534. } else {
  535. hpic->slice_type = 6;
  536. hpic->primary_pic_type = 2;
  537. }
  538. }
  539. hpic->pic_order_cnt = pic->display_order - hpic->last_idr_frame;
  540. hpic->dpb_delay = pic->display_order - pic->encode_order + ctx->max_b_depth;
  541. hpic->cpb_delay = pic->encode_order - hpic->last_idr_frame;
  542. if (priv->aud) {
  543. priv->aud_needed = 1;
  544. priv->raw_aud = (H264RawAUD) {
  545. .nal_unit_header = {
  546. .nal_unit_type = H264_NAL_AUD,
  547. },
  548. .primary_pic_type = hpic->primary_pic_type,
  549. };
  550. } else {
  551. priv->aud_needed = 0;
  552. }
  553. priv->sei_needed = 0;
  554. if (priv->sei & SEI_IDENTIFIER && pic->encode_order == 0)
  555. priv->sei_needed |= SEI_IDENTIFIER;
  556. #if !CONFIG_VAAPI_1
  557. if (ctx->va_rc_mode == VA_RC_CBR)
  558. priv->sei_cbr_workaround_needed = 1;
  559. #endif
  560. if (priv->sei & SEI_TIMING) {
  561. priv->sei_pic_timing = (H264RawSEIPicTiming) {
  562. .cpb_removal_delay = 2 * hpic->cpb_delay,
  563. .dpb_output_delay = 2 * hpic->dpb_delay,
  564. };
  565. priv->sei_needed |= SEI_TIMING;
  566. }
  567. if (priv->sei & SEI_RECOVERY_POINT && pic->type == PICTURE_TYPE_I) {
  568. priv->sei_recovery_point = (H264RawSEIRecoveryPoint) {
  569. .recovery_frame_cnt = 0,
  570. .exact_match_flag = 1,
  571. .broken_link_flag = ctx->b_per_p > 0,
  572. };
  573. priv->sei_needed |= SEI_RECOVERY_POINT;
  574. }
  575. vpic->CurrPic = (VAPictureH264) {
  576. .picture_id = pic->recon_surface,
  577. .frame_idx = hpic->frame_num,
  578. .flags = 0,
  579. .TopFieldOrderCnt = hpic->pic_order_cnt,
  580. .BottomFieldOrderCnt = hpic->pic_order_cnt,
  581. };
  582. for (i = 0; i < pic->nb_refs; i++) {
  583. VAAPIEncodePicture *ref = pic->refs[i];
  584. VAAPIEncodeH264Picture *href;
  585. av_assert0(ref && ref->encode_order < pic->encode_order);
  586. href = ref->priv_data;
  587. vpic->ReferenceFrames[i] = (VAPictureH264) {
  588. .picture_id = ref->recon_surface,
  589. .frame_idx = href->frame_num,
  590. .flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE,
  591. .TopFieldOrderCnt = href->pic_order_cnt,
  592. .BottomFieldOrderCnt = href->pic_order_cnt,
  593. };
  594. }
  595. for (; i < FF_ARRAY_ELEMS(vpic->ReferenceFrames); i++) {
  596. vpic->ReferenceFrames[i] = (VAPictureH264) {
  597. .picture_id = VA_INVALID_ID,
  598. .flags = VA_PICTURE_H264_INVALID,
  599. };
  600. }
  601. vpic->coded_buf = pic->output_buffer;
  602. vpic->frame_num = hpic->frame_num;
  603. vpic->pic_fields.bits.idr_pic_flag = (pic->type == PICTURE_TYPE_IDR);
  604. vpic->pic_fields.bits.reference_pic_flag = (pic->type != PICTURE_TYPE_B);
  605. return 0;
  606. }
  607. static void vaapi_encode_h264_default_ref_pic_list(AVCodecContext *avctx,
  608. VAAPIEncodePicture *pic,
  609. VAAPIEncodePicture **rpl0,
  610. VAAPIEncodePicture **rpl1,
  611. int *rpl_size)
  612. {
  613. VAAPIEncodePicture *prev;
  614. VAAPIEncodeH264Picture *hp, *hn, *hc;
  615. int i, j, n = 0;
  616. prev = pic->prev;
  617. av_assert0(prev);
  618. hp = pic->priv_data;
  619. for (i = 0; i < pic->prev->nb_dpb_pics; i++) {
  620. hn = prev->dpb[i]->priv_data;
  621. av_assert0(hn->frame_num < hp->frame_num);
  622. if (pic->type == PICTURE_TYPE_P) {
  623. for (j = n; j > 0; j--) {
  624. hc = rpl0[j - 1]->priv_data;
  625. av_assert0(hc->frame_num != hn->frame_num);
  626. if (hc->frame_num > hn->frame_num)
  627. break;
  628. rpl0[j] = rpl0[j - 1];
  629. }
  630. rpl0[j] = prev->dpb[i];
  631. } else if (pic->type == PICTURE_TYPE_B) {
  632. for (j = n; j > 0; j--) {
  633. hc = rpl0[j - 1]->priv_data;
  634. av_assert0(hc->pic_order_cnt != hp->pic_order_cnt);
  635. if (hc->pic_order_cnt < hp->pic_order_cnt) {
  636. if (hn->pic_order_cnt > hp->pic_order_cnt ||
  637. hn->pic_order_cnt < hc->pic_order_cnt)
  638. break;
  639. } else {
  640. if (hn->pic_order_cnt > hc->pic_order_cnt)
  641. break;
  642. }
  643. rpl0[j] = rpl0[j - 1];
  644. }
  645. rpl0[j] = prev->dpb[i];
  646. for (j = n; j > 0; j--) {
  647. hc = rpl1[j - 1]->priv_data;
  648. av_assert0(hc->pic_order_cnt != hp->pic_order_cnt);
  649. if (hc->pic_order_cnt > hp->pic_order_cnt) {
  650. if (hn->pic_order_cnt < hp->pic_order_cnt ||
  651. hn->pic_order_cnt > hc->pic_order_cnt)
  652. break;
  653. } else {
  654. if (hn->pic_order_cnt < hc->pic_order_cnt)
  655. break;
  656. }
  657. rpl1[j] = rpl1[j - 1];
  658. }
  659. rpl1[j] = prev->dpb[i];
  660. }
  661. ++n;
  662. }
  663. if (pic->type == PICTURE_TYPE_B) {
  664. for (i = 0; i < n; i++) {
  665. if (rpl0[i] != rpl1[i])
  666. break;
  667. }
  668. if (i == n)
  669. FFSWAP(VAAPIEncodePicture*, rpl1[0], rpl1[1]);
  670. }
  671. if (pic->type == PICTURE_TYPE_P ||
  672. pic->type == PICTURE_TYPE_B) {
  673. av_log(avctx, AV_LOG_DEBUG, "Default RefPicList0 for fn=%d/poc=%d:",
  674. hp->frame_num, hp->pic_order_cnt);
  675. for (i = 0; i < n; i++) {
  676. hn = rpl0[i]->priv_data;
  677. av_log(avctx, AV_LOG_DEBUG, " fn=%d/poc=%d",
  678. hn->frame_num, hn->pic_order_cnt);
  679. }
  680. av_log(avctx, AV_LOG_DEBUG, "\n");
  681. }
  682. if (pic->type == PICTURE_TYPE_B) {
  683. av_log(avctx, AV_LOG_DEBUG, "Default RefPicList1 for fn=%d/poc=%d:",
  684. hp->frame_num, hp->pic_order_cnt);
  685. for (i = 0; i < n; i++) {
  686. hn = rpl1[i]->priv_data;
  687. av_log(avctx, AV_LOG_DEBUG, " fn=%d/poc=%d",
  688. hn->frame_num, hn->pic_order_cnt);
  689. }
  690. av_log(avctx, AV_LOG_DEBUG, "\n");
  691. }
  692. *rpl_size = n;
  693. }
  694. static int vaapi_encode_h264_init_slice_params(AVCodecContext *avctx,
  695. VAAPIEncodePicture *pic,
  696. VAAPIEncodeSlice *slice)
  697. {
  698. VAAPIEncodeH264Context *priv = avctx->priv_data;
  699. VAAPIEncodeH264Picture *hpic = pic->priv_data;
  700. VAAPIEncodePicture *prev = pic->prev;
  701. H264RawSPS *sps = &priv->raw_sps;
  702. H264RawPPS *pps = &priv->raw_pps;
  703. H264RawSliceHeader *sh = &priv->raw_slice.header;
  704. VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
  705. VAEncSliceParameterBufferH264 *vslice = slice->codec_slice_params;
  706. int i, j;
  707. if (pic->type == PICTURE_TYPE_IDR) {
  708. sh->nal_unit_header.nal_unit_type = H264_NAL_IDR_SLICE;
  709. sh->nal_unit_header.nal_ref_idc = 3;
  710. } else {
  711. sh->nal_unit_header.nal_unit_type = H264_NAL_SLICE;
  712. sh->nal_unit_header.nal_ref_idc = pic->is_reference;
  713. }
  714. sh->first_mb_in_slice = slice->block_start;
  715. sh->slice_type = hpic->slice_type;
  716. sh->pic_parameter_set_id = pps->pic_parameter_set_id;
  717. sh->frame_num = hpic->frame_num &
  718. ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
  719. sh->idr_pic_id = hpic->idr_pic_id;
  720. sh->pic_order_cnt_lsb = hpic->pic_order_cnt &
  721. ((1 << (4 + sps->log2_max_pic_order_cnt_lsb_minus4)) - 1);
  722. sh->direct_spatial_mv_pred_flag = 1;
  723. if (pic->type == PICTURE_TYPE_B)
  724. sh->slice_qp_delta = priv->fixed_qp_b - (pps->pic_init_qp_minus26 + 26);
  725. else if (pic->type == PICTURE_TYPE_P)
  726. sh->slice_qp_delta = priv->fixed_qp_p - (pps->pic_init_qp_minus26 + 26);
  727. else
  728. sh->slice_qp_delta = priv->fixed_qp_idr - (pps->pic_init_qp_minus26 + 26);
  729. if (pic->is_reference && pic->type != PICTURE_TYPE_IDR) {
  730. VAAPIEncodePicture *discard_list[MAX_DPB_SIZE];
  731. int discard = 0, keep = 0;
  732. // Discard everything which is in the DPB of the previous frame but
  733. // not in the DPB of this one.
  734. for (i = 0; i < prev->nb_dpb_pics; i++) {
  735. for (j = 0; j < pic->nb_dpb_pics; j++) {
  736. if (prev->dpb[i] == pic->dpb[j])
  737. break;
  738. }
  739. if (j == pic->nb_dpb_pics) {
  740. discard_list[discard] = prev->dpb[i];
  741. ++discard;
  742. } else {
  743. ++keep;
  744. }
  745. }
  746. av_assert0(keep <= priv->dpb_frames);
  747. if (discard == 0) {
  748. sh->adaptive_ref_pic_marking_mode_flag = 0;
  749. } else {
  750. sh->adaptive_ref_pic_marking_mode_flag = 1;
  751. for (i = 0; i < discard; i++) {
  752. VAAPIEncodeH264Picture *old = discard_list[i]->priv_data;
  753. av_assert0(old->frame_num < hpic->frame_num);
  754. sh->mmco[i].memory_management_control_operation = 1;
  755. sh->mmco[i].difference_of_pic_nums_minus1 =
  756. hpic->frame_num - old->frame_num - 1;
  757. }
  758. sh->mmco[i].memory_management_control_operation = 0;
  759. }
  760. }
  761. // If the intended references are not the first entries of RefPicListN
  762. // by default, use ref-pic-list-modification to move them there.
  763. if (pic->type == PICTURE_TYPE_P || pic->type == PICTURE_TYPE_B) {
  764. VAAPIEncodePicture *def_l0[MAX_DPB_SIZE], *def_l1[MAX_DPB_SIZE];
  765. VAAPIEncodeH264Picture *href;
  766. int n;
  767. vaapi_encode_h264_default_ref_pic_list(avctx, pic,
  768. def_l0, def_l1, &n);
  769. if (pic->type == PICTURE_TYPE_P) {
  770. int need_rplm = 0;
  771. for (i = 0; i < pic->nb_refs; i++) {
  772. av_assert0(pic->refs[i]);
  773. if (pic->refs[i] != def_l0[i])
  774. need_rplm = 1;
  775. }
  776. sh->ref_pic_list_modification_flag_l0 = need_rplm;
  777. if (need_rplm) {
  778. int pic_num = hpic->frame_num;
  779. for (i = 0; i < pic->nb_refs; i++) {
  780. href = pic->refs[i]->priv_data;
  781. av_assert0(href->frame_num != pic_num);
  782. if (href->frame_num < pic_num) {
  783. sh->rplm_l0[i].modification_of_pic_nums_idc = 0;
  784. sh->rplm_l0[i].abs_diff_pic_num_minus1 =
  785. pic_num - href->frame_num - 1;
  786. } else {
  787. sh->rplm_l0[i].modification_of_pic_nums_idc = 1;
  788. sh->rplm_l0[i].abs_diff_pic_num_minus1 =
  789. href->frame_num - pic_num - 1;
  790. }
  791. pic_num = href->frame_num;
  792. }
  793. sh->rplm_l0[i].modification_of_pic_nums_idc = 3;
  794. }
  795. } else {
  796. int need_rplm_l0 = 0, need_rplm_l1 = 0;
  797. int n0 = 0, n1 = 0;
  798. for (i = 0; i < pic->nb_refs; i++) {
  799. av_assert0(pic->refs[i]);
  800. href = pic->refs[i]->priv_data;
  801. av_assert0(href->pic_order_cnt != hpic->pic_order_cnt);
  802. if (href->pic_order_cnt < hpic->pic_order_cnt) {
  803. if (pic->refs[i] != def_l0[n0])
  804. need_rplm_l0 = 1;
  805. ++n0;
  806. } else {
  807. if (pic->refs[i] != def_l1[n1])
  808. need_rplm_l1 = 1;
  809. ++n1;
  810. }
  811. }
  812. sh->ref_pic_list_modification_flag_l0 = need_rplm_l0;
  813. if (need_rplm_l0) {
  814. int pic_num = hpic->frame_num;
  815. for (i = j = 0; i < pic->nb_refs; i++) {
  816. href = pic->refs[i]->priv_data;
  817. if (href->pic_order_cnt > hpic->pic_order_cnt)
  818. continue;
  819. av_assert0(href->frame_num != pic_num);
  820. if (href->frame_num < pic_num) {
  821. sh->rplm_l0[j].modification_of_pic_nums_idc = 0;
  822. sh->rplm_l0[j].abs_diff_pic_num_minus1 =
  823. pic_num - href->frame_num - 1;
  824. } else {
  825. sh->rplm_l0[j].modification_of_pic_nums_idc = 1;
  826. sh->rplm_l0[j].abs_diff_pic_num_minus1 =
  827. href->frame_num - pic_num - 1;
  828. }
  829. pic_num = href->frame_num;
  830. ++j;
  831. }
  832. av_assert0(j == n0);
  833. sh->rplm_l0[j].modification_of_pic_nums_idc = 3;
  834. }
  835. sh->ref_pic_list_modification_flag_l1 = need_rplm_l1;
  836. if (need_rplm_l1) {
  837. int pic_num = hpic->frame_num;
  838. for (i = j = 0; i < pic->nb_refs; i++) {
  839. href = pic->refs[i]->priv_data;
  840. if (href->pic_order_cnt < hpic->pic_order_cnt)
  841. continue;
  842. av_assert0(href->frame_num != pic_num);
  843. if (href->frame_num < pic_num) {
  844. sh->rplm_l1[j].modification_of_pic_nums_idc = 0;
  845. sh->rplm_l1[j].abs_diff_pic_num_minus1 =
  846. pic_num - href->frame_num - 1;
  847. } else {
  848. sh->rplm_l1[j].modification_of_pic_nums_idc = 1;
  849. sh->rplm_l1[j].abs_diff_pic_num_minus1 =
  850. href->frame_num - pic_num - 1;
  851. }
  852. pic_num = href->frame_num;
  853. ++j;
  854. }
  855. av_assert0(j == n1);
  856. sh->rplm_l1[j].modification_of_pic_nums_idc = 3;
  857. }
  858. }
  859. }
  860. vslice->macroblock_address = slice->block_start;
  861. vslice->num_macroblocks = slice->block_size;
  862. vslice->macroblock_info = VA_INVALID_ID;
  863. vslice->slice_type = sh->slice_type % 5;
  864. vslice->pic_parameter_set_id = sh->pic_parameter_set_id;
  865. vslice->idr_pic_id = sh->idr_pic_id;
  866. vslice->pic_order_cnt_lsb = sh->pic_order_cnt_lsb;
  867. vslice->direct_spatial_mv_pred_flag = sh->direct_spatial_mv_pred_flag;
  868. for (i = 0; i < FF_ARRAY_ELEMS(vslice->RefPicList0); i++) {
  869. vslice->RefPicList0[i].picture_id = VA_INVALID_ID;
  870. vslice->RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
  871. vslice->RefPicList1[i].picture_id = VA_INVALID_ID;
  872. vslice->RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
  873. }
  874. av_assert0(pic->nb_refs <= 2);
  875. if (pic->nb_refs >= 1) {
  876. // Backward reference for P- or B-frame.
  877. av_assert0(pic->type == PICTURE_TYPE_P ||
  878. pic->type == PICTURE_TYPE_B);
  879. vslice->RefPicList0[0] = vpic->ReferenceFrames[0];
  880. }
  881. if (pic->nb_refs >= 2) {
  882. // Forward reference for B-frame.
  883. av_assert0(pic->type == PICTURE_TYPE_B);
  884. vslice->RefPicList1[0] = vpic->ReferenceFrames[1];
  885. }
  886. vslice->slice_qp_delta = sh->slice_qp_delta;
  887. return 0;
  888. }
  889. static av_cold int vaapi_encode_h264_configure(AVCodecContext *avctx)
  890. {
  891. VAAPIEncodeContext *ctx = avctx->priv_data;
  892. VAAPIEncodeH264Context *priv = avctx->priv_data;
  893. int err;
  894. err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_H264, avctx);
  895. if (err < 0)
  896. return err;
  897. priv->mb_width = FFALIGN(avctx->width, 16) / 16;
  898. priv->mb_height = FFALIGN(avctx->height, 16) / 16;
  899. if (ctx->va_rc_mode == VA_RC_CQP) {
  900. priv->fixed_qp_p = priv->qp;
  901. if (avctx->i_quant_factor > 0.0)
  902. priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
  903. avctx->i_quant_offset) + 0.5);
  904. else
  905. priv->fixed_qp_idr = priv->fixed_qp_p;
  906. if (avctx->b_quant_factor > 0.0)
  907. priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
  908. avctx->b_quant_offset) + 0.5);
  909. else
  910. priv->fixed_qp_b = priv->fixed_qp_p;
  911. priv->sei &= ~SEI_TIMING;
  912. av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
  913. "%d / %d / %d for IDR- / P- / B-frames.\n",
  914. priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
  915. } else if (ctx->va_rc_mode == VA_RC_CBR ||
  916. ctx->va_rc_mode == VA_RC_VBR) {
  917. // These still need to be set for pic_init_qp/slice_qp_delta.
  918. priv->fixed_qp_idr = 26;
  919. priv->fixed_qp_p = 26;
  920. priv->fixed_qp_b = 26;
  921. } else {
  922. av_assert0(0 && "Invalid RC mode.");
  923. }
  924. if (priv->sei & SEI_IDENTIFIER) {
  925. const char *lavc = LIBAVCODEC_IDENT;
  926. const char *vaapi = VA_VERSION_S;
  927. const char *driver;
  928. int len;
  929. memcpy(priv->sei_identifier.uuid_iso_iec_11578,
  930. vaapi_encode_h264_sei_identifier_uuid,
  931. sizeof(priv->sei_identifier.uuid_iso_iec_11578));
  932. driver = vaQueryVendorString(ctx->hwctx->display);
  933. if (!driver)
  934. driver = "unknown driver";
  935. len = snprintf(NULL, 0, "%s / VAAPI %s / %s", lavc, vaapi, driver);
  936. if (len >= 0) {
  937. priv->sei_identifier_string = av_malloc(len + 1);
  938. if (!priv->sei_identifier_string)
  939. return AVERROR(ENOMEM);
  940. snprintf(priv->sei_identifier_string, len + 1,
  941. "%s / VAAPI %s / %s", lavc, vaapi, driver);
  942. priv->sei_identifier.data = priv->sei_identifier_string;
  943. priv->sei_identifier.data_length = len + 1;
  944. }
  945. }
  946. return 0;
  947. }
  948. static const VAAPIEncodeProfile vaapi_encode_h264_profiles[] = {
  949. { FF_PROFILE_H264_HIGH, 8, 3, 1, 1, VAProfileH264High },
  950. { FF_PROFILE_H264_MAIN, 8, 3, 1, 1, VAProfileH264Main },
  951. { FF_PROFILE_H264_CONSTRAINED_BASELINE,
  952. 8, 3, 1, 1, VAProfileH264ConstrainedBaseline },
  953. { FF_PROFILE_UNKNOWN }
  954. };
  955. static const VAAPIEncodeType vaapi_encode_type_h264 = {
  956. .profiles = vaapi_encode_h264_profiles,
  957. .flags = FLAG_SLICE_CONTROL |
  958. FLAG_B_PICTURES |
  959. FLAG_B_PICTURE_REFERENCES |
  960. FLAG_NON_IDR_KEY_PICTURES,
  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. return ff_vaapi_encode_init(avctx);
  1025. }
  1026. static av_cold int vaapi_encode_h264_close(AVCodecContext *avctx)
  1027. {
  1028. VAAPIEncodeH264Context *priv = avctx->priv_data;
  1029. ff_cbs_fragment_free(priv->cbc, &priv->current_access_unit);
  1030. ff_cbs_close(&priv->cbc);
  1031. av_freep(&priv->sei_identifier_string);
  1032. return ff_vaapi_encode_close(avctx);
  1033. }
  1034. #define OFFSET(x) offsetof(VAAPIEncodeH264Context, x)
  1035. #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
  1036. static const AVOption vaapi_encode_h264_options[] = {
  1037. VAAPI_ENCODE_COMMON_OPTIONS,
  1038. { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
  1039. OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 20 }, 0, 52, FLAGS },
  1040. { "quality", "Set encode quality (trades off against speed, higher is faster)",
  1041. OFFSET(quality), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS },
  1042. { "coder", "Entropy coder type",
  1043. OFFSET(coder), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS, "coder" },
  1044. { "cavlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
  1045. { "cabac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
  1046. { "vlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
  1047. { "ac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
  1048. { "aud", "Include AUD",
  1049. OFFSET(aud), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
  1050. { "sei", "Set SEI to include",
  1051. OFFSET(sei), AV_OPT_TYPE_FLAGS,
  1052. { .i64 = SEI_IDENTIFIER | SEI_TIMING | SEI_RECOVERY_POINT },
  1053. 0, INT_MAX, FLAGS, "sei" },
  1054. { "identifier", "Include encoder version identifier",
  1055. 0, AV_OPT_TYPE_CONST, { .i64 = SEI_IDENTIFIER },
  1056. INT_MIN, INT_MAX, FLAGS, "sei" },
  1057. { "timing", "Include timing parameters (buffering_period and pic_timing)",
  1058. 0, AV_OPT_TYPE_CONST, { .i64 = SEI_TIMING },
  1059. INT_MIN, INT_MAX, FLAGS, "sei" },
  1060. { "recovery_point", "Include recovery points where appropriate",
  1061. 0, AV_OPT_TYPE_CONST, { .i64 = SEI_RECOVERY_POINT },
  1062. INT_MIN, INT_MAX, FLAGS, "sei" },
  1063. { "profile", "Set profile (profile_idc and constraint_set*_flag)",
  1064. OFFSET(profile), AV_OPT_TYPE_INT,
  1065. { .i64 = FF_PROFILE_UNKNOWN }, FF_PROFILE_UNKNOWN, 0xffff, FLAGS, "profile" },
  1066. #define PROFILE(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
  1067. { .i64 = value }, 0, 0, FLAGS, "profile"
  1068. { PROFILE("constrained_baseline", FF_PROFILE_H264_CONSTRAINED_BASELINE) },
  1069. { PROFILE("main", FF_PROFILE_H264_MAIN) },
  1070. { PROFILE("high", FF_PROFILE_H264_HIGH) },
  1071. #undef PROFILE
  1072. { "level", "Set level (level_idc)",
  1073. OFFSET(level), AV_OPT_TYPE_INT,
  1074. { .i64 = FF_LEVEL_UNKNOWN }, FF_LEVEL_UNKNOWN, 0xff, FLAGS, "level" },
  1075. #define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
  1076. { .i64 = value }, 0, 0, FLAGS, "level"
  1077. { LEVEL("1", 10) },
  1078. { LEVEL("1.1", 11) },
  1079. { LEVEL("1.2", 12) },
  1080. { LEVEL("1.3", 13) },
  1081. { LEVEL("2", 20) },
  1082. { LEVEL("2.1", 21) },
  1083. { LEVEL("2.2", 22) },
  1084. { LEVEL("3", 30) },
  1085. { LEVEL("3.1", 31) },
  1086. { LEVEL("3.2", 32) },
  1087. { LEVEL("4", 40) },
  1088. { LEVEL("4.1", 41) },
  1089. { LEVEL("4.2", 42) },
  1090. { LEVEL("5", 50) },
  1091. { LEVEL("5.1", 51) },
  1092. { LEVEL("5.2", 52) },
  1093. { LEVEL("6", 60) },
  1094. { LEVEL("6.1", 61) },
  1095. { LEVEL("6.2", 62) },
  1096. #undef LEVEL
  1097. { NULL },
  1098. };
  1099. static const AVCodecDefault vaapi_encode_h264_defaults[] = {
  1100. { "b", "0" },
  1101. { "bf", "2" },
  1102. { "g", "120" },
  1103. { "i_qfactor", "1" },
  1104. { "i_qoffset", "0" },
  1105. { "b_qfactor", "6/5" },
  1106. { "b_qoffset", "0" },
  1107. { "qmin", "-1" },
  1108. { "qmax", "-1" },
  1109. { NULL },
  1110. };
  1111. static const AVClass vaapi_encode_h264_class = {
  1112. .class_name = "h264_vaapi",
  1113. .item_name = av_default_item_name,
  1114. .option = vaapi_encode_h264_options,
  1115. .version = LIBAVUTIL_VERSION_INT,
  1116. };
  1117. AVCodec ff_h264_vaapi_encoder = {
  1118. .name = "h264_vaapi",
  1119. .long_name = NULL_IF_CONFIG_SMALL("H.264/AVC (VAAPI)"),
  1120. .type = AVMEDIA_TYPE_VIDEO,
  1121. .id = AV_CODEC_ID_H264,
  1122. .priv_data_size = sizeof(VAAPIEncodeH264Context),
  1123. .init = &vaapi_encode_h264_init,
  1124. .send_frame = &ff_vaapi_encode_send_frame,
  1125. .receive_packet = &ff_vaapi_encode_receive_packet,
  1126. .close = &vaapi_encode_h264_close,
  1127. .priv_class = &vaapi_encode_h264_class,
  1128. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
  1129. .defaults = vaapi_encode_h264_defaults,
  1130. .pix_fmts = (const enum AVPixelFormat[]) {
  1131. AV_PIX_FMT_VAAPI,
  1132. AV_PIX_FMT_NONE,
  1133. },
  1134. .wrapper_name = "vaapi",
  1135. };