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.

1040 lines
37KB

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