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.

2231 lines
76KB

  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 const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
  1116. // Bitrate Quality
  1117. // | Maxrate | HRD/VBV
  1118. { 0 }, // | | | |
  1119. { RC_MODE_CQP, "CQP", 1, VA_RC_CQP, 0, 0, 1, 0 },
  1120. { RC_MODE_CBR, "CBR", 1, VA_RC_CBR, 1, 0, 0, 1 },
  1121. { RC_MODE_VBR, "VBR", 1, VA_RC_VBR, 1, 1, 0, 1 },
  1122. #if VA_CHECK_VERSION(1, 1, 0)
  1123. { RC_MODE_ICQ, "ICQ", 1, VA_RC_ICQ, 0, 0, 1, 0 },
  1124. #else
  1125. { RC_MODE_ICQ, "ICQ", 0 },
  1126. #endif
  1127. #if VA_CHECK_VERSION(1, 3, 0)
  1128. { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1, 1, 1, 1 },
  1129. { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1, 0, 0, 0 },
  1130. #else
  1131. { RC_MODE_QVBR, "QVBR", 0 },
  1132. { RC_MODE_AVBR, "AVBR", 0 },
  1133. #endif
  1134. };
  1135. static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
  1136. {
  1137. VAAPIEncodeContext *ctx = avctx->priv_data;
  1138. uint32_t supported_va_rc_modes;
  1139. const VAAPIEncodeRCMode *rc_mode;
  1140. int64_t rc_bits_per_second;
  1141. int rc_target_percentage;
  1142. int rc_window_size;
  1143. int rc_quality;
  1144. int64_t hrd_buffer_size;
  1145. int64_t hrd_initial_buffer_fullness;
  1146. int fr_num, fr_den;
  1147. VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
  1148. VAStatus vas;
  1149. char supported_rc_modes_string[64];
  1150. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1151. ctx->va_profile, ctx->va_entrypoint,
  1152. &rc_attr, 1);
  1153. if (vas != VA_STATUS_SUCCESS) {
  1154. av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
  1155. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1156. return AVERROR_EXTERNAL;
  1157. }
  1158. if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1159. av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
  1160. "supported rate control modes: assuming CQP only.\n");
  1161. supported_va_rc_modes = VA_RC_CQP;
  1162. strcpy(supported_rc_modes_string, "unknown");
  1163. } else {
  1164. char *str = supported_rc_modes_string;
  1165. size_t len = sizeof(supported_rc_modes_string);
  1166. int i, first = 1, res;
  1167. supported_va_rc_modes = rc_attr.value;
  1168. for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
  1169. rc_mode = &vaapi_encode_rc_modes[i];
  1170. if (supported_va_rc_modes & rc_mode->va_mode) {
  1171. res = snprintf(str, len, "%s%s",
  1172. first ? "" : ", ", rc_mode->name);
  1173. first = 0;
  1174. if (res < 0) {
  1175. *str = 0;
  1176. break;
  1177. }
  1178. len -= res;
  1179. str += res;
  1180. if (len == 0)
  1181. break;
  1182. }
  1183. }
  1184. av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
  1185. supported_rc_modes_string);
  1186. }
  1187. // Rate control mode selection:
  1188. // * If the user has set a mode explicitly with the rc_mode option,
  1189. // use it and fail if it is not available.
  1190. // * If an explicit QP option has been set, use CQP.
  1191. // * If the codec is CQ-only, use CQP.
  1192. // * If the QSCALE avcodec option is set, use CQP.
  1193. // * If bitrate and quality are both set, try QVBR.
  1194. // * If quality is set, try ICQ, then CQP.
  1195. // * If bitrate and maxrate are set and have the same value, try CBR.
  1196. // * If a bitrate is set, try AVBR, then VBR, then CBR.
  1197. // * If no bitrate is set, try ICQ, then CQP.
  1198. #define TRY_RC_MODE(mode, fail) do { \
  1199. rc_mode = &vaapi_encode_rc_modes[mode]; \
  1200. if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
  1201. if (fail) { \
  1202. av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
  1203. "RC mode (supported modes: %s).\n", rc_mode->name, \
  1204. supported_rc_modes_string); \
  1205. return AVERROR(EINVAL); \
  1206. } \
  1207. av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
  1208. "RC mode.\n", rc_mode->name); \
  1209. rc_mode = NULL; \
  1210. } else { \
  1211. goto rc_mode_found; \
  1212. } \
  1213. } while (0)
  1214. if (ctx->explicit_rc_mode)
  1215. TRY_RC_MODE(ctx->explicit_rc_mode, 1);
  1216. if (ctx->explicit_qp)
  1217. TRY_RC_MODE(RC_MODE_CQP, 1);
  1218. if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY)
  1219. TRY_RC_MODE(RC_MODE_CQP, 1);
  1220. if (avctx->flags & AV_CODEC_FLAG_QSCALE)
  1221. TRY_RC_MODE(RC_MODE_CQP, 1);
  1222. if (avctx->bit_rate > 0 && avctx->global_quality > 0)
  1223. TRY_RC_MODE(RC_MODE_QVBR, 0);
  1224. if (avctx->global_quality > 0) {
  1225. TRY_RC_MODE(RC_MODE_ICQ, 0);
  1226. TRY_RC_MODE(RC_MODE_CQP, 0);
  1227. }
  1228. if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
  1229. TRY_RC_MODE(RC_MODE_CBR, 0);
  1230. if (avctx->bit_rate > 0) {
  1231. TRY_RC_MODE(RC_MODE_AVBR, 0);
  1232. TRY_RC_MODE(RC_MODE_VBR, 0);
  1233. TRY_RC_MODE(RC_MODE_CBR, 0);
  1234. } else {
  1235. TRY_RC_MODE(RC_MODE_ICQ, 0);
  1236. TRY_RC_MODE(RC_MODE_CQP, 0);
  1237. }
  1238. av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
  1239. "RC mode compatible with selected options "
  1240. "(supported modes: %s).\n", supported_rc_modes_string);
  1241. return AVERROR(EINVAL);
  1242. rc_mode_found:
  1243. if (rc_mode->bitrate) {
  1244. if (avctx->bit_rate <= 0) {
  1245. av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
  1246. "RC mode.\n", rc_mode->name);
  1247. return AVERROR(EINVAL);
  1248. }
  1249. if (rc_mode->mode == RC_MODE_AVBR) {
  1250. // For maximum confusion AVBR is hacked into the existing API
  1251. // by overloading some of the fields with completely different
  1252. // meanings.
  1253. // Target percentage does not apply in AVBR mode.
  1254. rc_bits_per_second = avctx->bit_rate;
  1255. // Accuracy tolerance range for meeting the specified target
  1256. // bitrate. It's very unclear how this is actually intended
  1257. // to work - since we do want to get the specified bitrate,
  1258. // set the accuracy to 100% for now.
  1259. rc_target_percentage = 100;
  1260. // Convergence period in frames. The GOP size reflects the
  1261. // user's intended block size for cutting, so reusing that
  1262. // as the convergence period seems a reasonable default.
  1263. rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
  1264. } else if (rc_mode->maxrate) {
  1265. if (avctx->rc_max_rate > 0) {
  1266. if (avctx->rc_max_rate < avctx->bit_rate) {
  1267. av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
  1268. "bitrate (%"PRId64") must not be greater than "
  1269. "maxrate (%"PRId64").\n", avctx->bit_rate,
  1270. avctx->rc_max_rate);
  1271. return AVERROR(EINVAL);
  1272. }
  1273. rc_bits_per_second = avctx->rc_max_rate;
  1274. rc_target_percentage = (avctx->bit_rate * 100) /
  1275. avctx->rc_max_rate;
  1276. } else {
  1277. // We only have a target bitrate, but this mode requires
  1278. // that a maximum rate be supplied as well. Since the
  1279. // user does not want this to be a constraint, arbitrarily
  1280. // pick a maximum rate of double the target rate.
  1281. rc_bits_per_second = 2 * avctx->bit_rate;
  1282. rc_target_percentage = 50;
  1283. }
  1284. } else {
  1285. if (avctx->rc_max_rate > avctx->bit_rate) {
  1286. av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
  1287. "in %s RC mode.\n", rc_mode->name);
  1288. }
  1289. rc_bits_per_second = avctx->bit_rate;
  1290. rc_target_percentage = 100;
  1291. }
  1292. } else {
  1293. rc_bits_per_second = 0;
  1294. rc_target_percentage = 100;
  1295. }
  1296. if (rc_mode->quality) {
  1297. if (ctx->explicit_qp) {
  1298. rc_quality = ctx->explicit_qp;
  1299. } else if (avctx->global_quality > 0) {
  1300. rc_quality = avctx->global_quality;
  1301. } else {
  1302. rc_quality = ctx->codec->default_quality;
  1303. av_log(avctx, AV_LOG_WARNING, "No quality level set; "
  1304. "using default (%d).\n", rc_quality);
  1305. }
  1306. } else {
  1307. rc_quality = 0;
  1308. }
  1309. if (rc_mode->hrd) {
  1310. if (avctx->rc_buffer_size)
  1311. hrd_buffer_size = avctx->rc_buffer_size;
  1312. else if (avctx->rc_max_rate > 0)
  1313. hrd_buffer_size = avctx->rc_max_rate;
  1314. else
  1315. hrd_buffer_size = avctx->bit_rate;
  1316. if (avctx->rc_initial_buffer_occupancy) {
  1317. if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
  1318. av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
  1319. "must have initial buffer size (%d) <= "
  1320. "buffer size (%"PRId64").\n",
  1321. avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
  1322. return AVERROR(EINVAL);
  1323. }
  1324. hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
  1325. } else {
  1326. hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
  1327. }
  1328. rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
  1329. } else {
  1330. if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
  1331. av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
  1332. "in %s RC mode.\n", rc_mode->name);
  1333. }
  1334. hrd_buffer_size = 0;
  1335. hrd_initial_buffer_fullness = 0;
  1336. if (rc_mode->mode != RC_MODE_AVBR) {
  1337. // Already set (with completely different meaning) for AVBR.
  1338. rc_window_size = 1000;
  1339. }
  1340. }
  1341. if (rc_bits_per_second > UINT32_MAX ||
  1342. hrd_buffer_size > UINT32_MAX ||
  1343. hrd_initial_buffer_fullness > UINT32_MAX) {
  1344. av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
  1345. "greater are not supported by VAAPI.\n");
  1346. return AVERROR(EINVAL);
  1347. }
  1348. ctx->rc_mode = rc_mode;
  1349. ctx->rc_quality = rc_quality;
  1350. ctx->va_rc_mode = rc_mode->va_mode;
  1351. ctx->va_bit_rate = rc_bits_per_second;
  1352. av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
  1353. if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1354. // This driver does not want the RC mode attribute to be set.
  1355. } else {
  1356. ctx->config_attributes[ctx->nb_config_attributes++] =
  1357. (VAConfigAttrib) {
  1358. .type = VAConfigAttribRateControl,
  1359. .value = ctx->va_rc_mode,
  1360. };
  1361. }
  1362. if (rc_mode->quality)
  1363. av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
  1364. if (rc_mode->va_mode != VA_RC_CQP) {
  1365. if (rc_mode->mode == RC_MODE_AVBR) {
  1366. av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
  1367. "converging in %d frames with %d%% accuracy.\n",
  1368. rc_bits_per_second, rc_window_size,
  1369. rc_target_percentage);
  1370. } else if (rc_mode->bitrate) {
  1371. av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
  1372. "%"PRId64" bps over %d ms.\n", rc_target_percentage,
  1373. rc_bits_per_second, rc_window_size);
  1374. }
  1375. ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
  1376. ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
  1377. .bits_per_second = rc_bits_per_second,
  1378. .target_percentage = rc_target_percentage,
  1379. .window_size = rc_window_size,
  1380. .initial_qp = 0,
  1381. .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
  1382. .basic_unit_size = 0,
  1383. #if VA_CHECK_VERSION(1, 1, 0)
  1384. .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
  1385. .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
  1386. #endif
  1387. #if VA_CHECK_VERSION(1, 3, 0)
  1388. .quality_factor = rc_quality,
  1389. #endif
  1390. };
  1391. vaapi_encode_add_global_param(avctx, &ctx->rc_params.misc,
  1392. sizeof(ctx->rc_params));
  1393. }
  1394. if (rc_mode->hrd) {
  1395. av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
  1396. "initial fullness %"PRId64" bits.\n",
  1397. hrd_buffer_size, hrd_initial_buffer_fullness);
  1398. ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
  1399. ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
  1400. .initial_buffer_fullness = hrd_initial_buffer_fullness,
  1401. .buffer_size = hrd_buffer_size,
  1402. };
  1403. vaapi_encode_add_global_param(avctx, &ctx->hrd_params.misc,
  1404. sizeof(ctx->hrd_params));
  1405. }
  1406. if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
  1407. av_reduce(&fr_num, &fr_den,
  1408. avctx->framerate.num, avctx->framerate.den, 65535);
  1409. else
  1410. av_reduce(&fr_num, &fr_den,
  1411. avctx->time_base.den, avctx->time_base.num, 65535);
  1412. av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
  1413. fr_num, fr_den, (double)fr_num / fr_den);
  1414. ctx->fr_params.misc.type = VAEncMiscParameterTypeFrameRate;
  1415. ctx->fr_params.fr.framerate = (unsigned int)fr_den << 16 | fr_num;
  1416. #if VA_CHECK_VERSION(0, 40, 0)
  1417. vaapi_encode_add_global_param(avctx, &ctx->fr_params.misc,
  1418. sizeof(ctx->fr_params));
  1419. #endif
  1420. return 0;
  1421. }
  1422. static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
  1423. {
  1424. VAAPIEncodeContext *ctx = avctx->priv_data;
  1425. VAStatus vas;
  1426. VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
  1427. uint32_t ref_l0, ref_l1;
  1428. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1429. ctx->va_profile,
  1430. ctx->va_entrypoint,
  1431. &attr, 1);
  1432. if (vas != VA_STATUS_SUCCESS) {
  1433. av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
  1434. "attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1435. return AVERROR_EXTERNAL;
  1436. }
  1437. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1438. ref_l0 = ref_l1 = 0;
  1439. } else {
  1440. ref_l0 = attr.value & 0xffff;
  1441. ref_l1 = attr.value >> 16 & 0xffff;
  1442. }
  1443. if (ctx->codec->flags & FLAG_INTRA_ONLY ||
  1444. avctx->gop_size <= 1) {
  1445. av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
  1446. ctx->gop_size = 1;
  1447. } else if (ref_l0 < 1) {
  1448. av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
  1449. "reference frames.\n");
  1450. return AVERROR(EINVAL);
  1451. } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
  1452. ref_l1 < 1 || avctx->max_b_frames < 1) {
  1453. av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
  1454. "(supported references: %d / %d).\n", ref_l0, ref_l1);
  1455. ctx->gop_size = avctx->gop_size;
  1456. ctx->p_per_i = INT_MAX;
  1457. ctx->b_per_p = 0;
  1458. } else {
  1459. av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
  1460. "(supported references: %d / %d).\n", ref_l0, ref_l1);
  1461. ctx->gop_size = avctx->gop_size;
  1462. ctx->p_per_i = INT_MAX;
  1463. ctx->b_per_p = avctx->max_b_frames;
  1464. if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
  1465. ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
  1466. av_log2(ctx->b_per_p) + 1);
  1467. } else {
  1468. ctx->max_b_depth = 1;
  1469. }
  1470. }
  1471. if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
  1472. ctx->closed_gop = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
  1473. ctx->gop_per_idr = ctx->idr_interval + 1;
  1474. } else {
  1475. ctx->closed_gop = 1;
  1476. ctx->gop_per_idr = 1;
  1477. }
  1478. return 0;
  1479. }
  1480. static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
  1481. {
  1482. VAAPIEncodeContext *ctx = avctx->priv_data;
  1483. VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
  1484. { VAConfigAttribEncSliceStructure } };
  1485. VAStatus vas;
  1486. uint32_t max_slices, slice_structure;
  1487. int req_slices;
  1488. if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
  1489. if (avctx->slices > 0) {
  1490. av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
  1491. "but this codec does not support controlling slices.\n");
  1492. }
  1493. return 0;
  1494. }
  1495. ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
  1496. ctx->slice_block_height;
  1497. ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
  1498. ctx->slice_block_width;
  1499. if (avctx->slices <= 1) {
  1500. ctx->nb_slices = 1;
  1501. ctx->slice_size = ctx->slice_block_rows;
  1502. return 0;
  1503. }
  1504. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1505. ctx->va_profile,
  1506. ctx->va_entrypoint,
  1507. attr, FF_ARRAY_ELEMS(attr));
  1508. if (vas != VA_STATUS_SUCCESS) {
  1509. av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
  1510. "attributes: %d (%s).\n", vas, vaErrorStr(vas));
  1511. return AVERROR_EXTERNAL;
  1512. }
  1513. max_slices = attr[0].value;
  1514. slice_structure = attr[1].value;
  1515. if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
  1516. slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
  1517. av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
  1518. "pictures as multiple slices.\n.");
  1519. return AVERROR(EINVAL);
  1520. }
  1521. // For fixed-size slices currently we only support whole rows, making
  1522. // rectangular slices. This could be extended to arbitrary runs of
  1523. // blocks, but since slices tend to be a conformance requirement and
  1524. // most cases (such as broadcast or bluray) want rectangular slices
  1525. // only it would need to be gated behind another option.
  1526. if (avctx->slices > ctx->slice_block_rows) {
  1527. av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
  1528. "configured number of slices (%d < %d); using "
  1529. "maximum.\n", ctx->slice_block_rows, avctx->slices);
  1530. req_slices = ctx->slice_block_rows;
  1531. } else {
  1532. req_slices = avctx->slices;
  1533. }
  1534. if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
  1535. slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
  1536. ctx->nb_slices = req_slices;
  1537. ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
  1538. } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
  1539. int k;
  1540. for (k = 1;; k *= 2) {
  1541. if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
  1542. break;
  1543. }
  1544. ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
  1545. ctx->slice_size = k;
  1546. #if VA_CHECK_VERSION(1, 0, 0)
  1547. } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
  1548. ctx->nb_slices = ctx->slice_block_rows;
  1549. ctx->slice_size = 1;
  1550. #endif
  1551. } else {
  1552. av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
  1553. "slice structure modes (%#x).\n", slice_structure);
  1554. return AVERROR(EINVAL);
  1555. }
  1556. if (ctx->nb_slices > avctx->slices) {
  1557. av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
  1558. "%d (from %d) due to driver constraints on slice "
  1559. "structure.\n", ctx->nb_slices, avctx->slices);
  1560. }
  1561. if (ctx->nb_slices > max_slices) {
  1562. av_log(avctx, AV_LOG_ERROR, "Driver does not support "
  1563. "encoding with %d slices (max %"PRIu32").\n",
  1564. ctx->nb_slices, max_slices);
  1565. return AVERROR(EINVAL);
  1566. }
  1567. av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
  1568. "(default size %d block rows).\n",
  1569. ctx->nb_slices, ctx->slice_size);
  1570. return 0;
  1571. }
  1572. static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
  1573. {
  1574. VAAPIEncodeContext *ctx = avctx->priv_data;
  1575. VAStatus vas;
  1576. VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
  1577. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1578. ctx->va_profile,
  1579. ctx->va_entrypoint,
  1580. &attr, 1);
  1581. if (vas != VA_STATUS_SUCCESS) {
  1582. av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
  1583. "attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1584. return AVERROR_EXTERNAL;
  1585. }
  1586. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1587. if (ctx->desired_packed_headers) {
  1588. av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
  1589. "packed headers (wanted %#x).\n",
  1590. ctx->desired_packed_headers);
  1591. } else {
  1592. av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
  1593. "packed headers (none wanted).\n");
  1594. }
  1595. ctx->va_packed_headers = 0;
  1596. } else {
  1597. if (ctx->desired_packed_headers & ~attr.value) {
  1598. av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
  1599. "wanted packed headers (wanted %#x, found %#x).\n",
  1600. ctx->desired_packed_headers, attr.value);
  1601. } else {
  1602. av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
  1603. "available (wanted %#x, found %#x).\n",
  1604. ctx->desired_packed_headers, attr.value);
  1605. }
  1606. ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
  1607. }
  1608. if (ctx->va_packed_headers) {
  1609. ctx->config_attributes[ctx->nb_config_attributes++] =
  1610. (VAConfigAttrib) {
  1611. .type = VAConfigAttribEncPackedHeaders,
  1612. .value = ctx->va_packed_headers,
  1613. };
  1614. }
  1615. if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
  1616. !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
  1617. (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
  1618. av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
  1619. "sequence headers, but a global header is requested.\n");
  1620. av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
  1621. "this may result in a stream which is not usable for some "
  1622. "purposes (e.g. not muxable to some containers).\n");
  1623. }
  1624. return 0;
  1625. }
  1626. static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
  1627. {
  1628. #if VA_CHECK_VERSION(0, 36, 0)
  1629. VAAPIEncodeContext *ctx = avctx->priv_data;
  1630. VAStatus vas;
  1631. VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
  1632. int quality = avctx->compression_level;
  1633. vas = vaGetConfigAttributes(ctx->hwctx->display,
  1634. ctx->va_profile,
  1635. ctx->va_entrypoint,
  1636. &attr, 1);
  1637. if (vas != VA_STATUS_SUCCESS) {
  1638. av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
  1639. "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
  1640. return AVERROR_EXTERNAL;
  1641. }
  1642. if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
  1643. if (quality != 0) {
  1644. av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
  1645. "supported: will use default quality level.\n");
  1646. }
  1647. } else {
  1648. if (quality > attr.value) {
  1649. av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
  1650. "valid range is 0-%d, using %d.\n",
  1651. attr.value, attr.value);
  1652. quality = attr.value;
  1653. }
  1654. ctx->quality_params.misc.type = VAEncMiscParameterTypeQualityLevel;
  1655. ctx->quality_params.quality.quality_level = quality;
  1656. vaapi_encode_add_global_param(avctx, &ctx->quality_params.misc,
  1657. sizeof(ctx->quality_params));
  1658. }
  1659. #else
  1660. av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
  1661. "not supported with this VAAPI version.\n");
  1662. #endif
  1663. return 0;
  1664. }
  1665. static void vaapi_encode_free_output_buffer(void *opaque,
  1666. uint8_t *data)
  1667. {
  1668. AVCodecContext *avctx = opaque;
  1669. VAAPIEncodeContext *ctx = avctx->priv_data;
  1670. VABufferID buffer_id;
  1671. buffer_id = (VABufferID)(uintptr_t)data;
  1672. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  1673. av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
  1674. }
  1675. static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
  1676. int size)
  1677. {
  1678. AVCodecContext *avctx = opaque;
  1679. VAAPIEncodeContext *ctx = avctx->priv_data;
  1680. VABufferID buffer_id;
  1681. VAStatus vas;
  1682. AVBufferRef *ref;
  1683. // The output buffer size is fixed, so it needs to be large enough
  1684. // to hold the largest possible compressed frame. We assume here
  1685. // that the uncompressed frame plus some header data is an upper
  1686. // bound on that.
  1687. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  1688. VAEncCodedBufferType,
  1689. 3 * ctx->surface_width * ctx->surface_height +
  1690. (1 << 16), 1, 0, &buffer_id);
  1691. if (vas != VA_STATUS_SUCCESS) {
  1692. av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
  1693. "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
  1694. return NULL;
  1695. }
  1696. av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
  1697. ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
  1698. sizeof(buffer_id),
  1699. &vaapi_encode_free_output_buffer,
  1700. avctx, AV_BUFFER_FLAG_READONLY);
  1701. if (!ref) {
  1702. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  1703. return NULL;
  1704. }
  1705. return ref;
  1706. }
  1707. static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
  1708. {
  1709. VAAPIEncodeContext *ctx = avctx->priv_data;
  1710. AVVAAPIHWConfig *hwconfig = NULL;
  1711. AVHWFramesConstraints *constraints = NULL;
  1712. enum AVPixelFormat recon_format;
  1713. int err, i;
  1714. hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
  1715. if (!hwconfig) {
  1716. err = AVERROR(ENOMEM);
  1717. goto fail;
  1718. }
  1719. hwconfig->config_id = ctx->va_config;
  1720. constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
  1721. hwconfig);
  1722. if (!constraints) {
  1723. err = AVERROR(ENOMEM);
  1724. goto fail;
  1725. }
  1726. // Probably we can use the input surface format as the surface format
  1727. // of the reconstructed frames. If not, we just pick the first (only?)
  1728. // format in the valid list and hope that it all works.
  1729. recon_format = AV_PIX_FMT_NONE;
  1730. if (constraints->valid_sw_formats) {
  1731. for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
  1732. if (ctx->input_frames->sw_format ==
  1733. constraints->valid_sw_formats[i]) {
  1734. recon_format = ctx->input_frames->sw_format;
  1735. break;
  1736. }
  1737. }
  1738. if (recon_format == AV_PIX_FMT_NONE) {
  1739. // No match. Just use the first in the supported list and
  1740. // hope for the best.
  1741. recon_format = constraints->valid_sw_formats[0];
  1742. }
  1743. } else {
  1744. // No idea what to use; copy input format.
  1745. recon_format = ctx->input_frames->sw_format;
  1746. }
  1747. av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
  1748. "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
  1749. if (ctx->surface_width < constraints->min_width ||
  1750. ctx->surface_height < constraints->min_height ||
  1751. ctx->surface_width > constraints->max_width ||
  1752. ctx->surface_height > constraints->max_height) {
  1753. av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
  1754. "size %dx%d (constraints: width %d-%d height %d-%d).\n",
  1755. ctx->surface_width, ctx->surface_height,
  1756. constraints->min_width, constraints->max_width,
  1757. constraints->min_height, constraints->max_height);
  1758. err = AVERROR(EINVAL);
  1759. goto fail;
  1760. }
  1761. av_freep(&hwconfig);
  1762. av_hwframe_constraints_free(&constraints);
  1763. ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
  1764. if (!ctx->recon_frames_ref) {
  1765. err = AVERROR(ENOMEM);
  1766. goto fail;
  1767. }
  1768. ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
  1769. ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
  1770. ctx->recon_frames->sw_format = recon_format;
  1771. ctx->recon_frames->width = ctx->surface_width;
  1772. ctx->recon_frames->height = ctx->surface_height;
  1773. err = av_hwframe_ctx_init(ctx->recon_frames_ref);
  1774. if (err < 0) {
  1775. av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
  1776. "frame context: %d.\n", err);
  1777. goto fail;
  1778. }
  1779. err = 0;
  1780. fail:
  1781. av_freep(&hwconfig);
  1782. av_hwframe_constraints_free(&constraints);
  1783. return err;
  1784. }
  1785. av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
  1786. {
  1787. VAAPIEncodeContext *ctx = avctx->priv_data;
  1788. AVVAAPIFramesContext *recon_hwctx = NULL;
  1789. VAStatus vas;
  1790. int err;
  1791. if (!avctx->hw_frames_ctx) {
  1792. av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
  1793. "required to associate the encoding device.\n");
  1794. return AVERROR(EINVAL);
  1795. }
  1796. ctx->va_config = VA_INVALID_ID;
  1797. ctx->va_context = VA_INVALID_ID;
  1798. ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
  1799. if (!ctx->input_frames_ref) {
  1800. err = AVERROR(ENOMEM);
  1801. goto fail;
  1802. }
  1803. ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
  1804. ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
  1805. if (!ctx->device_ref) {
  1806. err = AVERROR(ENOMEM);
  1807. goto fail;
  1808. }
  1809. ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
  1810. ctx->hwctx = ctx->device->hwctx;
  1811. err = vaapi_encode_profile_entrypoint(avctx);
  1812. if (err < 0)
  1813. goto fail;
  1814. err = vaapi_encode_init_rate_control(avctx);
  1815. if (err < 0)
  1816. goto fail;
  1817. err = vaapi_encode_init_gop_structure(avctx);
  1818. if (err < 0)
  1819. goto fail;
  1820. err = vaapi_encode_init_slice_structure(avctx);
  1821. if (err < 0)
  1822. goto fail;
  1823. err = vaapi_encode_init_packed_headers(avctx);
  1824. if (err < 0)
  1825. goto fail;
  1826. if (avctx->compression_level >= 0) {
  1827. err = vaapi_encode_init_quality(avctx);
  1828. if (err < 0)
  1829. goto fail;
  1830. }
  1831. vas = vaCreateConfig(ctx->hwctx->display,
  1832. ctx->va_profile, ctx->va_entrypoint,
  1833. ctx->config_attributes, ctx->nb_config_attributes,
  1834. &ctx->va_config);
  1835. if (vas != VA_STATUS_SUCCESS) {
  1836. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  1837. "configuration: %d (%s).\n", vas, vaErrorStr(vas));
  1838. err = AVERROR(EIO);
  1839. goto fail;
  1840. }
  1841. err = vaapi_encode_create_recon_frames(avctx);
  1842. if (err < 0)
  1843. goto fail;
  1844. recon_hwctx = ctx->recon_frames->hwctx;
  1845. vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
  1846. ctx->surface_width, ctx->surface_height,
  1847. VA_PROGRESSIVE,
  1848. recon_hwctx->surface_ids,
  1849. recon_hwctx->nb_surfaces,
  1850. &ctx->va_context);
  1851. if (vas != VA_STATUS_SUCCESS) {
  1852. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  1853. "context: %d (%s).\n", vas, vaErrorStr(vas));
  1854. err = AVERROR(EIO);
  1855. goto fail;
  1856. }
  1857. ctx->output_buffer_pool =
  1858. av_buffer_pool_init2(sizeof(VABufferID), avctx,
  1859. &vaapi_encode_alloc_output_buffer, NULL);
  1860. if (!ctx->output_buffer_pool) {
  1861. err = AVERROR(ENOMEM);
  1862. goto fail;
  1863. }
  1864. if (ctx->codec->configure) {
  1865. err = ctx->codec->configure(avctx);
  1866. if (err < 0)
  1867. goto fail;
  1868. }
  1869. ctx->output_delay = ctx->b_per_p;
  1870. ctx->decode_delay = ctx->max_b_depth;
  1871. if (ctx->codec->sequence_params_size > 0) {
  1872. ctx->codec_sequence_params =
  1873. av_mallocz(ctx->codec->sequence_params_size);
  1874. if (!ctx->codec_sequence_params) {
  1875. err = AVERROR(ENOMEM);
  1876. goto fail;
  1877. }
  1878. }
  1879. if (ctx->codec->picture_params_size > 0) {
  1880. ctx->codec_picture_params =
  1881. av_mallocz(ctx->codec->picture_params_size);
  1882. if (!ctx->codec_picture_params) {
  1883. err = AVERROR(ENOMEM);
  1884. goto fail;
  1885. }
  1886. }
  1887. if (ctx->codec->init_sequence_params) {
  1888. err = ctx->codec->init_sequence_params(avctx);
  1889. if (err < 0) {
  1890. av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
  1891. "failed: %d.\n", err);
  1892. goto fail;
  1893. }
  1894. }
  1895. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
  1896. ctx->codec->write_sequence_header &&
  1897. avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  1898. char data[MAX_PARAM_BUFFER_SIZE];
  1899. size_t bit_len = 8 * sizeof(data);
  1900. err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
  1901. if (err < 0) {
  1902. av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
  1903. "for extradata: %d.\n", err);
  1904. goto fail;
  1905. } else {
  1906. avctx->extradata_size = (bit_len + 7) / 8;
  1907. avctx->extradata = av_mallocz(avctx->extradata_size +
  1908. AV_INPUT_BUFFER_PADDING_SIZE);
  1909. if (!avctx->extradata) {
  1910. err = AVERROR(ENOMEM);
  1911. goto fail;
  1912. }
  1913. memcpy(avctx->extradata, data, avctx->extradata_size);
  1914. }
  1915. }
  1916. return 0;
  1917. fail:
  1918. ff_vaapi_encode_close(avctx);
  1919. return err;
  1920. }
  1921. av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
  1922. {
  1923. VAAPIEncodeContext *ctx = avctx->priv_data;
  1924. VAAPIEncodePicture *pic, *next;
  1925. for (pic = ctx->pic_start; pic; pic = next) {
  1926. next = pic->next;
  1927. vaapi_encode_free(avctx, pic);
  1928. }
  1929. av_buffer_pool_uninit(&ctx->output_buffer_pool);
  1930. if (ctx->va_context != VA_INVALID_ID) {
  1931. vaDestroyContext(ctx->hwctx->display, ctx->va_context);
  1932. ctx->va_context = VA_INVALID_ID;
  1933. }
  1934. if (ctx->va_config != VA_INVALID_ID) {
  1935. vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
  1936. ctx->va_config = VA_INVALID_ID;
  1937. }
  1938. av_freep(&ctx->codec_sequence_params);
  1939. av_freep(&ctx->codec_picture_params);
  1940. av_buffer_unref(&ctx->recon_frames_ref);
  1941. av_buffer_unref(&ctx->input_frames_ref);
  1942. av_buffer_unref(&ctx->device_ref);
  1943. return 0;
  1944. }