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.

2562 lines
87KB

  1. /*
  2. * This file is part of FFmpeg.
  3. *
  4. * FFmpeg is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * FFmpeg is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with FFmpeg; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include <inttypes.h>
  19. #include <string.h>
  20. #include "libavutil/avassert.h"
  21. #include "libavutil/common.h"
  22. #include "libavutil/internal.h"
  23. #include "libavutil/log.h"
  24. #include "libavutil/pixdesc.h"
  25. #include "vaapi_encode.h"
  26. #include "encode.h"
  27. #include "avcodec.h"
  28. const AVCodecHWConfigInternal *const ff_vaapi_encode_hw_configs[] = {
  29. HW_CONFIG_ENCODER_FRAMES(VAAPI, VAAPI),
  30. NULL,
  31. };
  32. static const char * const picture_type_name[] = { "IDR", "I", "P", "B" };
  33. static int vaapi_encode_make_packed_header(AVCodecContext *avctx,
  34. VAAPIEncodePicture *pic,
  35. int type, char *data, size_t bit_len)
  36. {
  37. VAAPIEncodeContext *ctx = avctx->priv_data;
  38. VAStatus vas;
  39. VABufferID param_buffer, data_buffer;
  40. VABufferID *tmp;
  41. VAEncPackedHeaderParameterBuffer params = {
  42. .type = type,
  43. .bit_length = bit_len,
  44. .has_emulation_bytes = 1,
  45. };
  46. tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 2);
  47. if (!tmp)
  48. return AVERROR(ENOMEM);
  49. pic->param_buffers = tmp;
  50. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  51. VAEncPackedHeaderParameterBufferType,
  52. sizeof(params), 1, &params, &param_buffer);
  53. if (vas != VA_STATUS_SUCCESS) {
  54. av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
  55. "for packed header (type %d): %d (%s).\n",
  56. type, vas, vaErrorStr(vas));
  57. return AVERROR(EIO);
  58. }
  59. pic->param_buffers[pic->nb_param_buffers++] = param_buffer;
  60. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  61. VAEncPackedHeaderDataBufferType,
  62. (bit_len + 7) / 8, 1, data, &data_buffer);
  63. if (vas != VA_STATUS_SUCCESS) {
  64. av_log(avctx, AV_LOG_ERROR, "Failed to create data buffer "
  65. "for packed header (type %d): %d (%s).\n",
  66. type, vas, vaErrorStr(vas));
  67. return AVERROR(EIO);
  68. }
  69. pic->param_buffers[pic->nb_param_buffers++] = data_buffer;
  70. av_log(avctx, AV_LOG_DEBUG, "Packed header buffer (%d) is %#x/%#x "
  71. "(%zu bits).\n", type, param_buffer, data_buffer, bit_len);
  72. return 0;
  73. }
  74. static int vaapi_encode_make_param_buffer(AVCodecContext *avctx,
  75. VAAPIEncodePicture *pic,
  76. int type, char *data, size_t len)
  77. {
  78. VAAPIEncodeContext *ctx = avctx->priv_data;
  79. VAStatus vas;
  80. VABufferID *tmp;
  81. VABufferID buffer;
  82. tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 1);
  83. if (!tmp)
  84. return AVERROR(ENOMEM);
  85. pic->param_buffers = tmp;
  86. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  87. type, len, 1, data, &buffer);
  88. if (vas != VA_STATUS_SUCCESS) {
  89. av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
  90. "(type %d): %d (%s).\n", type, vas, vaErrorStr(vas));
  91. return AVERROR(EIO);
  92. }
  93. pic->param_buffers[pic->nb_param_buffers++] = buffer;
  94. av_log(avctx, AV_LOG_DEBUG, "Param buffer (%d) is %#x.\n",
  95. type, buffer);
  96. return 0;
  97. }
  98. static int vaapi_encode_make_misc_param_buffer(AVCodecContext *avctx,
  99. VAAPIEncodePicture *pic,
  100. int type,
  101. const void *data, size_t len)
  102. {
  103. // Construct the buffer on the stack - 1KB is much larger than any
  104. // current misc parameter buffer type (the largest is EncQuality at
  105. // 224 bytes).
  106. uint8_t buffer[1024];
  107. VAEncMiscParameterBuffer header = {
  108. .type = type,
  109. };
  110. size_t buffer_size = sizeof(header) + len;
  111. av_assert0(buffer_size <= sizeof(buffer));
  112. memcpy(buffer, &header, sizeof(header));
  113. memcpy(buffer + sizeof(header), data, len);
  114. return vaapi_encode_make_param_buffer(avctx, pic,
  115. VAEncMiscParameterBufferType,
  116. buffer, buffer_size);
  117. }
  118. static int vaapi_encode_wait(AVCodecContext *avctx,
  119. VAAPIEncodePicture *pic)
  120. {
  121. VAAPIEncodeContext *ctx = avctx->priv_data;
  122. VAStatus vas;
  123. av_assert0(pic->encode_issued);
  124. if (pic->encode_complete) {
  125. // Already waited for this picture.
  126. return 0;
  127. }
  128. av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
  129. "(input surface %#x).\n", pic->display_order,
  130. pic->encode_order, pic->input_surface);
  131. vas = vaSyncSurface(ctx->hwctx->display, pic->input_surface);
  132. if (vas != VA_STATUS_SUCCESS) {
  133. av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
  134. "%d (%s).\n", vas, vaErrorStr(vas));
  135. return AVERROR(EIO);
  136. }
  137. // Input is definitely finished with now.
  138. av_frame_free(&pic->input_image);
  139. pic->encode_complete = 1;
  140. return 0;
  141. }
  142. static int vaapi_encode_make_row_slice(AVCodecContext *avctx,
  143. VAAPIEncodePicture *pic)
  144. {
  145. VAAPIEncodeContext *ctx = avctx->priv_data;
  146. VAAPIEncodeSlice *slice;
  147. int i, rounding;
  148. for (i = 0; i < pic->nb_slices; i++)
  149. pic->slices[i].row_size = ctx->slice_size;
  150. rounding = ctx->slice_block_rows - ctx->nb_slices * ctx->slice_size;
  151. if (rounding > 0) {
  152. // Place rounding error at top and bottom of frame.
  153. av_assert0(rounding < pic->nb_slices);
  154. // Some Intel drivers contain a bug where the encoder will fail
  155. // if the last slice is smaller than the one before it. Since
  156. // that's straightforward to avoid here, just do so.
  157. if (rounding <= 2) {
  158. for (i = 0; i < rounding; i++)
  159. ++pic->slices[i].row_size;
  160. } else {
  161. for (i = 0; i < (rounding + 1) / 2; i++)
  162. ++pic->slices[pic->nb_slices - i - 1].row_size;
  163. for (i = 0; i < rounding / 2; i++)
  164. ++pic->slices[i].row_size;
  165. }
  166. } else if (rounding < 0) {
  167. // Remove rounding error from last slice only.
  168. av_assert0(rounding < ctx->slice_size);
  169. pic->slices[pic->nb_slices - 1].row_size += rounding;
  170. }
  171. for (i = 0; i < pic->nb_slices; i++) {
  172. slice = &pic->slices[i];
  173. slice->index = i;
  174. if (i == 0) {
  175. slice->row_start = 0;
  176. slice->block_start = 0;
  177. } else {
  178. const VAAPIEncodeSlice *prev = &pic->slices[i - 1];
  179. slice->row_start = prev->row_start + prev->row_size;
  180. slice->block_start = prev->block_start + prev->block_size;
  181. }
  182. slice->block_size = slice->row_size * ctx->slice_block_cols;
  183. av_log(avctx, AV_LOG_DEBUG, "Slice %d: %d-%d (%d rows), "
  184. "%d-%d (%d blocks).\n", i, slice->row_start,
  185. slice->row_start + slice->row_size - 1, slice->row_size,
  186. slice->block_start, slice->block_start + slice->block_size - 1,
  187. slice->block_size);
  188. }
  189. return 0;
  190. }
  191. static int vaapi_encode_make_tile_slice(AVCodecContext *avctx,
  192. VAAPIEncodePicture *pic)
  193. {
  194. VAAPIEncodeContext *ctx = avctx->priv_data;
  195. VAAPIEncodeSlice *slice;
  196. int i, j, index;
  197. for (i = 0; i < ctx->tile_cols; i++) {
  198. for (j = 0; j < ctx->tile_rows; j++) {
  199. index = j * ctx->tile_cols + i;
  200. slice = &pic->slices[index];
  201. slice->index = index;
  202. pic->slices[index].block_start = ctx->col_bd[i] +
  203. ctx->row_bd[j] * ctx->slice_block_cols;
  204. pic->slices[index].block_size = ctx->row_height[j] * ctx->col_width[i];
  205. av_log(avctx, AV_LOG_DEBUG, "Slice %2d: (%2d, %2d) start at: %4d "
  206. "width:%2d height:%2d (%d blocks).\n", index, ctx->col_bd[i],
  207. ctx->row_bd[j], slice->block_start, ctx->col_width[i],
  208. ctx->row_height[j], slice->block_size);
  209. }
  210. }
  211. return 0;
  212. }
  213. static int vaapi_encode_issue(AVCodecContext *avctx,
  214. VAAPIEncodePicture *pic)
  215. {
  216. VAAPIEncodeContext *ctx = avctx->priv_data;
  217. VAAPIEncodeSlice *slice;
  218. VAStatus vas;
  219. int err, i;
  220. char data[MAX_PARAM_BUFFER_SIZE];
  221. size_t bit_len;
  222. av_unused AVFrameSideData *sd;
  223. av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
  224. "as type %s.\n", pic->display_order, pic->encode_order,
  225. picture_type_name[pic->type]);
  226. if (pic->nb_refs == 0) {
  227. av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
  228. } else {
  229. av_log(avctx, AV_LOG_DEBUG, "Refers to:");
  230. for (i = 0; i < pic->nb_refs; i++) {
  231. av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
  232. pic->refs[i]->display_order, pic->refs[i]->encode_order);
  233. }
  234. av_log(avctx, AV_LOG_DEBUG, ".\n");
  235. }
  236. av_assert0(!pic->encode_issued);
  237. for (i = 0; i < pic->nb_refs; i++) {
  238. av_assert0(pic->refs[i]);
  239. av_assert0(pic->refs[i]->encode_issued);
  240. }
  241. av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
  242. pic->recon_image = av_frame_alloc();
  243. if (!pic->recon_image) {
  244. err = AVERROR(ENOMEM);
  245. goto fail;
  246. }
  247. err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
  248. if (err < 0) {
  249. err = AVERROR(ENOMEM);
  250. goto fail;
  251. }
  252. pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
  253. av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
  254. pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
  255. if (!pic->output_buffer_ref) {
  256. err = AVERROR(ENOMEM);
  257. goto fail;
  258. }
  259. pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
  260. av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
  261. pic->output_buffer);
  262. if (ctx->codec->picture_params_size > 0) {
  263. pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
  264. if (!pic->codec_picture_params)
  265. goto fail;
  266. memcpy(pic->codec_picture_params, ctx->codec_picture_params,
  267. ctx->codec->picture_params_size);
  268. } else {
  269. av_assert0(!ctx->codec_picture_params);
  270. }
  271. pic->nb_param_buffers = 0;
  272. if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
  273. err = vaapi_encode_make_param_buffer(avctx, pic,
  274. VAEncSequenceParameterBufferType,
  275. ctx->codec_sequence_params,
  276. ctx->codec->sequence_params_size);
  277. if (err < 0)
  278. goto fail;
  279. }
  280. if (pic->type == PICTURE_TYPE_IDR) {
  281. for (i = 0; i < ctx->nb_global_params; i++) {
  282. err = vaapi_encode_make_misc_param_buffer(avctx, pic,
  283. ctx->global_params_type[i],
  284. ctx->global_params[i],
  285. ctx->global_params_size[i]);
  286. if (err < 0)
  287. goto fail;
  288. }
  289. }
  290. if (ctx->codec->init_picture_params) {
  291. err = ctx->codec->init_picture_params(avctx, pic);
  292. if (err < 0) {
  293. av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
  294. "parameters: %d.\n", err);
  295. goto fail;
  296. }
  297. err = vaapi_encode_make_param_buffer(avctx, pic,
  298. VAEncPictureParameterBufferType,
  299. pic->codec_picture_params,
  300. ctx->codec->picture_params_size);
  301. if (err < 0)
  302. goto fail;
  303. }
  304. if (pic->type == PICTURE_TYPE_IDR) {
  305. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
  306. ctx->codec->write_sequence_header) {
  307. bit_len = 8 * sizeof(data);
  308. err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
  309. if (err < 0) {
  310. av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
  311. "header: %d.\n", err);
  312. goto fail;
  313. }
  314. err = vaapi_encode_make_packed_header(avctx, pic,
  315. ctx->codec->sequence_header_type,
  316. data, bit_len);
  317. if (err < 0)
  318. goto fail;
  319. }
  320. }
  321. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
  322. ctx->codec->write_picture_header) {
  323. bit_len = 8 * sizeof(data);
  324. err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
  325. if (err < 0) {
  326. av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
  327. "header: %d.\n", err);
  328. goto fail;
  329. }
  330. err = vaapi_encode_make_packed_header(avctx, pic,
  331. ctx->codec->picture_header_type,
  332. data, bit_len);
  333. if (err < 0)
  334. goto fail;
  335. }
  336. if (ctx->codec->write_extra_buffer) {
  337. for (i = 0;; i++) {
  338. size_t len = sizeof(data);
  339. int type;
  340. err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
  341. data, &len);
  342. if (err == AVERROR_EOF)
  343. break;
  344. if (err < 0) {
  345. av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
  346. "buffer %d: %d.\n", i, err);
  347. goto fail;
  348. }
  349. err = vaapi_encode_make_param_buffer(avctx, pic, type,
  350. data, len);
  351. if (err < 0)
  352. goto fail;
  353. }
  354. }
  355. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
  356. ctx->codec->write_extra_header) {
  357. for (i = 0;; i++) {
  358. int type;
  359. bit_len = 8 * sizeof(data);
  360. err = ctx->codec->write_extra_header(avctx, pic, i, &type,
  361. data, &bit_len);
  362. if (err == AVERROR_EOF)
  363. break;
  364. if (err < 0) {
  365. av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
  366. "header %d: %d.\n", i, err);
  367. goto fail;
  368. }
  369. err = vaapi_encode_make_packed_header(avctx, pic, type,
  370. data, bit_len);
  371. if (err < 0)
  372. goto fail;
  373. }
  374. }
  375. if (pic->nb_slices == 0)
  376. pic->nb_slices = ctx->nb_slices;
  377. if (pic->nb_slices > 0) {
  378. pic->slices = av_mallocz_array(pic->nb_slices, sizeof(*pic->slices));
  379. if (!pic->slices) {
  380. err = AVERROR(ENOMEM);
  381. goto fail;
  382. }
  383. if (ctx->tile_rows && ctx->tile_cols)
  384. vaapi_encode_make_tile_slice(avctx, pic);
  385. else
  386. vaapi_encode_make_row_slice(avctx, pic);
  387. }
  388. for (i = 0; i < pic->nb_slices; i++) {
  389. slice = &pic->slices[i];
  390. if (ctx->codec->slice_params_size > 0) {
  391. slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
  392. if (!slice->codec_slice_params) {
  393. err = AVERROR(ENOMEM);
  394. goto fail;
  395. }
  396. }
  397. if (ctx->codec->init_slice_params) {
  398. err = ctx->codec->init_slice_params(avctx, pic, slice);
  399. if (err < 0) {
  400. av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
  401. "parameters: %d.\n", err);
  402. goto fail;
  403. }
  404. }
  405. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
  406. ctx->codec->write_slice_header) {
  407. bit_len = 8 * sizeof(data);
  408. err = ctx->codec->write_slice_header(avctx, pic, slice,
  409. data, &bit_len);
  410. if (err < 0) {
  411. av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
  412. "header: %d.\n", err);
  413. goto fail;
  414. }
  415. err = vaapi_encode_make_packed_header(avctx, pic,
  416. ctx->codec->slice_header_type,
  417. data, bit_len);
  418. if (err < 0)
  419. goto fail;
  420. }
  421. if (ctx->codec->init_slice_params) {
  422. err = vaapi_encode_make_param_buffer(avctx, pic,
  423. VAEncSliceParameterBufferType,
  424. slice->codec_slice_params,
  425. ctx->codec->slice_params_size);
  426. if (err < 0)
  427. goto fail;
  428. }
  429. }
  430. #if VA_CHECK_VERSION(1, 0, 0)
  431. sd = av_frame_get_side_data(pic->input_image,
  432. AV_FRAME_DATA_REGIONS_OF_INTEREST);
  433. if (sd && ctx->roi_allowed) {
  434. const AVRegionOfInterest *roi;
  435. uint32_t roi_size;
  436. VAEncMiscParameterBufferROI param_roi;
  437. int nb_roi, i, v;
  438. roi = (const AVRegionOfInterest*)sd->data;
  439. roi_size = roi->self_size;
  440. av_assert0(roi_size && sd->size % roi_size == 0);
  441. nb_roi = sd->size / roi_size;
  442. if (nb_roi > ctx->roi_max_regions) {
  443. if (!ctx->roi_warned) {
  444. av_log(avctx, AV_LOG_WARNING, "More ROIs set than "
  445. "supported by driver (%d > %d).\n",
  446. nb_roi, ctx->roi_max_regions);
  447. ctx->roi_warned = 1;
  448. }
  449. nb_roi = ctx->roi_max_regions;
  450. }
  451. pic->roi = av_mallocz_array(nb_roi, sizeof(*pic->roi));
  452. if (!pic->roi) {
  453. err = AVERROR(ENOMEM);
  454. goto fail;
  455. }
  456. // For overlapping regions, the first in the array takes priority.
  457. for (i = 0; i < nb_roi; i++) {
  458. roi = (const AVRegionOfInterest*)(sd->data + roi_size * i);
  459. av_assert0(roi->qoffset.den != 0);
  460. v = roi->qoffset.num * ctx->roi_quant_range / roi->qoffset.den;
  461. av_log(avctx, AV_LOG_DEBUG, "ROI: (%d,%d)-(%d,%d) -> %+d.\n",
  462. roi->top, roi->left, roi->bottom, roi->right, v);
  463. pic->roi[i] = (VAEncROI) {
  464. .roi_rectangle = {
  465. .x = roi->left,
  466. .y = roi->top,
  467. .width = roi->right - roi->left,
  468. .height = roi->bottom - roi->top,
  469. },
  470. .roi_value = av_clip_int8(v),
  471. };
  472. }
  473. param_roi = (VAEncMiscParameterBufferROI) {
  474. .num_roi = nb_roi,
  475. .max_delta_qp = INT8_MAX,
  476. .min_delta_qp = INT8_MIN,
  477. .roi = pic->roi,
  478. .roi_flags.bits.roi_value_is_qp_delta = 1,
  479. };
  480. err = vaapi_encode_make_misc_param_buffer(avctx, pic,
  481. VAEncMiscParameterTypeROI,
  482. &param_roi,
  483. sizeof(param_roi));
  484. if (err < 0)
  485. goto fail;
  486. }
  487. #endif
  488. vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
  489. pic->input_surface);
  490. if (vas != VA_STATUS_SUCCESS) {
  491. av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
  492. "%d (%s).\n", vas, vaErrorStr(vas));
  493. err = AVERROR(EIO);
  494. goto fail_with_picture;
  495. }
  496. vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
  497. pic->param_buffers, pic->nb_param_buffers);
  498. if (vas != VA_STATUS_SUCCESS) {
  499. av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
  500. "%d (%s).\n", vas, vaErrorStr(vas));
  501. err = AVERROR(EIO);
  502. goto fail_with_picture;
  503. }
  504. vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
  505. if (vas != VA_STATUS_SUCCESS) {
  506. av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
  507. "%d (%s).\n", vas, vaErrorStr(vas));
  508. err = AVERROR(EIO);
  509. // vaRenderPicture() has been called here, so we should not destroy
  510. // the parameter buffers unless separate destruction is required.
  511. if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
  512. AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
  513. goto fail;
  514. else
  515. goto fail_at_end;
  516. }
  517. if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
  518. AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
  519. for (i = 0; i < pic->nb_param_buffers; i++) {
  520. vas = vaDestroyBuffer(ctx->hwctx->display,
  521. pic->param_buffers[i]);
  522. if (vas != VA_STATUS_SUCCESS) {
  523. av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
  524. "param buffer %#x: %d (%s).\n",
  525. pic->param_buffers[i], vas, vaErrorStr(vas));
  526. // And ignore.
  527. }
  528. }
  529. }
  530. pic->encode_issued = 1;
  531. return 0;
  532. fail_with_picture:
  533. vaEndPicture(ctx->hwctx->display, ctx->va_context);
  534. fail:
  535. for(i = 0; i < pic->nb_param_buffers; i++)
  536. vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
  537. if (pic->slices) {
  538. for (i = 0; i < pic->nb_slices; i++)
  539. av_freep(&pic->slices[i].codec_slice_params);
  540. }
  541. fail_at_end:
  542. av_freep(&pic->codec_picture_params);
  543. av_freep(&pic->param_buffers);
  544. av_freep(&pic->slices);
  545. av_freep(&pic->roi);
  546. av_frame_free(&pic->recon_image);
  547. av_buffer_unref(&pic->output_buffer_ref);
  548. pic->output_buffer = VA_INVALID_ID;
  549. return err;
  550. }
  551. static int vaapi_encode_output(AVCodecContext *avctx,
  552. VAAPIEncodePicture *pic, AVPacket *pkt)
  553. {
  554. VAAPIEncodeContext *ctx = avctx->priv_data;
  555. VACodedBufferSegment *buf_list, *buf;
  556. VAStatus vas;
  557. int total_size = 0;
  558. uint8_t *ptr;
  559. int err;
  560. err = vaapi_encode_wait(avctx, pic);
  561. if (err < 0)
  562. return err;
  563. buf_list = NULL;
  564. vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
  565. (void**)&buf_list);
  566. if (vas != VA_STATUS_SUCCESS) {
  567. av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
  568. "%d (%s).\n", vas, vaErrorStr(vas));
  569. err = AVERROR(EIO);
  570. goto fail;
  571. }
  572. for (buf = buf_list; buf; buf = buf->next)
  573. total_size += buf->size;
  574. err = ff_get_encode_buffer(avctx, pkt, total_size, 0);
  575. ptr = pkt->data;
  576. if (err < 0)
  577. goto fail_mapped;
  578. for (buf = buf_list; buf; buf = buf->next) {
  579. av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
  580. "(status %08x).\n", buf->size, buf->status);
  581. memcpy(ptr, buf->buf, buf->size);
  582. ptr += buf->size;
  583. }
  584. if (pic->type == PICTURE_TYPE_IDR)
  585. pkt->flags |= AV_PKT_FLAG_KEY;
  586. pkt->pts = pic->pts;
  587. vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
  588. if (vas != VA_STATUS_SUCCESS) {
  589. av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
  590. "%d (%s).\n", vas, vaErrorStr(vas));
  591. err = AVERROR(EIO);
  592. goto fail;
  593. }
  594. av_buffer_unref(&pic->output_buffer_ref);
  595. pic->output_buffer = VA_INVALID_ID;
  596. av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
  597. pic->display_order, pic->encode_order);
  598. return 0;
  599. fail_mapped:
  600. vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
  601. fail:
  602. av_buffer_unref(&pic->output_buffer_ref);
  603. pic->output_buffer = VA_INVALID_ID;
  604. return err;
  605. }
  606. static int vaapi_encode_discard(AVCodecContext *avctx,
  607. VAAPIEncodePicture *pic)
  608. {
  609. vaapi_encode_wait(avctx, pic);
  610. if (pic->output_buffer_ref) {
  611. av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
  612. "%"PRId64"/%"PRId64".\n",
  613. pic->display_order, pic->encode_order);
  614. av_buffer_unref(&pic->output_buffer_ref);
  615. pic->output_buffer = VA_INVALID_ID;
  616. }
  617. return 0;
  618. }
  619. static VAAPIEncodePicture *vaapi_encode_alloc(AVCodecContext *avctx)
  620. {
  621. VAAPIEncodeContext *ctx = avctx->priv_data;
  622. VAAPIEncodePicture *pic;
  623. pic = av_mallocz(sizeof(*pic));
  624. if (!pic)
  625. return NULL;
  626. if (ctx->codec->picture_priv_data_size > 0) {
  627. pic->priv_data = av_mallocz(ctx->codec->picture_priv_data_size);
  628. if (!pic->priv_data) {
  629. av_freep(&pic);
  630. return NULL;
  631. }
  632. }
  633. pic->input_surface = VA_INVALID_ID;
  634. pic->recon_surface = VA_INVALID_ID;
  635. pic->output_buffer = VA_INVALID_ID;
  636. return pic;
  637. }
  638. static int vaapi_encode_free(AVCodecContext *avctx,
  639. VAAPIEncodePicture *pic)
  640. {
  641. int i;
  642. if (pic->encode_issued)
  643. vaapi_encode_discard(avctx, pic);
  644. if (pic->slices) {
  645. for (i = 0; i < pic->nb_slices; i++)
  646. av_freep(&pic->slices[i].codec_slice_params);
  647. }
  648. av_freep(&pic->codec_picture_params);
  649. av_frame_free(&pic->input_image);
  650. av_frame_free(&pic->recon_image);
  651. av_freep(&pic->param_buffers);
  652. av_freep(&pic->slices);
  653. // Output buffer should already be destroyed.
  654. av_assert0(pic->output_buffer == VA_INVALID_ID);
  655. av_freep(&pic->priv_data);
  656. av_freep(&pic->codec_picture_params);
  657. av_freep(&pic->roi);
  658. av_free(pic);
  659. return 0;
  660. }
  661. static void vaapi_encode_add_ref(AVCodecContext *avctx,
  662. VAAPIEncodePicture *pic,
  663. VAAPIEncodePicture *target,
  664. int is_ref, int in_dpb, int prev)
  665. {
  666. int refs = 0;
  667. if (is_ref) {
  668. av_assert0(pic != target);
  669. av_assert0(pic->nb_refs < MAX_PICTURE_REFERENCES);
  670. pic->refs[pic->nb_refs++] = target;
  671. ++refs;
  672. }
  673. if (in_dpb) {
  674. av_assert0(pic->nb_dpb_pics < MAX_DPB_SIZE);
  675. pic->dpb[pic->nb_dpb_pics++] = target;
  676. ++refs;
  677. }
  678. if (prev) {
  679. av_assert0(!pic->prev);
  680. pic->prev = target;
  681. ++refs;
  682. }
  683. target->ref_count[0] += refs;
  684. target->ref_count[1] += refs;
  685. }
  686. static void vaapi_encode_remove_refs(AVCodecContext *avctx,
  687. VAAPIEncodePicture *pic,
  688. int level)
  689. {
  690. int i;
  691. if (pic->ref_removed[level])
  692. return;
  693. for (i = 0; i < pic->nb_refs; i++) {
  694. av_assert0(pic->refs[i]);
  695. --pic->refs[i]->ref_count[level];
  696. av_assert0(pic->refs[i]->ref_count[level] >= 0);
  697. }
  698. for (i = 0; i < pic->nb_dpb_pics; i++) {
  699. av_assert0(pic->dpb[i]);
  700. --pic->dpb[i]->ref_count[level];
  701. av_assert0(pic->dpb[i]->ref_count[level] >= 0);
  702. }
  703. av_assert0(pic->prev || pic->type == PICTURE_TYPE_IDR);
  704. if (pic->prev) {
  705. --pic->prev->ref_count[level];
  706. av_assert0(pic->prev->ref_count[level] >= 0);
  707. }
  708. pic->ref_removed[level] = 1;
  709. }
  710. static void vaapi_encode_set_b_pictures(AVCodecContext *avctx,
  711. VAAPIEncodePicture *start,
  712. VAAPIEncodePicture *end,
  713. VAAPIEncodePicture *prev,
  714. int current_depth,
  715. VAAPIEncodePicture **last)
  716. {
  717. VAAPIEncodeContext *ctx = avctx->priv_data;
  718. VAAPIEncodePicture *pic, *next, *ref;
  719. int i, len;
  720. av_assert0(start && end && start != end && start->next != end);
  721. // If we are at the maximum depth then encode all pictures as
  722. // non-referenced B-pictures. Also do this if there is exactly one
  723. // picture left, since there will be nothing to reference it.
  724. if (current_depth == ctx->max_b_depth || start->next->next == end) {
  725. for (pic = start->next; pic; pic = pic->next) {
  726. if (pic == end)
  727. break;
  728. pic->type = PICTURE_TYPE_B;
  729. pic->b_depth = current_depth;
  730. vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
  731. vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
  732. vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
  733. for (ref = end->refs[1]; ref; ref = ref->refs[1])
  734. vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
  735. }
  736. *last = prev;
  737. } else {
  738. // Split the current list at the midpoint with a referenced
  739. // B-picture, then descend into each side separately.
  740. len = 0;
  741. for (pic = start->next; pic != end; pic = pic->next)
  742. ++len;
  743. for (pic = start->next, i = 1; 2 * i < len; pic = pic->next, i++);
  744. pic->type = PICTURE_TYPE_B;
  745. pic->b_depth = current_depth;
  746. pic->is_reference = 1;
  747. vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
  748. vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
  749. vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
  750. vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
  751. for (ref = end->refs[1]; ref; ref = ref->refs[1])
  752. vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
  753. if (i > 1)
  754. vaapi_encode_set_b_pictures(avctx, start, pic, pic,
  755. current_depth + 1, &next);
  756. else
  757. next = pic;
  758. vaapi_encode_set_b_pictures(avctx, pic, end, next,
  759. current_depth + 1, last);
  760. }
  761. }
  762. static int vaapi_encode_pick_next(AVCodecContext *avctx,
  763. VAAPIEncodePicture **pic_out)
  764. {
  765. VAAPIEncodeContext *ctx = avctx->priv_data;
  766. VAAPIEncodePicture *pic = NULL, *next, *start;
  767. int i, b_counter, closed_gop_end;
  768. // If there are any B-frames already queued, the next one to encode
  769. // is the earliest not-yet-issued frame for which all references are
  770. // available.
  771. for (pic = ctx->pic_start; pic; pic = pic->next) {
  772. if (pic->encode_issued)
  773. continue;
  774. if (pic->type != PICTURE_TYPE_B)
  775. continue;
  776. for (i = 0; i < pic->nb_refs; i++) {
  777. if (!pic->refs[i]->encode_issued)
  778. break;
  779. }
  780. if (i == pic->nb_refs)
  781. break;
  782. }
  783. if (pic) {
  784. av_log(avctx, AV_LOG_DEBUG, "Pick B-picture at depth %d to "
  785. "encode next.\n", pic->b_depth);
  786. *pic_out = pic;
  787. return 0;
  788. }
  789. // Find the B-per-Pth available picture to become the next picture
  790. // on the top layer.
  791. start = NULL;
  792. b_counter = 0;
  793. closed_gop_end = ctx->closed_gop ||
  794. ctx->idr_counter == ctx->gop_per_idr;
  795. for (pic = ctx->pic_start; pic; pic = next) {
  796. next = pic->next;
  797. if (pic->encode_issued) {
  798. start = pic;
  799. continue;
  800. }
  801. // If the next available picture is force-IDR, encode it to start
  802. // a new GOP immediately.
  803. if (pic->force_idr)
  804. break;
  805. if (b_counter == ctx->b_per_p)
  806. break;
  807. // If this picture ends a closed GOP or starts a new GOP then it
  808. // needs to be in the top layer.
  809. if (ctx->gop_counter + b_counter + closed_gop_end >= ctx->gop_size)
  810. break;
  811. // If the picture after this one is force-IDR, we need to encode
  812. // this one in the top layer.
  813. if (next && next->force_idr)
  814. break;
  815. ++b_counter;
  816. }
  817. // At the end of the stream the last picture must be in the top layer.
  818. if (!pic && ctx->end_of_stream) {
  819. --b_counter;
  820. pic = ctx->pic_end;
  821. if (pic->encode_issued)
  822. return AVERROR_EOF;
  823. }
  824. if (!pic) {
  825. av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
  826. "need more input for reference pictures.\n");
  827. return AVERROR(EAGAIN);
  828. }
  829. if (ctx->input_order <= ctx->decode_delay && !ctx->end_of_stream) {
  830. av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
  831. "need more input for timestamps.\n");
  832. return AVERROR(EAGAIN);
  833. }
  834. if (pic->force_idr) {
  835. av_log(avctx, AV_LOG_DEBUG, "Pick forced IDR-picture to "
  836. "encode next.\n");
  837. pic->type = PICTURE_TYPE_IDR;
  838. ctx->idr_counter = 1;
  839. ctx->gop_counter = 1;
  840. } else if (ctx->gop_counter + b_counter >= ctx->gop_size) {
  841. if (ctx->idr_counter == ctx->gop_per_idr) {
  842. av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP IDR-picture to "
  843. "encode next.\n");
  844. pic->type = PICTURE_TYPE_IDR;
  845. ctx->idr_counter = 1;
  846. } else {
  847. av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP I-picture to "
  848. "encode next.\n");
  849. pic->type = PICTURE_TYPE_I;
  850. ++ctx->idr_counter;
  851. }
  852. ctx->gop_counter = 1;
  853. } else {
  854. if (ctx->gop_counter + b_counter + closed_gop_end == ctx->gop_size) {
  855. av_log(avctx, AV_LOG_DEBUG, "Pick group-end P-picture to "
  856. "encode next.\n");
  857. } else {
  858. av_log(avctx, AV_LOG_DEBUG, "Pick normal P-picture to "
  859. "encode next.\n");
  860. }
  861. pic->type = PICTURE_TYPE_P;
  862. av_assert0(start);
  863. ctx->gop_counter += 1 + b_counter;
  864. }
  865. pic->is_reference = 1;
  866. *pic_out = pic;
  867. vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
  868. if (pic->type != PICTURE_TYPE_IDR) {
  869. vaapi_encode_add_ref(avctx, pic, start,
  870. pic->type == PICTURE_TYPE_P,
  871. b_counter > 0, 0);
  872. vaapi_encode_add_ref(avctx, pic, ctx->next_prev, 0, 0, 1);
  873. }
  874. if (ctx->next_prev)
  875. --ctx->next_prev->ref_count[0];
  876. if (b_counter > 0) {
  877. vaapi_encode_set_b_pictures(avctx, start, pic, pic, 1,
  878. &ctx->next_prev);
  879. } else {
  880. ctx->next_prev = pic;
  881. }
  882. ++ctx->next_prev->ref_count[0];
  883. return 0;
  884. }
  885. static int vaapi_encode_clear_old(AVCodecContext *avctx)
  886. {
  887. VAAPIEncodeContext *ctx = avctx->priv_data;
  888. VAAPIEncodePicture *pic, *prev, *next;
  889. av_assert0(ctx->pic_start);
  890. // Remove direct references once each picture is complete.
  891. for (pic = ctx->pic_start; pic; pic = pic->next) {
  892. if (pic->encode_complete && pic->next)
  893. vaapi_encode_remove_refs(avctx, pic, 0);
  894. }
  895. // Remove indirect references once a picture has no direct references.
  896. for (pic = ctx->pic_start; pic; pic = pic->next) {
  897. if (pic->encode_complete && pic->ref_count[0] == 0)
  898. vaapi_encode_remove_refs(avctx, pic, 1);
  899. }
  900. // Clear out all complete pictures with no remaining references.
  901. prev = NULL;
  902. for (pic = ctx->pic_start; pic; pic = next) {
  903. next = pic->next;
  904. if (pic->encode_complete && pic->ref_count[1] == 0) {
  905. av_assert0(pic->ref_removed[0] && pic->ref_removed[1]);
  906. if (prev)
  907. prev->next = next;
  908. else
  909. ctx->pic_start = next;
  910. vaapi_encode_free(avctx, pic);
  911. } else {
  912. prev = pic;
  913. }
  914. }
  915. return 0;
  916. }
  917. static int vaapi_encode_check_frame(AVCodecContext *avctx,
  918. const AVFrame *frame)
  919. {
  920. VAAPIEncodeContext *ctx = avctx->priv_data;
  921. if ((frame->crop_top || frame->crop_bottom ||
  922. frame->crop_left || frame->crop_right) && !ctx->crop_warned) {
  923. av_log(avctx, AV_LOG_WARNING, "Cropping information on input "
  924. "frames ignored due to lack of API support.\n");
  925. ctx->crop_warned = 1;
  926. }
  927. if (!ctx->roi_allowed) {
  928. AVFrameSideData *sd =
  929. av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
  930. if (sd && !ctx->roi_warned) {
  931. av_log(avctx, AV_LOG_WARNING, "ROI side data on input "
  932. "frames ignored due to lack of driver support.\n");
  933. ctx->roi_warned = 1;
  934. }
  935. }
  936. return 0;
  937. }
  938. static int vaapi_encode_send_frame(AVCodecContext *avctx, AVFrame *frame)
  939. {
  940. VAAPIEncodeContext *ctx = avctx->priv_data;
  941. VAAPIEncodePicture *pic;
  942. int err;
  943. if (frame) {
  944. av_log(avctx, AV_LOG_DEBUG, "Input frame: %ux%u (%"PRId64").\n",
  945. frame->width, frame->height, frame->pts);
  946. err = vaapi_encode_check_frame(avctx, frame);
  947. if (err < 0)
  948. return err;
  949. pic = vaapi_encode_alloc(avctx);
  950. if (!pic)
  951. return AVERROR(ENOMEM);
  952. pic->input_image = av_frame_alloc();
  953. if (!pic->input_image) {
  954. err = AVERROR(ENOMEM);
  955. goto fail;
  956. }
  957. if (ctx->input_order == 0 || frame->pict_type == AV_PICTURE_TYPE_I)
  958. pic->force_idr = 1;
  959. pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
  960. pic->pts = frame->pts;
  961. av_frame_move_ref(pic->input_image, frame);
  962. if (ctx->input_order == 0)
  963. ctx->first_pts = pic->pts;
  964. if (ctx->input_order == ctx->decode_delay)
  965. ctx->dts_pts_diff = pic->pts - ctx->first_pts;
  966. if (ctx->output_delay > 0)
  967. ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
  968. pic->display_order = ctx->input_order;
  969. ++ctx->input_order;
  970. if (ctx->pic_start) {
  971. ctx->pic_end->next = pic;
  972. ctx->pic_end = pic;
  973. } else {
  974. ctx->pic_start = pic;
  975. ctx->pic_end = pic;
  976. }
  977. } else {
  978. ctx->end_of_stream = 1;
  979. // Fix timestamps if we hit end-of-stream before the initial decode
  980. // delay has elapsed.
  981. if (ctx->input_order < ctx->decode_delay)
  982. ctx->dts_pts_diff = ctx->pic_end->pts - ctx->first_pts;
  983. }
  984. return 0;
  985. fail:
  986. vaapi_encode_free(avctx, pic);
  987. return err;
  988. }
  989. int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
  990. {
  991. VAAPIEncodeContext *ctx = avctx->priv_data;
  992. VAAPIEncodePicture *pic;
  993. AVFrame *frame = ctx->frame;
  994. int err;
  995. err = ff_encode_get_frame(avctx, frame);
  996. if (err < 0 && err != AVERROR_EOF)
  997. return err;
  998. if (err == AVERROR_EOF)
  999. frame = NULL;
  1000. err = vaapi_encode_send_frame(avctx, frame);
  1001. if (err < 0)
  1002. return err;
  1003. if (!ctx->pic_start) {
  1004. if (ctx->end_of_stream)
  1005. return AVERROR_EOF;
  1006. else
  1007. return AVERROR(EAGAIN);
  1008. }
  1009. pic = NULL;
  1010. err = vaapi_encode_pick_next(avctx, &pic);
  1011. if (err < 0)
  1012. return err;
  1013. av_assert0(pic);
  1014. pic->encode_order = ctx->encode_order++;
  1015. err = vaapi_encode_issue(avctx, pic);
  1016. if (err < 0) {
  1017. av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
  1018. return err;
  1019. }
  1020. err = vaapi_encode_output(avctx, pic, pkt);
  1021. if (err < 0) {
  1022. av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
  1023. return err;
  1024. }
  1025. if (ctx->output_delay == 0) {
  1026. pkt->dts = pkt->pts;
  1027. } else if (pic->encode_order < ctx->decode_delay) {
  1028. if (ctx->ts_ring[pic->encode_order] < INT64_MIN + ctx->dts_pts_diff)
  1029. pkt->dts = INT64_MIN;
  1030. else
  1031. pkt->dts = ctx->ts_ring[pic->encode_order] - ctx->dts_pts_diff;
  1032. } else {
  1033. pkt->dts = ctx->ts_ring[(pic->encode_order - ctx->decode_delay) %
  1034. (3 * ctx->output_delay)];
  1035. }
  1036. av_log(avctx, AV_LOG_DEBUG, "Output packet: pts %"PRId64" dts %"PRId64".\n",
  1037. pkt->pts, pkt->dts);
  1038. ctx->output_order = pic->encode_order;
  1039. vaapi_encode_clear_old(avctx);
  1040. return 0;
  1041. }
  1042. static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx, int type,
  1043. void *buffer, size_t size)
  1044. {
  1045. VAAPIEncodeContext *ctx = avctx->priv_data;
  1046. av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
  1047. ctx->global_params_type[ctx->nb_global_params] = type;
  1048. ctx->global_params [ctx->nb_global_params] = buffer;
  1049. ctx->global_params_size[ctx->nb_global_params] = size;
  1050. ++ctx->nb_global_params;
  1051. }
  1052. typedef struct VAAPIEncodeRTFormat {
  1053. const char *name;
  1054. unsigned int value;
  1055. int depth;
  1056. int nb_components;
  1057. int log2_chroma_w;
  1058. int log2_chroma_h;
  1059. } VAAPIEncodeRTFormat;
  1060. static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
  1061. { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
  1062. { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
  1063. { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
  1064. #if VA_CHECK_VERSION(1, 2, 0)
  1065. { "YUV422_10", VA_RT_FORMAT_YUV422_10, 10, 3, 1, 0 },
  1066. #endif
  1067. { "YUV444", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
  1068. { "YUV411", VA_RT_FORMAT_YUV411, 8, 3, 2, 0 },
  1069. #if VA_CHECK_VERSION(0, 38, 1)
  1070. { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
  1071. #endif
  1072. };
  1073. static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
  1074. VAEntrypointEncSlice,
  1075. VAEntrypointEncPicture,
  1076. #if VA_CHECK_VERSION(0, 39, 2)
  1077. VAEntrypointEncSliceLP,
  1078. #endif
  1079. 0
  1080. };
  1081. #if VA_CHECK_VERSION(0, 39, 2)
  1082. static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
  1083. VAEntrypointEncSliceLP,
  1084. 0
  1085. };
  1086. #endif
  1087. static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
  1088. {
  1089. VAAPIEncodeContext *ctx = avctx->priv_data;
  1090. VAProfile *va_profiles = NULL;
  1091. VAEntrypoint *va_entrypoints = NULL;
  1092. VAStatus vas;
  1093. const VAEntrypoint *usable_entrypoints;
  1094. const VAAPIEncodeProfile *profile;
  1095. const AVPixFmtDescriptor *desc;
  1096. VAConfigAttrib rt_format_attr;
  1097. const VAAPIEncodeRTFormat *rt_format;
  1098. const char *profile_string, *entrypoint_string;
  1099. int i, j, n, depth, err;
  1100. if (ctx->low_power) {
  1101. #if VA_CHECK_VERSION(0, 39, 2)
  1102. usable_entrypoints = vaapi_encode_entrypoints_low_power;
  1103. #else
  1104. av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
  1105. "supported with this VAAPI version.\n");
  1106. return AVERROR(EINVAL);
  1107. #endif
  1108. } else {
  1109. usable_entrypoints = vaapi_encode_entrypoints_normal;
  1110. }
  1111. desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
  1112. if (!desc) {
  1113. av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
  1114. ctx->input_frames->sw_format);
  1115. return AVERROR(EINVAL);
  1116. }
  1117. depth = desc->comp[0].depth;
  1118. for (i = 1; i < desc->nb_components; i++) {
  1119. if (desc->comp[i].depth != depth) {
  1120. av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
  1121. desc->name);
  1122. return AVERROR(EINVAL);
  1123. }
  1124. }
  1125. av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
  1126. desc->name);
  1127. n = vaMaxNumProfiles(ctx->hwctx->display);
  1128. va_profiles = av_malloc_array(n, sizeof(VAProfile));
  1129. if (!va_profiles) {
  1130. err = AVERROR(ENOMEM);
  1131. goto fail;
  1132. }
  1133. vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
  1134. if (vas != VA_STATUS_SUCCESS) {
  1135. av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
  1136. vas, vaErrorStr(vas));
  1137. err = AVERROR_EXTERNAL;
  1138. goto fail;
  1139. }
  1140. av_assert0(ctx->codec->profiles);
  1141. for (i = 0; (ctx->codec->profiles[i].av_profile !=
  1142. FF_PROFILE_UNKNOWN); i++) {
  1143. profile = &ctx->codec->profiles[i];
  1144. if (depth != profile->depth ||
  1145. desc->nb_components != profile->nb_components)
  1146. continue;
  1147. if (desc->nb_components > 1 &&
  1148. (desc->log2_chroma_w != profile->log2_chroma_w ||
  1149. desc->log2_chroma_h != profile->log2_chroma_h))
  1150. continue;
  1151. if (avctx->profile != profile->av_profile &&
  1152. avctx->profile != FF_PROFILE_UNKNOWN)
  1153. continue;
  1154. #if VA_CHECK_VERSION(1, 0, 0)
  1155. profile_string = vaProfileStr(profile->va_profile);
  1156. #else
  1157. profile_string = "(no profile names)";
  1158. #endif
  1159. for (j = 0; j < n; j++) {
  1160. if (va_profiles[j] == profile->va_profile)
  1161. break;
  1162. }
  1163. if (j >= n) {
  1164. av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
  1165. "is not supported by driver.\n", profile_string,
  1166. profile->va_profile);
  1167. continue;
  1168. }
  1169. ctx->profile = profile;
  1170. break;
  1171. }
  1172. if (!ctx->profile) {
  1173. av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
  1174. err = AVERROR(ENOSYS);
  1175. goto fail;
  1176. }
  1177. avctx->profile = profile->av_profile;
  1178. ctx->va_profile = profile->va_profile;
  1179. av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
  1180. profile_string, ctx->va_profile);
  1181. n = vaMaxNumEntrypoints(ctx->hwctx->display);
  1182. va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
  1183. if (!va_entrypoints) {
  1184. err = AVERROR(ENOMEM);
  1185. goto fail;
  1186. }
  1187. vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
  1188. va_entrypoints, &n);
  1189. if (vas != VA_STATUS_SUCCESS) {
  1190. av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
  1191. "profile %s (%d): %d (%s).\n", profile_string,
  1192. ctx->va_profile, vas, vaErrorStr(vas));
  1193. err = AVERROR_EXTERNAL;
  1194. goto fail;
  1195. }
  1196. for (i = 0; i < n; i++) {
  1197. for (j = 0; usable_entrypoints[j]; j++) {
  1198. if (va_entrypoints[i] == usable_entrypoints[j])
  1199. break;
  1200. }
  1201. if (usable_entrypoints[j])
  1202. break;
  1203. }
  1204. if (i >= n) {
  1205. av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
  1206. "for profile %s (%d).\n", profile_string, ctx->va_profile);
  1207. err = AVERROR(ENOSYS);
  1208. goto fail;
  1209. }
  1210. ctx->va_entrypoint = va_entrypoints[i];
  1211. #if VA_CHECK_VERSION(1, 0, 0)
  1212. entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
  1213. #else
  1214. entrypoint_string = "(no entrypoint names)";
  1215. #endif
  1216. av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
  1217. entrypoint_string, ctx->va_entrypoint);
  1218. for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
  1219. rt_format = &vaapi_encode_rt_formats[i];
  1220. if (rt_format->depth == depth &&
  1221. rt_format->nb_components == profile->nb_components &&
  1222. rt_format->log2_chroma_w == profile->log2_chroma_w &&
  1223. rt_format->log2_chroma_h == profile->log2_chroma_h)
  1224. break;
  1225. }
  1226. if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
  1227. av_log(avctx, AV_LOG_ERROR, "No usable render target format "
  1228. "found for profile %s (%d) entrypoint %s (%d).\n",
  1229. profile_string, ctx->va_profile,
  1230. entrypoint_string, ctx->va_entrypoint);
  1231. err = AVERROR(ENOSYS);
  1232. goto fail;
  1233. }
  1234. rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
  1235. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1236. ctx->va_profile, ctx->va_entrypoint,
  1237. &rt_format_attr, 1);
  1238. if (vas != VA_STATUS_SUCCESS) {
  1239. av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
  1240. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1241. err = AVERROR_EXTERNAL;
  1242. goto fail;
  1243. }
  1244. if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1245. av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
  1246. "supported by driver: assuming surface RT format %s "
  1247. "is valid.\n", rt_format->name);
  1248. } else if (!(rt_format_attr.value & rt_format->value)) {
  1249. av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
  1250. "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
  1251. rt_format->name, profile_string, ctx->va_profile,
  1252. entrypoint_string, ctx->va_entrypoint);
  1253. err = AVERROR(ENOSYS);
  1254. goto fail;
  1255. } else {
  1256. av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
  1257. "format %s (%#x).\n", rt_format->name, rt_format->value);
  1258. ctx->config_attributes[ctx->nb_config_attributes++] =
  1259. (VAConfigAttrib) {
  1260. .type = VAConfigAttribRTFormat,
  1261. .value = rt_format->value,
  1262. };
  1263. }
  1264. err = 0;
  1265. fail:
  1266. av_freep(&va_profiles);
  1267. av_freep(&va_entrypoints);
  1268. return err;
  1269. }
  1270. static const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
  1271. // Bitrate Quality
  1272. // | Maxrate | HRD/VBV
  1273. { 0 }, // | | | |
  1274. { RC_MODE_CQP, "CQP", 1, VA_RC_CQP, 0, 0, 1, 0 },
  1275. { RC_MODE_CBR, "CBR", 1, VA_RC_CBR, 1, 0, 0, 1 },
  1276. { RC_MODE_VBR, "VBR", 1, VA_RC_VBR, 1, 1, 0, 1 },
  1277. #if VA_CHECK_VERSION(1, 1, 0)
  1278. { RC_MODE_ICQ, "ICQ", 1, VA_RC_ICQ, 0, 0, 1, 0 },
  1279. #else
  1280. { RC_MODE_ICQ, "ICQ", 0 },
  1281. #endif
  1282. #if VA_CHECK_VERSION(1, 3, 0)
  1283. { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1, 1, 1, 1 },
  1284. { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1, 0, 0, 0 },
  1285. #else
  1286. { RC_MODE_QVBR, "QVBR", 0 },
  1287. { RC_MODE_AVBR, "AVBR", 0 },
  1288. #endif
  1289. };
  1290. static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
  1291. {
  1292. VAAPIEncodeContext *ctx = avctx->priv_data;
  1293. uint32_t supported_va_rc_modes;
  1294. const VAAPIEncodeRCMode *rc_mode;
  1295. int64_t rc_bits_per_second;
  1296. int rc_target_percentage;
  1297. int rc_window_size;
  1298. int rc_quality;
  1299. int64_t hrd_buffer_size;
  1300. int64_t hrd_initial_buffer_fullness;
  1301. int fr_num, fr_den;
  1302. VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
  1303. VAStatus vas;
  1304. char supported_rc_modes_string[64];
  1305. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1306. ctx->va_profile, ctx->va_entrypoint,
  1307. &rc_attr, 1);
  1308. if (vas != VA_STATUS_SUCCESS) {
  1309. av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
  1310. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1311. return AVERROR_EXTERNAL;
  1312. }
  1313. if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1314. av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
  1315. "supported rate control modes: assuming CQP only.\n");
  1316. supported_va_rc_modes = VA_RC_CQP;
  1317. strcpy(supported_rc_modes_string, "unknown");
  1318. } else {
  1319. char *str = supported_rc_modes_string;
  1320. size_t len = sizeof(supported_rc_modes_string);
  1321. int i, first = 1, res;
  1322. supported_va_rc_modes = rc_attr.value;
  1323. for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
  1324. rc_mode = &vaapi_encode_rc_modes[i];
  1325. if (supported_va_rc_modes & rc_mode->va_mode) {
  1326. res = snprintf(str, len, "%s%s",
  1327. first ? "" : ", ", rc_mode->name);
  1328. first = 0;
  1329. if (res < 0) {
  1330. *str = 0;
  1331. break;
  1332. }
  1333. len -= res;
  1334. str += res;
  1335. if (len == 0)
  1336. break;
  1337. }
  1338. }
  1339. av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
  1340. supported_rc_modes_string);
  1341. }
  1342. // Rate control mode selection:
  1343. // * If the user has set a mode explicitly with the rc_mode option,
  1344. // use it and fail if it is not available.
  1345. // * If an explicit QP option has been set, use CQP.
  1346. // * If the codec is CQ-only, use CQP.
  1347. // * If the QSCALE avcodec option is set, use CQP.
  1348. // * If bitrate and quality are both set, try QVBR.
  1349. // * If quality is set, try ICQ, then CQP.
  1350. // * If bitrate and maxrate are set and have the same value, try CBR.
  1351. // * If a bitrate is set, try AVBR, then VBR, then CBR.
  1352. // * If no bitrate is set, try ICQ, then CQP.
  1353. #define TRY_RC_MODE(mode, fail) do { \
  1354. rc_mode = &vaapi_encode_rc_modes[mode]; \
  1355. if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
  1356. if (fail) { \
  1357. av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
  1358. "RC mode (supported modes: %s).\n", rc_mode->name, \
  1359. supported_rc_modes_string); \
  1360. return AVERROR(EINVAL); \
  1361. } \
  1362. av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
  1363. "RC mode.\n", rc_mode->name); \
  1364. rc_mode = NULL; \
  1365. } else { \
  1366. goto rc_mode_found; \
  1367. } \
  1368. } while (0)
  1369. if (ctx->explicit_rc_mode)
  1370. TRY_RC_MODE(ctx->explicit_rc_mode, 1);
  1371. if (ctx->explicit_qp)
  1372. TRY_RC_MODE(RC_MODE_CQP, 1);
  1373. if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY)
  1374. TRY_RC_MODE(RC_MODE_CQP, 1);
  1375. if (avctx->flags & AV_CODEC_FLAG_QSCALE)
  1376. TRY_RC_MODE(RC_MODE_CQP, 1);
  1377. if (avctx->bit_rate > 0 && avctx->global_quality > 0)
  1378. TRY_RC_MODE(RC_MODE_QVBR, 0);
  1379. if (avctx->global_quality > 0) {
  1380. TRY_RC_MODE(RC_MODE_ICQ, 0);
  1381. TRY_RC_MODE(RC_MODE_CQP, 0);
  1382. }
  1383. if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
  1384. TRY_RC_MODE(RC_MODE_CBR, 0);
  1385. if (avctx->bit_rate > 0) {
  1386. TRY_RC_MODE(RC_MODE_AVBR, 0);
  1387. TRY_RC_MODE(RC_MODE_VBR, 0);
  1388. TRY_RC_MODE(RC_MODE_CBR, 0);
  1389. } else {
  1390. TRY_RC_MODE(RC_MODE_ICQ, 0);
  1391. TRY_RC_MODE(RC_MODE_CQP, 0);
  1392. }
  1393. av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
  1394. "RC mode compatible with selected options "
  1395. "(supported modes: %s).\n", supported_rc_modes_string);
  1396. return AVERROR(EINVAL);
  1397. rc_mode_found:
  1398. if (rc_mode->bitrate) {
  1399. if (avctx->bit_rate <= 0) {
  1400. av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
  1401. "RC mode.\n", rc_mode->name);
  1402. return AVERROR(EINVAL);
  1403. }
  1404. if (rc_mode->mode == RC_MODE_AVBR) {
  1405. // For maximum confusion AVBR is hacked into the existing API
  1406. // by overloading some of the fields with completely different
  1407. // meanings.
  1408. // Target percentage does not apply in AVBR mode.
  1409. rc_bits_per_second = avctx->bit_rate;
  1410. // Accuracy tolerance range for meeting the specified target
  1411. // bitrate. It's very unclear how this is actually intended
  1412. // to work - since we do want to get the specified bitrate,
  1413. // set the accuracy to 100% for now.
  1414. rc_target_percentage = 100;
  1415. // Convergence period in frames. The GOP size reflects the
  1416. // user's intended block size for cutting, so reusing that
  1417. // as the convergence period seems a reasonable default.
  1418. rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
  1419. } else if (rc_mode->maxrate) {
  1420. if (avctx->rc_max_rate > 0) {
  1421. if (avctx->rc_max_rate < avctx->bit_rate) {
  1422. av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
  1423. "bitrate (%"PRId64") must not be greater than "
  1424. "maxrate (%"PRId64").\n", avctx->bit_rate,
  1425. avctx->rc_max_rate);
  1426. return AVERROR(EINVAL);
  1427. }
  1428. rc_bits_per_second = avctx->rc_max_rate;
  1429. rc_target_percentage = (avctx->bit_rate * 100) /
  1430. avctx->rc_max_rate;
  1431. } else {
  1432. // We only have a target bitrate, but this mode requires
  1433. // that a maximum rate be supplied as well. Since the
  1434. // user does not want this to be a constraint, arbitrarily
  1435. // pick a maximum rate of double the target rate.
  1436. rc_bits_per_second = 2 * avctx->bit_rate;
  1437. rc_target_percentage = 50;
  1438. }
  1439. } else {
  1440. if (avctx->rc_max_rate > avctx->bit_rate) {
  1441. av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
  1442. "in %s RC mode.\n", rc_mode->name);
  1443. }
  1444. rc_bits_per_second = avctx->bit_rate;
  1445. rc_target_percentage = 100;
  1446. }
  1447. } else {
  1448. rc_bits_per_second = 0;
  1449. rc_target_percentage = 100;
  1450. }
  1451. if (rc_mode->quality) {
  1452. if (ctx->explicit_qp) {
  1453. rc_quality = ctx->explicit_qp;
  1454. } else if (avctx->global_quality > 0) {
  1455. rc_quality = avctx->global_quality;
  1456. } else {
  1457. rc_quality = ctx->codec->default_quality;
  1458. av_log(avctx, AV_LOG_WARNING, "No quality level set; "
  1459. "using default (%d).\n", rc_quality);
  1460. }
  1461. } else {
  1462. rc_quality = 0;
  1463. }
  1464. if (rc_mode->hrd) {
  1465. if (avctx->rc_buffer_size)
  1466. hrd_buffer_size = avctx->rc_buffer_size;
  1467. else if (avctx->rc_max_rate > 0)
  1468. hrd_buffer_size = avctx->rc_max_rate;
  1469. else
  1470. hrd_buffer_size = avctx->bit_rate;
  1471. if (avctx->rc_initial_buffer_occupancy) {
  1472. if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
  1473. av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
  1474. "must have initial buffer size (%d) <= "
  1475. "buffer size (%"PRId64").\n",
  1476. avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
  1477. return AVERROR(EINVAL);
  1478. }
  1479. hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
  1480. } else {
  1481. hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
  1482. }
  1483. rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
  1484. } else {
  1485. if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
  1486. av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
  1487. "in %s RC mode.\n", rc_mode->name);
  1488. }
  1489. hrd_buffer_size = 0;
  1490. hrd_initial_buffer_fullness = 0;
  1491. if (rc_mode->mode != RC_MODE_AVBR) {
  1492. // Already set (with completely different meaning) for AVBR.
  1493. rc_window_size = 1000;
  1494. }
  1495. }
  1496. if (rc_bits_per_second > UINT32_MAX ||
  1497. hrd_buffer_size > UINT32_MAX ||
  1498. hrd_initial_buffer_fullness > UINT32_MAX) {
  1499. av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
  1500. "greater are not supported by VAAPI.\n");
  1501. return AVERROR(EINVAL);
  1502. }
  1503. ctx->rc_mode = rc_mode;
  1504. ctx->rc_quality = rc_quality;
  1505. ctx->va_rc_mode = rc_mode->va_mode;
  1506. ctx->va_bit_rate = rc_bits_per_second;
  1507. av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
  1508. if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1509. // This driver does not want the RC mode attribute to be set.
  1510. } else {
  1511. ctx->config_attributes[ctx->nb_config_attributes++] =
  1512. (VAConfigAttrib) {
  1513. .type = VAConfigAttribRateControl,
  1514. .value = ctx->va_rc_mode,
  1515. };
  1516. }
  1517. if (rc_mode->quality)
  1518. av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
  1519. if (rc_mode->va_mode != VA_RC_CQP) {
  1520. if (rc_mode->mode == RC_MODE_AVBR) {
  1521. av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
  1522. "converging in %d frames with %d%% accuracy.\n",
  1523. rc_bits_per_second, rc_window_size,
  1524. rc_target_percentage);
  1525. } else if (rc_mode->bitrate) {
  1526. av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
  1527. "%"PRId64" bps over %d ms.\n", rc_target_percentage,
  1528. rc_bits_per_second, rc_window_size);
  1529. }
  1530. ctx->rc_params = (VAEncMiscParameterRateControl) {
  1531. .bits_per_second = rc_bits_per_second,
  1532. .target_percentage = rc_target_percentage,
  1533. .window_size = rc_window_size,
  1534. .initial_qp = 0,
  1535. .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
  1536. .basic_unit_size = 0,
  1537. #if VA_CHECK_VERSION(1, 1, 0)
  1538. .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
  1539. .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
  1540. #endif
  1541. #if VA_CHECK_VERSION(1, 3, 0)
  1542. .quality_factor = rc_quality,
  1543. #endif
  1544. };
  1545. vaapi_encode_add_global_param(avctx,
  1546. VAEncMiscParameterTypeRateControl,
  1547. &ctx->rc_params,
  1548. sizeof(ctx->rc_params));
  1549. }
  1550. if (rc_mode->hrd) {
  1551. av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
  1552. "initial fullness %"PRId64" bits.\n",
  1553. hrd_buffer_size, hrd_initial_buffer_fullness);
  1554. ctx->hrd_params = (VAEncMiscParameterHRD) {
  1555. .initial_buffer_fullness = hrd_initial_buffer_fullness,
  1556. .buffer_size = hrd_buffer_size,
  1557. };
  1558. vaapi_encode_add_global_param(avctx,
  1559. VAEncMiscParameterTypeHRD,
  1560. &ctx->hrd_params,
  1561. sizeof(ctx->hrd_params));
  1562. }
  1563. if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
  1564. av_reduce(&fr_num, &fr_den,
  1565. avctx->framerate.num, avctx->framerate.den, 65535);
  1566. else
  1567. av_reduce(&fr_num, &fr_den,
  1568. avctx->time_base.den, avctx->time_base.num, 65535);
  1569. av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
  1570. fr_num, fr_den, (double)fr_num / fr_den);
  1571. ctx->fr_params = (VAEncMiscParameterFrameRate) {
  1572. .framerate = (unsigned int)fr_den << 16 | fr_num,
  1573. };
  1574. #if VA_CHECK_VERSION(0, 40, 0)
  1575. vaapi_encode_add_global_param(avctx,
  1576. VAEncMiscParameterTypeFrameRate,
  1577. &ctx->fr_params,
  1578. sizeof(ctx->fr_params));
  1579. #endif
  1580. return 0;
  1581. }
  1582. static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
  1583. {
  1584. VAAPIEncodeContext *ctx = avctx->priv_data;
  1585. VAStatus vas;
  1586. VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
  1587. uint32_t ref_l0, ref_l1;
  1588. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1589. ctx->va_profile,
  1590. ctx->va_entrypoint,
  1591. &attr, 1);
  1592. if (vas != VA_STATUS_SUCCESS) {
  1593. av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
  1594. "attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1595. return AVERROR_EXTERNAL;
  1596. }
  1597. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1598. ref_l0 = ref_l1 = 0;
  1599. } else {
  1600. ref_l0 = attr.value & 0xffff;
  1601. ref_l1 = attr.value >> 16 & 0xffff;
  1602. }
  1603. if (ctx->codec->flags & FLAG_INTRA_ONLY ||
  1604. avctx->gop_size <= 1) {
  1605. av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
  1606. ctx->gop_size = 1;
  1607. } else if (ref_l0 < 1) {
  1608. av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
  1609. "reference frames.\n");
  1610. return AVERROR(EINVAL);
  1611. } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
  1612. ref_l1 < 1 || avctx->max_b_frames < 1) {
  1613. av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
  1614. "(supported references: %d / %d).\n", ref_l0, ref_l1);
  1615. ctx->gop_size = avctx->gop_size;
  1616. ctx->p_per_i = INT_MAX;
  1617. ctx->b_per_p = 0;
  1618. } else {
  1619. av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
  1620. "(supported references: %d / %d).\n", ref_l0, ref_l1);
  1621. ctx->gop_size = avctx->gop_size;
  1622. ctx->p_per_i = INT_MAX;
  1623. ctx->b_per_p = avctx->max_b_frames;
  1624. if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
  1625. ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
  1626. av_log2(ctx->b_per_p) + 1);
  1627. } else {
  1628. ctx->max_b_depth = 1;
  1629. }
  1630. }
  1631. if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
  1632. ctx->closed_gop = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
  1633. ctx->gop_per_idr = ctx->idr_interval + 1;
  1634. } else {
  1635. ctx->closed_gop = 1;
  1636. ctx->gop_per_idr = 1;
  1637. }
  1638. return 0;
  1639. }
  1640. static av_cold int vaapi_encode_init_row_slice_structure(AVCodecContext *avctx,
  1641. uint32_t slice_structure)
  1642. {
  1643. VAAPIEncodeContext *ctx = avctx->priv_data;
  1644. int req_slices;
  1645. // For fixed-size slices currently we only support whole rows, making
  1646. // rectangular slices. This could be extended to arbitrary runs of
  1647. // blocks, but since slices tend to be a conformance requirement and
  1648. // most cases (such as broadcast or bluray) want rectangular slices
  1649. // only it would need to be gated behind another option.
  1650. if (avctx->slices > ctx->slice_block_rows) {
  1651. av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
  1652. "configured number of slices (%d < %d); using "
  1653. "maximum.\n", ctx->slice_block_rows, avctx->slices);
  1654. req_slices = ctx->slice_block_rows;
  1655. } else {
  1656. req_slices = avctx->slices;
  1657. }
  1658. if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
  1659. slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
  1660. ctx->nb_slices = req_slices;
  1661. ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
  1662. } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
  1663. int k;
  1664. for (k = 1;; k *= 2) {
  1665. if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
  1666. break;
  1667. }
  1668. ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
  1669. ctx->slice_size = k;
  1670. #if VA_CHECK_VERSION(1, 0, 0)
  1671. } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
  1672. ctx->nb_slices = ctx->slice_block_rows;
  1673. ctx->slice_size = 1;
  1674. #endif
  1675. } else {
  1676. av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
  1677. "slice structure modes (%#x).\n", slice_structure);
  1678. return AVERROR(EINVAL);
  1679. }
  1680. return 0;
  1681. }
  1682. static av_cold int vaapi_encode_init_tile_slice_structure(AVCodecContext *avctx,
  1683. uint32_t slice_structure)
  1684. {
  1685. VAAPIEncodeContext *ctx = avctx->priv_data;
  1686. int i, req_tiles;
  1687. if (!(slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS ||
  1688. (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS &&
  1689. ctx->tile_cols == 1))) {
  1690. av_log(avctx, AV_LOG_ERROR, "Supported slice structure (%#x) doesn't work for "
  1691. "current tile requirement.\n", slice_structure);
  1692. return AVERROR(EINVAL);
  1693. }
  1694. if (ctx->tile_rows > ctx->slice_block_rows ||
  1695. ctx->tile_cols > ctx->slice_block_cols) {
  1696. av_log(avctx, AV_LOG_WARNING, "Not enough block rows/cols (%d x %d) "
  1697. "for configured number of tile (%d x %d); ",
  1698. ctx->slice_block_rows, ctx->slice_block_cols,
  1699. ctx->tile_rows, ctx->tile_cols);
  1700. ctx->tile_rows = ctx->tile_rows > ctx->slice_block_rows ?
  1701. ctx->slice_block_rows : ctx->tile_rows;
  1702. ctx->tile_cols = ctx->tile_cols > ctx->slice_block_cols ?
  1703. ctx->slice_block_cols : ctx->tile_cols;
  1704. av_log(avctx, AV_LOG_WARNING, "using allowed maximum (%d x %d).\n",
  1705. ctx->tile_rows, ctx->tile_cols);
  1706. }
  1707. req_tiles = ctx->tile_rows * ctx->tile_cols;
  1708. // Tile slice is not allowed to cross the boundary of a tile due to
  1709. // the constraints of media-driver. Currently we support one slice
  1710. // per tile. This could be extended to multiple slices per tile.
  1711. if (avctx->slices != req_tiles)
  1712. av_log(avctx, AV_LOG_WARNING, "The number of requested slices "
  1713. "mismatches with configured number of tile (%d != %d); "
  1714. "using requested tile number for slice.\n",
  1715. avctx->slices, req_tiles);
  1716. ctx->nb_slices = req_tiles;
  1717. // Default in uniform spacing
  1718. // 6-3, 6-5
  1719. for (i = 0; i < ctx->tile_cols; i++) {
  1720. ctx->col_width[i] = ( i + 1 ) * ctx->slice_block_cols / ctx->tile_cols -
  1721. i * ctx->slice_block_cols / ctx->tile_cols;
  1722. ctx->col_bd[i + 1] = ctx->col_bd[i] + ctx->col_width[i];
  1723. }
  1724. // 6-4, 6-6
  1725. for (i = 0; i < ctx->tile_rows; i++) {
  1726. ctx->row_height[i] = ( i + 1 ) * ctx->slice_block_rows / ctx->tile_rows -
  1727. i * ctx->slice_block_rows / ctx->tile_rows;
  1728. ctx->row_bd[i + 1] = ctx->row_bd[i] + ctx->row_height[i];
  1729. }
  1730. av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d x %d tile.\n",
  1731. ctx->tile_rows, ctx->tile_cols);
  1732. return 0;
  1733. }
  1734. static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
  1735. {
  1736. VAAPIEncodeContext *ctx = avctx->priv_data;
  1737. VAConfigAttrib attr[3] = { { VAConfigAttribEncMaxSlices },
  1738. { VAConfigAttribEncSliceStructure },
  1739. #if VA_CHECK_VERSION(1, 1, 0)
  1740. { VAConfigAttribEncTileSupport },
  1741. #endif
  1742. };
  1743. VAStatus vas;
  1744. uint32_t max_slices, slice_structure;
  1745. int ret;
  1746. if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
  1747. if (avctx->slices > 0) {
  1748. av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
  1749. "but this codec does not support controlling slices.\n");
  1750. }
  1751. return 0;
  1752. }
  1753. ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
  1754. ctx->slice_block_height;
  1755. ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
  1756. ctx->slice_block_width;
  1757. if (avctx->slices <= 1 && !ctx->tile_rows && !ctx->tile_cols) {
  1758. ctx->nb_slices = 1;
  1759. ctx->slice_size = ctx->slice_block_rows;
  1760. return 0;
  1761. }
  1762. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1763. ctx->va_profile,
  1764. ctx->va_entrypoint,
  1765. attr, FF_ARRAY_ELEMS(attr));
  1766. if (vas != VA_STATUS_SUCCESS) {
  1767. av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
  1768. "attributes: %d (%s).\n", vas, vaErrorStr(vas));
  1769. return AVERROR_EXTERNAL;
  1770. }
  1771. max_slices = attr[0].value;
  1772. slice_structure = attr[1].value;
  1773. if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
  1774. slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
  1775. av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
  1776. "pictures as multiple slices.\n.");
  1777. return AVERROR(EINVAL);
  1778. }
  1779. if (ctx->tile_rows && ctx->tile_cols) {
  1780. #if VA_CHECK_VERSION(1, 1, 0)
  1781. uint32_t tile_support = attr[2].value;
  1782. if (tile_support == VA_ATTRIB_NOT_SUPPORTED) {
  1783. av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
  1784. "pictures as multiple tiles.\n.");
  1785. return AVERROR(EINVAL);
  1786. }
  1787. #else
  1788. av_log(avctx, AV_LOG_ERROR, "Tile encoding option is "
  1789. "not supported with this VAAPI version.\n");
  1790. return AVERROR(EINVAL);
  1791. #endif
  1792. }
  1793. if (ctx->tile_rows && ctx->tile_cols)
  1794. ret = vaapi_encode_init_tile_slice_structure(avctx, slice_structure);
  1795. else
  1796. ret = vaapi_encode_init_row_slice_structure(avctx, slice_structure);
  1797. if (ret < 0)
  1798. return ret;
  1799. if (ctx->nb_slices > avctx->slices) {
  1800. av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
  1801. "%d (from %d) due to driver constraints on slice "
  1802. "structure.\n", ctx->nb_slices, avctx->slices);
  1803. }
  1804. if (ctx->nb_slices > max_slices) {
  1805. av_log(avctx, AV_LOG_ERROR, "Driver does not support "
  1806. "encoding with %d slices (max %"PRIu32").\n",
  1807. ctx->nb_slices, max_slices);
  1808. return AVERROR(EINVAL);
  1809. }
  1810. av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices.\n",
  1811. ctx->nb_slices);
  1812. return 0;
  1813. }
  1814. static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
  1815. {
  1816. VAAPIEncodeContext *ctx = avctx->priv_data;
  1817. VAStatus vas;
  1818. VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
  1819. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1820. ctx->va_profile,
  1821. ctx->va_entrypoint,
  1822. &attr, 1);
  1823. if (vas != VA_STATUS_SUCCESS) {
  1824. av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
  1825. "attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1826. return AVERROR_EXTERNAL;
  1827. }
  1828. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1829. if (ctx->desired_packed_headers) {
  1830. av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
  1831. "packed headers (wanted %#x).\n",
  1832. ctx->desired_packed_headers);
  1833. } else {
  1834. av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
  1835. "packed headers (none wanted).\n");
  1836. }
  1837. ctx->va_packed_headers = 0;
  1838. } else {
  1839. if (ctx->desired_packed_headers & ~attr.value) {
  1840. av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
  1841. "wanted packed headers (wanted %#x, found %#x).\n",
  1842. ctx->desired_packed_headers, attr.value);
  1843. } else {
  1844. av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
  1845. "available (wanted %#x, found %#x).\n",
  1846. ctx->desired_packed_headers, attr.value);
  1847. }
  1848. ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
  1849. }
  1850. if (ctx->va_packed_headers) {
  1851. ctx->config_attributes[ctx->nb_config_attributes++] =
  1852. (VAConfigAttrib) {
  1853. .type = VAConfigAttribEncPackedHeaders,
  1854. .value = ctx->va_packed_headers,
  1855. };
  1856. }
  1857. if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
  1858. !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
  1859. (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
  1860. av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
  1861. "sequence headers, but a global header is requested.\n");
  1862. av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
  1863. "this may result in a stream which is not usable for some "
  1864. "purposes (e.g. not muxable to some containers).\n");
  1865. }
  1866. return 0;
  1867. }
  1868. static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
  1869. {
  1870. #if VA_CHECK_VERSION(0, 36, 0)
  1871. VAAPIEncodeContext *ctx = avctx->priv_data;
  1872. VAStatus vas;
  1873. VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
  1874. int quality = avctx->compression_level;
  1875. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1876. ctx->va_profile,
  1877. ctx->va_entrypoint,
  1878. &attr, 1);
  1879. if (vas != VA_STATUS_SUCCESS) {
  1880. av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
  1881. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1882. return AVERROR_EXTERNAL;
  1883. }
  1884. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1885. if (quality != 0) {
  1886. av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
  1887. "supported: will use default quality level.\n");
  1888. }
  1889. } else {
  1890. if (quality > attr.value) {
  1891. av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
  1892. "valid range is 0-%d, using %d.\n",
  1893. attr.value, attr.value);
  1894. quality = attr.value;
  1895. }
  1896. ctx->quality_params = (VAEncMiscParameterBufferQualityLevel) {
  1897. .quality_level = quality,
  1898. };
  1899. vaapi_encode_add_global_param(avctx,
  1900. VAEncMiscParameterTypeQualityLevel,
  1901. &ctx->quality_params,
  1902. sizeof(ctx->quality_params));
  1903. }
  1904. #else
  1905. av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
  1906. "not supported with this VAAPI version.\n");
  1907. #endif
  1908. return 0;
  1909. }
  1910. static av_cold int vaapi_encode_init_roi(AVCodecContext *avctx)
  1911. {
  1912. #if VA_CHECK_VERSION(1, 0, 0)
  1913. VAAPIEncodeContext *ctx = avctx->priv_data;
  1914. VAStatus vas;
  1915. VAConfigAttrib attr = { VAConfigAttribEncROI };
  1916. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1917. ctx->va_profile,
  1918. ctx->va_entrypoint,
  1919. &attr, 1);
  1920. if (vas != VA_STATUS_SUCCESS) {
  1921. av_log(avctx, AV_LOG_ERROR, "Failed to query ROI "
  1922. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1923. return AVERROR_EXTERNAL;
  1924. }
  1925. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1926. ctx->roi_allowed = 0;
  1927. } else {
  1928. VAConfigAttribValEncROI roi = {
  1929. .value = attr.value,
  1930. };
  1931. ctx->roi_max_regions = roi.bits.num_roi_regions;
  1932. ctx->roi_allowed = ctx->roi_max_regions > 0 &&
  1933. (ctx->va_rc_mode == VA_RC_CQP ||
  1934. roi.bits.roi_rc_qp_delta_support);
  1935. }
  1936. #endif
  1937. return 0;
  1938. }
  1939. static void vaapi_encode_free_output_buffer(void *opaque,
  1940. uint8_t *data)
  1941. {
  1942. AVCodecContext *avctx = opaque;
  1943. VAAPIEncodeContext *ctx = avctx->priv_data;
  1944. VABufferID buffer_id;
  1945. buffer_id = (VABufferID)(uintptr_t)data;
  1946. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  1947. av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
  1948. }
  1949. static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
  1950. buffer_size_t size)
  1951. {
  1952. AVCodecContext *avctx = opaque;
  1953. VAAPIEncodeContext *ctx = avctx->priv_data;
  1954. VABufferID buffer_id;
  1955. VAStatus vas;
  1956. AVBufferRef *ref;
  1957. // The output buffer size is fixed, so it needs to be large enough
  1958. // to hold the largest possible compressed frame. We assume here
  1959. // that the uncompressed frame plus some header data is an upper
  1960. // bound on that.
  1961. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  1962. VAEncCodedBufferType,
  1963. 3 * ctx->surface_width * ctx->surface_height +
  1964. (1 << 16), 1, 0, &buffer_id);
  1965. if (vas != VA_STATUS_SUCCESS) {
  1966. av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
  1967. "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
  1968. return NULL;
  1969. }
  1970. av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
  1971. ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
  1972. sizeof(buffer_id),
  1973. &vaapi_encode_free_output_buffer,
  1974. avctx, AV_BUFFER_FLAG_READONLY);
  1975. if (!ref) {
  1976. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  1977. return NULL;
  1978. }
  1979. return ref;
  1980. }
  1981. static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
  1982. {
  1983. VAAPIEncodeContext *ctx = avctx->priv_data;
  1984. AVVAAPIHWConfig *hwconfig = NULL;
  1985. AVHWFramesConstraints *constraints = NULL;
  1986. enum AVPixelFormat recon_format;
  1987. int err, i;
  1988. hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
  1989. if (!hwconfig) {
  1990. err = AVERROR(ENOMEM);
  1991. goto fail;
  1992. }
  1993. hwconfig->config_id = ctx->va_config;
  1994. constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
  1995. hwconfig);
  1996. if (!constraints) {
  1997. err = AVERROR(ENOMEM);
  1998. goto fail;
  1999. }
  2000. // Probably we can use the input surface format as the surface format
  2001. // of the reconstructed frames. If not, we just pick the first (only?)
  2002. // format in the valid list and hope that it all works.
  2003. recon_format = AV_PIX_FMT_NONE;
  2004. if (constraints->valid_sw_formats) {
  2005. for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
  2006. if (ctx->input_frames->sw_format ==
  2007. constraints->valid_sw_formats[i]) {
  2008. recon_format = ctx->input_frames->sw_format;
  2009. break;
  2010. }
  2011. }
  2012. if (recon_format == AV_PIX_FMT_NONE) {
  2013. // No match. Just use the first in the supported list and
  2014. // hope for the best.
  2015. recon_format = constraints->valid_sw_formats[0];
  2016. }
  2017. } else {
  2018. // No idea what to use; copy input format.
  2019. recon_format = ctx->input_frames->sw_format;
  2020. }
  2021. av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
  2022. "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
  2023. if (ctx->surface_width < constraints->min_width ||
  2024. ctx->surface_height < constraints->min_height ||
  2025. ctx->surface_width > constraints->max_width ||
  2026. ctx->surface_height > constraints->max_height) {
  2027. av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
  2028. "size %dx%d (constraints: width %d-%d height %d-%d).\n",
  2029. ctx->surface_width, ctx->surface_height,
  2030. constraints->min_width, constraints->max_width,
  2031. constraints->min_height, constraints->max_height);
  2032. err = AVERROR(EINVAL);
  2033. goto fail;
  2034. }
  2035. av_freep(&hwconfig);
  2036. av_hwframe_constraints_free(&constraints);
  2037. ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
  2038. if (!ctx->recon_frames_ref) {
  2039. err = AVERROR(ENOMEM);
  2040. goto fail;
  2041. }
  2042. ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
  2043. ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
  2044. ctx->recon_frames->sw_format = recon_format;
  2045. ctx->recon_frames->width = ctx->surface_width;
  2046. ctx->recon_frames->height = ctx->surface_height;
  2047. err = av_hwframe_ctx_init(ctx->recon_frames_ref);
  2048. if (err < 0) {
  2049. av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
  2050. "frame context: %d.\n", err);
  2051. goto fail;
  2052. }
  2053. err = 0;
  2054. fail:
  2055. av_freep(&hwconfig);
  2056. av_hwframe_constraints_free(&constraints);
  2057. return err;
  2058. }
  2059. av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
  2060. {
  2061. VAAPIEncodeContext *ctx = avctx->priv_data;
  2062. AVVAAPIFramesContext *recon_hwctx = NULL;
  2063. VAStatus vas;
  2064. int err;
  2065. ctx->frame = av_frame_alloc();
  2066. if (!ctx->frame) {
  2067. return AVERROR(ENOMEM);
  2068. }
  2069. if (!avctx->hw_frames_ctx) {
  2070. av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
  2071. "required to associate the encoding device.\n");
  2072. return AVERROR(EINVAL);
  2073. }
  2074. ctx->va_config = VA_INVALID_ID;
  2075. ctx->va_context = VA_INVALID_ID;
  2076. ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
  2077. if (!ctx->input_frames_ref) {
  2078. err = AVERROR(ENOMEM);
  2079. goto fail;
  2080. }
  2081. ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
  2082. ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
  2083. if (!ctx->device_ref) {
  2084. err = AVERROR(ENOMEM);
  2085. goto fail;
  2086. }
  2087. ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
  2088. ctx->hwctx = ctx->device->hwctx;
  2089. err = vaapi_encode_profile_entrypoint(avctx);
  2090. if (err < 0)
  2091. goto fail;
  2092. err = vaapi_encode_init_rate_control(avctx);
  2093. if (err < 0)
  2094. goto fail;
  2095. err = vaapi_encode_init_gop_structure(avctx);
  2096. if (err < 0)
  2097. goto fail;
  2098. err = vaapi_encode_init_slice_structure(avctx);
  2099. if (err < 0)
  2100. goto fail;
  2101. err = vaapi_encode_init_packed_headers(avctx);
  2102. if (err < 0)
  2103. goto fail;
  2104. err = vaapi_encode_init_roi(avctx);
  2105. if (err < 0)
  2106. goto fail;
  2107. if (avctx->compression_level >= 0) {
  2108. err = vaapi_encode_init_quality(avctx);
  2109. if (err < 0)
  2110. goto fail;
  2111. }
  2112. vas = vaCreateConfig(ctx->hwctx->display,
  2113. ctx->va_profile, ctx->va_entrypoint,
  2114. ctx->config_attributes, ctx->nb_config_attributes,
  2115. &ctx->va_config);
  2116. if (vas != VA_STATUS_SUCCESS) {
  2117. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  2118. "configuration: %d (%s).\n", vas, vaErrorStr(vas));
  2119. err = AVERROR(EIO);
  2120. goto fail;
  2121. }
  2122. err = vaapi_encode_create_recon_frames(avctx);
  2123. if (err < 0)
  2124. goto fail;
  2125. recon_hwctx = ctx->recon_frames->hwctx;
  2126. vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
  2127. ctx->surface_width, ctx->surface_height,
  2128. VA_PROGRESSIVE,
  2129. recon_hwctx->surface_ids,
  2130. recon_hwctx->nb_surfaces,
  2131. &ctx->va_context);
  2132. if (vas != VA_STATUS_SUCCESS) {
  2133. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  2134. "context: %d (%s).\n", vas, vaErrorStr(vas));
  2135. err = AVERROR(EIO);
  2136. goto fail;
  2137. }
  2138. ctx->output_buffer_pool =
  2139. av_buffer_pool_init2(sizeof(VABufferID), avctx,
  2140. &vaapi_encode_alloc_output_buffer, NULL);
  2141. if (!ctx->output_buffer_pool) {
  2142. err = AVERROR(ENOMEM);
  2143. goto fail;
  2144. }
  2145. if (ctx->codec->configure) {
  2146. err = ctx->codec->configure(avctx);
  2147. if (err < 0)
  2148. goto fail;
  2149. }
  2150. ctx->output_delay = ctx->b_per_p;
  2151. ctx->decode_delay = ctx->max_b_depth;
  2152. if (ctx->codec->sequence_params_size > 0) {
  2153. ctx->codec_sequence_params =
  2154. av_mallocz(ctx->codec->sequence_params_size);
  2155. if (!ctx->codec_sequence_params) {
  2156. err = AVERROR(ENOMEM);
  2157. goto fail;
  2158. }
  2159. }
  2160. if (ctx->codec->picture_params_size > 0) {
  2161. ctx->codec_picture_params =
  2162. av_mallocz(ctx->codec->picture_params_size);
  2163. if (!ctx->codec_picture_params) {
  2164. err = AVERROR(ENOMEM);
  2165. goto fail;
  2166. }
  2167. }
  2168. if (ctx->codec->init_sequence_params) {
  2169. err = ctx->codec->init_sequence_params(avctx);
  2170. if (err < 0) {
  2171. av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
  2172. "failed: %d.\n", err);
  2173. goto fail;
  2174. }
  2175. }
  2176. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
  2177. ctx->codec->write_sequence_header &&
  2178. avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  2179. char data[MAX_PARAM_BUFFER_SIZE];
  2180. size_t bit_len = 8 * sizeof(data);
  2181. err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
  2182. if (err < 0) {
  2183. av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
  2184. "for extradata: %d.\n", err);
  2185. goto fail;
  2186. } else {
  2187. avctx->extradata_size = (bit_len + 7) / 8;
  2188. avctx->extradata = av_mallocz(avctx->extradata_size +
  2189. AV_INPUT_BUFFER_PADDING_SIZE);
  2190. if (!avctx->extradata) {
  2191. err = AVERROR(ENOMEM);
  2192. goto fail;
  2193. }
  2194. memcpy(avctx->extradata, data, avctx->extradata_size);
  2195. }
  2196. }
  2197. return 0;
  2198. fail:
  2199. return err;
  2200. }
  2201. av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
  2202. {
  2203. VAAPIEncodeContext *ctx = avctx->priv_data;
  2204. VAAPIEncodePicture *pic, *next;
  2205. for (pic = ctx->pic_start; pic; pic = next) {
  2206. next = pic->next;
  2207. vaapi_encode_free(avctx, pic);
  2208. }
  2209. av_buffer_pool_uninit(&ctx->output_buffer_pool);
  2210. if (ctx->va_context != VA_INVALID_ID) {
  2211. vaDestroyContext(ctx->hwctx->display, ctx->va_context);
  2212. ctx->va_context = VA_INVALID_ID;
  2213. }
  2214. if (ctx->va_config != VA_INVALID_ID) {
  2215. vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
  2216. ctx->va_config = VA_INVALID_ID;
  2217. }
  2218. av_frame_free(&ctx->frame);
  2219. av_freep(&ctx->codec_sequence_params);
  2220. av_freep(&ctx->codec_picture_params);
  2221. av_buffer_unref(&ctx->recon_frames_ref);
  2222. av_buffer_unref(&ctx->input_frames_ref);
  2223. av_buffer_unref(&ctx->device_ref);
  2224. return 0;
  2225. }