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.

2399 lines
82KB

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