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.

1879 lines
62KB

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