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.

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