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.

2075 lines
70KB

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