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.

970 lines
34KB

  1. /*
  2. * This file is part of Libav.
  3. *
  4. * Libav 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. * Libav 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 Libav; 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_sei.h"
  30. #include "internal.h"
  31. #include "vaapi_encode.h"
  32. enum {
  33. SEI_TIMING = 0x01,
  34. SEI_IDENTIFIER = 0x02,
  35. };
  36. // Random (version 4) ISO 11578 UUID.
  37. static const uint8_t vaapi_encode_h264_sei_identifier_uuid[16] = {
  38. 0x59, 0x94, 0x8b, 0x28, 0x11, 0xec, 0x45, 0xaf,
  39. 0x96, 0x75, 0x19, 0xd4, 0x1f, 0xea, 0xa9, 0x4d,
  40. };
  41. typedef struct VAAPIEncodeH264Context {
  42. int mb_width;
  43. int mb_height;
  44. int fixed_qp_idr;
  45. int fixed_qp_p;
  46. int fixed_qp_b;
  47. H264RawSPS sps;
  48. H264RawPPS pps;
  49. H264RawSEI sei;
  50. H264RawSlice slice;
  51. H264RawSEIBufferingPeriod buffering_period;
  52. H264RawSEIPicTiming pic_timing;
  53. H264RawSEIUserDataUnregistered identifier;
  54. char *identifier_string;
  55. int frame_num;
  56. int pic_order_cnt;
  57. int next_frame_num;
  58. int64_t last_idr_frame;
  59. int64_t idr_pic_count;
  60. int primary_pic_type;
  61. int slice_type;
  62. int cpb_delay;
  63. int dpb_delay;
  64. CodedBitstreamContext cbc;
  65. CodedBitstreamFragment current_access_unit;
  66. int sei_needed;
  67. } VAAPIEncodeH264Context;
  68. typedef struct VAAPIEncodeH264Options {
  69. int qp;
  70. int quality;
  71. int low_power;
  72. int sei;
  73. } VAAPIEncodeH264Options;
  74. static int vaapi_encode_h264_write_access_unit(AVCodecContext *avctx,
  75. char *data, size_t *data_len,
  76. CodedBitstreamFragment *au)
  77. {
  78. VAAPIEncodeContext *ctx = avctx->priv_data;
  79. VAAPIEncodeH264Context *priv = ctx->priv_data;
  80. int err;
  81. err = ff_cbs_write_fragment_data(&priv->cbc, au);
  82. if (err < 0) {
  83. av_log(avctx, AV_LOG_ERROR, "Failed to write packed header.\n");
  84. return err;
  85. }
  86. if (*data_len < 8 * au->data_size - au->data_bit_padding) {
  87. av_log(avctx, AV_LOG_ERROR, "Access unit too large: "
  88. "%zu < %zu.\n", *data_len,
  89. 8 * au->data_size - au->data_bit_padding);
  90. return AVERROR(ENOSPC);
  91. }
  92. memcpy(data, au->data, au->data_size);
  93. *data_len = 8 * au->data_size - au->data_bit_padding;
  94. return 0;
  95. }
  96. static int vaapi_encode_h264_add_nal(AVCodecContext *avctx,
  97. CodedBitstreamFragment *au,
  98. void *nal_unit)
  99. {
  100. VAAPIEncodeContext *ctx = avctx->priv_data;
  101. VAAPIEncodeH264Context *priv = ctx->priv_data;
  102. H264RawNALUnitHeader *header = nal_unit;
  103. int err;
  104. err = ff_cbs_insert_unit_content(&priv->cbc, au, -1,
  105. header->nal_unit_type, nal_unit);
  106. if (err < 0) {
  107. av_log(avctx, AV_LOG_ERROR, "Failed to add NAL unit: "
  108. "type = %d.\n", header->nal_unit_type);
  109. return err;
  110. }
  111. return 0;
  112. }
  113. static int vaapi_encode_h264_write_sequence_header(AVCodecContext *avctx,
  114. char *data, size_t *data_len)
  115. {
  116. VAAPIEncodeContext *ctx = avctx->priv_data;
  117. VAAPIEncodeH264Context *priv = ctx->priv_data;
  118. CodedBitstreamFragment *au = &priv->current_access_unit;
  119. int err;
  120. err = vaapi_encode_h264_add_nal(avctx, au, &priv->sps);
  121. if (err < 0)
  122. goto fail;
  123. err = vaapi_encode_h264_add_nal(avctx, au, &priv->pps);
  124. if (err < 0)
  125. goto fail;
  126. err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
  127. fail:
  128. ff_cbs_fragment_uninit(&priv->cbc, au);
  129. return err;
  130. }
  131. static int vaapi_encode_h264_write_slice_header(AVCodecContext *avctx,
  132. VAAPIEncodePicture *pic,
  133. VAAPIEncodeSlice *slice,
  134. char *data, size_t *data_len)
  135. {
  136. VAAPIEncodeContext *ctx = avctx->priv_data;
  137. VAAPIEncodeH264Context *priv = ctx->priv_data;
  138. CodedBitstreamFragment *au = &priv->current_access_unit;
  139. int err;
  140. err = vaapi_encode_h264_add_nal(avctx, au, &priv->slice);
  141. if (err < 0)
  142. goto fail;
  143. err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
  144. fail:
  145. ff_cbs_fragment_uninit(&priv->cbc, au);
  146. return err;
  147. }
  148. static int vaapi_encode_h264_write_extra_header(AVCodecContext *avctx,
  149. VAAPIEncodePicture *pic,
  150. int index, int *type,
  151. char *data, size_t *data_len)
  152. {
  153. VAAPIEncodeContext *ctx = avctx->priv_data;
  154. VAAPIEncodeH264Context *priv = ctx->priv_data;
  155. VAAPIEncodeH264Options *opt = ctx->codec_options;
  156. CodedBitstreamFragment *au = &priv->current_access_unit;
  157. int err, i;
  158. if (priv->sei_needed) {
  159. memset(&priv->sei, 0, sizeof(priv->sei));
  160. priv->sei.nal_unit_header.nal_unit_type = H264_NAL_SEI;
  161. i = 0;
  162. if (pic->encode_order == 0 && opt->sei & SEI_IDENTIFIER) {
  163. priv->sei.payload[i].payload_type = H264_SEI_TYPE_USER_DATA_UNREGISTERED;
  164. priv->sei.payload[i].payload.user_data_unregistered = priv->identifier;
  165. ++i;
  166. }
  167. if (opt->sei & SEI_TIMING) {
  168. if (pic->type == PICTURE_TYPE_IDR) {
  169. priv->sei.payload[i].payload_type = H264_SEI_TYPE_BUFFERING_PERIOD;
  170. priv->sei.payload[i].payload.buffering_period = priv->buffering_period;
  171. ++i;
  172. }
  173. priv->sei.payload[i].payload_type = H264_SEI_TYPE_PIC_TIMING;
  174. priv->sei.payload[i].payload.pic_timing = priv->pic_timing;
  175. ++i;
  176. }
  177. priv->sei.payload_count = i;
  178. av_assert0(priv->sei.payload_count > 0);
  179. err = vaapi_encode_h264_add_nal(avctx, au, &priv->sei);
  180. if (err < 0)
  181. goto fail;
  182. priv->sei_needed = 0;
  183. err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
  184. if (err < 0)
  185. goto fail;
  186. ff_cbs_fragment_uninit(&priv->cbc, au);
  187. *type = VAEncPackedHeaderH264_SEI;
  188. return 0;
  189. } else {
  190. return AVERROR_EOF;
  191. }
  192. fail:
  193. ff_cbs_fragment_uninit(&priv->cbc, au);
  194. return err;
  195. }
  196. static int vaapi_encode_h264_init_sequence_params(AVCodecContext *avctx)
  197. {
  198. VAAPIEncodeContext *ctx = avctx->priv_data;
  199. VAAPIEncodeH264Context *priv = ctx->priv_data;
  200. VAAPIEncodeH264Options *opt = ctx->codec_options;
  201. H264RawSPS *sps = &priv->sps;
  202. H264RawPPS *pps = &priv->pps;
  203. VAEncSequenceParameterBufferH264 *vseq = ctx->codec_sequence_params;
  204. VAEncPictureParameterBufferH264 *vpic = ctx->codec_picture_params;
  205. memset(&priv->current_access_unit, 0,
  206. sizeof(priv->current_access_unit));
  207. memset(sps, 0, sizeof(*sps));
  208. memset(pps, 0, sizeof(*pps));
  209. sps->nal_unit_header.nal_ref_idc = 3;
  210. sps->nal_unit_header.nal_unit_type = H264_NAL_SPS;
  211. sps->profile_idc = avctx->profile & 0xff;
  212. sps->constraint_set1_flag =
  213. !!(avctx->profile & FF_PROFILE_H264_CONSTRAINED);
  214. sps->constraint_set3_flag =
  215. !!(avctx->profile & FF_PROFILE_H264_INTRA);
  216. sps->level_idc = avctx->level;
  217. sps->seq_parameter_set_id = 0;
  218. sps->chroma_format_idc = 1;
  219. sps->log2_max_frame_num_minus4 = 4;
  220. sps->pic_order_cnt_type = 0;
  221. sps->log2_max_pic_order_cnt_lsb_minus4 =
  222. av_clip(av_log2(ctx->b_per_p + 1) - 2, 0, 12);
  223. sps->max_num_ref_frames =
  224. (avctx->profile & FF_PROFILE_H264_INTRA) ? 0 :
  225. 1 + (ctx->b_per_p > 0);
  226. sps->pic_width_in_mbs_minus1 = priv->mb_width - 1;
  227. sps->pic_height_in_map_units_minus1 = priv->mb_height - 1;
  228. sps->frame_mbs_only_flag = 1;
  229. sps->direct_8x8_inference_flag = 1;
  230. if (avctx->width != 16 * priv->mb_width ||
  231. avctx->height != 16 * priv->mb_height) {
  232. sps->frame_cropping_flag = 1;
  233. sps->frame_crop_left_offset = 0;
  234. sps->frame_crop_right_offset =
  235. (16 * priv->mb_width - avctx->width) / 2;
  236. sps->frame_crop_top_offset = 0;
  237. sps->frame_crop_bottom_offset =
  238. (16 * priv->mb_height - avctx->height) / 2;
  239. } else {
  240. sps->frame_cropping_flag = 0;
  241. }
  242. sps->vui_parameters_present_flag = 1;
  243. if (avctx->sample_aspect_ratio.num != 0 &&
  244. avctx->sample_aspect_ratio.den != 0) {
  245. static const AVRational sar_idc[] = {
  246. { 0, 0 },
  247. { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 },
  248. { 40, 33 }, { 24, 11 }, { 20, 11 }, { 32, 11 },
  249. { 80, 33 }, { 18, 11 }, { 15, 11 }, { 64, 33 },
  250. { 160, 99 }, { 4, 3 }, { 3, 2 }, { 2, 1 },
  251. };
  252. int i;
  253. for (i = 0; i < FF_ARRAY_ELEMS(sar_idc); i++) {
  254. if (avctx->sample_aspect_ratio.num == sar_idc[i].num &&
  255. avctx->sample_aspect_ratio.den == sar_idc[i].den) {
  256. sps->vui.aspect_ratio_idc = i;
  257. break;
  258. }
  259. }
  260. if (i >= FF_ARRAY_ELEMS(sar_idc)) {
  261. sps->vui.aspect_ratio_idc = 255;
  262. sps->vui.sar_width = avctx->sample_aspect_ratio.num;
  263. sps->vui.sar_height = avctx->sample_aspect_ratio.den;
  264. }
  265. sps->vui.aspect_ratio_info_present_flag = 1;
  266. }
  267. if (avctx->color_range != AVCOL_RANGE_UNSPECIFIED ||
  268. avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
  269. avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
  270. avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
  271. sps->vui.video_signal_type_present_flag = 1;
  272. sps->vui.video_format = 5; // Unspecified.
  273. sps->vui.video_full_range_flag =
  274. avctx->color_range == AVCOL_RANGE_JPEG;
  275. if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
  276. avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
  277. avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
  278. sps->vui.colour_description_present_flag = 1;
  279. sps->vui.colour_primaries = avctx->color_primaries;
  280. sps->vui.transfer_characteristics = avctx->color_trc;
  281. sps->vui.matrix_coefficients = avctx->colorspace;
  282. }
  283. } else {
  284. sps->vui.video_format = 5;
  285. sps->vui.video_full_range_flag = 0;
  286. sps->vui.colour_primaries = avctx->color_primaries;
  287. sps->vui.transfer_characteristics = avctx->color_trc;
  288. sps->vui.matrix_coefficients = avctx->colorspace;
  289. }
  290. if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
  291. sps->vui.chroma_loc_info_present_flag = 1;
  292. sps->vui.chroma_sample_loc_type_top_field =
  293. sps->vui.chroma_sample_loc_type_bottom_field =
  294. avctx->chroma_sample_location - 1;
  295. }
  296. sps->vui.timing_info_present_flag = 1;
  297. if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
  298. sps->vui.num_units_in_tick = avctx->framerate.den;
  299. sps->vui.time_scale = 2 * avctx->framerate.num;
  300. sps->vui.fixed_frame_rate_flag = 1;
  301. } else {
  302. sps->vui.num_units_in_tick = avctx->time_base.num;
  303. sps->vui.time_scale = 2 * avctx->time_base.den;
  304. sps->vui.fixed_frame_rate_flag = 0;
  305. }
  306. if (opt->sei & SEI_TIMING) {
  307. H264RawHRD *hrd = &sps->vui.nal_hrd_parameters;
  308. sps->vui.nal_hrd_parameters_present_flag = 1;
  309. hrd->cpb_cnt_minus1 = 0;
  310. // Try to scale these to a sensible range so that the
  311. // golomb encode of the value is not overlong.
  312. hrd->bit_rate_scale =
  313. av_clip_uintp2(av_log2(avctx->bit_rate) - 15 - 6, 4);
  314. hrd->bit_rate_value_minus1[0] =
  315. (avctx->bit_rate >> hrd->bit_rate_scale + 6) - 1;
  316. hrd->cpb_size_scale =
  317. av_clip_uintp2(av_log2(ctx->hrd_params.hrd.buffer_size) - 15 - 4, 4);
  318. hrd->cpb_size_value_minus1[0] =
  319. (ctx->hrd_params.hrd.buffer_size >> hrd->cpb_size_scale + 4) - 1;
  320. // CBR mode as defined for the HRD cannot be achieved without filler
  321. // data, so this flag cannot be set even with VAAPI CBR modes.
  322. hrd->cbr_flag[0] = 0;
  323. hrd->initial_cpb_removal_delay_length_minus1 = 23;
  324. hrd->cpb_removal_delay_length_minus1 = 23;
  325. hrd->dpb_output_delay_length_minus1 = 7;
  326. hrd->time_offset_length = 0;
  327. priv->buffering_period.seq_parameter_set_id = sps->seq_parameter_set_id;
  328. // This calculation can easily overflow 32 bits.
  329. priv->buffering_period.nal.initial_cpb_removal_delay[0] = 90000 *
  330. (uint64_t)ctx->hrd_params.hrd.initial_buffer_fullness /
  331. ctx->hrd_params.hrd.buffer_size;
  332. priv->buffering_period.nal.initial_cpb_removal_delay_offset[0] = 0;
  333. } else {
  334. sps->vui.nal_hrd_parameters_present_flag = 0;
  335. sps->vui.low_delay_hrd_flag = 1 - sps->vui.fixed_frame_rate_flag;
  336. }
  337. sps->vui.bitstream_restriction_flag = 1;
  338. sps->vui.motion_vectors_over_pic_boundaries_flag = 1;
  339. sps->vui.log2_max_mv_length_horizontal = 16;
  340. sps->vui.log2_max_mv_length_vertical = 16;
  341. sps->vui.max_num_reorder_frames = (ctx->b_per_p > 0);
  342. sps->vui.max_dec_frame_buffering = vseq->max_num_ref_frames;
  343. pps->nal_unit_header.nal_ref_idc = 3;
  344. pps->nal_unit_header.nal_unit_type = H264_NAL_PPS;
  345. pps->pic_parameter_set_id = 0;
  346. pps->seq_parameter_set_id = 0;
  347. pps->entropy_coding_mode_flag =
  348. !(sps->profile_idc == FF_PROFILE_H264_BASELINE ||
  349. sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
  350. sps->profile_idc == FF_PROFILE_H264_CAVLC_444);
  351. pps->num_ref_idx_l0_default_active_minus1 = 0;
  352. pps->num_ref_idx_l1_default_active_minus1 = 0;
  353. pps->pic_init_qp_minus26 = priv->fixed_qp_idr - 26;
  354. if (sps->profile_idc == FF_PROFILE_H264_BASELINE ||
  355. sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
  356. sps->profile_idc == FF_PROFILE_H264_MAIN) {
  357. pps->more_rbsp_data = 0;
  358. } else {
  359. pps->more_rbsp_data = 1;
  360. pps->transform_8x8_mode_flag = 1;
  361. }
  362. *vseq = (VAEncSequenceParameterBufferH264) {
  363. .seq_parameter_set_id = sps->seq_parameter_set_id,
  364. .level_idc = sps->level_idc,
  365. .intra_period = avctx->gop_size,
  366. .intra_idr_period = avctx->gop_size,
  367. .ip_period = ctx->b_per_p + 1,
  368. .bits_per_second = avctx->bit_rate,
  369. .max_num_ref_frames = sps->max_num_ref_frames,
  370. .picture_width_in_mbs = sps->pic_width_in_mbs_minus1 + 1,
  371. .picture_height_in_mbs = sps->pic_height_in_map_units_minus1 + 1,
  372. .seq_fields.bits = {
  373. .chroma_format_idc = sps->chroma_format_idc,
  374. .frame_mbs_only_flag = sps->frame_mbs_only_flag,
  375. .mb_adaptive_frame_field_flag = sps->mb_adaptive_frame_field_flag,
  376. .seq_scaling_matrix_present_flag = sps->seq_scaling_matrix_present_flag,
  377. .direct_8x8_inference_flag = sps->direct_8x8_inference_flag,
  378. .log2_max_frame_num_minus4 = sps->log2_max_frame_num_minus4,
  379. .pic_order_cnt_type = sps->pic_order_cnt_type,
  380. .log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_pic_order_cnt_lsb_minus4,
  381. .delta_pic_order_always_zero_flag = sps->delta_pic_order_always_zero_flag,
  382. },
  383. .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
  384. .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
  385. .frame_cropping_flag = sps->frame_cropping_flag,
  386. .frame_crop_left_offset = sps->frame_crop_left_offset,
  387. .frame_crop_right_offset = sps->frame_crop_right_offset,
  388. .frame_crop_top_offset = sps->frame_crop_top_offset,
  389. .frame_crop_bottom_offset = sps->frame_crop_bottom_offset,
  390. .vui_parameters_present_flag = sps->vui_parameters_present_flag,
  391. .vui_fields.bits = {
  392. .aspect_ratio_info_present_flag = sps->vui.aspect_ratio_info_present_flag,
  393. .timing_info_present_flag = sps->vui.timing_info_present_flag,
  394. .bitstream_restriction_flag = sps->vui.bitstream_restriction_flag,
  395. .log2_max_mv_length_horizontal = sps->vui.log2_max_mv_length_horizontal,
  396. .log2_max_mv_length_vertical = sps->vui.log2_max_mv_length_vertical,
  397. },
  398. .aspect_ratio_idc = sps->vui.aspect_ratio_idc,
  399. .sar_width = sps->vui.sar_width,
  400. .sar_height = sps->vui.sar_height,
  401. .num_units_in_tick = sps->vui.num_units_in_tick,
  402. .time_scale = sps->vui.time_scale,
  403. };
  404. *vpic = (VAEncPictureParameterBufferH264) {
  405. .CurrPic = {
  406. .picture_id = VA_INVALID_ID,
  407. .flags = VA_PICTURE_H264_INVALID,
  408. },
  409. .coded_buf = VA_INVALID_ID,
  410. .pic_parameter_set_id = pps->pic_parameter_set_id,
  411. .seq_parameter_set_id = pps->seq_parameter_set_id,
  412. .pic_init_qp = pps->pic_init_qp_minus26 + 26,
  413. .num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1,
  414. .num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1,
  415. .chroma_qp_index_offset = pps->chroma_qp_index_offset,
  416. .second_chroma_qp_index_offset = pps->second_chroma_qp_index_offset,
  417. .pic_fields.bits = {
  418. .entropy_coding_mode_flag = pps->entropy_coding_mode_flag,
  419. .weighted_pred_flag = pps->weighted_pred_flag,
  420. .weighted_bipred_idc = pps->weighted_bipred_idc,
  421. .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
  422. .transform_8x8_mode_flag = pps->transform_8x8_mode_flag,
  423. .deblocking_filter_control_present_flag =
  424. pps->deblocking_filter_control_present_flag,
  425. .redundant_pic_cnt_present_flag = pps->redundant_pic_cnt_present_flag,
  426. .pic_order_present_flag =
  427. pps->bottom_field_pic_order_in_frame_present_flag,
  428. .pic_scaling_matrix_present_flag = pps->pic_scaling_matrix_present_flag,
  429. },
  430. };
  431. return 0;
  432. }
  433. static int vaapi_encode_h264_init_picture_params(AVCodecContext *avctx,
  434. VAAPIEncodePicture *pic)
  435. {
  436. VAAPIEncodeContext *ctx = avctx->priv_data;
  437. VAAPIEncodeH264Context *priv = ctx->priv_data;
  438. VAAPIEncodeH264Options *opt = ctx->codec_options;
  439. H264RawSPS *sps = &priv->sps;
  440. VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
  441. int i;
  442. memset(&priv->current_access_unit, 0,
  443. sizeof(priv->current_access_unit));
  444. if (pic->type == PICTURE_TYPE_IDR) {
  445. av_assert0(pic->display_order == pic->encode_order);
  446. priv->frame_num = 0;
  447. priv->next_frame_num = 1;
  448. priv->cpb_delay = 0;
  449. priv->last_idr_frame = pic->display_order;
  450. ++priv->idr_pic_count;
  451. priv->slice_type = 7;
  452. priv->primary_pic_type = 0;
  453. } else {
  454. priv->frame_num = priv->next_frame_num;
  455. if (pic->type != PICTURE_TYPE_B) {
  456. // Reference picture, so frame_num advances.
  457. priv->next_frame_num = (priv->frame_num + 1) &
  458. ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
  459. }
  460. ++priv->cpb_delay;
  461. if (pic->type == PICTURE_TYPE_I) {
  462. priv->slice_type = 7;
  463. priv->primary_pic_type = 0;
  464. } else if (pic->type == PICTURE_TYPE_P) {
  465. priv->slice_type = 5;
  466. priv->primary_pic_type = 1;
  467. } else {
  468. priv->slice_type = 6;
  469. priv->primary_pic_type = 2;
  470. }
  471. }
  472. priv->pic_order_cnt = pic->display_order - priv->last_idr_frame;
  473. priv->dpb_delay = pic->display_order - pic->encode_order + 1;
  474. if (opt->sei & SEI_IDENTIFIER && pic->encode_order == 0)
  475. priv->sei_needed = 1;
  476. if (opt->sei & SEI_TIMING) {
  477. memset(&priv->pic_timing, 0, sizeof(priv->pic_timing));
  478. priv->pic_timing.cpb_removal_delay =
  479. 2 * sps->vui.num_units_in_tick * priv->cpb_delay;
  480. priv->pic_timing.dpb_output_delay =
  481. 2 * sps->vui.num_units_in_tick * priv->dpb_delay;
  482. priv->sei_needed = 1;
  483. }
  484. vpic->CurrPic = (VAPictureH264) {
  485. .picture_id = pic->recon_surface,
  486. .frame_idx = priv->frame_num,
  487. .flags = 0,
  488. .TopFieldOrderCnt = priv->pic_order_cnt,
  489. .BottomFieldOrderCnt = priv->pic_order_cnt,
  490. };
  491. for (i = 0; i < pic->nb_refs; i++) {
  492. VAAPIEncodePicture *ref = pic->refs[i];
  493. unsigned int frame_num = (ref->encode_order - priv->last_idr_frame) &
  494. ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
  495. unsigned int pic_order_cnt = ref->display_order - priv->last_idr_frame;
  496. av_assert0(ref && ref->encode_order < pic->encode_order);
  497. vpic->ReferenceFrames[i] = (VAPictureH264) {
  498. .picture_id = ref->recon_surface,
  499. .frame_idx = frame_num,
  500. .flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE,
  501. .TopFieldOrderCnt = pic_order_cnt,
  502. .BottomFieldOrderCnt = pic_order_cnt,
  503. };
  504. }
  505. for (; i < FF_ARRAY_ELEMS(vpic->ReferenceFrames); i++) {
  506. vpic->ReferenceFrames[i] = (VAPictureH264) {
  507. .picture_id = VA_INVALID_ID,
  508. .flags = VA_PICTURE_H264_INVALID,
  509. };
  510. }
  511. vpic->coded_buf = pic->output_buffer;
  512. vpic->frame_num = priv->frame_num;
  513. vpic->pic_fields.bits.idr_pic_flag = (pic->type == PICTURE_TYPE_IDR);
  514. vpic->pic_fields.bits.reference_pic_flag = (pic->type != PICTURE_TYPE_B);
  515. pic->nb_slices = 1;
  516. return 0;
  517. }
  518. static int vaapi_encode_h264_init_slice_params(AVCodecContext *avctx,
  519. VAAPIEncodePicture *pic,
  520. VAAPIEncodeSlice *slice)
  521. {
  522. VAAPIEncodeContext *ctx = avctx->priv_data;
  523. VAAPIEncodeH264Context *priv = ctx->priv_data;
  524. H264RawSPS *sps = &priv->sps;
  525. H264RawPPS *pps = &priv->pps;
  526. H264RawSliceHeader *sh = &priv->slice.header;
  527. VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
  528. VAEncSliceParameterBufferH264 *vslice = slice->codec_slice_params;
  529. int i;
  530. if (pic->type == PICTURE_TYPE_IDR) {
  531. sh->nal_unit_header.nal_unit_type = H264_NAL_IDR_SLICE;
  532. sh->nal_unit_header.nal_ref_idc = 3;
  533. } else {
  534. sh->nal_unit_header.nal_unit_type = H264_NAL_SLICE;
  535. sh->nal_unit_header.nal_ref_idc = pic->type != PICTURE_TYPE_B;
  536. }
  537. // Only one slice per frame.
  538. sh->first_mb_in_slice = 0;
  539. sh->slice_type = priv->slice_type;
  540. sh->pic_parameter_set_id = pps->pic_parameter_set_id;
  541. sh->frame_num = priv->frame_num;
  542. sh->idr_pic_id = priv->idr_pic_count;
  543. sh->pic_order_cnt_lsb = priv->pic_order_cnt &
  544. ((1 << (4 + sps->log2_max_pic_order_cnt_lsb_minus4)) - 1);
  545. sh->direct_spatial_mv_pred_flag = 1;
  546. if (pic->type == PICTURE_TYPE_B)
  547. sh->slice_qp_delta = priv->fixed_qp_b - (pps->pic_init_qp_minus26 + 26);
  548. else if (pic->type == PICTURE_TYPE_P)
  549. sh->slice_qp_delta = priv->fixed_qp_p - (pps->pic_init_qp_minus26 + 26);
  550. else
  551. sh->slice_qp_delta = priv->fixed_qp_idr - (pps->pic_init_qp_minus26 + 26);
  552. vslice->macroblock_address = sh->first_mb_in_slice;
  553. vslice->num_macroblocks = priv->mb_width * priv->mb_height;
  554. vslice->macroblock_info = VA_INVALID_ID;
  555. vslice->slice_type = sh->slice_type % 5;
  556. vslice->pic_parameter_set_id = sh->pic_parameter_set_id;
  557. vslice->idr_pic_id = sh->idr_pic_id;
  558. vslice->pic_order_cnt_lsb = sh->pic_order_cnt_lsb;
  559. vslice->direct_spatial_mv_pred_flag = sh->direct_spatial_mv_pred_flag;
  560. for (i = 0; i < FF_ARRAY_ELEMS(vslice->RefPicList0); i++) {
  561. vslice->RefPicList0[i].picture_id = VA_INVALID_ID;
  562. vslice->RefPicList0[i].flags = VA_PICTURE_H264_INVALID;
  563. vslice->RefPicList1[i].picture_id = VA_INVALID_ID;
  564. vslice->RefPicList1[i].flags = VA_PICTURE_H264_INVALID;
  565. }
  566. av_assert0(pic->nb_refs <= 2);
  567. if (pic->nb_refs >= 1) {
  568. // Backward reference for P- or B-frame.
  569. av_assert0(pic->type == PICTURE_TYPE_P ||
  570. pic->type == PICTURE_TYPE_B);
  571. vslice->RefPicList0[0] = vpic->ReferenceFrames[0];
  572. }
  573. if (pic->nb_refs >= 2) {
  574. // Forward reference for B-frame.
  575. av_assert0(pic->type == PICTURE_TYPE_B);
  576. vslice->RefPicList1[0] = vpic->ReferenceFrames[1];
  577. }
  578. vslice->slice_qp_delta = sh->slice_qp_delta;
  579. return 0;
  580. }
  581. static av_cold int vaapi_encode_h264_configure(AVCodecContext *avctx)
  582. {
  583. VAAPIEncodeContext *ctx = avctx->priv_data;
  584. VAAPIEncodeH264Context *priv = ctx->priv_data;
  585. VAAPIEncodeH264Options *opt = ctx->codec_options;
  586. int err;
  587. err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_H264, avctx);
  588. if (err < 0)
  589. return err;
  590. priv->mb_width = FFALIGN(avctx->width, 16) / 16;
  591. priv->mb_height = FFALIGN(avctx->height, 16) / 16;
  592. if (ctx->va_rc_mode == VA_RC_CQP) {
  593. priv->fixed_qp_p = opt->qp;
  594. if (avctx->i_quant_factor > 0.0)
  595. priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
  596. avctx->i_quant_offset) + 0.5);
  597. else
  598. priv->fixed_qp_idr = priv->fixed_qp_p;
  599. if (avctx->b_quant_factor > 0.0)
  600. priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
  601. avctx->b_quant_offset) + 0.5);
  602. else
  603. priv->fixed_qp_b = priv->fixed_qp_p;
  604. opt->sei &= ~SEI_TIMING;
  605. av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
  606. "%d / %d / %d for IDR- / P- / B-frames.\n",
  607. priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
  608. } else if (ctx->va_rc_mode == VA_RC_CBR ||
  609. ctx->va_rc_mode == VA_RC_VBR) {
  610. // These still need to be set for pic_init_qp/slice_qp_delta.
  611. priv->fixed_qp_idr = 26;
  612. priv->fixed_qp_p = 26;
  613. priv->fixed_qp_b = 26;
  614. av_log(avctx, AV_LOG_DEBUG, "Using %s-bitrate = %d bps.\n",
  615. ctx->va_rc_mode == VA_RC_CBR ? "constant" : "variable",
  616. avctx->bit_rate);
  617. } else {
  618. av_assert0(0 && "Invalid RC mode.");
  619. }
  620. if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
  621. avctx->compression_level = opt->quality;
  622. if (opt->sei & SEI_IDENTIFIER) {
  623. const char *lavc = LIBAVCODEC_IDENT;
  624. const char *vaapi = VA_VERSION_S;
  625. const char *driver;
  626. int len;
  627. memcpy(priv->identifier.uuid_iso_iec_11578,
  628. vaapi_encode_h264_sei_identifier_uuid,
  629. sizeof(priv->identifier.uuid_iso_iec_11578));
  630. driver = vaQueryVendorString(ctx->hwctx->display);
  631. if (!driver)
  632. driver = "unknown driver";
  633. len = snprintf(NULL, 0, "%s / VAAPI %s / %s", lavc, vaapi, driver);
  634. if (len >= 0) {
  635. priv->identifier_string = av_malloc(len + 1);
  636. if (!priv->identifier_string)
  637. return AVERROR(ENOMEM);
  638. snprintf(priv->identifier_string, len + 1,
  639. "%s / VAAPI %s / %s", lavc, vaapi, driver);
  640. priv->identifier.data = priv->identifier_string;
  641. priv->identifier.data_length = len + 1;
  642. }
  643. }
  644. return 0;
  645. }
  646. static const VAAPIEncodeType vaapi_encode_type_h264 = {
  647. .priv_data_size = sizeof(VAAPIEncodeH264Context),
  648. .configure = &vaapi_encode_h264_configure,
  649. .sequence_params_size = sizeof(VAEncSequenceParameterBufferH264),
  650. .init_sequence_params = &vaapi_encode_h264_init_sequence_params,
  651. .picture_params_size = sizeof(VAEncPictureParameterBufferH264),
  652. .init_picture_params = &vaapi_encode_h264_init_picture_params,
  653. .slice_params_size = sizeof(VAEncSliceParameterBufferH264),
  654. .init_slice_params = &vaapi_encode_h264_init_slice_params,
  655. .sequence_header_type = VAEncPackedHeaderSequence,
  656. .write_sequence_header = &vaapi_encode_h264_write_sequence_header,
  657. .slice_header_type = VAEncPackedHeaderH264_Slice,
  658. .write_slice_header = &vaapi_encode_h264_write_slice_header,
  659. .write_extra_header = &vaapi_encode_h264_write_extra_header,
  660. };
  661. static av_cold int vaapi_encode_h264_init(AVCodecContext *avctx)
  662. {
  663. VAAPIEncodeContext *ctx = avctx->priv_data;
  664. VAAPIEncodeH264Options *opt =
  665. (VAAPIEncodeH264Options*)ctx->codec_options_data;
  666. ctx->codec = &vaapi_encode_type_h264;
  667. switch (avctx->profile) {
  668. case FF_PROFILE_H264_CONSTRAINED_BASELINE:
  669. ctx->va_profile = VAProfileH264ConstrainedBaseline;
  670. break;
  671. case FF_PROFILE_H264_BASELINE:
  672. ctx->va_profile = VAProfileH264Baseline;
  673. break;
  674. case FF_PROFILE_H264_MAIN:
  675. ctx->va_profile = VAProfileH264Main;
  676. break;
  677. case FF_PROFILE_H264_EXTENDED:
  678. av_log(avctx, AV_LOG_ERROR, "H.264 extended profile "
  679. "is not supported.\n");
  680. return AVERROR_PATCHWELCOME;
  681. case FF_PROFILE_UNKNOWN:
  682. case FF_PROFILE_H264_HIGH:
  683. ctx->va_profile = VAProfileH264High;
  684. break;
  685. case FF_PROFILE_H264_HIGH_10:
  686. case FF_PROFILE_H264_HIGH_10_INTRA:
  687. av_log(avctx, AV_LOG_ERROR, "H.264 10-bit profiles "
  688. "are not supported.\n");
  689. return AVERROR_PATCHWELCOME;
  690. case FF_PROFILE_H264_HIGH_422:
  691. case FF_PROFILE_H264_HIGH_422_INTRA:
  692. case FF_PROFILE_H264_HIGH_444:
  693. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  694. case FF_PROFILE_H264_HIGH_444_INTRA:
  695. case FF_PROFILE_H264_CAVLC_444:
  696. av_log(avctx, AV_LOG_ERROR, "H.264 non-4:2:0 profiles "
  697. "are not supported.\n");
  698. return AVERROR_PATCHWELCOME;
  699. default:
  700. av_log(avctx, AV_LOG_ERROR, "Unknown H.264 profile %d.\n",
  701. avctx->profile);
  702. return AVERROR(EINVAL);
  703. }
  704. if (opt->low_power) {
  705. #if VA_CHECK_VERSION(0, 39, 2)
  706. ctx->va_entrypoint = VAEntrypointEncSliceLP;
  707. #else
  708. av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
  709. "supported with this VAAPI version.\n");
  710. return AVERROR(EINVAL);
  711. #endif
  712. } else {
  713. ctx->va_entrypoint = VAEntrypointEncSlice;
  714. }
  715. // Only 8-bit encode is supported.
  716. ctx->va_rt_format = VA_RT_FORMAT_YUV420;
  717. if (avctx->bit_rate > 0) {
  718. if (avctx->rc_max_rate == avctx->bit_rate)
  719. ctx->va_rc_mode = VA_RC_CBR;
  720. else
  721. ctx->va_rc_mode = VA_RC_VBR;
  722. } else
  723. ctx->va_rc_mode = VA_RC_CQP;
  724. ctx->va_packed_headers =
  725. VA_ENC_PACKED_HEADER_SEQUENCE | // SPS and PPS.
  726. VA_ENC_PACKED_HEADER_SLICE | // Slice headers.
  727. VA_ENC_PACKED_HEADER_MISC; // SEI.
  728. ctx->surface_width = FFALIGN(avctx->width, 16);
  729. ctx->surface_height = FFALIGN(avctx->height, 16);
  730. return ff_vaapi_encode_init(avctx);
  731. }
  732. static av_cold int vaapi_encode_h264_close(AVCodecContext *avctx)
  733. {
  734. VAAPIEncodeContext *ctx = avctx->priv_data;
  735. VAAPIEncodeH264Context *priv = ctx->priv_data;
  736. if (priv) {
  737. ff_cbs_close(&priv->cbc);
  738. av_freep(&priv->identifier_string);
  739. }
  740. return ff_vaapi_encode_close(avctx);
  741. }
  742. #define OFFSET(x) (offsetof(VAAPIEncodeContext, codec_options_data) + \
  743. offsetof(VAAPIEncodeH264Options, x))
  744. #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
  745. static const AVOption vaapi_encode_h264_options[] = {
  746. { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
  747. OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 20 }, 0, 52, FLAGS },
  748. { "quality", "Set encode quality (trades off against speed, higher is faster)",
  749. OFFSET(quality), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 8, FLAGS },
  750. { "low_power", "Use low-power encoding mode (experimental: only supported "
  751. "on some platforms, does not support all features)",
  752. OFFSET(low_power), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
  753. { "sei", "Set SEI to include",
  754. OFFSET(sei), AV_OPT_TYPE_FLAGS,
  755. { .i64 = SEI_IDENTIFIER | SEI_TIMING },
  756. 0, INT_MAX, FLAGS, "sei" },
  757. { "identifier", "Include encoder version identifier",
  758. 0, AV_OPT_TYPE_CONST, { .i64 = SEI_IDENTIFIER },
  759. INT_MIN, INT_MAX, FLAGS, "sei" },
  760. { "timing", "Include timing parameters (buffering_period and pic_timing)",
  761. 0, AV_OPT_TYPE_CONST, { .i64 = SEI_TIMING },
  762. INT_MIN, INT_MAX, FLAGS, "sei" },
  763. { NULL },
  764. };
  765. static const AVCodecDefault vaapi_encode_h264_defaults[] = {
  766. { "profile", "100" },
  767. { "level", "51" },
  768. { "b", "0" },
  769. { "bf", "2" },
  770. { "g", "120" },
  771. { "i_qfactor", "1.0" },
  772. { "i_qoffset", "0.0" },
  773. { "b_qfactor", "1.2" },
  774. { "b_qoffset", "0.0" },
  775. { "qmin", "0" },
  776. { NULL },
  777. };
  778. static const AVClass vaapi_encode_h264_class = {
  779. .class_name = "h264_vaapi",
  780. .item_name = av_default_item_name,
  781. .option = vaapi_encode_h264_options,
  782. .version = LIBAVUTIL_VERSION_INT,
  783. };
  784. AVCodec ff_h264_vaapi_encoder = {
  785. .name = "h264_vaapi",
  786. .long_name = NULL_IF_CONFIG_SMALL("H.264/AVC (VAAPI)"),
  787. .type = AVMEDIA_TYPE_VIDEO,
  788. .id = AV_CODEC_ID_H264,
  789. .priv_data_size = (sizeof(VAAPIEncodeContext) +
  790. sizeof(VAAPIEncodeH264Options)),
  791. .init = &vaapi_encode_h264_init,
  792. .encode2 = &ff_vaapi_encode2,
  793. .close = &vaapi_encode_h264_close,
  794. .priv_class = &vaapi_encode_h264_class,
  795. .capabilities = AV_CODEC_CAP_DELAY,
  796. .defaults = vaapi_encode_h264_defaults,
  797. .pix_fmts = (const enum AVPixelFormat[]) {
  798. AV_PIX_FMT_VAAPI,
  799. AV_PIX_FMT_NONE,
  800. },
  801. };