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.

1019 lines
36KB

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