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.

2390 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 err;
  518. err = vaapi_encode_wait(avctx, pic);
  519. if (err < 0)
  520. return err;
  521. buf_list = NULL;
  522. vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
  523. (void**)&buf_list);
  524. if (vas != VA_STATUS_SUCCESS) {
  525. av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
  526. "%d (%s).\n", vas, vaErrorStr(vas));
  527. err = AVERROR(EIO);
  528. goto fail;
  529. }
  530. for (buf = buf_list; buf; buf = buf->next) {
  531. av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
  532. "(status %08x).\n", buf->size, buf->status);
  533. err = av_new_packet(pkt, buf->size);
  534. if (err < 0)
  535. goto fail_mapped;
  536. memcpy(pkt->data, buf->buf, buf->size);
  537. }
  538. if (pic->type == PICTURE_TYPE_IDR)
  539. pkt->flags |= AV_PKT_FLAG_KEY;
  540. pkt->pts = pic->pts;
  541. vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
  542. if (vas != VA_STATUS_SUCCESS) {
  543. av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
  544. "%d (%s).\n", vas, vaErrorStr(vas));
  545. err = AVERROR(EIO);
  546. goto fail;
  547. }
  548. av_buffer_unref(&pic->output_buffer_ref);
  549. pic->output_buffer = VA_INVALID_ID;
  550. av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
  551. pic->display_order, pic->encode_order);
  552. return 0;
  553. fail_mapped:
  554. vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
  555. fail:
  556. av_buffer_unref(&pic->output_buffer_ref);
  557. pic->output_buffer = VA_INVALID_ID;
  558. return err;
  559. }
  560. static int vaapi_encode_discard(AVCodecContext *avctx,
  561. VAAPIEncodePicture *pic)
  562. {
  563. vaapi_encode_wait(avctx, pic);
  564. if (pic->output_buffer_ref) {
  565. av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
  566. "%"PRId64"/%"PRId64".\n",
  567. pic->display_order, pic->encode_order);
  568. av_buffer_unref(&pic->output_buffer_ref);
  569. pic->output_buffer = VA_INVALID_ID;
  570. }
  571. return 0;
  572. }
  573. static VAAPIEncodePicture *vaapi_encode_alloc(AVCodecContext *avctx)
  574. {
  575. VAAPIEncodeContext *ctx = avctx->priv_data;
  576. VAAPIEncodePicture *pic;
  577. pic = av_mallocz(sizeof(*pic));
  578. if (!pic)
  579. return NULL;
  580. if (ctx->codec->picture_priv_data_size > 0) {
  581. pic->priv_data = av_mallocz(ctx->codec->picture_priv_data_size);
  582. if (!pic->priv_data) {
  583. av_freep(&pic);
  584. return NULL;
  585. }
  586. }
  587. pic->input_surface = VA_INVALID_ID;
  588. pic->recon_surface = VA_INVALID_ID;
  589. pic->output_buffer = VA_INVALID_ID;
  590. return pic;
  591. }
  592. static int vaapi_encode_free(AVCodecContext *avctx,
  593. VAAPIEncodePicture *pic)
  594. {
  595. int i;
  596. if (pic->encode_issued)
  597. vaapi_encode_discard(avctx, pic);
  598. for (i = 0; i < pic->nb_slices; i++) {
  599. if (pic->slices) {
  600. av_freep(&pic->slices[i].priv_data);
  601. av_freep(&pic->slices[i].codec_slice_params);
  602. }
  603. }
  604. av_freep(&pic->codec_picture_params);
  605. av_frame_free(&pic->input_image);
  606. av_frame_free(&pic->recon_image);
  607. av_freep(&pic->param_buffers);
  608. av_freep(&pic->slices);
  609. // Output buffer should already be destroyed.
  610. av_assert0(pic->output_buffer == VA_INVALID_ID);
  611. av_freep(&pic->priv_data);
  612. av_freep(&pic->codec_picture_params);
  613. av_freep(&pic->roi);
  614. av_free(pic);
  615. return 0;
  616. }
  617. static void vaapi_encode_add_ref(AVCodecContext *avctx,
  618. VAAPIEncodePicture *pic,
  619. VAAPIEncodePicture *target,
  620. int is_ref, int in_dpb, int prev)
  621. {
  622. int refs = 0;
  623. if (is_ref) {
  624. av_assert0(pic != target);
  625. av_assert0(pic->nb_refs < MAX_PICTURE_REFERENCES);
  626. pic->refs[pic->nb_refs++] = target;
  627. ++refs;
  628. }
  629. if (in_dpb) {
  630. av_assert0(pic->nb_dpb_pics < MAX_DPB_SIZE);
  631. pic->dpb[pic->nb_dpb_pics++] = target;
  632. ++refs;
  633. }
  634. if (prev) {
  635. av_assert0(!pic->prev);
  636. pic->prev = target;
  637. ++refs;
  638. }
  639. target->ref_count[0] += refs;
  640. target->ref_count[1] += refs;
  641. }
  642. static void vaapi_encode_remove_refs(AVCodecContext *avctx,
  643. VAAPIEncodePicture *pic,
  644. int level)
  645. {
  646. int i;
  647. if (pic->ref_removed[level])
  648. return;
  649. for (i = 0; i < pic->nb_refs; i++) {
  650. av_assert0(pic->refs[i]);
  651. --pic->refs[i]->ref_count[level];
  652. av_assert0(pic->refs[i]->ref_count[level] >= 0);
  653. }
  654. for (i = 0; i < pic->nb_dpb_pics; i++) {
  655. av_assert0(pic->dpb[i]);
  656. --pic->dpb[i]->ref_count[level];
  657. av_assert0(pic->dpb[i]->ref_count[level] >= 0);
  658. }
  659. av_assert0(pic->prev || pic->type == PICTURE_TYPE_IDR);
  660. if (pic->prev) {
  661. --pic->prev->ref_count[level];
  662. av_assert0(pic->prev->ref_count[level] >= 0);
  663. }
  664. pic->ref_removed[level] = 1;
  665. }
  666. static void vaapi_encode_set_b_pictures(AVCodecContext *avctx,
  667. VAAPIEncodePicture *start,
  668. VAAPIEncodePicture *end,
  669. VAAPIEncodePicture *prev,
  670. int current_depth,
  671. VAAPIEncodePicture **last)
  672. {
  673. VAAPIEncodeContext *ctx = avctx->priv_data;
  674. VAAPIEncodePicture *pic, *next, *ref;
  675. int i, len;
  676. av_assert0(start && end && start != end && start->next != end);
  677. // If we are at the maximum depth then encode all pictures as
  678. // non-referenced B-pictures. Also do this if there is exactly one
  679. // picture left, since there will be nothing to reference it.
  680. if (current_depth == ctx->max_b_depth || start->next->next == end) {
  681. for (pic = start->next; pic; pic = pic->next) {
  682. if (pic == end)
  683. break;
  684. pic->type = PICTURE_TYPE_B;
  685. pic->b_depth = current_depth;
  686. vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
  687. vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
  688. vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
  689. for (ref = end->refs[1]; ref; ref = ref->refs[1])
  690. vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
  691. }
  692. *last = prev;
  693. } else {
  694. // Split the current list at the midpoint with a referenced
  695. // B-picture, then descend into each side separately.
  696. len = 0;
  697. for (pic = start->next; pic != end; pic = pic->next)
  698. ++len;
  699. for (pic = start->next, i = 1; 2 * i < len; pic = pic->next, i++);
  700. pic->type = PICTURE_TYPE_B;
  701. pic->b_depth = current_depth;
  702. pic->is_reference = 1;
  703. vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
  704. vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
  705. vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
  706. vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
  707. for (ref = end->refs[1]; ref; ref = ref->refs[1])
  708. vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
  709. if (i > 1)
  710. vaapi_encode_set_b_pictures(avctx, start, pic, pic,
  711. current_depth + 1, &next);
  712. else
  713. next = pic;
  714. vaapi_encode_set_b_pictures(avctx, pic, end, next,
  715. current_depth + 1, last);
  716. }
  717. }
  718. static int vaapi_encode_pick_next(AVCodecContext *avctx,
  719. VAAPIEncodePicture **pic_out)
  720. {
  721. VAAPIEncodeContext *ctx = avctx->priv_data;
  722. VAAPIEncodePicture *pic = NULL, *next, *start;
  723. int i, b_counter, closed_gop_end;
  724. // If there are any B-frames already queued, the next one to encode
  725. // is the earliest not-yet-issued frame for which all references are
  726. // available.
  727. for (pic = ctx->pic_start; pic; pic = pic->next) {
  728. if (pic->encode_issued)
  729. continue;
  730. if (pic->type != PICTURE_TYPE_B)
  731. continue;
  732. for (i = 0; i < pic->nb_refs; i++) {
  733. if (!pic->refs[i]->encode_issued)
  734. break;
  735. }
  736. if (i == pic->nb_refs)
  737. break;
  738. }
  739. if (pic) {
  740. av_log(avctx, AV_LOG_DEBUG, "Pick B-picture at depth %d to "
  741. "encode next.\n", pic->b_depth);
  742. *pic_out = pic;
  743. return 0;
  744. }
  745. // Find the B-per-Pth available picture to become the next picture
  746. // on the top layer.
  747. start = NULL;
  748. b_counter = 0;
  749. closed_gop_end = ctx->closed_gop ||
  750. ctx->idr_counter == ctx->gop_per_idr;
  751. for (pic = ctx->pic_start; pic; pic = next) {
  752. next = pic->next;
  753. if (pic->encode_issued) {
  754. start = pic;
  755. continue;
  756. }
  757. // If the next available picture is force-IDR, encode it to start
  758. // a new GOP immediately.
  759. if (pic->force_idr)
  760. break;
  761. if (b_counter == ctx->b_per_p)
  762. break;
  763. // If this picture ends a closed GOP or starts a new GOP then it
  764. // needs to be in the top layer.
  765. if (ctx->gop_counter + b_counter + closed_gop_end >= ctx->gop_size)
  766. break;
  767. // If the picture after this one is force-IDR, we need to encode
  768. // this one in the top layer.
  769. if (next && next->force_idr)
  770. break;
  771. ++b_counter;
  772. }
  773. // At the end of the stream the last picture must be in the top layer.
  774. if (!pic && ctx->end_of_stream) {
  775. --b_counter;
  776. pic = ctx->pic_end;
  777. if (pic->encode_issued)
  778. return AVERROR_EOF;
  779. }
  780. if (!pic) {
  781. av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
  782. "need more input for reference pictures.\n");
  783. return AVERROR(EAGAIN);
  784. }
  785. if (ctx->input_order <= ctx->decode_delay && !ctx->end_of_stream) {
  786. av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
  787. "need more input for timestamps.\n");
  788. return AVERROR(EAGAIN);
  789. }
  790. if (pic->force_idr) {
  791. av_log(avctx, AV_LOG_DEBUG, "Pick forced IDR-picture to "
  792. "encode next.\n");
  793. pic->type = PICTURE_TYPE_IDR;
  794. ctx->idr_counter = 1;
  795. ctx->gop_counter = 1;
  796. } else if (ctx->gop_counter + b_counter >= ctx->gop_size) {
  797. if (ctx->idr_counter == ctx->gop_per_idr) {
  798. av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP IDR-picture to "
  799. "encode next.\n");
  800. pic->type = PICTURE_TYPE_IDR;
  801. ctx->idr_counter = 1;
  802. } else {
  803. av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP I-picture to "
  804. "encode next.\n");
  805. pic->type = PICTURE_TYPE_I;
  806. ++ctx->idr_counter;
  807. }
  808. ctx->gop_counter = 1;
  809. } else {
  810. if (ctx->gop_counter + b_counter + closed_gop_end == ctx->gop_size) {
  811. av_log(avctx, AV_LOG_DEBUG, "Pick group-end P-picture to "
  812. "encode next.\n");
  813. } else {
  814. av_log(avctx, AV_LOG_DEBUG, "Pick normal P-picture to "
  815. "encode next.\n");
  816. }
  817. pic->type = PICTURE_TYPE_P;
  818. av_assert0(start);
  819. ctx->gop_counter += 1 + b_counter;
  820. }
  821. pic->is_reference = 1;
  822. *pic_out = pic;
  823. vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
  824. if (pic->type != PICTURE_TYPE_IDR) {
  825. vaapi_encode_add_ref(avctx, pic, start,
  826. pic->type == PICTURE_TYPE_P,
  827. b_counter > 0, 0);
  828. vaapi_encode_add_ref(avctx, pic, ctx->next_prev, 0, 0, 1);
  829. }
  830. if (ctx->next_prev)
  831. --ctx->next_prev->ref_count[0];
  832. if (b_counter > 0) {
  833. vaapi_encode_set_b_pictures(avctx, start, pic, pic, 1,
  834. &ctx->next_prev);
  835. } else {
  836. ctx->next_prev = pic;
  837. }
  838. ++ctx->next_prev->ref_count[0];
  839. return 0;
  840. }
  841. static int vaapi_encode_clear_old(AVCodecContext *avctx)
  842. {
  843. VAAPIEncodeContext *ctx = avctx->priv_data;
  844. VAAPIEncodePicture *pic, *prev, *next;
  845. av_assert0(ctx->pic_start);
  846. // Remove direct references once each picture is complete.
  847. for (pic = ctx->pic_start; pic; pic = pic->next) {
  848. if (pic->encode_complete && pic->next)
  849. vaapi_encode_remove_refs(avctx, pic, 0);
  850. }
  851. // Remove indirect references once a picture has no direct references.
  852. for (pic = ctx->pic_start; pic; pic = pic->next) {
  853. if (pic->encode_complete && pic->ref_count[0] == 0)
  854. vaapi_encode_remove_refs(avctx, pic, 1);
  855. }
  856. // Clear out all complete pictures with no remaining references.
  857. prev = NULL;
  858. for (pic = ctx->pic_start; pic; pic = next) {
  859. next = pic->next;
  860. if (pic->encode_complete && pic->ref_count[1] == 0) {
  861. av_assert0(pic->ref_removed[0] && pic->ref_removed[1]);
  862. if (prev)
  863. prev->next = next;
  864. else
  865. ctx->pic_start = next;
  866. vaapi_encode_free(avctx, pic);
  867. } else {
  868. prev = pic;
  869. }
  870. }
  871. return 0;
  872. }
  873. static int vaapi_encode_check_frame(AVCodecContext *avctx,
  874. const AVFrame *frame)
  875. {
  876. VAAPIEncodeContext *ctx = avctx->priv_data;
  877. if ((frame->crop_top || frame->crop_bottom ||
  878. frame->crop_left || frame->crop_right) && !ctx->crop_warned) {
  879. av_log(avctx, AV_LOG_WARNING, "Cropping information on input "
  880. "frames ignored due to lack of API support.\n");
  881. ctx->crop_warned = 1;
  882. }
  883. if (!ctx->roi_allowed) {
  884. AVFrameSideData *sd =
  885. av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
  886. if (sd && !ctx->roi_warned) {
  887. av_log(avctx, AV_LOG_WARNING, "ROI side data on input "
  888. "frames ignored due to lack of driver support.\n");
  889. ctx->roi_warned = 1;
  890. }
  891. }
  892. return 0;
  893. }
  894. int ff_vaapi_encode_send_frame(AVCodecContext *avctx, const AVFrame *frame)
  895. {
  896. VAAPIEncodeContext *ctx = avctx->priv_data;
  897. VAAPIEncodePicture *pic;
  898. int err;
  899. if (frame) {
  900. av_log(avctx, AV_LOG_DEBUG, "Input frame: %ux%u (%"PRId64").\n",
  901. frame->width, frame->height, frame->pts);
  902. err = vaapi_encode_check_frame(avctx, frame);
  903. if (err < 0)
  904. return err;
  905. pic = vaapi_encode_alloc(avctx);
  906. if (!pic)
  907. return AVERROR(ENOMEM);
  908. pic->input_image = av_frame_alloc();
  909. if (!pic->input_image) {
  910. err = AVERROR(ENOMEM);
  911. goto fail;
  912. }
  913. err = av_frame_ref(pic->input_image, frame);
  914. if (err < 0)
  915. goto fail;
  916. if (ctx->input_order == 0 || frame->pict_type == AV_PICTURE_TYPE_I)
  917. pic->force_idr = 1;
  918. pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
  919. pic->pts = frame->pts;
  920. if (ctx->input_order == 0)
  921. ctx->first_pts = pic->pts;
  922. if (ctx->input_order == ctx->decode_delay)
  923. ctx->dts_pts_diff = pic->pts - ctx->first_pts;
  924. if (ctx->output_delay > 0)
  925. ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
  926. pic->display_order = ctx->input_order;
  927. ++ctx->input_order;
  928. if (ctx->pic_start) {
  929. ctx->pic_end->next = pic;
  930. ctx->pic_end = pic;
  931. } else {
  932. ctx->pic_start = pic;
  933. ctx->pic_end = pic;
  934. }
  935. } else {
  936. ctx->end_of_stream = 1;
  937. // Fix timestamps if we hit end-of-stream before the initial decode
  938. // delay has elapsed.
  939. if (ctx->input_order < ctx->decode_delay)
  940. ctx->dts_pts_diff = ctx->pic_end->pts - ctx->first_pts;
  941. }
  942. return 0;
  943. fail:
  944. return err;
  945. }
  946. int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
  947. {
  948. VAAPIEncodeContext *ctx = avctx->priv_data;
  949. VAAPIEncodePicture *pic;
  950. int err;
  951. if (!ctx->pic_start) {
  952. if (ctx->end_of_stream)
  953. return AVERROR_EOF;
  954. else
  955. return AVERROR(EAGAIN);
  956. }
  957. pic = NULL;
  958. err = vaapi_encode_pick_next(avctx, &pic);
  959. if (err < 0)
  960. return err;
  961. av_assert0(pic);
  962. pic->encode_order = ctx->encode_order++;
  963. err = vaapi_encode_issue(avctx, pic);
  964. if (err < 0) {
  965. av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
  966. return err;
  967. }
  968. err = vaapi_encode_output(avctx, pic, pkt);
  969. if (err < 0) {
  970. av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
  971. return err;
  972. }
  973. if (ctx->output_delay == 0) {
  974. pkt->dts = pkt->pts;
  975. } else if (pic->encode_order < ctx->decode_delay) {
  976. if (ctx->ts_ring[pic->encode_order] < INT64_MIN + ctx->dts_pts_diff)
  977. pkt->dts = INT64_MIN;
  978. else
  979. pkt->dts = ctx->ts_ring[pic->encode_order] - ctx->dts_pts_diff;
  980. } else {
  981. pkt->dts = ctx->ts_ring[(pic->encode_order - ctx->decode_delay) %
  982. (3 * ctx->output_delay)];
  983. }
  984. av_log(avctx, AV_LOG_DEBUG, "Output packet: pts %"PRId64" dts %"PRId64".\n",
  985. pkt->pts, pkt->dts);
  986. ctx->output_order = pic->encode_order;
  987. vaapi_encode_clear_old(avctx);
  988. return 0;
  989. }
  990. static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx, int type,
  991. void *buffer, size_t size)
  992. {
  993. VAAPIEncodeContext *ctx = avctx->priv_data;
  994. av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
  995. ctx->global_params_type[ctx->nb_global_params] = type;
  996. ctx->global_params [ctx->nb_global_params] = buffer;
  997. ctx->global_params_size[ctx->nb_global_params] = size;
  998. ++ctx->nb_global_params;
  999. }
  1000. typedef struct VAAPIEncodeRTFormat {
  1001. const char *name;
  1002. unsigned int value;
  1003. int depth;
  1004. int nb_components;
  1005. int log2_chroma_w;
  1006. int log2_chroma_h;
  1007. } VAAPIEncodeRTFormat;
  1008. static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
  1009. { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
  1010. { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
  1011. { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
  1012. { "YUV444", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
  1013. { "YUV411", VA_RT_FORMAT_YUV411, 8, 3, 2, 0 },
  1014. #if VA_CHECK_VERSION(0, 38, 1)
  1015. { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
  1016. #endif
  1017. };
  1018. static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
  1019. VAEntrypointEncSlice,
  1020. VAEntrypointEncPicture,
  1021. #if VA_CHECK_VERSION(0, 39, 2)
  1022. VAEntrypointEncSliceLP,
  1023. #endif
  1024. 0
  1025. };
  1026. #if VA_CHECK_VERSION(0, 39, 2)
  1027. static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
  1028. VAEntrypointEncSliceLP,
  1029. 0
  1030. };
  1031. #endif
  1032. static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
  1033. {
  1034. VAAPIEncodeContext *ctx = avctx->priv_data;
  1035. VAProfile *va_profiles = NULL;
  1036. VAEntrypoint *va_entrypoints = NULL;
  1037. VAStatus vas;
  1038. const VAEntrypoint *usable_entrypoints;
  1039. const VAAPIEncodeProfile *profile;
  1040. const AVPixFmtDescriptor *desc;
  1041. VAConfigAttrib rt_format_attr;
  1042. const VAAPIEncodeRTFormat *rt_format;
  1043. const char *profile_string, *entrypoint_string;
  1044. int i, j, n, depth, err;
  1045. if (ctx->low_power) {
  1046. #if VA_CHECK_VERSION(0, 39, 2)
  1047. usable_entrypoints = vaapi_encode_entrypoints_low_power;
  1048. #else
  1049. av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
  1050. "supported with this VAAPI version.\n");
  1051. return AVERROR(EINVAL);
  1052. #endif
  1053. } else {
  1054. usable_entrypoints = vaapi_encode_entrypoints_normal;
  1055. }
  1056. desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
  1057. if (!desc) {
  1058. av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
  1059. ctx->input_frames->sw_format);
  1060. return AVERROR(EINVAL);
  1061. }
  1062. depth = desc->comp[0].depth;
  1063. for (i = 1; i < desc->nb_components; i++) {
  1064. if (desc->comp[i].depth != depth) {
  1065. av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
  1066. desc->name);
  1067. return AVERROR(EINVAL);
  1068. }
  1069. }
  1070. av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
  1071. desc->name);
  1072. n = vaMaxNumProfiles(ctx->hwctx->display);
  1073. va_profiles = av_malloc_array(n, sizeof(VAProfile));
  1074. if (!va_profiles) {
  1075. err = AVERROR(ENOMEM);
  1076. goto fail;
  1077. }
  1078. vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
  1079. if (vas != VA_STATUS_SUCCESS) {
  1080. av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
  1081. vas, vaErrorStr(vas));
  1082. err = AVERROR_EXTERNAL;
  1083. goto fail;
  1084. }
  1085. av_assert0(ctx->codec->profiles);
  1086. for (i = 0; (ctx->codec->profiles[i].av_profile !=
  1087. FF_PROFILE_UNKNOWN); i++) {
  1088. profile = &ctx->codec->profiles[i];
  1089. if (depth != profile->depth ||
  1090. desc->nb_components != profile->nb_components)
  1091. continue;
  1092. if (desc->nb_components > 1 &&
  1093. (desc->log2_chroma_w != profile->log2_chroma_w ||
  1094. desc->log2_chroma_h != profile->log2_chroma_h))
  1095. continue;
  1096. if (avctx->profile != profile->av_profile &&
  1097. avctx->profile != FF_PROFILE_UNKNOWN)
  1098. continue;
  1099. #if VA_CHECK_VERSION(1, 0, 0)
  1100. profile_string = vaProfileStr(profile->va_profile);
  1101. #else
  1102. profile_string = "(no profile names)";
  1103. #endif
  1104. for (j = 0; j < n; j++) {
  1105. if (va_profiles[j] == profile->va_profile)
  1106. break;
  1107. }
  1108. if (j >= n) {
  1109. av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
  1110. "is not supported by driver.\n", profile_string,
  1111. profile->va_profile);
  1112. continue;
  1113. }
  1114. ctx->profile = profile;
  1115. break;
  1116. }
  1117. if (!ctx->profile) {
  1118. av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
  1119. err = AVERROR(ENOSYS);
  1120. goto fail;
  1121. }
  1122. avctx->profile = profile->av_profile;
  1123. ctx->va_profile = profile->va_profile;
  1124. av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
  1125. profile_string, ctx->va_profile);
  1126. n = vaMaxNumEntrypoints(ctx->hwctx->display);
  1127. va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
  1128. if (!va_entrypoints) {
  1129. err = AVERROR(ENOMEM);
  1130. goto fail;
  1131. }
  1132. vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
  1133. va_entrypoints, &n);
  1134. if (vas != VA_STATUS_SUCCESS) {
  1135. av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
  1136. "profile %s (%d): %d (%s).\n", profile_string,
  1137. ctx->va_profile, vas, vaErrorStr(vas));
  1138. err = AVERROR_EXTERNAL;
  1139. goto fail;
  1140. }
  1141. for (i = 0; i < n; i++) {
  1142. for (j = 0; usable_entrypoints[j]; j++) {
  1143. if (va_entrypoints[i] == usable_entrypoints[j])
  1144. break;
  1145. }
  1146. if (usable_entrypoints[j])
  1147. break;
  1148. }
  1149. if (i >= n) {
  1150. av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
  1151. "for profile %s (%d).\n", profile_string, ctx->va_profile);
  1152. err = AVERROR(ENOSYS);
  1153. goto fail;
  1154. }
  1155. ctx->va_entrypoint = va_entrypoints[i];
  1156. #if VA_CHECK_VERSION(1, 0, 0)
  1157. entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
  1158. #else
  1159. entrypoint_string = "(no entrypoint names)";
  1160. #endif
  1161. av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
  1162. entrypoint_string, ctx->va_entrypoint);
  1163. for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
  1164. rt_format = &vaapi_encode_rt_formats[i];
  1165. if (rt_format->depth == depth &&
  1166. rt_format->nb_components == profile->nb_components &&
  1167. rt_format->log2_chroma_w == profile->log2_chroma_w &&
  1168. rt_format->log2_chroma_h == profile->log2_chroma_h)
  1169. break;
  1170. }
  1171. if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
  1172. av_log(avctx, AV_LOG_ERROR, "No usable render target format "
  1173. "found for profile %s (%d) entrypoint %s (%d).\n",
  1174. profile_string, ctx->va_profile,
  1175. entrypoint_string, ctx->va_entrypoint);
  1176. err = AVERROR(ENOSYS);
  1177. goto fail;
  1178. }
  1179. rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
  1180. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1181. ctx->va_profile, ctx->va_entrypoint,
  1182. &rt_format_attr, 1);
  1183. if (vas != VA_STATUS_SUCCESS) {
  1184. av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
  1185. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1186. err = AVERROR_EXTERNAL;
  1187. goto fail;
  1188. }
  1189. if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1190. av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
  1191. "supported by driver: assuming surface RT format %s "
  1192. "is valid.\n", rt_format->name);
  1193. } else if (!(rt_format_attr.value & rt_format->value)) {
  1194. av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
  1195. "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
  1196. rt_format->name, profile_string, ctx->va_profile,
  1197. entrypoint_string, ctx->va_entrypoint);
  1198. err = AVERROR(ENOSYS);
  1199. goto fail;
  1200. } else {
  1201. av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
  1202. "format %s (%#x).\n", rt_format->name, rt_format->value);
  1203. ctx->config_attributes[ctx->nb_config_attributes++] =
  1204. (VAConfigAttrib) {
  1205. .type = VAConfigAttribRTFormat,
  1206. .value = rt_format->value,
  1207. };
  1208. }
  1209. err = 0;
  1210. fail:
  1211. av_freep(&va_profiles);
  1212. av_freep(&va_entrypoints);
  1213. return err;
  1214. }
  1215. static const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
  1216. // Bitrate Quality
  1217. // | Maxrate | HRD/VBV
  1218. { 0 }, // | | | |
  1219. { RC_MODE_CQP, "CQP", 1, VA_RC_CQP, 0, 0, 1, 0 },
  1220. { RC_MODE_CBR, "CBR", 1, VA_RC_CBR, 1, 0, 0, 1 },
  1221. { RC_MODE_VBR, "VBR", 1, VA_RC_VBR, 1, 1, 0, 1 },
  1222. #if VA_CHECK_VERSION(1, 1, 0)
  1223. { RC_MODE_ICQ, "ICQ", 1, VA_RC_ICQ, 0, 0, 1, 0 },
  1224. #else
  1225. { RC_MODE_ICQ, "ICQ", 0 },
  1226. #endif
  1227. #if VA_CHECK_VERSION(1, 3, 0)
  1228. { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1, 1, 1, 1 },
  1229. { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1, 0, 0, 0 },
  1230. #else
  1231. { RC_MODE_QVBR, "QVBR", 0 },
  1232. { RC_MODE_AVBR, "AVBR", 0 },
  1233. #endif
  1234. };
  1235. static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
  1236. {
  1237. VAAPIEncodeContext *ctx = avctx->priv_data;
  1238. uint32_t supported_va_rc_modes;
  1239. const VAAPIEncodeRCMode *rc_mode;
  1240. int64_t rc_bits_per_second;
  1241. int rc_target_percentage;
  1242. int rc_window_size;
  1243. int rc_quality;
  1244. int64_t hrd_buffer_size;
  1245. int64_t hrd_initial_buffer_fullness;
  1246. int fr_num, fr_den;
  1247. VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
  1248. VAStatus vas;
  1249. char supported_rc_modes_string[64];
  1250. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1251. ctx->va_profile, ctx->va_entrypoint,
  1252. &rc_attr, 1);
  1253. if (vas != VA_STATUS_SUCCESS) {
  1254. av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
  1255. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1256. return AVERROR_EXTERNAL;
  1257. }
  1258. if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1259. av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
  1260. "supported rate control modes: assuming CQP only.\n");
  1261. supported_va_rc_modes = VA_RC_CQP;
  1262. strcpy(supported_rc_modes_string, "unknown");
  1263. } else {
  1264. char *str = supported_rc_modes_string;
  1265. size_t len = sizeof(supported_rc_modes_string);
  1266. int i, first = 1, res;
  1267. supported_va_rc_modes = rc_attr.value;
  1268. for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
  1269. rc_mode = &vaapi_encode_rc_modes[i];
  1270. if (supported_va_rc_modes & rc_mode->va_mode) {
  1271. res = snprintf(str, len, "%s%s",
  1272. first ? "" : ", ", rc_mode->name);
  1273. first = 0;
  1274. if (res < 0) {
  1275. *str = 0;
  1276. break;
  1277. }
  1278. len -= res;
  1279. str += res;
  1280. if (len == 0)
  1281. break;
  1282. }
  1283. }
  1284. av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
  1285. supported_rc_modes_string);
  1286. }
  1287. // Rate control mode selection:
  1288. // * If the user has set a mode explicitly with the rc_mode option,
  1289. // use it and fail if it is not available.
  1290. // * If an explicit QP option has been set, use CQP.
  1291. // * If the codec is CQ-only, use CQP.
  1292. // * If the QSCALE avcodec option is set, use CQP.
  1293. // * If bitrate and quality are both set, try QVBR.
  1294. // * If quality is set, try ICQ, then CQP.
  1295. // * If bitrate and maxrate are set and have the same value, try CBR.
  1296. // * If a bitrate is set, try AVBR, then VBR, then CBR.
  1297. // * If no bitrate is set, try ICQ, then CQP.
  1298. #define TRY_RC_MODE(mode, fail) do { \
  1299. rc_mode = &vaapi_encode_rc_modes[mode]; \
  1300. if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
  1301. if (fail) { \
  1302. av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
  1303. "RC mode (supported modes: %s).\n", rc_mode->name, \
  1304. supported_rc_modes_string); \
  1305. return AVERROR(EINVAL); \
  1306. } \
  1307. av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
  1308. "RC mode.\n", rc_mode->name); \
  1309. rc_mode = NULL; \
  1310. } else { \
  1311. goto rc_mode_found; \
  1312. } \
  1313. } while (0)
  1314. if (ctx->explicit_rc_mode)
  1315. TRY_RC_MODE(ctx->explicit_rc_mode, 1);
  1316. if (ctx->explicit_qp)
  1317. TRY_RC_MODE(RC_MODE_CQP, 1);
  1318. if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY)
  1319. TRY_RC_MODE(RC_MODE_CQP, 1);
  1320. if (avctx->flags & AV_CODEC_FLAG_QSCALE)
  1321. TRY_RC_MODE(RC_MODE_CQP, 1);
  1322. if (avctx->bit_rate > 0 && avctx->global_quality > 0)
  1323. TRY_RC_MODE(RC_MODE_QVBR, 0);
  1324. if (avctx->global_quality > 0) {
  1325. TRY_RC_MODE(RC_MODE_ICQ, 0);
  1326. TRY_RC_MODE(RC_MODE_CQP, 0);
  1327. }
  1328. if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
  1329. TRY_RC_MODE(RC_MODE_CBR, 0);
  1330. if (avctx->bit_rate > 0) {
  1331. TRY_RC_MODE(RC_MODE_AVBR, 0);
  1332. TRY_RC_MODE(RC_MODE_VBR, 0);
  1333. TRY_RC_MODE(RC_MODE_CBR, 0);
  1334. } else {
  1335. TRY_RC_MODE(RC_MODE_ICQ, 0);
  1336. TRY_RC_MODE(RC_MODE_CQP, 0);
  1337. }
  1338. av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
  1339. "RC mode compatible with selected options "
  1340. "(supported modes: %s).\n", supported_rc_modes_string);
  1341. return AVERROR(EINVAL);
  1342. rc_mode_found:
  1343. if (rc_mode->bitrate) {
  1344. if (avctx->bit_rate <= 0) {
  1345. av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
  1346. "RC mode.\n", rc_mode->name);
  1347. return AVERROR(EINVAL);
  1348. }
  1349. if (rc_mode->mode == RC_MODE_AVBR) {
  1350. // For maximum confusion AVBR is hacked into the existing API
  1351. // by overloading some of the fields with completely different
  1352. // meanings.
  1353. // Target percentage does not apply in AVBR mode.
  1354. rc_bits_per_second = avctx->bit_rate;
  1355. // Accuracy tolerance range for meeting the specified target
  1356. // bitrate. It's very unclear how this is actually intended
  1357. // to work - since we do want to get the specified bitrate,
  1358. // set the accuracy to 100% for now.
  1359. rc_target_percentage = 100;
  1360. // Convergence period in frames. The GOP size reflects the
  1361. // user's intended block size for cutting, so reusing that
  1362. // as the convergence period seems a reasonable default.
  1363. rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
  1364. } else if (rc_mode->maxrate) {
  1365. if (avctx->rc_max_rate > 0) {
  1366. if (avctx->rc_max_rate < avctx->bit_rate) {
  1367. av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
  1368. "bitrate (%"PRId64") must not be greater than "
  1369. "maxrate (%"PRId64").\n", avctx->bit_rate,
  1370. avctx->rc_max_rate);
  1371. return AVERROR(EINVAL);
  1372. }
  1373. rc_bits_per_second = avctx->rc_max_rate;
  1374. rc_target_percentage = (avctx->bit_rate * 100) /
  1375. avctx->rc_max_rate;
  1376. } else {
  1377. // We only have a target bitrate, but this mode requires
  1378. // that a maximum rate be supplied as well. Since the
  1379. // user does not want this to be a constraint, arbitrarily
  1380. // pick a maximum rate of double the target rate.
  1381. rc_bits_per_second = 2 * avctx->bit_rate;
  1382. rc_target_percentage = 50;
  1383. }
  1384. } else {
  1385. if (avctx->rc_max_rate > avctx->bit_rate) {
  1386. av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
  1387. "in %s RC mode.\n", rc_mode->name);
  1388. }
  1389. rc_bits_per_second = avctx->bit_rate;
  1390. rc_target_percentage = 100;
  1391. }
  1392. } else {
  1393. rc_bits_per_second = 0;
  1394. rc_target_percentage = 100;
  1395. }
  1396. if (rc_mode->quality) {
  1397. if (ctx->explicit_qp) {
  1398. rc_quality = ctx->explicit_qp;
  1399. } else if (avctx->global_quality > 0) {
  1400. rc_quality = avctx->global_quality;
  1401. } else {
  1402. rc_quality = ctx->codec->default_quality;
  1403. av_log(avctx, AV_LOG_WARNING, "No quality level set; "
  1404. "using default (%d).\n", rc_quality);
  1405. }
  1406. } else {
  1407. rc_quality = 0;
  1408. }
  1409. if (rc_mode->hrd) {
  1410. if (avctx->rc_buffer_size)
  1411. hrd_buffer_size = avctx->rc_buffer_size;
  1412. else if (avctx->rc_max_rate > 0)
  1413. hrd_buffer_size = avctx->rc_max_rate;
  1414. else
  1415. hrd_buffer_size = avctx->bit_rate;
  1416. if (avctx->rc_initial_buffer_occupancy) {
  1417. if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
  1418. av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
  1419. "must have initial buffer size (%d) <= "
  1420. "buffer size (%"PRId64").\n",
  1421. avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
  1422. return AVERROR(EINVAL);
  1423. }
  1424. hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
  1425. } else {
  1426. hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
  1427. }
  1428. rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
  1429. } else {
  1430. if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
  1431. av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
  1432. "in %s RC mode.\n", rc_mode->name);
  1433. }
  1434. hrd_buffer_size = 0;
  1435. hrd_initial_buffer_fullness = 0;
  1436. if (rc_mode->mode != RC_MODE_AVBR) {
  1437. // Already set (with completely different meaning) for AVBR.
  1438. rc_window_size = 1000;
  1439. }
  1440. }
  1441. if (rc_bits_per_second > UINT32_MAX ||
  1442. hrd_buffer_size > UINT32_MAX ||
  1443. hrd_initial_buffer_fullness > UINT32_MAX) {
  1444. av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
  1445. "greater are not supported by VAAPI.\n");
  1446. return AVERROR(EINVAL);
  1447. }
  1448. ctx->rc_mode = rc_mode;
  1449. ctx->rc_quality = rc_quality;
  1450. ctx->va_rc_mode = rc_mode->va_mode;
  1451. ctx->va_bit_rate = rc_bits_per_second;
  1452. av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
  1453. if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1454. // This driver does not want the RC mode attribute to be set.
  1455. } else {
  1456. ctx->config_attributes[ctx->nb_config_attributes++] =
  1457. (VAConfigAttrib) {
  1458. .type = VAConfigAttribRateControl,
  1459. .value = ctx->va_rc_mode,
  1460. };
  1461. }
  1462. if (rc_mode->quality)
  1463. av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
  1464. if (rc_mode->va_mode != VA_RC_CQP) {
  1465. if (rc_mode->mode == RC_MODE_AVBR) {
  1466. av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
  1467. "converging in %d frames with %d%% accuracy.\n",
  1468. rc_bits_per_second, rc_window_size,
  1469. rc_target_percentage);
  1470. } else if (rc_mode->bitrate) {
  1471. av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
  1472. "%"PRId64" bps over %d ms.\n", rc_target_percentage,
  1473. rc_bits_per_second, rc_window_size);
  1474. }
  1475. ctx->rc_params = (VAEncMiscParameterRateControl) {
  1476. .bits_per_second = rc_bits_per_second,
  1477. .target_percentage = rc_target_percentage,
  1478. .window_size = rc_window_size,
  1479. .initial_qp = 0,
  1480. .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
  1481. .basic_unit_size = 0,
  1482. #if VA_CHECK_VERSION(1, 1, 0)
  1483. .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
  1484. .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
  1485. #endif
  1486. #if VA_CHECK_VERSION(1, 3, 0)
  1487. .quality_factor = rc_quality,
  1488. #endif
  1489. };
  1490. vaapi_encode_add_global_param(avctx,
  1491. VAEncMiscParameterTypeRateControl,
  1492. &ctx->rc_params,
  1493. sizeof(ctx->rc_params));
  1494. }
  1495. if (rc_mode->hrd) {
  1496. av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
  1497. "initial fullness %"PRId64" bits.\n",
  1498. hrd_buffer_size, hrd_initial_buffer_fullness);
  1499. ctx->hrd_params = (VAEncMiscParameterHRD) {
  1500. .initial_buffer_fullness = hrd_initial_buffer_fullness,
  1501. .buffer_size = hrd_buffer_size,
  1502. };
  1503. vaapi_encode_add_global_param(avctx,
  1504. VAEncMiscParameterTypeHRD,
  1505. &ctx->hrd_params,
  1506. sizeof(ctx->hrd_params));
  1507. }
  1508. if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
  1509. av_reduce(&fr_num, &fr_den,
  1510. avctx->framerate.num, avctx->framerate.den, 65535);
  1511. else
  1512. av_reduce(&fr_num, &fr_den,
  1513. avctx->time_base.den, avctx->time_base.num, 65535);
  1514. av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
  1515. fr_num, fr_den, (double)fr_num / fr_den);
  1516. ctx->fr_params = (VAEncMiscParameterFrameRate) {
  1517. .framerate = (unsigned int)fr_den << 16 | fr_num,
  1518. };
  1519. #if VA_CHECK_VERSION(0, 40, 0)
  1520. vaapi_encode_add_global_param(avctx,
  1521. VAEncMiscParameterTypeFrameRate,
  1522. &ctx->fr_params,
  1523. sizeof(ctx->fr_params));
  1524. #endif
  1525. return 0;
  1526. }
  1527. static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
  1528. {
  1529. VAAPIEncodeContext *ctx = avctx->priv_data;
  1530. VAStatus vas;
  1531. VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
  1532. uint32_t ref_l0, ref_l1;
  1533. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1534. ctx->va_profile,
  1535. ctx->va_entrypoint,
  1536. &attr, 1);
  1537. if (vas != VA_STATUS_SUCCESS) {
  1538. av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
  1539. "attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1540. return AVERROR_EXTERNAL;
  1541. }
  1542. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1543. ref_l0 = ref_l1 = 0;
  1544. } else {
  1545. ref_l0 = attr.value & 0xffff;
  1546. ref_l1 = attr.value >> 16 & 0xffff;
  1547. }
  1548. if (ctx->codec->flags & FLAG_INTRA_ONLY ||
  1549. avctx->gop_size <= 1) {
  1550. av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
  1551. ctx->gop_size = 1;
  1552. } else if (ref_l0 < 1) {
  1553. av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
  1554. "reference frames.\n");
  1555. return AVERROR(EINVAL);
  1556. } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
  1557. ref_l1 < 1 || avctx->max_b_frames < 1) {
  1558. av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
  1559. "(supported references: %d / %d).\n", ref_l0, ref_l1);
  1560. ctx->gop_size = avctx->gop_size;
  1561. ctx->p_per_i = INT_MAX;
  1562. ctx->b_per_p = 0;
  1563. } else {
  1564. av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
  1565. "(supported references: %d / %d).\n", ref_l0, ref_l1);
  1566. ctx->gop_size = avctx->gop_size;
  1567. ctx->p_per_i = INT_MAX;
  1568. ctx->b_per_p = avctx->max_b_frames;
  1569. if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
  1570. ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
  1571. av_log2(ctx->b_per_p) + 1);
  1572. } else {
  1573. ctx->max_b_depth = 1;
  1574. }
  1575. }
  1576. if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
  1577. ctx->closed_gop = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
  1578. ctx->gop_per_idr = ctx->idr_interval + 1;
  1579. } else {
  1580. ctx->closed_gop = 1;
  1581. ctx->gop_per_idr = 1;
  1582. }
  1583. return 0;
  1584. }
  1585. static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
  1586. {
  1587. VAAPIEncodeContext *ctx = avctx->priv_data;
  1588. VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
  1589. { VAConfigAttribEncSliceStructure } };
  1590. VAStatus vas;
  1591. uint32_t max_slices, slice_structure;
  1592. int req_slices;
  1593. if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
  1594. if (avctx->slices > 0) {
  1595. av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
  1596. "but this codec does not support controlling slices.\n");
  1597. }
  1598. return 0;
  1599. }
  1600. ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
  1601. ctx->slice_block_height;
  1602. ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
  1603. ctx->slice_block_width;
  1604. if (avctx->slices <= 1) {
  1605. ctx->nb_slices = 1;
  1606. ctx->slice_size = ctx->slice_block_rows;
  1607. return 0;
  1608. }
  1609. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1610. ctx->va_profile,
  1611. ctx->va_entrypoint,
  1612. attr, FF_ARRAY_ELEMS(attr));
  1613. if (vas != VA_STATUS_SUCCESS) {
  1614. av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
  1615. "attributes: %d (%s).\n", vas, vaErrorStr(vas));
  1616. return AVERROR_EXTERNAL;
  1617. }
  1618. max_slices = attr[0].value;
  1619. slice_structure = attr[1].value;
  1620. if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
  1621. slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
  1622. av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
  1623. "pictures as multiple slices.\n.");
  1624. return AVERROR(EINVAL);
  1625. }
  1626. // For fixed-size slices currently we only support whole rows, making
  1627. // rectangular slices. This could be extended to arbitrary runs of
  1628. // blocks, but since slices tend to be a conformance requirement and
  1629. // most cases (such as broadcast or bluray) want rectangular slices
  1630. // only it would need to be gated behind another option.
  1631. if (avctx->slices > ctx->slice_block_rows) {
  1632. av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
  1633. "configured number of slices (%d < %d); using "
  1634. "maximum.\n", ctx->slice_block_rows, avctx->slices);
  1635. req_slices = ctx->slice_block_rows;
  1636. } else {
  1637. req_slices = avctx->slices;
  1638. }
  1639. if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
  1640. slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
  1641. ctx->nb_slices = req_slices;
  1642. ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
  1643. } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
  1644. int k;
  1645. for (k = 1;; k *= 2) {
  1646. if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
  1647. break;
  1648. }
  1649. ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
  1650. ctx->slice_size = k;
  1651. #if VA_CHECK_VERSION(1, 0, 0)
  1652. } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
  1653. ctx->nb_slices = ctx->slice_block_rows;
  1654. ctx->slice_size = 1;
  1655. #endif
  1656. } else {
  1657. av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
  1658. "slice structure modes (%#x).\n", slice_structure);
  1659. return AVERROR(EINVAL);
  1660. }
  1661. if (ctx->nb_slices > avctx->slices) {
  1662. av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
  1663. "%d (from %d) due to driver constraints on slice "
  1664. "structure.\n", ctx->nb_slices, avctx->slices);
  1665. }
  1666. if (ctx->nb_slices > max_slices) {
  1667. av_log(avctx, AV_LOG_ERROR, "Driver does not support "
  1668. "encoding with %d slices (max %"PRIu32").\n",
  1669. ctx->nb_slices, max_slices);
  1670. return AVERROR(EINVAL);
  1671. }
  1672. av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
  1673. "(default size %d block rows).\n",
  1674. ctx->nb_slices, ctx->slice_size);
  1675. return 0;
  1676. }
  1677. static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
  1678. {
  1679. VAAPIEncodeContext *ctx = avctx->priv_data;
  1680. VAStatus vas;
  1681. VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
  1682. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1683. ctx->va_profile,
  1684. ctx->va_entrypoint,
  1685. &attr, 1);
  1686. if (vas != VA_STATUS_SUCCESS) {
  1687. av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
  1688. "attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1689. return AVERROR_EXTERNAL;
  1690. }
  1691. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1692. if (ctx->desired_packed_headers) {
  1693. av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
  1694. "packed headers (wanted %#x).\n",
  1695. ctx->desired_packed_headers);
  1696. } else {
  1697. av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
  1698. "packed headers (none wanted).\n");
  1699. }
  1700. ctx->va_packed_headers = 0;
  1701. } else {
  1702. if (ctx->desired_packed_headers & ~attr.value) {
  1703. av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
  1704. "wanted packed headers (wanted %#x, found %#x).\n",
  1705. ctx->desired_packed_headers, attr.value);
  1706. } else {
  1707. av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
  1708. "available (wanted %#x, found %#x).\n",
  1709. ctx->desired_packed_headers, attr.value);
  1710. }
  1711. ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
  1712. }
  1713. if (ctx->va_packed_headers) {
  1714. ctx->config_attributes[ctx->nb_config_attributes++] =
  1715. (VAConfigAttrib) {
  1716. .type = VAConfigAttribEncPackedHeaders,
  1717. .value = ctx->va_packed_headers,
  1718. };
  1719. }
  1720. if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
  1721. !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
  1722. (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
  1723. av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
  1724. "sequence headers, but a global header is requested.\n");
  1725. av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
  1726. "this may result in a stream which is not usable for some "
  1727. "purposes (e.g. not muxable to some containers).\n");
  1728. }
  1729. return 0;
  1730. }
  1731. static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
  1732. {
  1733. #if VA_CHECK_VERSION(0, 36, 0)
  1734. VAAPIEncodeContext *ctx = avctx->priv_data;
  1735. VAStatus vas;
  1736. VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
  1737. int quality = avctx->compression_level;
  1738. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1739. ctx->va_profile,
  1740. ctx->va_entrypoint,
  1741. &attr, 1);
  1742. if (vas != VA_STATUS_SUCCESS) {
  1743. av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
  1744. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1745. return AVERROR_EXTERNAL;
  1746. }
  1747. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1748. if (quality != 0) {
  1749. av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
  1750. "supported: will use default quality level.\n");
  1751. }
  1752. } else {
  1753. if (quality > attr.value) {
  1754. av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
  1755. "valid range is 0-%d, using %d.\n",
  1756. attr.value, attr.value);
  1757. quality = attr.value;
  1758. }
  1759. ctx->quality_params = (VAEncMiscParameterBufferQualityLevel) {
  1760. .quality_level = quality,
  1761. };
  1762. vaapi_encode_add_global_param(avctx,
  1763. VAEncMiscParameterTypeQualityLevel,
  1764. &ctx->quality_params,
  1765. sizeof(ctx->quality_params));
  1766. }
  1767. #else
  1768. av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
  1769. "not supported with this VAAPI version.\n");
  1770. #endif
  1771. return 0;
  1772. }
  1773. static av_cold int vaapi_encode_init_roi(AVCodecContext *avctx)
  1774. {
  1775. #if VA_CHECK_VERSION(1, 0, 0)
  1776. VAAPIEncodeContext *ctx = avctx->priv_data;
  1777. VAStatus vas;
  1778. VAConfigAttrib attr = { VAConfigAttribEncROI };
  1779. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1780. ctx->va_profile,
  1781. ctx->va_entrypoint,
  1782. &attr, 1);
  1783. if (vas != VA_STATUS_SUCCESS) {
  1784. av_log(avctx, AV_LOG_ERROR, "Failed to query ROI "
  1785. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1786. return AVERROR_EXTERNAL;
  1787. }
  1788. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1789. ctx->roi_allowed = 0;
  1790. } else {
  1791. VAConfigAttribValEncROI roi = {
  1792. .value = attr.value,
  1793. };
  1794. ctx->roi_max_regions = roi.bits.num_roi_regions;
  1795. ctx->roi_allowed = ctx->roi_max_regions > 0 &&
  1796. (ctx->va_rc_mode == VA_RC_CQP ||
  1797. roi.bits.roi_rc_qp_delta_support);
  1798. }
  1799. #endif
  1800. return 0;
  1801. }
  1802. static void vaapi_encode_free_output_buffer(void *opaque,
  1803. uint8_t *data)
  1804. {
  1805. AVCodecContext *avctx = opaque;
  1806. VAAPIEncodeContext *ctx = avctx->priv_data;
  1807. VABufferID buffer_id;
  1808. buffer_id = (VABufferID)(uintptr_t)data;
  1809. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  1810. av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
  1811. }
  1812. static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
  1813. int size)
  1814. {
  1815. AVCodecContext *avctx = opaque;
  1816. VAAPIEncodeContext *ctx = avctx->priv_data;
  1817. VABufferID buffer_id;
  1818. VAStatus vas;
  1819. AVBufferRef *ref;
  1820. // The output buffer size is fixed, so it needs to be large enough
  1821. // to hold the largest possible compressed frame. We assume here
  1822. // that the uncompressed frame plus some header data is an upper
  1823. // bound on that.
  1824. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  1825. VAEncCodedBufferType,
  1826. 3 * ctx->surface_width * ctx->surface_height +
  1827. (1 << 16), 1, 0, &buffer_id);
  1828. if (vas != VA_STATUS_SUCCESS) {
  1829. av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
  1830. "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
  1831. return NULL;
  1832. }
  1833. av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
  1834. ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
  1835. sizeof(buffer_id),
  1836. &vaapi_encode_free_output_buffer,
  1837. avctx, AV_BUFFER_FLAG_READONLY);
  1838. if (!ref) {
  1839. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  1840. return NULL;
  1841. }
  1842. return ref;
  1843. }
  1844. static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
  1845. {
  1846. VAAPIEncodeContext *ctx = avctx->priv_data;
  1847. AVVAAPIHWConfig *hwconfig = NULL;
  1848. AVHWFramesConstraints *constraints = NULL;
  1849. enum AVPixelFormat recon_format;
  1850. int err, i;
  1851. hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
  1852. if (!hwconfig) {
  1853. err = AVERROR(ENOMEM);
  1854. goto fail;
  1855. }
  1856. hwconfig->config_id = ctx->va_config;
  1857. constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
  1858. hwconfig);
  1859. if (!constraints) {
  1860. err = AVERROR(ENOMEM);
  1861. goto fail;
  1862. }
  1863. // Probably we can use the input surface format as the surface format
  1864. // of the reconstructed frames. If not, we just pick the first (only?)
  1865. // format in the valid list and hope that it all works.
  1866. recon_format = AV_PIX_FMT_NONE;
  1867. if (constraints->valid_sw_formats) {
  1868. for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
  1869. if (ctx->input_frames->sw_format ==
  1870. constraints->valid_sw_formats[i]) {
  1871. recon_format = ctx->input_frames->sw_format;
  1872. break;
  1873. }
  1874. }
  1875. if (recon_format == AV_PIX_FMT_NONE) {
  1876. // No match. Just use the first in the supported list and
  1877. // hope for the best.
  1878. recon_format = constraints->valid_sw_formats[0];
  1879. }
  1880. } else {
  1881. // No idea what to use; copy input format.
  1882. recon_format = ctx->input_frames->sw_format;
  1883. }
  1884. av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
  1885. "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
  1886. if (ctx->surface_width < constraints->min_width ||
  1887. ctx->surface_height < constraints->min_height ||
  1888. ctx->surface_width > constraints->max_width ||
  1889. ctx->surface_height > constraints->max_height) {
  1890. av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
  1891. "size %dx%d (constraints: width %d-%d height %d-%d).\n",
  1892. ctx->surface_width, ctx->surface_height,
  1893. constraints->min_width, constraints->max_width,
  1894. constraints->min_height, constraints->max_height);
  1895. err = AVERROR(EINVAL);
  1896. goto fail;
  1897. }
  1898. av_freep(&hwconfig);
  1899. av_hwframe_constraints_free(&constraints);
  1900. ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
  1901. if (!ctx->recon_frames_ref) {
  1902. err = AVERROR(ENOMEM);
  1903. goto fail;
  1904. }
  1905. ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
  1906. ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
  1907. ctx->recon_frames->sw_format = recon_format;
  1908. ctx->recon_frames->width = ctx->surface_width;
  1909. ctx->recon_frames->height = ctx->surface_height;
  1910. err = av_hwframe_ctx_init(ctx->recon_frames_ref);
  1911. if (err < 0) {
  1912. av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
  1913. "frame context: %d.\n", err);
  1914. goto fail;
  1915. }
  1916. err = 0;
  1917. fail:
  1918. av_freep(&hwconfig);
  1919. av_hwframe_constraints_free(&constraints);
  1920. return err;
  1921. }
  1922. av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
  1923. {
  1924. VAAPIEncodeContext *ctx = avctx->priv_data;
  1925. AVVAAPIFramesContext *recon_hwctx = NULL;
  1926. VAStatus vas;
  1927. int err;
  1928. if (!avctx->hw_frames_ctx) {
  1929. av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
  1930. "required to associate the encoding device.\n");
  1931. return AVERROR(EINVAL);
  1932. }
  1933. ctx->va_config = VA_INVALID_ID;
  1934. ctx->va_context = VA_INVALID_ID;
  1935. ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
  1936. if (!ctx->input_frames_ref) {
  1937. err = AVERROR(ENOMEM);
  1938. goto fail;
  1939. }
  1940. ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
  1941. ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
  1942. if (!ctx->device_ref) {
  1943. err = AVERROR(ENOMEM);
  1944. goto fail;
  1945. }
  1946. ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
  1947. ctx->hwctx = ctx->device->hwctx;
  1948. err = vaapi_encode_profile_entrypoint(avctx);
  1949. if (err < 0)
  1950. goto fail;
  1951. err = vaapi_encode_init_rate_control(avctx);
  1952. if (err < 0)
  1953. goto fail;
  1954. err = vaapi_encode_init_gop_structure(avctx);
  1955. if (err < 0)
  1956. goto fail;
  1957. err = vaapi_encode_init_slice_structure(avctx);
  1958. if (err < 0)
  1959. goto fail;
  1960. err = vaapi_encode_init_packed_headers(avctx);
  1961. if (err < 0)
  1962. goto fail;
  1963. err = vaapi_encode_init_roi(avctx);
  1964. if (err < 0)
  1965. goto fail;
  1966. if (avctx->compression_level >= 0) {
  1967. err = vaapi_encode_init_quality(avctx);
  1968. if (err < 0)
  1969. goto fail;
  1970. }
  1971. vas = vaCreateConfig(ctx->hwctx->display,
  1972. ctx->va_profile, ctx->va_entrypoint,
  1973. ctx->config_attributes, ctx->nb_config_attributes,
  1974. &ctx->va_config);
  1975. if (vas != VA_STATUS_SUCCESS) {
  1976. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  1977. "configuration: %d (%s).\n", vas, vaErrorStr(vas));
  1978. err = AVERROR(EIO);
  1979. goto fail;
  1980. }
  1981. err = vaapi_encode_create_recon_frames(avctx);
  1982. if (err < 0)
  1983. goto fail;
  1984. recon_hwctx = ctx->recon_frames->hwctx;
  1985. vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
  1986. ctx->surface_width, ctx->surface_height,
  1987. VA_PROGRESSIVE,
  1988. recon_hwctx->surface_ids,
  1989. recon_hwctx->nb_surfaces,
  1990. &ctx->va_context);
  1991. if (vas != VA_STATUS_SUCCESS) {
  1992. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  1993. "context: %d (%s).\n", vas, vaErrorStr(vas));
  1994. err = AVERROR(EIO);
  1995. goto fail;
  1996. }
  1997. ctx->output_buffer_pool =
  1998. av_buffer_pool_init2(sizeof(VABufferID), avctx,
  1999. &vaapi_encode_alloc_output_buffer, NULL);
  2000. if (!ctx->output_buffer_pool) {
  2001. err = AVERROR(ENOMEM);
  2002. goto fail;
  2003. }
  2004. if (ctx->codec->configure) {
  2005. err = ctx->codec->configure(avctx);
  2006. if (err < 0)
  2007. goto fail;
  2008. }
  2009. ctx->output_delay = ctx->b_per_p;
  2010. ctx->decode_delay = ctx->max_b_depth;
  2011. if (ctx->codec->sequence_params_size > 0) {
  2012. ctx->codec_sequence_params =
  2013. av_mallocz(ctx->codec->sequence_params_size);
  2014. if (!ctx->codec_sequence_params) {
  2015. err = AVERROR(ENOMEM);
  2016. goto fail;
  2017. }
  2018. }
  2019. if (ctx->codec->picture_params_size > 0) {
  2020. ctx->codec_picture_params =
  2021. av_mallocz(ctx->codec->picture_params_size);
  2022. if (!ctx->codec_picture_params) {
  2023. err = AVERROR(ENOMEM);
  2024. goto fail;
  2025. }
  2026. }
  2027. if (ctx->codec->init_sequence_params) {
  2028. err = ctx->codec->init_sequence_params(avctx);
  2029. if (err < 0) {
  2030. av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
  2031. "failed: %d.\n", err);
  2032. goto fail;
  2033. }
  2034. }
  2035. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
  2036. ctx->codec->write_sequence_header &&
  2037. avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  2038. char data[MAX_PARAM_BUFFER_SIZE];
  2039. size_t bit_len = 8 * sizeof(data);
  2040. err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
  2041. if (err < 0) {
  2042. av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
  2043. "for extradata: %d.\n", err);
  2044. goto fail;
  2045. } else {
  2046. avctx->extradata_size = (bit_len + 7) / 8;
  2047. avctx->extradata = av_mallocz(avctx->extradata_size +
  2048. AV_INPUT_BUFFER_PADDING_SIZE);
  2049. if (!avctx->extradata) {
  2050. err = AVERROR(ENOMEM);
  2051. goto fail;
  2052. }
  2053. memcpy(avctx->extradata, data, avctx->extradata_size);
  2054. }
  2055. }
  2056. return 0;
  2057. fail:
  2058. ff_vaapi_encode_close(avctx);
  2059. return err;
  2060. }
  2061. av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
  2062. {
  2063. VAAPIEncodeContext *ctx = avctx->priv_data;
  2064. VAAPIEncodePicture *pic, *next;
  2065. for (pic = ctx->pic_start; pic; pic = next) {
  2066. next = pic->next;
  2067. vaapi_encode_free(avctx, pic);
  2068. }
  2069. av_buffer_pool_uninit(&ctx->output_buffer_pool);
  2070. if (ctx->va_context != VA_INVALID_ID) {
  2071. vaDestroyContext(ctx->hwctx->display, ctx->va_context);
  2072. ctx->va_context = VA_INVALID_ID;
  2073. }
  2074. if (ctx->va_config != VA_INVALID_ID) {
  2075. vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
  2076. ctx->va_config = VA_INVALID_ID;
  2077. }
  2078. av_freep(&ctx->codec_sequence_params);
  2079. av_freep(&ctx->codec_picture_params);
  2080. av_buffer_unref(&ctx->recon_frames_ref);
  2081. av_buffer_unref(&ctx->input_frames_ref);
  2082. av_buffer_unref(&ctx->device_ref);
  2083. return 0;
  2084. }