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.

2244 lines
77KB

  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. static int vaapi_encode_check_frame(AVCodecContext *avctx,
  793. const AVFrame *frame)
  794. {
  795. VAAPIEncodeContext *ctx = avctx->priv_data;
  796. if ((frame->crop_top || frame->crop_bottom ||
  797. frame->crop_left || frame->crop_right) && !ctx->crop_warned) {
  798. av_log(avctx, AV_LOG_WARNING, "Cropping information on input "
  799. "frames ignored due to lack of API support.\n");
  800. ctx->crop_warned = 1;
  801. }
  802. return 0;
  803. }
  804. int ff_vaapi_encode_send_frame(AVCodecContext *avctx, const AVFrame *frame)
  805. {
  806. VAAPIEncodeContext *ctx = avctx->priv_data;
  807. VAAPIEncodePicture *pic;
  808. int err;
  809. if (frame) {
  810. av_log(avctx, AV_LOG_DEBUG, "Input frame: %ux%u (%"PRId64").\n",
  811. frame->width, frame->height, frame->pts);
  812. err = vaapi_encode_check_frame(avctx, frame);
  813. if (err < 0)
  814. return err;
  815. pic = vaapi_encode_alloc(avctx);
  816. if (!pic)
  817. return AVERROR(ENOMEM);
  818. pic->input_image = av_frame_alloc();
  819. if (!pic->input_image) {
  820. err = AVERROR(ENOMEM);
  821. goto fail;
  822. }
  823. err = av_frame_ref(pic->input_image, frame);
  824. if (err < 0)
  825. goto fail;
  826. if (ctx->input_order == 0)
  827. pic->force_idr = 1;
  828. pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
  829. pic->pts = frame->pts;
  830. if (ctx->input_order == 0)
  831. ctx->first_pts = pic->pts;
  832. if (ctx->input_order == ctx->decode_delay)
  833. ctx->dts_pts_diff = pic->pts - ctx->first_pts;
  834. if (ctx->output_delay > 0)
  835. ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
  836. pic->display_order = ctx->input_order;
  837. ++ctx->input_order;
  838. if (ctx->pic_start) {
  839. ctx->pic_end->next = pic;
  840. ctx->pic_end = pic;
  841. } else {
  842. ctx->pic_start = pic;
  843. ctx->pic_end = pic;
  844. }
  845. } else {
  846. ctx->end_of_stream = 1;
  847. // Fix timestamps if we hit end-of-stream before the initial decode
  848. // delay has elapsed.
  849. if (ctx->input_order < ctx->decode_delay)
  850. ctx->dts_pts_diff = ctx->pic_end->pts - ctx->first_pts;
  851. }
  852. return 0;
  853. fail:
  854. return err;
  855. }
  856. int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
  857. {
  858. VAAPIEncodeContext *ctx = avctx->priv_data;
  859. VAAPIEncodePicture *pic;
  860. int err;
  861. if (!ctx->pic_start) {
  862. if (ctx->end_of_stream)
  863. return AVERROR_EOF;
  864. else
  865. return AVERROR(EAGAIN);
  866. }
  867. pic = NULL;
  868. err = vaapi_encode_pick_next(avctx, &pic);
  869. if (err < 0)
  870. return err;
  871. av_assert0(pic);
  872. pic->encode_order = ctx->encode_order++;
  873. err = vaapi_encode_issue(avctx, pic);
  874. if (err < 0) {
  875. av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
  876. return err;
  877. }
  878. err = vaapi_encode_output(avctx, pic, pkt);
  879. if (err < 0) {
  880. av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
  881. return err;
  882. }
  883. if (ctx->output_delay == 0) {
  884. pkt->dts = pkt->pts;
  885. } else if (pic->encode_order < ctx->decode_delay) {
  886. if (ctx->ts_ring[pic->encode_order] < INT64_MIN + ctx->dts_pts_diff)
  887. pkt->dts = INT64_MIN;
  888. else
  889. pkt->dts = ctx->ts_ring[pic->encode_order] - ctx->dts_pts_diff;
  890. } else {
  891. pkt->dts = ctx->ts_ring[(pic->encode_order - ctx->decode_delay) %
  892. (3 * ctx->output_delay)];
  893. }
  894. av_log(avctx, AV_LOG_DEBUG, "Output packet: pts %"PRId64" dts %"PRId64".\n",
  895. pkt->pts, pkt->dts);
  896. ctx->output_order = pic->encode_order;
  897. vaapi_encode_clear_old(avctx);
  898. return 0;
  899. }
  900. static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx,
  901. VAEncMiscParameterBuffer *buffer,
  902. size_t size)
  903. {
  904. VAAPIEncodeContext *ctx = avctx->priv_data;
  905. av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
  906. ctx->global_params [ctx->nb_global_params] = buffer;
  907. ctx->global_params_size[ctx->nb_global_params] = size;
  908. ++ctx->nb_global_params;
  909. }
  910. typedef struct VAAPIEncodeRTFormat {
  911. const char *name;
  912. unsigned int value;
  913. int depth;
  914. int nb_components;
  915. int log2_chroma_w;
  916. int log2_chroma_h;
  917. } VAAPIEncodeRTFormat;
  918. static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
  919. { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
  920. { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
  921. { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
  922. { "YUV444", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
  923. { "YUV411", VA_RT_FORMAT_YUV411, 8, 3, 2, 0 },
  924. #if VA_CHECK_VERSION(0, 38, 1)
  925. { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
  926. #endif
  927. };
  928. static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
  929. VAEntrypointEncSlice,
  930. VAEntrypointEncPicture,
  931. #if VA_CHECK_VERSION(0, 39, 2)
  932. VAEntrypointEncSliceLP,
  933. #endif
  934. 0
  935. };
  936. #if VA_CHECK_VERSION(0, 39, 2)
  937. static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
  938. VAEntrypointEncSliceLP,
  939. 0
  940. };
  941. #endif
  942. static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
  943. {
  944. VAAPIEncodeContext *ctx = avctx->priv_data;
  945. VAProfile *va_profiles = NULL;
  946. VAEntrypoint *va_entrypoints = NULL;
  947. VAStatus vas;
  948. const VAEntrypoint *usable_entrypoints;
  949. const VAAPIEncodeProfile *profile;
  950. const AVPixFmtDescriptor *desc;
  951. VAConfigAttrib rt_format_attr;
  952. const VAAPIEncodeRTFormat *rt_format;
  953. const char *profile_string, *entrypoint_string;
  954. int i, j, n, depth, err;
  955. if (ctx->low_power) {
  956. #if VA_CHECK_VERSION(0, 39, 2)
  957. usable_entrypoints = vaapi_encode_entrypoints_low_power;
  958. #else
  959. av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
  960. "supported with this VAAPI version.\n");
  961. return AVERROR(EINVAL);
  962. #endif
  963. } else {
  964. usable_entrypoints = vaapi_encode_entrypoints_normal;
  965. }
  966. desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
  967. if (!desc) {
  968. av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
  969. ctx->input_frames->sw_format);
  970. return AVERROR(EINVAL);
  971. }
  972. depth = desc->comp[0].depth;
  973. for (i = 1; i < desc->nb_components; i++) {
  974. if (desc->comp[i].depth != depth) {
  975. av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
  976. desc->name);
  977. return AVERROR(EINVAL);
  978. }
  979. }
  980. av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
  981. desc->name);
  982. n = vaMaxNumProfiles(ctx->hwctx->display);
  983. va_profiles = av_malloc_array(n, sizeof(VAProfile));
  984. if (!va_profiles) {
  985. err = AVERROR(ENOMEM);
  986. goto fail;
  987. }
  988. vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
  989. if (vas != VA_STATUS_SUCCESS) {
  990. av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
  991. vas, vaErrorStr(vas));
  992. err = AVERROR_EXTERNAL;
  993. goto fail;
  994. }
  995. av_assert0(ctx->codec->profiles);
  996. for (i = 0; (ctx->codec->profiles[i].av_profile !=
  997. FF_PROFILE_UNKNOWN); i++) {
  998. profile = &ctx->codec->profiles[i];
  999. if (depth != profile->depth ||
  1000. desc->nb_components != profile->nb_components)
  1001. continue;
  1002. if (desc->nb_components > 1 &&
  1003. (desc->log2_chroma_w != profile->log2_chroma_w ||
  1004. desc->log2_chroma_h != profile->log2_chroma_h))
  1005. continue;
  1006. if (avctx->profile != profile->av_profile &&
  1007. avctx->profile != FF_PROFILE_UNKNOWN)
  1008. continue;
  1009. #if VA_CHECK_VERSION(1, 0, 0)
  1010. profile_string = vaProfileStr(profile->va_profile);
  1011. #else
  1012. profile_string = "(no profile names)";
  1013. #endif
  1014. for (j = 0; j < n; j++) {
  1015. if (va_profiles[j] == profile->va_profile)
  1016. break;
  1017. }
  1018. if (j >= n) {
  1019. av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
  1020. "is not supported by driver.\n", profile_string,
  1021. profile->va_profile);
  1022. continue;
  1023. }
  1024. ctx->profile = profile;
  1025. break;
  1026. }
  1027. if (!ctx->profile) {
  1028. av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
  1029. err = AVERROR(ENOSYS);
  1030. goto fail;
  1031. }
  1032. avctx->profile = profile->av_profile;
  1033. ctx->va_profile = profile->va_profile;
  1034. av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
  1035. profile_string, ctx->va_profile);
  1036. n = vaMaxNumEntrypoints(ctx->hwctx->display);
  1037. va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
  1038. if (!va_entrypoints) {
  1039. err = AVERROR(ENOMEM);
  1040. goto fail;
  1041. }
  1042. vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
  1043. va_entrypoints, &n);
  1044. if (vas != VA_STATUS_SUCCESS) {
  1045. av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
  1046. "profile %s (%d): %d (%s).\n", profile_string,
  1047. ctx->va_profile, vas, vaErrorStr(vas));
  1048. err = AVERROR_EXTERNAL;
  1049. goto fail;
  1050. }
  1051. for (i = 0; i < n; i++) {
  1052. for (j = 0; usable_entrypoints[j]; j++) {
  1053. if (va_entrypoints[i] == usable_entrypoints[j])
  1054. break;
  1055. }
  1056. if (usable_entrypoints[j])
  1057. break;
  1058. }
  1059. if (i >= n) {
  1060. av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
  1061. "for profile %s (%d).\n", profile_string, ctx->va_profile);
  1062. err = AVERROR(ENOSYS);
  1063. goto fail;
  1064. }
  1065. ctx->va_entrypoint = va_entrypoints[i];
  1066. #if VA_CHECK_VERSION(1, 0, 0)
  1067. entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
  1068. #else
  1069. entrypoint_string = "(no entrypoint names)";
  1070. #endif
  1071. av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
  1072. entrypoint_string, ctx->va_entrypoint);
  1073. for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
  1074. rt_format = &vaapi_encode_rt_formats[i];
  1075. if (rt_format->depth == depth &&
  1076. rt_format->nb_components == profile->nb_components &&
  1077. rt_format->log2_chroma_w == profile->log2_chroma_w &&
  1078. rt_format->log2_chroma_h == profile->log2_chroma_h)
  1079. break;
  1080. }
  1081. if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
  1082. av_log(avctx, AV_LOG_ERROR, "No usable render target format "
  1083. "found for profile %s (%d) entrypoint %s (%d).\n",
  1084. profile_string, ctx->va_profile,
  1085. entrypoint_string, ctx->va_entrypoint);
  1086. err = AVERROR(ENOSYS);
  1087. goto fail;
  1088. }
  1089. rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
  1090. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1091. ctx->va_profile, ctx->va_entrypoint,
  1092. &rt_format_attr, 1);
  1093. if (vas != VA_STATUS_SUCCESS) {
  1094. av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
  1095. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1096. err = AVERROR_EXTERNAL;
  1097. goto fail;
  1098. }
  1099. if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1100. av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
  1101. "supported by driver: assuming surface RT format %s "
  1102. "is valid.\n", rt_format->name);
  1103. } else if (!(rt_format_attr.value & rt_format->value)) {
  1104. av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
  1105. "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
  1106. rt_format->name, profile_string, ctx->va_profile,
  1107. entrypoint_string, ctx->va_entrypoint);
  1108. err = AVERROR(ENOSYS);
  1109. goto fail;
  1110. } else {
  1111. av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
  1112. "format %s (%#x).\n", rt_format->name, rt_format->value);
  1113. ctx->config_attributes[ctx->nb_config_attributes++] =
  1114. (VAConfigAttrib) {
  1115. .type = VAConfigAttribRTFormat,
  1116. .value = rt_format->value,
  1117. };
  1118. }
  1119. err = 0;
  1120. fail:
  1121. av_freep(&va_profiles);
  1122. av_freep(&va_entrypoints);
  1123. return err;
  1124. }
  1125. static const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
  1126. // Bitrate Quality
  1127. // | Maxrate | HRD/VBV
  1128. { 0 }, // | | | |
  1129. { RC_MODE_CQP, "CQP", 1, VA_RC_CQP, 0, 0, 1, 0 },
  1130. { RC_MODE_CBR, "CBR", 1, VA_RC_CBR, 1, 0, 0, 1 },
  1131. { RC_MODE_VBR, "VBR", 1, VA_RC_VBR, 1, 1, 0, 1 },
  1132. #if VA_CHECK_VERSION(1, 1, 0)
  1133. { RC_MODE_ICQ, "ICQ", 1, VA_RC_ICQ, 0, 0, 1, 0 },
  1134. #else
  1135. { RC_MODE_ICQ, "ICQ", 0 },
  1136. #endif
  1137. #if VA_CHECK_VERSION(1, 3, 0)
  1138. { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1, 1, 1, 1 },
  1139. { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1, 0, 0, 0 },
  1140. #else
  1141. { RC_MODE_QVBR, "QVBR", 0 },
  1142. { RC_MODE_AVBR, "AVBR", 0 },
  1143. #endif
  1144. };
  1145. static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
  1146. {
  1147. VAAPIEncodeContext *ctx = avctx->priv_data;
  1148. uint32_t supported_va_rc_modes;
  1149. const VAAPIEncodeRCMode *rc_mode;
  1150. int64_t rc_bits_per_second;
  1151. int rc_target_percentage;
  1152. int rc_window_size;
  1153. int rc_quality;
  1154. int64_t hrd_buffer_size;
  1155. int64_t hrd_initial_buffer_fullness;
  1156. int fr_num, fr_den;
  1157. VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
  1158. VAStatus vas;
  1159. char supported_rc_modes_string[64];
  1160. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1161. ctx->va_profile, ctx->va_entrypoint,
  1162. &rc_attr, 1);
  1163. if (vas != VA_STATUS_SUCCESS) {
  1164. av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
  1165. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1166. return AVERROR_EXTERNAL;
  1167. }
  1168. if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1169. av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
  1170. "supported rate control modes: assuming CQP only.\n");
  1171. supported_va_rc_modes = VA_RC_CQP;
  1172. strcpy(supported_rc_modes_string, "unknown");
  1173. } else {
  1174. char *str = supported_rc_modes_string;
  1175. size_t len = sizeof(supported_rc_modes_string);
  1176. int i, first = 1, res;
  1177. supported_va_rc_modes = rc_attr.value;
  1178. for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
  1179. rc_mode = &vaapi_encode_rc_modes[i];
  1180. if (supported_va_rc_modes & rc_mode->va_mode) {
  1181. res = snprintf(str, len, "%s%s",
  1182. first ? "" : ", ", rc_mode->name);
  1183. first = 0;
  1184. if (res < 0) {
  1185. *str = 0;
  1186. break;
  1187. }
  1188. len -= res;
  1189. str += res;
  1190. if (len == 0)
  1191. break;
  1192. }
  1193. }
  1194. av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
  1195. supported_rc_modes_string);
  1196. }
  1197. // Rate control mode selection:
  1198. // * If the user has set a mode explicitly with the rc_mode option,
  1199. // use it and fail if it is not available.
  1200. // * If an explicit QP option has been set, use CQP.
  1201. // * If the codec is CQ-only, use CQP.
  1202. // * If the QSCALE avcodec option is set, use CQP.
  1203. // * If bitrate and quality are both set, try QVBR.
  1204. // * If quality is set, try ICQ, then CQP.
  1205. // * If bitrate and maxrate are set and have the same value, try CBR.
  1206. // * If a bitrate is set, try AVBR, then VBR, then CBR.
  1207. // * If no bitrate is set, try ICQ, then CQP.
  1208. #define TRY_RC_MODE(mode, fail) do { \
  1209. rc_mode = &vaapi_encode_rc_modes[mode]; \
  1210. if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
  1211. if (fail) { \
  1212. av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
  1213. "RC mode (supported modes: %s).\n", rc_mode->name, \
  1214. supported_rc_modes_string); \
  1215. return AVERROR(EINVAL); \
  1216. } \
  1217. av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
  1218. "RC mode.\n", rc_mode->name); \
  1219. rc_mode = NULL; \
  1220. } else { \
  1221. goto rc_mode_found; \
  1222. } \
  1223. } while (0)
  1224. if (ctx->explicit_rc_mode)
  1225. TRY_RC_MODE(ctx->explicit_rc_mode, 1);
  1226. if (ctx->explicit_qp)
  1227. TRY_RC_MODE(RC_MODE_CQP, 1);
  1228. if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY)
  1229. TRY_RC_MODE(RC_MODE_CQP, 1);
  1230. if (avctx->flags & AV_CODEC_FLAG_QSCALE)
  1231. TRY_RC_MODE(RC_MODE_CQP, 1);
  1232. if (avctx->bit_rate > 0 && avctx->global_quality > 0)
  1233. TRY_RC_MODE(RC_MODE_QVBR, 0);
  1234. if (avctx->global_quality > 0) {
  1235. TRY_RC_MODE(RC_MODE_ICQ, 0);
  1236. TRY_RC_MODE(RC_MODE_CQP, 0);
  1237. }
  1238. if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
  1239. TRY_RC_MODE(RC_MODE_CBR, 0);
  1240. if (avctx->bit_rate > 0) {
  1241. TRY_RC_MODE(RC_MODE_AVBR, 0);
  1242. TRY_RC_MODE(RC_MODE_VBR, 0);
  1243. TRY_RC_MODE(RC_MODE_CBR, 0);
  1244. } else {
  1245. TRY_RC_MODE(RC_MODE_ICQ, 0);
  1246. TRY_RC_MODE(RC_MODE_CQP, 0);
  1247. }
  1248. av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
  1249. "RC mode compatible with selected options "
  1250. "(supported modes: %s).\n", supported_rc_modes_string);
  1251. return AVERROR(EINVAL);
  1252. rc_mode_found:
  1253. if (rc_mode->bitrate) {
  1254. if (avctx->bit_rate <= 0) {
  1255. av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
  1256. "RC mode.\n", rc_mode->name);
  1257. return AVERROR(EINVAL);
  1258. }
  1259. if (rc_mode->mode == RC_MODE_AVBR) {
  1260. // For maximum confusion AVBR is hacked into the existing API
  1261. // by overloading some of the fields with completely different
  1262. // meanings.
  1263. // Target percentage does not apply in AVBR mode.
  1264. rc_bits_per_second = avctx->bit_rate;
  1265. // Accuracy tolerance range for meeting the specified target
  1266. // bitrate. It's very unclear how this is actually intended
  1267. // to work - since we do want to get the specified bitrate,
  1268. // set the accuracy to 100% for now.
  1269. rc_target_percentage = 100;
  1270. // Convergence period in frames. The GOP size reflects the
  1271. // user's intended block size for cutting, so reusing that
  1272. // as the convergence period seems a reasonable default.
  1273. rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
  1274. } else if (rc_mode->maxrate) {
  1275. if (avctx->rc_max_rate > 0) {
  1276. if (avctx->rc_max_rate < avctx->bit_rate) {
  1277. av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
  1278. "bitrate (%"PRId64") must not be greater than "
  1279. "maxrate (%"PRId64").\n", avctx->bit_rate,
  1280. avctx->rc_max_rate);
  1281. return AVERROR(EINVAL);
  1282. }
  1283. rc_bits_per_second = avctx->rc_max_rate;
  1284. rc_target_percentage = (avctx->bit_rate * 100) /
  1285. avctx->rc_max_rate;
  1286. } else {
  1287. // We only have a target bitrate, but this mode requires
  1288. // that a maximum rate be supplied as well. Since the
  1289. // user does not want this to be a constraint, arbitrarily
  1290. // pick a maximum rate of double the target rate.
  1291. rc_bits_per_second = 2 * avctx->bit_rate;
  1292. rc_target_percentage = 50;
  1293. }
  1294. } else {
  1295. if (avctx->rc_max_rate > avctx->bit_rate) {
  1296. av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
  1297. "in %s RC mode.\n", rc_mode->name);
  1298. }
  1299. rc_bits_per_second = avctx->bit_rate;
  1300. rc_target_percentage = 100;
  1301. }
  1302. } else {
  1303. rc_bits_per_second = 0;
  1304. rc_target_percentage = 100;
  1305. }
  1306. if (rc_mode->quality) {
  1307. if (ctx->explicit_qp) {
  1308. rc_quality = ctx->explicit_qp;
  1309. } else if (avctx->global_quality > 0) {
  1310. rc_quality = avctx->global_quality;
  1311. } else {
  1312. rc_quality = ctx->codec->default_quality;
  1313. av_log(avctx, AV_LOG_WARNING, "No quality level set; "
  1314. "using default (%d).\n", rc_quality);
  1315. }
  1316. } else {
  1317. rc_quality = 0;
  1318. }
  1319. if (rc_mode->hrd) {
  1320. if (avctx->rc_buffer_size)
  1321. hrd_buffer_size = avctx->rc_buffer_size;
  1322. else if (avctx->rc_max_rate > 0)
  1323. hrd_buffer_size = avctx->rc_max_rate;
  1324. else
  1325. hrd_buffer_size = avctx->bit_rate;
  1326. if (avctx->rc_initial_buffer_occupancy) {
  1327. if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
  1328. av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
  1329. "must have initial buffer size (%d) <= "
  1330. "buffer size (%"PRId64").\n",
  1331. avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
  1332. return AVERROR(EINVAL);
  1333. }
  1334. hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
  1335. } else {
  1336. hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
  1337. }
  1338. rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
  1339. } else {
  1340. if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
  1341. av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
  1342. "in %s RC mode.\n", rc_mode->name);
  1343. }
  1344. hrd_buffer_size = 0;
  1345. hrd_initial_buffer_fullness = 0;
  1346. if (rc_mode->mode != RC_MODE_AVBR) {
  1347. // Already set (with completely different meaning) for AVBR.
  1348. rc_window_size = 1000;
  1349. }
  1350. }
  1351. if (rc_bits_per_second > UINT32_MAX ||
  1352. hrd_buffer_size > UINT32_MAX ||
  1353. hrd_initial_buffer_fullness > UINT32_MAX) {
  1354. av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
  1355. "greater are not supported by VAAPI.\n");
  1356. return AVERROR(EINVAL);
  1357. }
  1358. ctx->rc_mode = rc_mode;
  1359. ctx->rc_quality = rc_quality;
  1360. ctx->va_rc_mode = rc_mode->va_mode;
  1361. ctx->va_bit_rate = rc_bits_per_second;
  1362. av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
  1363. if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1364. // This driver does not want the RC mode attribute to be set.
  1365. } else {
  1366. ctx->config_attributes[ctx->nb_config_attributes++] =
  1367. (VAConfigAttrib) {
  1368. .type = VAConfigAttribRateControl,
  1369. .value = ctx->va_rc_mode,
  1370. };
  1371. }
  1372. if (rc_mode->quality)
  1373. av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
  1374. if (rc_mode->va_mode != VA_RC_CQP) {
  1375. if (rc_mode->mode == RC_MODE_AVBR) {
  1376. av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
  1377. "converging in %d frames with %d%% accuracy.\n",
  1378. rc_bits_per_second, rc_window_size,
  1379. rc_target_percentage);
  1380. } else if (rc_mode->bitrate) {
  1381. av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
  1382. "%"PRId64" bps over %d ms.\n", rc_target_percentage,
  1383. rc_bits_per_second, rc_window_size);
  1384. }
  1385. ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
  1386. ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
  1387. .bits_per_second = rc_bits_per_second,
  1388. .target_percentage = rc_target_percentage,
  1389. .window_size = rc_window_size,
  1390. .initial_qp = 0,
  1391. .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
  1392. .basic_unit_size = 0,
  1393. #if VA_CHECK_VERSION(1, 1, 0)
  1394. .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
  1395. .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
  1396. #endif
  1397. #if VA_CHECK_VERSION(1, 3, 0)
  1398. .quality_factor = rc_quality,
  1399. #endif
  1400. };
  1401. vaapi_encode_add_global_param(avctx, &ctx->rc_params.misc,
  1402. sizeof(ctx->rc_params));
  1403. }
  1404. if (rc_mode->hrd) {
  1405. av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
  1406. "initial fullness %"PRId64" bits.\n",
  1407. hrd_buffer_size, hrd_initial_buffer_fullness);
  1408. ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
  1409. ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
  1410. .initial_buffer_fullness = hrd_initial_buffer_fullness,
  1411. .buffer_size = hrd_buffer_size,
  1412. };
  1413. vaapi_encode_add_global_param(avctx, &ctx->hrd_params.misc,
  1414. sizeof(ctx->hrd_params));
  1415. }
  1416. if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
  1417. av_reduce(&fr_num, &fr_den,
  1418. avctx->framerate.num, avctx->framerate.den, 65535);
  1419. else
  1420. av_reduce(&fr_num, &fr_den,
  1421. avctx->time_base.den, avctx->time_base.num, 65535);
  1422. av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
  1423. fr_num, fr_den, (double)fr_num / fr_den);
  1424. ctx->fr_params.misc.type = VAEncMiscParameterTypeFrameRate;
  1425. ctx->fr_params.fr.framerate = (unsigned int)fr_den << 16 | fr_num;
  1426. #if VA_CHECK_VERSION(0, 40, 0)
  1427. vaapi_encode_add_global_param(avctx, &ctx->fr_params.misc,
  1428. sizeof(ctx->fr_params));
  1429. #endif
  1430. return 0;
  1431. }
  1432. static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
  1433. {
  1434. VAAPIEncodeContext *ctx = avctx->priv_data;
  1435. VAStatus vas;
  1436. VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
  1437. uint32_t ref_l0, ref_l1;
  1438. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1439. ctx->va_profile,
  1440. ctx->va_entrypoint,
  1441. &attr, 1);
  1442. if (vas != VA_STATUS_SUCCESS) {
  1443. av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
  1444. "attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1445. return AVERROR_EXTERNAL;
  1446. }
  1447. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1448. ref_l0 = ref_l1 = 0;
  1449. } else {
  1450. ref_l0 = attr.value & 0xffff;
  1451. ref_l1 = attr.value >> 16 & 0xffff;
  1452. }
  1453. if (ctx->codec->flags & FLAG_INTRA_ONLY ||
  1454. avctx->gop_size <= 1) {
  1455. av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
  1456. ctx->gop_size = 1;
  1457. } else if (ref_l0 < 1) {
  1458. av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
  1459. "reference frames.\n");
  1460. return AVERROR(EINVAL);
  1461. } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
  1462. ref_l1 < 1 || avctx->max_b_frames < 1) {
  1463. av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
  1464. "(supported references: %d / %d).\n", ref_l0, ref_l1);
  1465. ctx->gop_size = avctx->gop_size;
  1466. ctx->p_per_i = INT_MAX;
  1467. ctx->b_per_p = 0;
  1468. } else {
  1469. av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
  1470. "(supported references: %d / %d).\n", ref_l0, ref_l1);
  1471. ctx->gop_size = avctx->gop_size;
  1472. ctx->p_per_i = INT_MAX;
  1473. ctx->b_per_p = avctx->max_b_frames;
  1474. if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
  1475. ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
  1476. av_log2(ctx->b_per_p) + 1);
  1477. } else {
  1478. ctx->max_b_depth = 1;
  1479. }
  1480. }
  1481. if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
  1482. ctx->closed_gop = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
  1483. ctx->gop_per_idr = ctx->idr_interval + 1;
  1484. } else {
  1485. ctx->closed_gop = 1;
  1486. ctx->gop_per_idr = 1;
  1487. }
  1488. return 0;
  1489. }
  1490. static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
  1491. {
  1492. VAAPIEncodeContext *ctx = avctx->priv_data;
  1493. VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
  1494. { VAConfigAttribEncSliceStructure } };
  1495. VAStatus vas;
  1496. uint32_t max_slices, slice_structure;
  1497. int req_slices;
  1498. if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
  1499. if (avctx->slices > 0) {
  1500. av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
  1501. "but this codec does not support controlling slices.\n");
  1502. }
  1503. return 0;
  1504. }
  1505. ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
  1506. ctx->slice_block_height;
  1507. ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
  1508. ctx->slice_block_width;
  1509. if (avctx->slices <= 1) {
  1510. ctx->nb_slices = 1;
  1511. ctx->slice_size = ctx->slice_block_rows;
  1512. return 0;
  1513. }
  1514. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1515. ctx->va_profile,
  1516. ctx->va_entrypoint,
  1517. attr, FF_ARRAY_ELEMS(attr));
  1518. if (vas != VA_STATUS_SUCCESS) {
  1519. av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
  1520. "attributes: %d (%s).\n", vas, vaErrorStr(vas));
  1521. return AVERROR_EXTERNAL;
  1522. }
  1523. max_slices = attr[0].value;
  1524. slice_structure = attr[1].value;
  1525. if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
  1526. slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
  1527. av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
  1528. "pictures as multiple slices.\n.");
  1529. return AVERROR(EINVAL);
  1530. }
  1531. // For fixed-size slices currently we only support whole rows, making
  1532. // rectangular slices. This could be extended to arbitrary runs of
  1533. // blocks, but since slices tend to be a conformance requirement and
  1534. // most cases (such as broadcast or bluray) want rectangular slices
  1535. // only it would need to be gated behind another option.
  1536. if (avctx->slices > ctx->slice_block_rows) {
  1537. av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
  1538. "configured number of slices (%d < %d); using "
  1539. "maximum.\n", ctx->slice_block_rows, avctx->slices);
  1540. req_slices = ctx->slice_block_rows;
  1541. } else {
  1542. req_slices = avctx->slices;
  1543. }
  1544. if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
  1545. slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
  1546. ctx->nb_slices = req_slices;
  1547. ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
  1548. } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
  1549. int k;
  1550. for (k = 1;; k *= 2) {
  1551. if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
  1552. break;
  1553. }
  1554. ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
  1555. ctx->slice_size = k;
  1556. #if VA_CHECK_VERSION(1, 0, 0)
  1557. } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
  1558. ctx->nb_slices = ctx->slice_block_rows;
  1559. ctx->slice_size = 1;
  1560. #endif
  1561. } else {
  1562. av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
  1563. "slice structure modes (%#x).\n", slice_structure);
  1564. return AVERROR(EINVAL);
  1565. }
  1566. if (ctx->nb_slices > avctx->slices) {
  1567. av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
  1568. "%d (from %d) due to driver constraints on slice "
  1569. "structure.\n", ctx->nb_slices, avctx->slices);
  1570. }
  1571. if (ctx->nb_slices > max_slices) {
  1572. av_log(avctx, AV_LOG_ERROR, "Driver does not support "
  1573. "encoding with %d slices (max %"PRIu32").\n",
  1574. ctx->nb_slices, max_slices);
  1575. return AVERROR(EINVAL);
  1576. }
  1577. av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
  1578. "(default size %d block rows).\n",
  1579. ctx->nb_slices, ctx->slice_size);
  1580. return 0;
  1581. }
  1582. static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
  1583. {
  1584. VAAPIEncodeContext *ctx = avctx->priv_data;
  1585. VAStatus vas;
  1586. VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
  1587. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1588. ctx->va_profile,
  1589. ctx->va_entrypoint,
  1590. &attr, 1);
  1591. if (vas != VA_STATUS_SUCCESS) {
  1592. av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
  1593. "attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1594. return AVERROR_EXTERNAL;
  1595. }
  1596. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1597. if (ctx->desired_packed_headers) {
  1598. av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
  1599. "packed headers (wanted %#x).\n",
  1600. ctx->desired_packed_headers);
  1601. } else {
  1602. av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
  1603. "packed headers (none wanted).\n");
  1604. }
  1605. ctx->va_packed_headers = 0;
  1606. } else {
  1607. if (ctx->desired_packed_headers & ~attr.value) {
  1608. av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
  1609. "wanted packed headers (wanted %#x, found %#x).\n",
  1610. ctx->desired_packed_headers, attr.value);
  1611. } else {
  1612. av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
  1613. "available (wanted %#x, found %#x).\n",
  1614. ctx->desired_packed_headers, attr.value);
  1615. }
  1616. ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
  1617. }
  1618. if (ctx->va_packed_headers) {
  1619. ctx->config_attributes[ctx->nb_config_attributes++] =
  1620. (VAConfigAttrib) {
  1621. .type = VAConfigAttribEncPackedHeaders,
  1622. .value = ctx->va_packed_headers,
  1623. };
  1624. }
  1625. if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
  1626. !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
  1627. (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
  1628. av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
  1629. "sequence headers, but a global header is requested.\n");
  1630. av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
  1631. "this may result in a stream which is not usable for some "
  1632. "purposes (e.g. not muxable to some containers).\n");
  1633. }
  1634. return 0;
  1635. }
  1636. static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
  1637. {
  1638. #if VA_CHECK_VERSION(0, 36, 0)
  1639. VAAPIEncodeContext *ctx = avctx->priv_data;
  1640. VAStatus vas;
  1641. VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
  1642. int quality = avctx->compression_level;
  1643. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1644. ctx->va_profile,
  1645. ctx->va_entrypoint,
  1646. &attr, 1);
  1647. if (vas != VA_STATUS_SUCCESS) {
  1648. av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
  1649. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1650. return AVERROR_EXTERNAL;
  1651. }
  1652. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1653. if (quality != 0) {
  1654. av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
  1655. "supported: will use default quality level.\n");
  1656. }
  1657. } else {
  1658. if (quality > attr.value) {
  1659. av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
  1660. "valid range is 0-%d, using %d.\n",
  1661. attr.value, attr.value);
  1662. quality = attr.value;
  1663. }
  1664. ctx->quality_params.misc.type = VAEncMiscParameterTypeQualityLevel;
  1665. ctx->quality_params.quality.quality_level = quality;
  1666. vaapi_encode_add_global_param(avctx, &ctx->quality_params.misc,
  1667. sizeof(ctx->quality_params));
  1668. }
  1669. #else
  1670. av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
  1671. "not supported with this VAAPI version.\n");
  1672. #endif
  1673. return 0;
  1674. }
  1675. static void vaapi_encode_free_output_buffer(void *opaque,
  1676. uint8_t *data)
  1677. {
  1678. AVCodecContext *avctx = opaque;
  1679. VAAPIEncodeContext *ctx = avctx->priv_data;
  1680. VABufferID buffer_id;
  1681. buffer_id = (VABufferID)(uintptr_t)data;
  1682. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  1683. av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
  1684. }
  1685. static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
  1686. int size)
  1687. {
  1688. AVCodecContext *avctx = opaque;
  1689. VAAPIEncodeContext *ctx = avctx->priv_data;
  1690. VABufferID buffer_id;
  1691. VAStatus vas;
  1692. AVBufferRef *ref;
  1693. // The output buffer size is fixed, so it needs to be large enough
  1694. // to hold the largest possible compressed frame. We assume here
  1695. // that the uncompressed frame plus some header data is an upper
  1696. // bound on that.
  1697. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  1698. VAEncCodedBufferType,
  1699. 3 * ctx->surface_width * ctx->surface_height +
  1700. (1 << 16), 1, 0, &buffer_id);
  1701. if (vas != VA_STATUS_SUCCESS) {
  1702. av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
  1703. "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
  1704. return NULL;
  1705. }
  1706. av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
  1707. ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
  1708. sizeof(buffer_id),
  1709. &vaapi_encode_free_output_buffer,
  1710. avctx, AV_BUFFER_FLAG_READONLY);
  1711. if (!ref) {
  1712. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  1713. return NULL;
  1714. }
  1715. return ref;
  1716. }
  1717. static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
  1718. {
  1719. VAAPIEncodeContext *ctx = avctx->priv_data;
  1720. AVVAAPIHWConfig *hwconfig = NULL;
  1721. AVHWFramesConstraints *constraints = NULL;
  1722. enum AVPixelFormat recon_format;
  1723. int err, i;
  1724. hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
  1725. if (!hwconfig) {
  1726. err = AVERROR(ENOMEM);
  1727. goto fail;
  1728. }
  1729. hwconfig->config_id = ctx->va_config;
  1730. constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
  1731. hwconfig);
  1732. if (!constraints) {
  1733. err = AVERROR(ENOMEM);
  1734. goto fail;
  1735. }
  1736. // Probably we can use the input surface format as the surface format
  1737. // of the reconstructed frames. If not, we just pick the first (only?)
  1738. // format in the valid list and hope that it all works.
  1739. recon_format = AV_PIX_FMT_NONE;
  1740. if (constraints->valid_sw_formats) {
  1741. for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
  1742. if (ctx->input_frames->sw_format ==
  1743. constraints->valid_sw_formats[i]) {
  1744. recon_format = ctx->input_frames->sw_format;
  1745. break;
  1746. }
  1747. }
  1748. if (recon_format == AV_PIX_FMT_NONE) {
  1749. // No match. Just use the first in the supported list and
  1750. // hope for the best.
  1751. recon_format = constraints->valid_sw_formats[0];
  1752. }
  1753. } else {
  1754. // No idea what to use; copy input format.
  1755. recon_format = ctx->input_frames->sw_format;
  1756. }
  1757. av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
  1758. "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
  1759. if (ctx->surface_width < constraints->min_width ||
  1760. ctx->surface_height < constraints->min_height ||
  1761. ctx->surface_width > constraints->max_width ||
  1762. ctx->surface_height > constraints->max_height) {
  1763. av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
  1764. "size %dx%d (constraints: width %d-%d height %d-%d).\n",
  1765. ctx->surface_width, ctx->surface_height,
  1766. constraints->min_width, constraints->max_width,
  1767. constraints->min_height, constraints->max_height);
  1768. err = AVERROR(EINVAL);
  1769. goto fail;
  1770. }
  1771. av_freep(&hwconfig);
  1772. av_hwframe_constraints_free(&constraints);
  1773. ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
  1774. if (!ctx->recon_frames_ref) {
  1775. err = AVERROR(ENOMEM);
  1776. goto fail;
  1777. }
  1778. ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
  1779. ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
  1780. ctx->recon_frames->sw_format = recon_format;
  1781. ctx->recon_frames->width = ctx->surface_width;
  1782. ctx->recon_frames->height = ctx->surface_height;
  1783. err = av_hwframe_ctx_init(ctx->recon_frames_ref);
  1784. if (err < 0) {
  1785. av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
  1786. "frame context: %d.\n", err);
  1787. goto fail;
  1788. }
  1789. err = 0;
  1790. fail:
  1791. av_freep(&hwconfig);
  1792. av_hwframe_constraints_free(&constraints);
  1793. return err;
  1794. }
  1795. av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
  1796. {
  1797. VAAPIEncodeContext *ctx = avctx->priv_data;
  1798. AVVAAPIFramesContext *recon_hwctx = NULL;
  1799. VAStatus vas;
  1800. int err;
  1801. if (!avctx->hw_frames_ctx) {
  1802. av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
  1803. "required to associate the encoding device.\n");
  1804. return AVERROR(EINVAL);
  1805. }
  1806. ctx->va_config = VA_INVALID_ID;
  1807. ctx->va_context = VA_INVALID_ID;
  1808. ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
  1809. if (!ctx->input_frames_ref) {
  1810. err = AVERROR(ENOMEM);
  1811. goto fail;
  1812. }
  1813. ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
  1814. ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
  1815. if (!ctx->device_ref) {
  1816. err = AVERROR(ENOMEM);
  1817. goto fail;
  1818. }
  1819. ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
  1820. ctx->hwctx = ctx->device->hwctx;
  1821. err = vaapi_encode_profile_entrypoint(avctx);
  1822. if (err < 0)
  1823. goto fail;
  1824. err = vaapi_encode_init_rate_control(avctx);
  1825. if (err < 0)
  1826. goto fail;
  1827. err = vaapi_encode_init_gop_structure(avctx);
  1828. if (err < 0)
  1829. goto fail;
  1830. err = vaapi_encode_init_slice_structure(avctx);
  1831. if (err < 0)
  1832. goto fail;
  1833. err = vaapi_encode_init_packed_headers(avctx);
  1834. if (err < 0)
  1835. goto fail;
  1836. if (avctx->compression_level >= 0) {
  1837. err = vaapi_encode_init_quality(avctx);
  1838. if (err < 0)
  1839. goto fail;
  1840. }
  1841. vas = vaCreateConfig(ctx->hwctx->display,
  1842. ctx->va_profile, ctx->va_entrypoint,
  1843. ctx->config_attributes, ctx->nb_config_attributes,
  1844. &ctx->va_config);
  1845. if (vas != VA_STATUS_SUCCESS) {
  1846. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  1847. "configuration: %d (%s).\n", vas, vaErrorStr(vas));
  1848. err = AVERROR(EIO);
  1849. goto fail;
  1850. }
  1851. err = vaapi_encode_create_recon_frames(avctx);
  1852. if (err < 0)
  1853. goto fail;
  1854. recon_hwctx = ctx->recon_frames->hwctx;
  1855. vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
  1856. ctx->surface_width, ctx->surface_height,
  1857. VA_PROGRESSIVE,
  1858. recon_hwctx->surface_ids,
  1859. recon_hwctx->nb_surfaces,
  1860. &ctx->va_context);
  1861. if (vas != VA_STATUS_SUCCESS) {
  1862. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  1863. "context: %d (%s).\n", vas, vaErrorStr(vas));
  1864. err = AVERROR(EIO);
  1865. goto fail;
  1866. }
  1867. ctx->output_buffer_pool =
  1868. av_buffer_pool_init2(sizeof(VABufferID), avctx,
  1869. &vaapi_encode_alloc_output_buffer, NULL);
  1870. if (!ctx->output_buffer_pool) {
  1871. err = AVERROR(ENOMEM);
  1872. goto fail;
  1873. }
  1874. if (ctx->codec->configure) {
  1875. err = ctx->codec->configure(avctx);
  1876. if (err < 0)
  1877. goto fail;
  1878. }
  1879. ctx->output_delay = ctx->b_per_p;
  1880. ctx->decode_delay = ctx->max_b_depth;
  1881. if (ctx->codec->sequence_params_size > 0) {
  1882. ctx->codec_sequence_params =
  1883. av_mallocz(ctx->codec->sequence_params_size);
  1884. if (!ctx->codec_sequence_params) {
  1885. err = AVERROR(ENOMEM);
  1886. goto fail;
  1887. }
  1888. }
  1889. if (ctx->codec->picture_params_size > 0) {
  1890. ctx->codec_picture_params =
  1891. av_mallocz(ctx->codec->picture_params_size);
  1892. if (!ctx->codec_picture_params) {
  1893. err = AVERROR(ENOMEM);
  1894. goto fail;
  1895. }
  1896. }
  1897. if (ctx->codec->init_sequence_params) {
  1898. err = ctx->codec->init_sequence_params(avctx);
  1899. if (err < 0) {
  1900. av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
  1901. "failed: %d.\n", err);
  1902. goto fail;
  1903. }
  1904. }
  1905. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
  1906. ctx->codec->write_sequence_header &&
  1907. avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  1908. char data[MAX_PARAM_BUFFER_SIZE];
  1909. size_t bit_len = 8 * sizeof(data);
  1910. err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
  1911. if (err < 0) {
  1912. av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
  1913. "for extradata: %d.\n", err);
  1914. goto fail;
  1915. } else {
  1916. avctx->extradata_size = (bit_len + 7) / 8;
  1917. avctx->extradata = av_mallocz(avctx->extradata_size +
  1918. AV_INPUT_BUFFER_PADDING_SIZE);
  1919. if (!avctx->extradata) {
  1920. err = AVERROR(ENOMEM);
  1921. goto fail;
  1922. }
  1923. memcpy(avctx->extradata, data, avctx->extradata_size);
  1924. }
  1925. }
  1926. return 0;
  1927. fail:
  1928. ff_vaapi_encode_close(avctx);
  1929. return err;
  1930. }
  1931. av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
  1932. {
  1933. VAAPIEncodeContext *ctx = avctx->priv_data;
  1934. VAAPIEncodePicture *pic, *next;
  1935. for (pic = ctx->pic_start; pic; pic = next) {
  1936. next = pic->next;
  1937. vaapi_encode_free(avctx, pic);
  1938. }
  1939. av_buffer_pool_uninit(&ctx->output_buffer_pool);
  1940. if (ctx->va_context != VA_INVALID_ID) {
  1941. vaDestroyContext(ctx->hwctx->display, ctx->va_context);
  1942. ctx->va_context = VA_INVALID_ID;
  1943. }
  1944. if (ctx->va_config != VA_INVALID_ID) {
  1945. vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
  1946. ctx->va_config = VA_INVALID_ID;
  1947. }
  1948. av_freep(&ctx->codec_sequence_params);
  1949. av_freep(&ctx->codec_picture_params);
  1950. av_buffer_unref(&ctx->recon_frames_ref);
  1951. av_buffer_unref(&ctx->input_frames_ref);
  1952. av_buffer_unref(&ctx->device_ref);
  1953. return 0;
  1954. }