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.

2565 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 *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. for (i = 0; i < pic->nb_slices; i++) {
  537. if (pic->slices) {
  538. av_freep(&pic->slices[i].priv_data);
  539. av_freep(&pic->slices[i].codec_slice_params);
  540. }
  541. }
  542. fail_at_end:
  543. av_freep(&pic->codec_picture_params);
  544. av_freep(&pic->param_buffers);
  545. av_freep(&pic->slices);
  546. av_freep(&pic->roi);
  547. av_frame_free(&pic->recon_image);
  548. av_buffer_unref(&pic->output_buffer_ref);
  549. pic->output_buffer = VA_INVALID_ID;
  550. return err;
  551. }
  552. static int vaapi_encode_output(AVCodecContext *avctx,
  553. VAAPIEncodePicture *pic, AVPacket *pkt)
  554. {
  555. VAAPIEncodeContext *ctx = avctx->priv_data;
  556. VACodedBufferSegment *buf_list, *buf;
  557. VAStatus vas;
  558. int total_size = 0;
  559. uint8_t *ptr;
  560. int err;
  561. err = vaapi_encode_wait(avctx, pic);
  562. if (err < 0)
  563. return err;
  564. buf_list = NULL;
  565. vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
  566. (void**)&buf_list);
  567. if (vas != VA_STATUS_SUCCESS) {
  568. av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
  569. "%d (%s).\n", vas, vaErrorStr(vas));
  570. err = AVERROR(EIO);
  571. goto fail;
  572. }
  573. for (buf = buf_list; buf; buf = buf->next)
  574. total_size += buf->size;
  575. err = av_new_packet(pkt, total_size);
  576. ptr = pkt->data;
  577. if (err < 0)
  578. goto fail_mapped;
  579. for (buf = buf_list; buf; buf = buf->next) {
  580. av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
  581. "(status %08x).\n", buf->size, buf->status);
  582. memcpy(ptr, buf->buf, buf->size);
  583. ptr += buf->size;
  584. }
  585. if (pic->type == PICTURE_TYPE_IDR)
  586. pkt->flags |= AV_PKT_FLAG_KEY;
  587. pkt->pts = pic->pts;
  588. vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
  589. if (vas != VA_STATUS_SUCCESS) {
  590. av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
  591. "%d (%s).\n", vas, vaErrorStr(vas));
  592. err = AVERROR(EIO);
  593. goto fail;
  594. }
  595. av_buffer_unref(&pic->output_buffer_ref);
  596. pic->output_buffer = VA_INVALID_ID;
  597. av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
  598. pic->display_order, pic->encode_order);
  599. return 0;
  600. fail_mapped:
  601. vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
  602. fail:
  603. av_buffer_unref(&pic->output_buffer_ref);
  604. pic->output_buffer = VA_INVALID_ID;
  605. return err;
  606. }
  607. static int vaapi_encode_discard(AVCodecContext *avctx,
  608. VAAPIEncodePicture *pic)
  609. {
  610. vaapi_encode_wait(avctx, pic);
  611. if (pic->output_buffer_ref) {
  612. av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
  613. "%"PRId64"/%"PRId64".\n",
  614. pic->display_order, pic->encode_order);
  615. av_buffer_unref(&pic->output_buffer_ref);
  616. pic->output_buffer = VA_INVALID_ID;
  617. }
  618. return 0;
  619. }
  620. static VAAPIEncodePicture *vaapi_encode_alloc(AVCodecContext *avctx)
  621. {
  622. VAAPIEncodeContext *ctx = avctx->priv_data;
  623. VAAPIEncodePicture *pic;
  624. pic = av_mallocz(sizeof(*pic));
  625. if (!pic)
  626. return NULL;
  627. if (ctx->codec->picture_priv_data_size > 0) {
  628. pic->priv_data = av_mallocz(ctx->codec->picture_priv_data_size);
  629. if (!pic->priv_data) {
  630. av_freep(&pic);
  631. return NULL;
  632. }
  633. }
  634. pic->input_surface = VA_INVALID_ID;
  635. pic->recon_surface = VA_INVALID_ID;
  636. pic->output_buffer = VA_INVALID_ID;
  637. return pic;
  638. }
  639. static int vaapi_encode_free(AVCodecContext *avctx,
  640. VAAPIEncodePicture *pic)
  641. {
  642. int i;
  643. if (pic->encode_issued)
  644. vaapi_encode_discard(avctx, pic);
  645. for (i = 0; i < pic->nb_slices; i++) {
  646. if (pic->slices) {
  647. av_freep(&pic->slices[i].priv_data);
  648. av_freep(&pic->slices[i].codec_slice_params);
  649. }
  650. }
  651. av_freep(&pic->codec_picture_params);
  652. av_frame_free(&pic->input_image);
  653. av_frame_free(&pic->recon_image);
  654. av_freep(&pic->param_buffers);
  655. av_freep(&pic->slices);
  656. // Output buffer should already be destroyed.
  657. av_assert0(pic->output_buffer == VA_INVALID_ID);
  658. av_freep(&pic->priv_data);
  659. av_freep(&pic->codec_picture_params);
  660. av_freep(&pic->roi);
  661. av_free(pic);
  662. return 0;
  663. }
  664. static void vaapi_encode_add_ref(AVCodecContext *avctx,
  665. VAAPIEncodePicture *pic,
  666. VAAPIEncodePicture *target,
  667. int is_ref, int in_dpb, int prev)
  668. {
  669. int refs = 0;
  670. if (is_ref) {
  671. av_assert0(pic != target);
  672. av_assert0(pic->nb_refs < MAX_PICTURE_REFERENCES);
  673. pic->refs[pic->nb_refs++] = target;
  674. ++refs;
  675. }
  676. if (in_dpb) {
  677. av_assert0(pic->nb_dpb_pics < MAX_DPB_SIZE);
  678. pic->dpb[pic->nb_dpb_pics++] = target;
  679. ++refs;
  680. }
  681. if (prev) {
  682. av_assert0(!pic->prev);
  683. pic->prev = target;
  684. ++refs;
  685. }
  686. target->ref_count[0] += refs;
  687. target->ref_count[1] += refs;
  688. }
  689. static void vaapi_encode_remove_refs(AVCodecContext *avctx,
  690. VAAPIEncodePicture *pic,
  691. int level)
  692. {
  693. int i;
  694. if (pic->ref_removed[level])
  695. return;
  696. for (i = 0; i < pic->nb_refs; i++) {
  697. av_assert0(pic->refs[i]);
  698. --pic->refs[i]->ref_count[level];
  699. av_assert0(pic->refs[i]->ref_count[level] >= 0);
  700. }
  701. for (i = 0; i < pic->nb_dpb_pics; i++) {
  702. av_assert0(pic->dpb[i]);
  703. --pic->dpb[i]->ref_count[level];
  704. av_assert0(pic->dpb[i]->ref_count[level] >= 0);
  705. }
  706. av_assert0(pic->prev || pic->type == PICTURE_TYPE_IDR);
  707. if (pic->prev) {
  708. --pic->prev->ref_count[level];
  709. av_assert0(pic->prev->ref_count[level] >= 0);
  710. }
  711. pic->ref_removed[level] = 1;
  712. }
  713. static void vaapi_encode_set_b_pictures(AVCodecContext *avctx,
  714. VAAPIEncodePicture *start,
  715. VAAPIEncodePicture *end,
  716. VAAPIEncodePicture *prev,
  717. int current_depth,
  718. VAAPIEncodePicture **last)
  719. {
  720. VAAPIEncodeContext *ctx = avctx->priv_data;
  721. VAAPIEncodePicture *pic, *next, *ref;
  722. int i, len;
  723. av_assert0(start && end && start != end && start->next != end);
  724. // If we are at the maximum depth then encode all pictures as
  725. // non-referenced B-pictures. Also do this if there is exactly one
  726. // picture left, since there will be nothing to reference it.
  727. if (current_depth == ctx->max_b_depth || start->next->next == end) {
  728. for (pic = start->next; pic; pic = pic->next) {
  729. if (pic == end)
  730. break;
  731. pic->type = PICTURE_TYPE_B;
  732. pic->b_depth = current_depth;
  733. vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
  734. vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
  735. vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
  736. for (ref = end->refs[1]; ref; ref = ref->refs[1])
  737. vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
  738. }
  739. *last = prev;
  740. } else {
  741. // Split the current list at the midpoint with a referenced
  742. // B-picture, then descend into each side separately.
  743. len = 0;
  744. for (pic = start->next; pic != end; pic = pic->next)
  745. ++len;
  746. for (pic = start->next, i = 1; 2 * i < len; pic = pic->next, i++);
  747. pic->type = PICTURE_TYPE_B;
  748. pic->b_depth = current_depth;
  749. pic->is_reference = 1;
  750. vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
  751. vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
  752. vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
  753. vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
  754. for (ref = end->refs[1]; ref; ref = ref->refs[1])
  755. vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
  756. if (i > 1)
  757. vaapi_encode_set_b_pictures(avctx, start, pic, pic,
  758. current_depth + 1, &next);
  759. else
  760. next = pic;
  761. vaapi_encode_set_b_pictures(avctx, pic, end, next,
  762. current_depth + 1, last);
  763. }
  764. }
  765. static int vaapi_encode_pick_next(AVCodecContext *avctx,
  766. VAAPIEncodePicture **pic_out)
  767. {
  768. VAAPIEncodeContext *ctx = avctx->priv_data;
  769. VAAPIEncodePicture *pic = NULL, *next, *start;
  770. int i, b_counter, closed_gop_end;
  771. // If there are any B-frames already queued, the next one to encode
  772. // is the earliest not-yet-issued frame for which all references are
  773. // available.
  774. for (pic = ctx->pic_start; pic; pic = pic->next) {
  775. if (pic->encode_issued)
  776. continue;
  777. if (pic->type != PICTURE_TYPE_B)
  778. continue;
  779. for (i = 0; i < pic->nb_refs; i++) {
  780. if (!pic->refs[i]->encode_issued)
  781. break;
  782. }
  783. if (i == pic->nb_refs)
  784. break;
  785. }
  786. if (pic) {
  787. av_log(avctx, AV_LOG_DEBUG, "Pick B-picture at depth %d to "
  788. "encode next.\n", pic->b_depth);
  789. *pic_out = pic;
  790. return 0;
  791. }
  792. // Find the B-per-Pth available picture to become the next picture
  793. // on the top layer.
  794. start = NULL;
  795. b_counter = 0;
  796. closed_gop_end = ctx->closed_gop ||
  797. ctx->idr_counter == ctx->gop_per_idr;
  798. for (pic = ctx->pic_start; pic; pic = next) {
  799. next = pic->next;
  800. if (pic->encode_issued) {
  801. start = pic;
  802. continue;
  803. }
  804. // If the next available picture is force-IDR, encode it to start
  805. // a new GOP immediately.
  806. if (pic->force_idr)
  807. break;
  808. if (b_counter == ctx->b_per_p)
  809. break;
  810. // If this picture ends a closed GOP or starts a new GOP then it
  811. // needs to be in the top layer.
  812. if (ctx->gop_counter + b_counter + closed_gop_end >= ctx->gop_size)
  813. break;
  814. // If the picture after this one is force-IDR, we need to encode
  815. // this one in the top layer.
  816. if (next && next->force_idr)
  817. break;
  818. ++b_counter;
  819. }
  820. // At the end of the stream the last picture must be in the top layer.
  821. if (!pic && ctx->end_of_stream) {
  822. --b_counter;
  823. pic = ctx->pic_end;
  824. if (pic->encode_issued)
  825. return AVERROR_EOF;
  826. }
  827. if (!pic) {
  828. av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
  829. "need more input for reference pictures.\n");
  830. return AVERROR(EAGAIN);
  831. }
  832. if (ctx->input_order <= ctx->decode_delay && !ctx->end_of_stream) {
  833. av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
  834. "need more input for timestamps.\n");
  835. return AVERROR(EAGAIN);
  836. }
  837. if (pic->force_idr) {
  838. av_log(avctx, AV_LOG_DEBUG, "Pick forced IDR-picture to "
  839. "encode next.\n");
  840. pic->type = PICTURE_TYPE_IDR;
  841. ctx->idr_counter = 1;
  842. ctx->gop_counter = 1;
  843. } else if (ctx->gop_counter + b_counter >= ctx->gop_size) {
  844. if (ctx->idr_counter == ctx->gop_per_idr) {
  845. av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP IDR-picture to "
  846. "encode next.\n");
  847. pic->type = PICTURE_TYPE_IDR;
  848. ctx->idr_counter = 1;
  849. } else {
  850. av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP I-picture to "
  851. "encode next.\n");
  852. pic->type = PICTURE_TYPE_I;
  853. ++ctx->idr_counter;
  854. }
  855. ctx->gop_counter = 1;
  856. } else {
  857. if (ctx->gop_counter + b_counter + closed_gop_end == ctx->gop_size) {
  858. av_log(avctx, AV_LOG_DEBUG, "Pick group-end P-picture to "
  859. "encode next.\n");
  860. } else {
  861. av_log(avctx, AV_LOG_DEBUG, "Pick normal P-picture to "
  862. "encode next.\n");
  863. }
  864. pic->type = PICTURE_TYPE_P;
  865. av_assert0(start);
  866. ctx->gop_counter += 1 + b_counter;
  867. }
  868. pic->is_reference = 1;
  869. *pic_out = pic;
  870. vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
  871. if (pic->type != PICTURE_TYPE_IDR) {
  872. vaapi_encode_add_ref(avctx, pic, start,
  873. pic->type == PICTURE_TYPE_P,
  874. b_counter > 0, 0);
  875. vaapi_encode_add_ref(avctx, pic, ctx->next_prev, 0, 0, 1);
  876. }
  877. if (ctx->next_prev)
  878. --ctx->next_prev->ref_count[0];
  879. if (b_counter > 0) {
  880. vaapi_encode_set_b_pictures(avctx, start, pic, pic, 1,
  881. &ctx->next_prev);
  882. } else {
  883. ctx->next_prev = pic;
  884. }
  885. ++ctx->next_prev->ref_count[0];
  886. return 0;
  887. }
  888. static int vaapi_encode_clear_old(AVCodecContext *avctx)
  889. {
  890. VAAPIEncodeContext *ctx = avctx->priv_data;
  891. VAAPIEncodePicture *pic, *prev, *next;
  892. av_assert0(ctx->pic_start);
  893. // Remove direct references once each picture is complete.
  894. for (pic = ctx->pic_start; pic; pic = pic->next) {
  895. if (pic->encode_complete && pic->next)
  896. vaapi_encode_remove_refs(avctx, pic, 0);
  897. }
  898. // Remove indirect references once a picture has no direct references.
  899. for (pic = ctx->pic_start; pic; pic = pic->next) {
  900. if (pic->encode_complete && pic->ref_count[0] == 0)
  901. vaapi_encode_remove_refs(avctx, pic, 1);
  902. }
  903. // Clear out all complete pictures with no remaining references.
  904. prev = NULL;
  905. for (pic = ctx->pic_start; pic; pic = next) {
  906. next = pic->next;
  907. if (pic->encode_complete && pic->ref_count[1] == 0) {
  908. av_assert0(pic->ref_removed[0] && pic->ref_removed[1]);
  909. if (prev)
  910. prev->next = next;
  911. else
  912. ctx->pic_start = next;
  913. vaapi_encode_free(avctx, pic);
  914. } else {
  915. prev = pic;
  916. }
  917. }
  918. return 0;
  919. }
  920. static int vaapi_encode_check_frame(AVCodecContext *avctx,
  921. const AVFrame *frame)
  922. {
  923. VAAPIEncodeContext *ctx = avctx->priv_data;
  924. if ((frame->crop_top || frame->crop_bottom ||
  925. frame->crop_left || frame->crop_right) && !ctx->crop_warned) {
  926. av_log(avctx, AV_LOG_WARNING, "Cropping information on input "
  927. "frames ignored due to lack of API support.\n");
  928. ctx->crop_warned = 1;
  929. }
  930. if (!ctx->roi_allowed) {
  931. AVFrameSideData *sd =
  932. av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
  933. if (sd && !ctx->roi_warned) {
  934. av_log(avctx, AV_LOG_WARNING, "ROI side data on input "
  935. "frames ignored due to lack of driver support.\n");
  936. ctx->roi_warned = 1;
  937. }
  938. }
  939. return 0;
  940. }
  941. static int vaapi_encode_send_frame(AVCodecContext *avctx, AVFrame *frame)
  942. {
  943. VAAPIEncodeContext *ctx = avctx->priv_data;
  944. VAAPIEncodePicture *pic;
  945. int err;
  946. if (frame) {
  947. av_log(avctx, AV_LOG_DEBUG, "Input frame: %ux%u (%"PRId64").\n",
  948. frame->width, frame->height, frame->pts);
  949. err = vaapi_encode_check_frame(avctx, frame);
  950. if (err < 0)
  951. return err;
  952. pic = vaapi_encode_alloc(avctx);
  953. if (!pic)
  954. return AVERROR(ENOMEM);
  955. pic->input_image = av_frame_alloc();
  956. if (!pic->input_image) {
  957. err = AVERROR(ENOMEM);
  958. goto fail;
  959. }
  960. if (ctx->input_order == 0 || frame->pict_type == AV_PICTURE_TYPE_I)
  961. pic->force_idr = 1;
  962. pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
  963. pic->pts = frame->pts;
  964. av_frame_move_ref(pic->input_image, frame);
  965. if (ctx->input_order == 0)
  966. ctx->first_pts = pic->pts;
  967. if (ctx->input_order == ctx->decode_delay)
  968. ctx->dts_pts_diff = pic->pts - ctx->first_pts;
  969. if (ctx->output_delay > 0)
  970. ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
  971. pic->display_order = ctx->input_order;
  972. ++ctx->input_order;
  973. if (ctx->pic_start) {
  974. ctx->pic_end->next = pic;
  975. ctx->pic_end = pic;
  976. } else {
  977. ctx->pic_start = pic;
  978. ctx->pic_end = pic;
  979. }
  980. } else {
  981. ctx->end_of_stream = 1;
  982. // Fix timestamps if we hit end-of-stream before the initial decode
  983. // delay has elapsed.
  984. if (ctx->input_order < ctx->decode_delay)
  985. ctx->dts_pts_diff = ctx->pic_end->pts - ctx->first_pts;
  986. }
  987. return 0;
  988. fail:
  989. vaapi_encode_free(avctx, pic);
  990. return err;
  991. }
  992. int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
  993. {
  994. VAAPIEncodeContext *ctx = avctx->priv_data;
  995. VAAPIEncodePicture *pic;
  996. AVFrame *frame = ctx->frame;
  997. int err;
  998. err = ff_encode_get_frame(avctx, frame);
  999. if (err < 0 && err != AVERROR_EOF)
  1000. return err;
  1001. if (err == AVERROR_EOF)
  1002. frame = NULL;
  1003. err = vaapi_encode_send_frame(avctx, frame);
  1004. if (err < 0)
  1005. return err;
  1006. if (!ctx->pic_start) {
  1007. if (ctx->end_of_stream)
  1008. return AVERROR_EOF;
  1009. else
  1010. return AVERROR(EAGAIN);
  1011. }
  1012. pic = NULL;
  1013. err = vaapi_encode_pick_next(avctx, &pic);
  1014. if (err < 0)
  1015. return err;
  1016. av_assert0(pic);
  1017. pic->encode_order = ctx->encode_order++;
  1018. err = vaapi_encode_issue(avctx, pic);
  1019. if (err < 0) {
  1020. av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
  1021. return err;
  1022. }
  1023. err = vaapi_encode_output(avctx, pic, pkt);
  1024. if (err < 0) {
  1025. av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
  1026. return err;
  1027. }
  1028. if (ctx->output_delay == 0) {
  1029. pkt->dts = pkt->pts;
  1030. } else if (pic->encode_order < ctx->decode_delay) {
  1031. if (ctx->ts_ring[pic->encode_order] < INT64_MIN + ctx->dts_pts_diff)
  1032. pkt->dts = INT64_MIN;
  1033. else
  1034. pkt->dts = ctx->ts_ring[pic->encode_order] - ctx->dts_pts_diff;
  1035. } else {
  1036. pkt->dts = ctx->ts_ring[(pic->encode_order - ctx->decode_delay) %
  1037. (3 * ctx->output_delay)];
  1038. }
  1039. av_log(avctx, AV_LOG_DEBUG, "Output packet: pts %"PRId64" dts %"PRId64".\n",
  1040. pkt->pts, pkt->dts);
  1041. ctx->output_order = pic->encode_order;
  1042. vaapi_encode_clear_old(avctx);
  1043. return 0;
  1044. }
  1045. static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx, int type,
  1046. void *buffer, size_t size)
  1047. {
  1048. VAAPIEncodeContext *ctx = avctx->priv_data;
  1049. av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
  1050. ctx->global_params_type[ctx->nb_global_params] = type;
  1051. ctx->global_params [ctx->nb_global_params] = buffer;
  1052. ctx->global_params_size[ctx->nb_global_params] = size;
  1053. ++ctx->nb_global_params;
  1054. }
  1055. typedef struct VAAPIEncodeRTFormat {
  1056. const char *name;
  1057. unsigned int value;
  1058. int depth;
  1059. int nb_components;
  1060. int log2_chroma_w;
  1061. int log2_chroma_h;
  1062. } VAAPIEncodeRTFormat;
  1063. static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
  1064. { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
  1065. { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
  1066. { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
  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. #if VA_CHECK_VERSION(1, 8, 0)
  1660. slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_MULTI_ROWS ||
  1661. #endif
  1662. slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
  1663. ctx->nb_slices = req_slices;
  1664. ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
  1665. } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
  1666. int k;
  1667. for (k = 1;; k *= 2) {
  1668. if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
  1669. break;
  1670. }
  1671. ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
  1672. ctx->slice_size = k;
  1673. #if VA_CHECK_VERSION(1, 0, 0)
  1674. } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
  1675. ctx->nb_slices = ctx->slice_block_rows;
  1676. ctx->slice_size = 1;
  1677. #endif
  1678. } else {
  1679. av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
  1680. "slice structure modes (%#x).\n", slice_structure);
  1681. return AVERROR(EINVAL);
  1682. }
  1683. return 0;
  1684. }
  1685. static av_cold int vaapi_encode_init_tile_slice_structure(AVCodecContext *avctx,
  1686. uint32_t slice_structure)
  1687. {
  1688. VAAPIEncodeContext *ctx = avctx->priv_data;
  1689. int i, req_tiles;
  1690. if (!(slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS ||
  1691. (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS &&
  1692. ctx->tile_cols == 1))) {
  1693. av_log(avctx, AV_LOG_ERROR, "Supported slice structure (%#x) doesn't work for "
  1694. "current tile requirement.\n", slice_structure);
  1695. return AVERROR(EINVAL);
  1696. }
  1697. if (ctx->tile_rows > ctx->slice_block_rows ||
  1698. ctx->tile_cols > ctx->slice_block_cols) {
  1699. av_log(avctx, AV_LOG_WARNING, "Not enough block rows/cols (%d x %d) "
  1700. "for configured number of tile (%d x %d); ",
  1701. ctx->slice_block_rows, ctx->slice_block_cols,
  1702. ctx->tile_rows, ctx->tile_cols);
  1703. ctx->tile_rows = ctx->tile_rows > ctx->slice_block_rows ?
  1704. ctx->slice_block_rows : ctx->tile_rows;
  1705. ctx->tile_cols = ctx->tile_cols > ctx->slice_block_cols ?
  1706. ctx->slice_block_cols : ctx->tile_cols;
  1707. av_log(avctx, AV_LOG_WARNING, "using allowed maximum (%d x %d).\n",
  1708. ctx->tile_rows, ctx->tile_cols);
  1709. }
  1710. req_tiles = ctx->tile_rows * ctx->tile_cols;
  1711. // Tile slice is not allowed to cross the boundary of a tile due to
  1712. // the constraints of media-driver. Currently we support one slice
  1713. // per tile. This could be extended to multiple slices per tile.
  1714. if (avctx->slices != req_tiles)
  1715. av_log(avctx, AV_LOG_WARNING, "The number of requested slices "
  1716. "mismatches with configured number of tile (%d != %d); "
  1717. "using requested tile number for slice.\n",
  1718. avctx->slices, req_tiles);
  1719. ctx->nb_slices = req_tiles;
  1720. // Default in uniform spacing
  1721. // 6-3, 6-5
  1722. for (i = 0; i < ctx->tile_cols; i++) {
  1723. ctx->col_width[i] = ( i + 1 ) * ctx->slice_block_cols / ctx->tile_cols -
  1724. i * ctx->slice_block_cols / ctx->tile_cols;
  1725. ctx->col_bd[i + 1] = ctx->col_bd[i] + ctx->col_width[i];
  1726. }
  1727. // 6-4, 6-6
  1728. for (i = 0; i < ctx->tile_rows; i++) {
  1729. ctx->row_height[i] = ( i + 1 ) * ctx->slice_block_rows / ctx->tile_rows -
  1730. i * ctx->slice_block_rows / ctx->tile_rows;
  1731. ctx->row_bd[i + 1] = ctx->row_bd[i] + ctx->row_height[i];
  1732. }
  1733. av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d x %d tile.\n",
  1734. ctx->tile_rows, ctx->tile_cols);
  1735. return 0;
  1736. }
  1737. static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
  1738. {
  1739. VAAPIEncodeContext *ctx = avctx->priv_data;
  1740. VAConfigAttrib attr[3] = { { VAConfigAttribEncMaxSlices },
  1741. { VAConfigAttribEncSliceStructure },
  1742. #if VA_CHECK_VERSION(1, 1, 0)
  1743. { VAConfigAttribEncTileSupport },
  1744. #endif
  1745. };
  1746. VAStatus vas;
  1747. uint32_t max_slices, slice_structure;
  1748. int ret;
  1749. if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
  1750. if (avctx->slices > 0) {
  1751. av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
  1752. "but this codec does not support controlling slices.\n");
  1753. }
  1754. return 0;
  1755. }
  1756. ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
  1757. ctx->slice_block_height;
  1758. ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
  1759. ctx->slice_block_width;
  1760. if (avctx->slices <= 1 && !ctx->tile_rows && !ctx->tile_cols) {
  1761. ctx->nb_slices = 1;
  1762. ctx->slice_size = ctx->slice_block_rows;
  1763. return 0;
  1764. }
  1765. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1766. ctx->va_profile,
  1767. ctx->va_entrypoint,
  1768. attr, FF_ARRAY_ELEMS(attr));
  1769. if (vas != VA_STATUS_SUCCESS) {
  1770. av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
  1771. "attributes: %d (%s).\n", vas, vaErrorStr(vas));
  1772. return AVERROR_EXTERNAL;
  1773. }
  1774. max_slices = attr[0].value;
  1775. slice_structure = attr[1].value;
  1776. if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
  1777. slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
  1778. av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
  1779. "pictures as multiple slices.\n.");
  1780. return AVERROR(EINVAL);
  1781. }
  1782. if (ctx->tile_rows && ctx->tile_cols) {
  1783. #if VA_CHECK_VERSION(1, 1, 0)
  1784. uint32_t tile_support = attr[2].value;
  1785. if (tile_support == VA_ATTRIB_NOT_SUPPORTED) {
  1786. av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
  1787. "pictures as multiple tiles.\n.");
  1788. return AVERROR(EINVAL);
  1789. }
  1790. #else
  1791. av_log(avctx, AV_LOG_ERROR, "Tile encoding option is "
  1792. "not supported with this VAAPI version.\n");
  1793. return AVERROR(EINVAL);
  1794. #endif
  1795. }
  1796. if (ctx->tile_rows && ctx->tile_cols)
  1797. ret = vaapi_encode_init_tile_slice_structure(avctx, slice_structure);
  1798. else
  1799. ret = vaapi_encode_init_row_slice_structure(avctx, slice_structure);
  1800. if (ret < 0)
  1801. return ret;
  1802. if (ctx->nb_slices > avctx->slices) {
  1803. av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
  1804. "%d (from %d) due to driver constraints on slice "
  1805. "structure.\n", ctx->nb_slices, avctx->slices);
  1806. }
  1807. if (ctx->nb_slices > max_slices) {
  1808. av_log(avctx, AV_LOG_ERROR, "Driver does not support "
  1809. "encoding with %d slices (max %"PRIu32").\n",
  1810. ctx->nb_slices, max_slices);
  1811. return AVERROR(EINVAL);
  1812. }
  1813. av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices.\n",
  1814. ctx->nb_slices);
  1815. return 0;
  1816. }
  1817. static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
  1818. {
  1819. VAAPIEncodeContext *ctx = avctx->priv_data;
  1820. VAStatus vas;
  1821. VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
  1822. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1823. ctx->va_profile,
  1824. ctx->va_entrypoint,
  1825. &attr, 1);
  1826. if (vas != VA_STATUS_SUCCESS) {
  1827. av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
  1828. "attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1829. return AVERROR_EXTERNAL;
  1830. }
  1831. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1832. if (ctx->desired_packed_headers) {
  1833. av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
  1834. "packed headers (wanted %#x).\n",
  1835. ctx->desired_packed_headers);
  1836. } else {
  1837. av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
  1838. "packed headers (none wanted).\n");
  1839. }
  1840. ctx->va_packed_headers = 0;
  1841. } else {
  1842. if (ctx->desired_packed_headers & ~attr.value) {
  1843. av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
  1844. "wanted packed headers (wanted %#x, found %#x).\n",
  1845. ctx->desired_packed_headers, attr.value);
  1846. } else {
  1847. av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
  1848. "available (wanted %#x, found %#x).\n",
  1849. ctx->desired_packed_headers, attr.value);
  1850. }
  1851. ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
  1852. }
  1853. if (ctx->va_packed_headers) {
  1854. ctx->config_attributes[ctx->nb_config_attributes++] =
  1855. (VAConfigAttrib) {
  1856. .type = VAConfigAttribEncPackedHeaders,
  1857. .value = ctx->va_packed_headers,
  1858. };
  1859. }
  1860. if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
  1861. !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
  1862. (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
  1863. av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
  1864. "sequence headers, but a global header is requested.\n");
  1865. av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
  1866. "this may result in a stream which is not usable for some "
  1867. "purposes (e.g. not muxable to some containers).\n");
  1868. }
  1869. return 0;
  1870. }
  1871. static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
  1872. {
  1873. #if VA_CHECK_VERSION(0, 36, 0)
  1874. VAAPIEncodeContext *ctx = avctx->priv_data;
  1875. VAStatus vas;
  1876. VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
  1877. int quality = avctx->compression_level;
  1878. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1879. ctx->va_profile,
  1880. ctx->va_entrypoint,
  1881. &attr, 1);
  1882. if (vas != VA_STATUS_SUCCESS) {
  1883. av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
  1884. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1885. return AVERROR_EXTERNAL;
  1886. }
  1887. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1888. if (quality != 0) {
  1889. av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
  1890. "supported: will use default quality level.\n");
  1891. }
  1892. } else {
  1893. if (quality > attr.value) {
  1894. av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
  1895. "valid range is 0-%d, using %d.\n",
  1896. attr.value, attr.value);
  1897. quality = attr.value;
  1898. }
  1899. ctx->quality_params = (VAEncMiscParameterBufferQualityLevel) {
  1900. .quality_level = quality,
  1901. };
  1902. vaapi_encode_add_global_param(avctx,
  1903. VAEncMiscParameterTypeQualityLevel,
  1904. &ctx->quality_params,
  1905. sizeof(ctx->quality_params));
  1906. }
  1907. #else
  1908. av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
  1909. "not supported with this VAAPI version.\n");
  1910. #endif
  1911. return 0;
  1912. }
  1913. static av_cold int vaapi_encode_init_roi(AVCodecContext *avctx)
  1914. {
  1915. #if VA_CHECK_VERSION(1, 0, 0)
  1916. VAAPIEncodeContext *ctx = avctx->priv_data;
  1917. VAStatus vas;
  1918. VAConfigAttrib attr = { VAConfigAttribEncROI };
  1919. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1920. ctx->va_profile,
  1921. ctx->va_entrypoint,
  1922. &attr, 1);
  1923. if (vas != VA_STATUS_SUCCESS) {
  1924. av_log(avctx, AV_LOG_ERROR, "Failed to query ROI "
  1925. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1926. return AVERROR_EXTERNAL;
  1927. }
  1928. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1929. ctx->roi_allowed = 0;
  1930. } else {
  1931. VAConfigAttribValEncROI roi = {
  1932. .value = attr.value,
  1933. };
  1934. ctx->roi_max_regions = roi.bits.num_roi_regions;
  1935. ctx->roi_allowed = ctx->roi_max_regions > 0 &&
  1936. (ctx->va_rc_mode == VA_RC_CQP ||
  1937. roi.bits.roi_rc_qp_delta_support);
  1938. }
  1939. #endif
  1940. return 0;
  1941. }
  1942. static void vaapi_encode_free_output_buffer(void *opaque,
  1943. uint8_t *data)
  1944. {
  1945. AVCodecContext *avctx = opaque;
  1946. VAAPIEncodeContext *ctx = avctx->priv_data;
  1947. VABufferID buffer_id;
  1948. buffer_id = (VABufferID)(uintptr_t)data;
  1949. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  1950. av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
  1951. }
  1952. static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
  1953. int size)
  1954. {
  1955. AVCodecContext *avctx = opaque;
  1956. VAAPIEncodeContext *ctx = avctx->priv_data;
  1957. VABufferID buffer_id;
  1958. VAStatus vas;
  1959. AVBufferRef *ref;
  1960. // The output buffer size is fixed, so it needs to be large enough
  1961. // to hold the largest possible compressed frame. We assume here
  1962. // that the uncompressed frame plus some header data is an upper
  1963. // bound on that.
  1964. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  1965. VAEncCodedBufferType,
  1966. 3 * ctx->surface_width * ctx->surface_height +
  1967. (1 << 16), 1, 0, &buffer_id);
  1968. if (vas != VA_STATUS_SUCCESS) {
  1969. av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
  1970. "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
  1971. return NULL;
  1972. }
  1973. av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
  1974. ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
  1975. sizeof(buffer_id),
  1976. &vaapi_encode_free_output_buffer,
  1977. avctx, AV_BUFFER_FLAG_READONLY);
  1978. if (!ref) {
  1979. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  1980. return NULL;
  1981. }
  1982. return ref;
  1983. }
  1984. static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
  1985. {
  1986. VAAPIEncodeContext *ctx = avctx->priv_data;
  1987. AVVAAPIHWConfig *hwconfig = NULL;
  1988. AVHWFramesConstraints *constraints = NULL;
  1989. enum AVPixelFormat recon_format;
  1990. int err, i;
  1991. hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
  1992. if (!hwconfig) {
  1993. err = AVERROR(ENOMEM);
  1994. goto fail;
  1995. }
  1996. hwconfig->config_id = ctx->va_config;
  1997. constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
  1998. hwconfig);
  1999. if (!constraints) {
  2000. err = AVERROR(ENOMEM);
  2001. goto fail;
  2002. }
  2003. // Probably we can use the input surface format as the surface format
  2004. // of the reconstructed frames. If not, we just pick the first (only?)
  2005. // format in the valid list and hope that it all works.
  2006. recon_format = AV_PIX_FMT_NONE;
  2007. if (constraints->valid_sw_formats) {
  2008. for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
  2009. if (ctx->input_frames->sw_format ==
  2010. constraints->valid_sw_formats[i]) {
  2011. recon_format = ctx->input_frames->sw_format;
  2012. break;
  2013. }
  2014. }
  2015. if (recon_format == AV_PIX_FMT_NONE) {
  2016. // No match. Just use the first in the supported list and
  2017. // hope for the best.
  2018. recon_format = constraints->valid_sw_formats[0];
  2019. }
  2020. } else {
  2021. // No idea what to use; copy input format.
  2022. recon_format = ctx->input_frames->sw_format;
  2023. }
  2024. av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
  2025. "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
  2026. if (ctx->surface_width < constraints->min_width ||
  2027. ctx->surface_height < constraints->min_height ||
  2028. ctx->surface_width > constraints->max_width ||
  2029. ctx->surface_height > constraints->max_height) {
  2030. av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
  2031. "size %dx%d (constraints: width %d-%d height %d-%d).\n",
  2032. ctx->surface_width, ctx->surface_height,
  2033. constraints->min_width, constraints->max_width,
  2034. constraints->min_height, constraints->max_height);
  2035. err = AVERROR(EINVAL);
  2036. goto fail;
  2037. }
  2038. av_freep(&hwconfig);
  2039. av_hwframe_constraints_free(&constraints);
  2040. ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
  2041. if (!ctx->recon_frames_ref) {
  2042. err = AVERROR(ENOMEM);
  2043. goto fail;
  2044. }
  2045. ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
  2046. ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
  2047. ctx->recon_frames->sw_format = recon_format;
  2048. ctx->recon_frames->width = ctx->surface_width;
  2049. ctx->recon_frames->height = ctx->surface_height;
  2050. err = av_hwframe_ctx_init(ctx->recon_frames_ref);
  2051. if (err < 0) {
  2052. av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
  2053. "frame context: %d.\n", err);
  2054. goto fail;
  2055. }
  2056. err = 0;
  2057. fail:
  2058. av_freep(&hwconfig);
  2059. av_hwframe_constraints_free(&constraints);
  2060. return err;
  2061. }
  2062. av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
  2063. {
  2064. VAAPIEncodeContext *ctx = avctx->priv_data;
  2065. AVVAAPIFramesContext *recon_hwctx = NULL;
  2066. VAStatus vas;
  2067. int err;
  2068. ctx->frame = av_frame_alloc();
  2069. if (!ctx->frame) {
  2070. return AVERROR(ENOMEM);
  2071. }
  2072. if (!avctx->hw_frames_ctx) {
  2073. av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
  2074. "required to associate the encoding device.\n");
  2075. return AVERROR(EINVAL);
  2076. }
  2077. ctx->va_config = VA_INVALID_ID;
  2078. ctx->va_context = VA_INVALID_ID;
  2079. ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
  2080. if (!ctx->input_frames_ref) {
  2081. err = AVERROR(ENOMEM);
  2082. goto fail;
  2083. }
  2084. ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
  2085. ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
  2086. if (!ctx->device_ref) {
  2087. err = AVERROR(ENOMEM);
  2088. goto fail;
  2089. }
  2090. ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
  2091. ctx->hwctx = ctx->device->hwctx;
  2092. err = vaapi_encode_profile_entrypoint(avctx);
  2093. if (err < 0)
  2094. goto fail;
  2095. err = vaapi_encode_init_rate_control(avctx);
  2096. if (err < 0)
  2097. goto fail;
  2098. err = vaapi_encode_init_gop_structure(avctx);
  2099. if (err < 0)
  2100. goto fail;
  2101. err = vaapi_encode_init_slice_structure(avctx);
  2102. if (err < 0)
  2103. goto fail;
  2104. err = vaapi_encode_init_packed_headers(avctx);
  2105. if (err < 0)
  2106. goto fail;
  2107. err = vaapi_encode_init_roi(avctx);
  2108. if (err < 0)
  2109. goto fail;
  2110. if (avctx->compression_level >= 0) {
  2111. err = vaapi_encode_init_quality(avctx);
  2112. if (err < 0)
  2113. goto fail;
  2114. }
  2115. vas = vaCreateConfig(ctx->hwctx->display,
  2116. ctx->va_profile, ctx->va_entrypoint,
  2117. ctx->config_attributes, ctx->nb_config_attributes,
  2118. &ctx->va_config);
  2119. if (vas != VA_STATUS_SUCCESS) {
  2120. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  2121. "configuration: %d (%s).\n", vas, vaErrorStr(vas));
  2122. err = AVERROR(EIO);
  2123. goto fail;
  2124. }
  2125. err = vaapi_encode_create_recon_frames(avctx);
  2126. if (err < 0)
  2127. goto fail;
  2128. recon_hwctx = ctx->recon_frames->hwctx;
  2129. vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
  2130. ctx->surface_width, ctx->surface_height,
  2131. VA_PROGRESSIVE,
  2132. recon_hwctx->surface_ids,
  2133. recon_hwctx->nb_surfaces,
  2134. &ctx->va_context);
  2135. if (vas != VA_STATUS_SUCCESS) {
  2136. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  2137. "context: %d (%s).\n", vas, vaErrorStr(vas));
  2138. err = AVERROR(EIO);
  2139. goto fail;
  2140. }
  2141. ctx->output_buffer_pool =
  2142. av_buffer_pool_init2(sizeof(VABufferID), avctx,
  2143. &vaapi_encode_alloc_output_buffer, NULL);
  2144. if (!ctx->output_buffer_pool) {
  2145. err = AVERROR(ENOMEM);
  2146. goto fail;
  2147. }
  2148. if (ctx->codec->configure) {
  2149. err = ctx->codec->configure(avctx);
  2150. if (err < 0)
  2151. goto fail;
  2152. }
  2153. ctx->output_delay = ctx->b_per_p;
  2154. ctx->decode_delay = ctx->max_b_depth;
  2155. if (ctx->codec->sequence_params_size > 0) {
  2156. ctx->codec_sequence_params =
  2157. av_mallocz(ctx->codec->sequence_params_size);
  2158. if (!ctx->codec_sequence_params) {
  2159. err = AVERROR(ENOMEM);
  2160. goto fail;
  2161. }
  2162. }
  2163. if (ctx->codec->picture_params_size > 0) {
  2164. ctx->codec_picture_params =
  2165. av_mallocz(ctx->codec->picture_params_size);
  2166. if (!ctx->codec_picture_params) {
  2167. err = AVERROR(ENOMEM);
  2168. goto fail;
  2169. }
  2170. }
  2171. if (ctx->codec->init_sequence_params) {
  2172. err = ctx->codec->init_sequence_params(avctx);
  2173. if (err < 0) {
  2174. av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
  2175. "failed: %d.\n", err);
  2176. goto fail;
  2177. }
  2178. }
  2179. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
  2180. ctx->codec->write_sequence_header &&
  2181. avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  2182. char data[MAX_PARAM_BUFFER_SIZE];
  2183. size_t bit_len = 8 * sizeof(data);
  2184. err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
  2185. if (err < 0) {
  2186. av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
  2187. "for extradata: %d.\n", err);
  2188. goto fail;
  2189. } else {
  2190. avctx->extradata_size = (bit_len + 7) / 8;
  2191. avctx->extradata = av_mallocz(avctx->extradata_size +
  2192. AV_INPUT_BUFFER_PADDING_SIZE);
  2193. if (!avctx->extradata) {
  2194. err = AVERROR(ENOMEM);
  2195. goto fail;
  2196. }
  2197. memcpy(avctx->extradata, data, avctx->extradata_size);
  2198. }
  2199. }
  2200. return 0;
  2201. fail:
  2202. return err;
  2203. }
  2204. av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
  2205. {
  2206. VAAPIEncodeContext *ctx = avctx->priv_data;
  2207. VAAPIEncodePicture *pic, *next;
  2208. for (pic = ctx->pic_start; pic; pic = next) {
  2209. next = pic->next;
  2210. vaapi_encode_free(avctx, pic);
  2211. }
  2212. av_buffer_pool_uninit(&ctx->output_buffer_pool);
  2213. if (ctx->va_context != VA_INVALID_ID) {
  2214. vaDestroyContext(ctx->hwctx->display, ctx->va_context);
  2215. ctx->va_context = VA_INVALID_ID;
  2216. }
  2217. if (ctx->va_config != VA_INVALID_ID) {
  2218. vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
  2219. ctx->va_config = VA_INVALID_ID;
  2220. }
  2221. av_frame_free(&ctx->frame);
  2222. av_freep(&ctx->codec_sequence_params);
  2223. av_freep(&ctx->codec_picture_params);
  2224. av_buffer_unref(&ctx->recon_frames_ref);
  2225. av_buffer_unref(&ctx->input_frames_ref);
  2226. av_buffer_unref(&ctx->device_ref);
  2227. return 0;
  2228. }