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.

1464 lines
47KB

  1. /*
  2. * This file is part of Libav.
  3. *
  4. * Libav 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. * Libav 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 Libav; 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 *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. VAEncPackedHeaderParameterBuffer params = {
  35. .type = type,
  36. .bit_length = bit_len,
  37. .has_emulation_bytes = 1,
  38. };
  39. av_assert0(pic->nb_param_buffers + 2 <= MAX_PARAM_BUFFERS);
  40. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  41. VAEncPackedHeaderParameterBufferType,
  42. sizeof(params), 1, &params, &param_buffer);
  43. if (vas != VA_STATUS_SUCCESS) {
  44. av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
  45. "for packed header (type %d): %d (%s).\n",
  46. type, vas, vaErrorStr(vas));
  47. return AVERROR(EIO);
  48. }
  49. pic->param_buffers[pic->nb_param_buffers++] = param_buffer;
  50. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  51. VAEncPackedHeaderDataBufferType,
  52. (bit_len + 7) / 8, 1, data, &data_buffer);
  53. if (vas != VA_STATUS_SUCCESS) {
  54. av_log(avctx, AV_LOG_ERROR, "Failed to create data buffer "
  55. "for packed header (type %d): %d (%s).\n",
  56. type, vas, vaErrorStr(vas));
  57. return AVERROR(EIO);
  58. }
  59. pic->param_buffers[pic->nb_param_buffers++] = data_buffer;
  60. av_log(avctx, AV_LOG_DEBUG, "Packed header buffer (%d) is %#x/%#x "
  61. "(%zu bits).\n", type, param_buffer, data_buffer, bit_len);
  62. return 0;
  63. }
  64. static int vaapi_encode_make_param_buffer(AVCodecContext *avctx,
  65. VAAPIEncodePicture *pic,
  66. int type, char *data, size_t len)
  67. {
  68. VAAPIEncodeContext *ctx = avctx->priv_data;
  69. VAStatus vas;
  70. VABufferID buffer;
  71. av_assert0(pic->nb_param_buffers + 1 <= MAX_PARAM_BUFFERS);
  72. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  73. type, len, 1, data, &buffer);
  74. if (vas != VA_STATUS_SUCCESS) {
  75. av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
  76. "(type %d): %d (%s).\n", type, vas, vaErrorStr(vas));
  77. return AVERROR(EIO);
  78. }
  79. pic->param_buffers[pic->nb_param_buffers++] = buffer;
  80. av_log(avctx, AV_LOG_DEBUG, "Param buffer (%d) is %#x.\n",
  81. type, buffer);
  82. return 0;
  83. }
  84. static int vaapi_encode_wait(AVCodecContext *avctx,
  85. VAAPIEncodePicture *pic)
  86. {
  87. VAAPIEncodeContext *ctx = avctx->priv_data;
  88. VAStatus vas;
  89. av_assert0(pic->encode_issued);
  90. if (pic->encode_complete) {
  91. // Already waited for this picture.
  92. return 0;
  93. }
  94. av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
  95. "(input surface %#x).\n", pic->display_order,
  96. pic->encode_order, pic->input_surface);
  97. vas = vaSyncSurface(ctx->hwctx->display, pic->input_surface);
  98. if (vas != VA_STATUS_SUCCESS) {
  99. av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
  100. "%d (%s).\n", vas, vaErrorStr(vas));
  101. return AVERROR(EIO);
  102. }
  103. // Input is definitely finished with now.
  104. av_frame_free(&pic->input_image);
  105. pic->encode_complete = 1;
  106. return 0;
  107. }
  108. static int vaapi_encode_issue(AVCodecContext *avctx,
  109. VAAPIEncodePicture *pic)
  110. {
  111. VAAPIEncodeContext *ctx = avctx->priv_data;
  112. VAAPIEncodeSlice *slice;
  113. VAStatus vas;
  114. int err, i;
  115. char data[MAX_PARAM_BUFFER_SIZE];
  116. size_t bit_len;
  117. av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
  118. "as type %s.\n", pic->display_order, pic->encode_order,
  119. picture_type_name[pic->type]);
  120. if (pic->nb_refs == 0) {
  121. av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
  122. } else {
  123. av_log(avctx, AV_LOG_DEBUG, "Refers to:");
  124. for (i = 0; i < pic->nb_refs; i++) {
  125. av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
  126. pic->refs[i]->display_order, pic->refs[i]->encode_order);
  127. }
  128. av_log(avctx, AV_LOG_DEBUG, ".\n");
  129. }
  130. av_assert0(pic->input_available && !pic->encode_issued);
  131. for (i = 0; i < pic->nb_refs; i++) {
  132. av_assert0(pic->refs[i]);
  133. // If we are serialised then the references must have already
  134. // completed. If not, they must have been issued but need not
  135. // have completed yet.
  136. if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
  137. av_assert0(pic->refs[i]->encode_complete);
  138. else
  139. av_assert0(pic->refs[i]->encode_issued);
  140. }
  141. av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
  142. pic->recon_image = av_frame_alloc();
  143. if (!pic->recon_image) {
  144. err = AVERROR(ENOMEM);
  145. goto fail;
  146. }
  147. err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
  148. if (err < 0) {
  149. err = AVERROR(ENOMEM);
  150. goto fail;
  151. }
  152. pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
  153. av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
  154. pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
  155. if (!pic->output_buffer_ref) {
  156. err = AVERROR(ENOMEM);
  157. goto fail;
  158. }
  159. pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
  160. av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
  161. pic->output_buffer);
  162. if (ctx->codec->picture_params_size > 0) {
  163. pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
  164. if (!pic->codec_picture_params)
  165. goto fail;
  166. memcpy(pic->codec_picture_params, ctx->codec_picture_params,
  167. ctx->codec->picture_params_size);
  168. } else {
  169. av_assert0(!ctx->codec_picture_params);
  170. }
  171. pic->nb_param_buffers = 0;
  172. if (pic->encode_order == 0) {
  173. // Global parameter buffers are set on the first picture only.
  174. for (i = 0; i < ctx->nb_global_params; i++) {
  175. err = vaapi_encode_make_param_buffer(avctx, pic,
  176. VAEncMiscParameterBufferType,
  177. (char*)ctx->global_params[i],
  178. ctx->global_params_size[i]);
  179. if (err < 0)
  180. goto fail;
  181. }
  182. }
  183. if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
  184. err = vaapi_encode_make_param_buffer(avctx, pic,
  185. VAEncSequenceParameterBufferType,
  186. ctx->codec_sequence_params,
  187. ctx->codec->sequence_params_size);
  188. if (err < 0)
  189. goto fail;
  190. }
  191. if (ctx->codec->init_picture_params) {
  192. err = ctx->codec->init_picture_params(avctx, pic);
  193. if (err < 0) {
  194. av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
  195. "parameters: %d.\n", err);
  196. goto fail;
  197. }
  198. err = vaapi_encode_make_param_buffer(avctx, pic,
  199. VAEncPictureParameterBufferType,
  200. pic->codec_picture_params,
  201. ctx->codec->picture_params_size);
  202. if (err < 0)
  203. goto fail;
  204. }
  205. if (pic->type == PICTURE_TYPE_IDR) {
  206. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
  207. ctx->codec->write_sequence_header) {
  208. bit_len = 8 * sizeof(data);
  209. err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
  210. if (err < 0) {
  211. av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
  212. "header: %d.\n", err);
  213. goto fail;
  214. }
  215. err = vaapi_encode_make_packed_header(avctx, pic,
  216. ctx->codec->sequence_header_type,
  217. data, bit_len);
  218. if (err < 0)
  219. goto fail;
  220. }
  221. }
  222. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
  223. ctx->codec->write_picture_header) {
  224. bit_len = 8 * sizeof(data);
  225. err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
  226. if (err < 0) {
  227. av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
  228. "header: %d.\n", err);
  229. goto fail;
  230. }
  231. err = vaapi_encode_make_packed_header(avctx, pic,
  232. ctx->codec->picture_header_type,
  233. data, bit_len);
  234. if (err < 0)
  235. goto fail;
  236. }
  237. if (ctx->codec->write_extra_buffer) {
  238. for (i = 0;; i++) {
  239. size_t len = sizeof(data);
  240. int type;
  241. err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
  242. data, &len);
  243. if (err == AVERROR_EOF)
  244. break;
  245. if (err < 0) {
  246. av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
  247. "buffer %d: %d.\n", i, err);
  248. goto fail;
  249. }
  250. err = vaapi_encode_make_param_buffer(avctx, pic, type,
  251. data, len);
  252. if (err < 0)
  253. goto fail;
  254. }
  255. }
  256. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
  257. ctx->codec->write_extra_header) {
  258. for (i = 0;; i++) {
  259. int type;
  260. bit_len = 8 * sizeof(data);
  261. err = ctx->codec->write_extra_header(avctx, pic, i, &type,
  262. data, &bit_len);
  263. if (err == AVERROR_EOF)
  264. break;
  265. if (err < 0) {
  266. av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
  267. "header %d: %d.\n", i, err);
  268. goto fail;
  269. }
  270. err = vaapi_encode_make_packed_header(avctx, pic, type,
  271. data, bit_len);
  272. if (err < 0)
  273. goto fail;
  274. }
  275. }
  276. av_assert0(pic->nb_slices <= MAX_PICTURE_SLICES);
  277. for (i = 0; i < pic->nb_slices; i++) {
  278. slice = av_mallocz(sizeof(*slice));
  279. if (!slice) {
  280. err = AVERROR(ENOMEM);
  281. goto fail;
  282. }
  283. pic->slices[i] = slice;
  284. if (ctx->codec->slice_params_size > 0) {
  285. slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
  286. if (!slice->codec_slice_params) {
  287. err = AVERROR(ENOMEM);
  288. goto fail;
  289. }
  290. }
  291. if (ctx->codec->init_slice_params) {
  292. err = ctx->codec->init_slice_params(avctx, pic, slice);
  293. if (err < 0) {
  294. av_log(avctx, AV_LOG_ERROR, "Failed to initalise slice "
  295. "parameters: %d.\n", err);
  296. goto fail;
  297. }
  298. }
  299. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
  300. ctx->codec->write_slice_header) {
  301. bit_len = 8 * sizeof(data);
  302. err = ctx->codec->write_slice_header(avctx, pic, slice,
  303. data, &bit_len);
  304. if (err < 0) {
  305. av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
  306. "header: %d.\n", err);
  307. goto fail;
  308. }
  309. err = vaapi_encode_make_packed_header(avctx, pic,
  310. ctx->codec->slice_header_type,
  311. data, bit_len);
  312. if (err < 0)
  313. goto fail;
  314. }
  315. if (ctx->codec->init_slice_params) {
  316. err = vaapi_encode_make_param_buffer(avctx, pic,
  317. VAEncSliceParameterBufferType,
  318. slice->codec_slice_params,
  319. ctx->codec->slice_params_size);
  320. if (err < 0)
  321. goto fail;
  322. }
  323. }
  324. vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
  325. pic->input_surface);
  326. if (vas != VA_STATUS_SUCCESS) {
  327. av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
  328. "%d (%s).\n", vas, vaErrorStr(vas));
  329. err = AVERROR(EIO);
  330. goto fail_with_picture;
  331. }
  332. vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
  333. pic->param_buffers, pic->nb_param_buffers);
  334. if (vas != VA_STATUS_SUCCESS) {
  335. av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
  336. "%d (%s).\n", vas, vaErrorStr(vas));
  337. err = AVERROR(EIO);
  338. goto fail_with_picture;
  339. }
  340. vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
  341. if (vas != VA_STATUS_SUCCESS) {
  342. av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
  343. "%d (%s).\n", vas, vaErrorStr(vas));
  344. err = AVERROR(EIO);
  345. // vaRenderPicture() has been called here, so we should not destroy
  346. // the parameter buffers unless separate destruction is required.
  347. if (ctx->hwctx->driver_quirks &
  348. AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
  349. goto fail;
  350. else
  351. goto fail_at_end;
  352. }
  353. if (ctx->hwctx->driver_quirks &
  354. AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
  355. for (i = 0; i < pic->nb_param_buffers; i++) {
  356. vas = vaDestroyBuffer(ctx->hwctx->display,
  357. pic->param_buffers[i]);
  358. if (vas != VA_STATUS_SUCCESS) {
  359. av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
  360. "param buffer %#x: %d (%s).\n",
  361. pic->param_buffers[i], vas, vaErrorStr(vas));
  362. // And ignore.
  363. }
  364. }
  365. }
  366. pic->encode_issued = 1;
  367. if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
  368. return vaapi_encode_wait(avctx, pic);
  369. else
  370. return 0;
  371. fail_with_picture:
  372. vaEndPicture(ctx->hwctx->display, ctx->va_context);
  373. fail:
  374. for(i = 0; i < pic->nb_param_buffers; i++)
  375. vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
  376. fail_at_end:
  377. av_freep(&pic->codec_picture_params);
  378. av_frame_free(&pic->recon_image);
  379. return err;
  380. }
  381. static int vaapi_encode_output(AVCodecContext *avctx,
  382. VAAPIEncodePicture *pic, AVPacket *pkt)
  383. {
  384. VAAPIEncodeContext *ctx = avctx->priv_data;
  385. VACodedBufferSegment *buf_list, *buf;
  386. VAStatus vas;
  387. int err;
  388. err = vaapi_encode_wait(avctx, pic);
  389. if (err < 0)
  390. return err;
  391. buf_list = NULL;
  392. vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
  393. (void**)&buf_list);
  394. if (vas != VA_STATUS_SUCCESS) {
  395. av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
  396. "%d (%s).\n", vas, vaErrorStr(vas));
  397. err = AVERROR(EIO);
  398. goto fail;
  399. }
  400. for (buf = buf_list; buf; buf = buf->next) {
  401. av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
  402. "(status %08x).\n", buf->size, buf->status);
  403. err = av_new_packet(pkt, buf->size);
  404. if (err < 0)
  405. goto fail_mapped;
  406. memcpy(pkt->data, buf->buf, buf->size);
  407. }
  408. if (pic->type == PICTURE_TYPE_IDR)
  409. pkt->flags |= AV_PKT_FLAG_KEY;
  410. pkt->pts = pic->pts;
  411. vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
  412. if (vas != VA_STATUS_SUCCESS) {
  413. av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
  414. "%d (%s).\n", vas, vaErrorStr(vas));
  415. err = AVERROR(EIO);
  416. goto fail;
  417. }
  418. av_buffer_unref(&pic->output_buffer_ref);
  419. pic->output_buffer = VA_INVALID_ID;
  420. av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
  421. pic->display_order, pic->encode_order);
  422. return 0;
  423. fail_mapped:
  424. vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
  425. fail:
  426. av_buffer_unref(&pic->output_buffer_ref);
  427. pic->output_buffer = VA_INVALID_ID;
  428. return err;
  429. }
  430. static int vaapi_encode_discard(AVCodecContext *avctx,
  431. VAAPIEncodePicture *pic)
  432. {
  433. vaapi_encode_wait(avctx, pic);
  434. if (pic->output_buffer_ref) {
  435. av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
  436. "%"PRId64"/%"PRId64".\n",
  437. pic->display_order, pic->encode_order);
  438. av_buffer_unref(&pic->output_buffer_ref);
  439. pic->output_buffer = VA_INVALID_ID;
  440. }
  441. return 0;
  442. }
  443. static VAAPIEncodePicture *vaapi_encode_alloc(void)
  444. {
  445. VAAPIEncodePicture *pic;
  446. pic = av_mallocz(sizeof(*pic));
  447. if (!pic)
  448. return NULL;
  449. pic->input_surface = VA_INVALID_ID;
  450. pic->recon_surface = VA_INVALID_ID;
  451. pic->output_buffer = VA_INVALID_ID;
  452. return pic;
  453. }
  454. static int vaapi_encode_free(AVCodecContext *avctx,
  455. VAAPIEncodePicture *pic)
  456. {
  457. int i;
  458. if (pic->encode_issued)
  459. vaapi_encode_discard(avctx, pic);
  460. for (i = 0; i < pic->nb_slices; i++) {
  461. av_freep(&pic->slices[i]->priv_data);
  462. av_freep(&pic->slices[i]->codec_slice_params);
  463. av_freep(&pic->slices[i]);
  464. }
  465. av_freep(&pic->codec_picture_params);
  466. av_frame_free(&pic->input_image);
  467. av_frame_free(&pic->recon_image);
  468. // Output buffer should already be destroyed.
  469. av_assert0(pic->output_buffer == VA_INVALID_ID);
  470. av_freep(&pic->priv_data);
  471. av_freep(&pic->codec_picture_params);
  472. av_free(pic);
  473. return 0;
  474. }
  475. static int vaapi_encode_step(AVCodecContext *avctx,
  476. VAAPIEncodePicture *target)
  477. {
  478. VAAPIEncodeContext *ctx = avctx->priv_data;
  479. VAAPIEncodePicture *pic;
  480. int i, err;
  481. if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING ||
  482. ctx->issue_mode == ISSUE_MODE_MINIMISE_LATENCY) {
  483. // These two modes are equivalent, except that we wait for
  484. // immediate completion on each operation if serialised.
  485. if (!target) {
  486. // No target, nothing to do yet.
  487. return 0;
  488. }
  489. if (target->encode_complete) {
  490. // Already done.
  491. return 0;
  492. }
  493. pic = target;
  494. for (i = 0; i < pic->nb_refs; i++) {
  495. if (!pic->refs[i]->encode_complete) {
  496. err = vaapi_encode_step(avctx, pic->refs[i]);
  497. if (err < 0)
  498. return err;
  499. }
  500. }
  501. err = vaapi_encode_issue(avctx, pic);
  502. if (err < 0)
  503. return err;
  504. } else if (ctx->issue_mode == ISSUE_MODE_MAXIMISE_THROUGHPUT) {
  505. int activity;
  506. do {
  507. activity = 0;
  508. for (pic = ctx->pic_start; pic; pic = pic->next) {
  509. if (!pic->input_available || pic->encode_issued)
  510. continue;
  511. for (i = 0; i < pic->nb_refs; i++) {
  512. if (!pic->refs[i]->encode_issued)
  513. break;
  514. }
  515. if (i < pic->nb_refs)
  516. continue;
  517. err = vaapi_encode_issue(avctx, pic);
  518. if (err < 0)
  519. return err;
  520. activity = 1;
  521. }
  522. } while(activity);
  523. if (target) {
  524. av_assert0(target->encode_issued && "broken dependencies?");
  525. }
  526. } else {
  527. av_assert0(0);
  528. }
  529. return 0;
  530. }
  531. static int vaapi_encode_get_next(AVCodecContext *avctx,
  532. VAAPIEncodePicture **pic_out)
  533. {
  534. VAAPIEncodeContext *ctx = avctx->priv_data;
  535. VAAPIEncodePicture *start, *end, *pic;
  536. int i;
  537. for (pic = ctx->pic_start; pic; pic = pic->next) {
  538. if (pic->next)
  539. av_assert0(pic->display_order + 1 == pic->next->display_order);
  540. if (pic->display_order == ctx->input_order) {
  541. *pic_out = pic;
  542. return 0;
  543. }
  544. }
  545. if (ctx->input_order == 0) {
  546. // First frame is always an IDR frame.
  547. av_assert0(!ctx->pic_start && !ctx->pic_end);
  548. pic = vaapi_encode_alloc();
  549. if (!pic)
  550. return AVERROR(ENOMEM);
  551. pic->type = PICTURE_TYPE_IDR;
  552. pic->display_order = 0;
  553. pic->encode_order = 0;
  554. ctx->pic_start = ctx->pic_end = pic;
  555. *pic_out = pic;
  556. return 0;
  557. }
  558. pic = vaapi_encode_alloc();
  559. if (!pic)
  560. return AVERROR(ENOMEM);
  561. if (ctx->p_per_i == 0 || ctx->p_counter == ctx->p_per_i) {
  562. if (ctx->i_per_idr == 0 || ctx->i_counter == ctx->i_per_idr) {
  563. pic->type = PICTURE_TYPE_IDR;
  564. ctx->i_counter = 0;
  565. } else {
  566. pic->type = PICTURE_TYPE_I;
  567. ++ctx->i_counter;
  568. }
  569. ctx->p_counter = 0;
  570. } else {
  571. pic->type = PICTURE_TYPE_P;
  572. pic->refs[0] = ctx->pic_end;
  573. pic->nb_refs = 1;
  574. ++ctx->p_counter;
  575. }
  576. start = end = pic;
  577. if (pic->type != PICTURE_TYPE_IDR) {
  578. // If that was not an IDR frame, add B-frames display-before and
  579. // encode-after it.
  580. for (i = 0; i < ctx->b_per_p; i++) {
  581. pic = vaapi_encode_alloc();
  582. if (!pic)
  583. goto fail;
  584. pic->type = PICTURE_TYPE_B;
  585. pic->refs[0] = ctx->pic_end;
  586. pic->refs[1] = end;
  587. pic->nb_refs = 2;
  588. pic->next = start;
  589. pic->display_order = ctx->input_order + ctx->b_per_p - i - 1;
  590. pic->encode_order = pic->display_order + 1;
  591. start = pic;
  592. }
  593. }
  594. for (i = 0, pic = start; pic; i++, pic = pic->next) {
  595. pic->display_order = ctx->input_order + i;
  596. if (end->type == PICTURE_TYPE_IDR)
  597. pic->encode_order = ctx->input_order + i;
  598. else if (pic == end)
  599. pic->encode_order = ctx->input_order;
  600. else
  601. pic->encode_order = ctx->input_order + i + 1;
  602. }
  603. av_assert0(ctx->pic_end);
  604. ctx->pic_end->next = start;
  605. ctx->pic_end = end;
  606. *pic_out = start;
  607. av_log(avctx, AV_LOG_DEBUG, "Pictures:");
  608. for (pic = ctx->pic_start; pic; pic = pic->next) {
  609. av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
  610. picture_type_name[pic->type],
  611. pic->display_order, pic->encode_order);
  612. }
  613. av_log(avctx, AV_LOG_DEBUG, "\n");
  614. return 0;
  615. fail:
  616. while (start) {
  617. pic = start->next;
  618. vaapi_encode_free(avctx, start);
  619. start = pic;
  620. }
  621. return AVERROR(ENOMEM);
  622. }
  623. static int vaapi_encode_mangle_end(AVCodecContext *avctx)
  624. {
  625. VAAPIEncodeContext *ctx = avctx->priv_data;
  626. VAAPIEncodePicture *pic, *last_pic, *next;
  627. // Find the last picture we actually have input for.
  628. for (pic = ctx->pic_start; pic; pic = pic->next) {
  629. if (!pic->input_available)
  630. break;
  631. last_pic = pic;
  632. }
  633. if (pic) {
  634. av_assert0(last_pic);
  635. if (last_pic->type == PICTURE_TYPE_B) {
  636. // Some fixing up is required. Change the type of this
  637. // picture to P, then modify preceding B references which
  638. // point beyond it to point at it instead.
  639. last_pic->type = PICTURE_TYPE_P;
  640. last_pic->encode_order = last_pic->refs[1]->encode_order;
  641. for (pic = ctx->pic_start; pic != last_pic; pic = pic->next) {
  642. if (pic->type == PICTURE_TYPE_B &&
  643. pic->refs[1] == last_pic->refs[1])
  644. pic->refs[1] = last_pic;
  645. }
  646. last_pic->nb_refs = 1;
  647. last_pic->refs[1] = NULL;
  648. } else {
  649. // We can use the current structure (no references point
  650. // beyond the end), but there are unused pics to discard.
  651. }
  652. // Discard all following pics, they will never be used.
  653. for (pic = last_pic->next; pic; pic = next) {
  654. next = pic->next;
  655. vaapi_encode_free(avctx, pic);
  656. }
  657. last_pic->next = NULL;
  658. ctx->pic_end = last_pic;
  659. } else {
  660. // Input is available for all pictures, so we don't need to
  661. // mangle anything.
  662. }
  663. av_log(avctx, AV_LOG_DEBUG, "Pictures at end of stream:");
  664. for (pic = ctx->pic_start; pic; pic = pic->next) {
  665. av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
  666. picture_type_name[pic->type],
  667. pic->display_order, pic->encode_order);
  668. }
  669. av_log(avctx, AV_LOG_DEBUG, "\n");
  670. return 0;
  671. }
  672. static int vaapi_encode_clear_old(AVCodecContext *avctx)
  673. {
  674. VAAPIEncodeContext *ctx = avctx->priv_data;
  675. VAAPIEncodePicture *pic, *old;
  676. int i;
  677. while (ctx->pic_start != ctx->pic_end) {
  678. old = ctx->pic_start;
  679. if (old->encode_order > ctx->output_order)
  680. break;
  681. for (pic = old->next; pic; pic = pic->next) {
  682. if (pic->encode_complete)
  683. continue;
  684. for (i = 0; i < pic->nb_refs; i++) {
  685. if (pic->refs[i] == old) {
  686. // We still need this picture because it's referred to
  687. // directly by a later one, so it and all following
  688. // pictures have to stay.
  689. return 0;
  690. }
  691. }
  692. }
  693. pic = ctx->pic_start;
  694. ctx->pic_start = pic->next;
  695. vaapi_encode_free(avctx, pic);
  696. }
  697. return 0;
  698. }
  699. int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
  700. const AVFrame *input_image, int *got_packet)
  701. {
  702. VAAPIEncodeContext *ctx = avctx->priv_data;
  703. VAAPIEncodePicture *pic;
  704. int err;
  705. if (input_image) {
  706. av_log(avctx, AV_LOG_DEBUG, "Encode frame: %ux%u (%"PRId64").\n",
  707. input_image->width, input_image->height, input_image->pts);
  708. err = vaapi_encode_get_next(avctx, &pic);
  709. if (err) {
  710. av_log(avctx, AV_LOG_ERROR, "Input setup failed: %d.\n", err);
  711. return err;
  712. }
  713. pic->input_image = av_frame_alloc();
  714. if (!pic->input_image) {
  715. err = AVERROR(ENOMEM);
  716. goto fail;
  717. }
  718. err = av_frame_ref(pic->input_image, input_image);
  719. if (err < 0)
  720. goto fail;
  721. pic->input_surface = (VASurfaceID)(uintptr_t)input_image->data[3];
  722. pic->pts = input_image->pts;
  723. if (ctx->input_order == 0)
  724. ctx->first_pts = pic->pts;
  725. if (ctx->input_order == ctx->decode_delay)
  726. ctx->dts_pts_diff = pic->pts - ctx->first_pts;
  727. if (ctx->output_delay > 0)
  728. ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
  729. pic->input_available = 1;
  730. } else {
  731. if (!ctx->end_of_stream) {
  732. err = vaapi_encode_mangle_end(avctx);
  733. if (err < 0)
  734. goto fail;
  735. ctx->end_of_stream = 1;
  736. }
  737. }
  738. ++ctx->input_order;
  739. ++ctx->output_order;
  740. av_assert0(ctx->output_order + ctx->output_delay + 1 == ctx->input_order);
  741. for (pic = ctx->pic_start; pic; pic = pic->next)
  742. if (pic->encode_order == ctx->output_order)
  743. break;
  744. // pic can be null here if we don't have a specific target in this
  745. // iteration. We might still issue encodes if things can be overlapped,
  746. // even though we don't intend to output anything.
  747. err = vaapi_encode_step(avctx, pic);
  748. if (err < 0) {
  749. av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
  750. goto fail;
  751. }
  752. if (!pic) {
  753. *got_packet = 0;
  754. } else {
  755. err = vaapi_encode_output(avctx, pic, pkt);
  756. if (err < 0) {
  757. av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
  758. goto fail;
  759. }
  760. if (ctx->output_delay == 0) {
  761. pkt->dts = pkt->pts;
  762. } else if (ctx->output_order < ctx->decode_delay) {
  763. if (ctx->ts_ring[ctx->output_order] < INT64_MIN + ctx->dts_pts_diff)
  764. pkt->dts = INT64_MIN;
  765. else
  766. pkt->dts = ctx->ts_ring[ctx->output_order] - ctx->dts_pts_diff;
  767. } else {
  768. pkt->dts = ctx->ts_ring[(ctx->output_order - ctx->decode_delay) %
  769. (3 * ctx->output_delay)];
  770. }
  771. *got_packet = 1;
  772. }
  773. err = vaapi_encode_clear_old(avctx);
  774. if (err < 0) {
  775. av_log(avctx, AV_LOG_ERROR, "List clearing failed: %d.\n", err);
  776. goto fail;
  777. }
  778. return 0;
  779. fail:
  780. // Unclear what to clean up on failure. There are probably some things we
  781. // could do usefully clean up here, but for now just leave them for uninit()
  782. // to do instead.
  783. return err;
  784. }
  785. static av_cold int vaapi_encode_config_attributes(AVCodecContext *avctx)
  786. {
  787. VAAPIEncodeContext *ctx = avctx->priv_data;
  788. VAStatus vas;
  789. int i, n, err;
  790. VAProfile *profiles = NULL;
  791. VAEntrypoint *entrypoints = NULL;
  792. VAConfigAttrib attr[] = {
  793. { VAConfigAttribRTFormat },
  794. { VAConfigAttribRateControl },
  795. { VAConfigAttribEncMaxRefFrames },
  796. { VAConfigAttribEncPackedHeaders },
  797. };
  798. n = vaMaxNumProfiles(ctx->hwctx->display);
  799. profiles = av_malloc_array(n, sizeof(VAProfile));
  800. if (!profiles) {
  801. err = AVERROR(ENOMEM);
  802. goto fail;
  803. }
  804. vas = vaQueryConfigProfiles(ctx->hwctx->display, profiles, &n);
  805. if (vas != VA_STATUS_SUCCESS) {
  806. av_log(ctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
  807. vas, vaErrorStr(vas));
  808. err = AVERROR(ENOSYS);
  809. goto fail;
  810. }
  811. for (i = 0; i < n; i++) {
  812. if (profiles[i] == ctx->va_profile)
  813. break;
  814. }
  815. if (i >= n) {
  816. av_log(ctx, AV_LOG_ERROR, "Encoding profile not found (%d).\n",
  817. ctx->va_profile);
  818. err = AVERROR(ENOSYS);
  819. goto fail;
  820. }
  821. n = vaMaxNumEntrypoints(ctx->hwctx->display);
  822. entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
  823. if (!entrypoints) {
  824. err = AVERROR(ENOMEM);
  825. goto fail;
  826. }
  827. vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
  828. entrypoints, &n);
  829. if (vas != VA_STATUS_SUCCESS) {
  830. av_log(ctx, AV_LOG_ERROR, "Failed to query entrypoints for "
  831. "profile %u: %d (%s).\n", ctx->va_profile,
  832. vas, vaErrorStr(vas));
  833. err = AVERROR(ENOSYS);
  834. goto fail;
  835. }
  836. for (i = 0; i < n; i++) {
  837. if (entrypoints[i] == ctx->va_entrypoint)
  838. break;
  839. }
  840. if (i >= n) {
  841. av_log(ctx, AV_LOG_ERROR, "Encoding entrypoint not found "
  842. "(%d / %d).\n", ctx->va_profile, ctx->va_entrypoint);
  843. err = AVERROR(ENOSYS);
  844. goto fail;
  845. }
  846. vas = vaGetConfigAttributes(ctx->hwctx->display,
  847. ctx->va_profile, ctx->va_entrypoint,
  848. attr, FF_ARRAY_ELEMS(attr));
  849. if (vas != VA_STATUS_SUCCESS) {
  850. av_log(avctx, AV_LOG_ERROR, "Failed to fetch config "
  851. "attributes: %d (%s).\n", vas, vaErrorStr(vas));
  852. return AVERROR(EINVAL);
  853. }
  854. for (i = 0; i < FF_ARRAY_ELEMS(attr); i++) {
  855. if (attr[i].value == VA_ATTRIB_NOT_SUPPORTED) {
  856. // Unfortunately we have to treat this as "don't know" and hope
  857. // for the best, because the Intel MJPEG encoder returns this
  858. // for all the interesting attributes.
  859. continue;
  860. }
  861. switch (attr[i].type) {
  862. case VAConfigAttribRTFormat:
  863. if (!(ctx->va_rt_format & attr[i].value)) {
  864. av_log(avctx, AV_LOG_ERROR, "Surface RT format %#x "
  865. "is not supported (mask %#x).\n",
  866. ctx->va_rt_format, attr[i].value);
  867. err = AVERROR(EINVAL);
  868. goto fail;
  869. }
  870. ctx->config_attributes[ctx->nb_config_attributes++] =
  871. (VAConfigAttrib) {
  872. .type = VAConfigAttribRTFormat,
  873. .value = ctx->va_rt_format,
  874. };
  875. break;
  876. case VAConfigAttribRateControl:
  877. if (!(ctx->va_rc_mode & attr[i].value)) {
  878. av_log(avctx, AV_LOG_ERROR, "Rate control mode %#x "
  879. "is not supported (mask: %#x).\n",
  880. ctx->va_rc_mode, attr[i].value);
  881. err = AVERROR(EINVAL);
  882. goto fail;
  883. }
  884. ctx->config_attributes[ctx->nb_config_attributes++] =
  885. (VAConfigAttrib) {
  886. .type = VAConfigAttribRateControl,
  887. .value = ctx->va_rc_mode,
  888. };
  889. break;
  890. case VAConfigAttribEncMaxRefFrames:
  891. {
  892. unsigned int ref_l0 = attr[i].value & 0xffff;
  893. unsigned int ref_l1 = (attr[i].value >> 16) & 0xffff;
  894. if (avctx->gop_size > 1 && ref_l0 < 1) {
  895. av_log(avctx, AV_LOG_ERROR, "P frames are not "
  896. "supported (%#x).\n", attr[i].value);
  897. err = AVERROR(EINVAL);
  898. goto fail;
  899. }
  900. if (avctx->max_b_frames > 0 && ref_l1 < 1) {
  901. av_log(avctx, AV_LOG_ERROR, "B frames are not "
  902. "supported (%#x).\n", attr[i].value);
  903. err = AVERROR(EINVAL);
  904. goto fail;
  905. }
  906. }
  907. break;
  908. case VAConfigAttribEncPackedHeaders:
  909. if (ctx->va_packed_headers & ~attr[i].value) {
  910. // This isn't fatal, but packed headers are always
  911. // preferable because they are under our control.
  912. // When absent, the driver is generating them and some
  913. // features may not work (e.g. VUI or SEI in H.264).
  914. av_log(avctx, AV_LOG_WARNING, "Warning: some packed "
  915. "headers are not supported (want %#x, got %#x).\n",
  916. ctx->va_packed_headers, attr[i].value);
  917. ctx->va_packed_headers &= attr[i].value;
  918. }
  919. ctx->config_attributes[ctx->nb_config_attributes++] =
  920. (VAConfigAttrib) {
  921. .type = VAConfigAttribEncPackedHeaders,
  922. .value = ctx->va_packed_headers,
  923. };
  924. break;
  925. default:
  926. av_assert0(0 && "Unexpected config attribute.");
  927. }
  928. }
  929. err = 0;
  930. fail:
  931. av_freep(&profiles);
  932. av_freep(&entrypoints);
  933. return err;
  934. }
  935. static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
  936. {
  937. VAAPIEncodeContext *ctx = avctx->priv_data;
  938. int hrd_buffer_size;
  939. int hrd_initial_buffer_fullness;
  940. if (avctx->rc_buffer_size)
  941. hrd_buffer_size = avctx->rc_buffer_size;
  942. else
  943. hrd_buffer_size = avctx->bit_rate;
  944. if (avctx->rc_initial_buffer_occupancy)
  945. hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
  946. else
  947. hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
  948. ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
  949. ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
  950. .bits_per_second = avctx->bit_rate,
  951. .target_percentage = 66,
  952. .window_size = 1000,
  953. .initial_qp = (avctx->qmax >= 0 ? avctx->qmax : 40),
  954. .min_qp = (avctx->qmin >= 0 ? avctx->qmin : 18),
  955. .basic_unit_size = 0,
  956. };
  957. ctx->global_params[ctx->nb_global_params] =
  958. &ctx->rc_params.misc;
  959. ctx->global_params_size[ctx->nb_global_params++] =
  960. sizeof(ctx->rc_params);
  961. ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
  962. ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
  963. .initial_buffer_fullness = hrd_initial_buffer_fullness,
  964. .buffer_size = hrd_buffer_size,
  965. };
  966. ctx->global_params[ctx->nb_global_params] =
  967. &ctx->hrd_params.misc;
  968. ctx->global_params_size[ctx->nb_global_params++] =
  969. sizeof(ctx->hrd_params);
  970. return 0;
  971. }
  972. static void vaapi_encode_free_output_buffer(void *opaque,
  973. uint8_t *data)
  974. {
  975. AVCodecContext *avctx = opaque;
  976. VAAPIEncodeContext *ctx = avctx->priv_data;
  977. VABufferID buffer_id;
  978. buffer_id = (VABufferID)(uintptr_t)data;
  979. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  980. av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
  981. }
  982. static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
  983. int size)
  984. {
  985. AVCodecContext *avctx = opaque;
  986. VAAPIEncodeContext *ctx = avctx->priv_data;
  987. VABufferID buffer_id;
  988. VAStatus vas;
  989. AVBufferRef *ref;
  990. // The output buffer size is fixed, so it needs to be large enough
  991. // to hold the largest possible compressed frame. We assume here
  992. // that the uncompressed frame plus some header data is an upper
  993. // bound on that.
  994. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  995. VAEncCodedBufferType,
  996. 3 * ctx->surface_width * ctx->surface_height +
  997. (1 << 16), 1, 0, &buffer_id);
  998. if (vas != VA_STATUS_SUCCESS) {
  999. av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
  1000. "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
  1001. return NULL;
  1002. }
  1003. av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
  1004. ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
  1005. sizeof(buffer_id),
  1006. &vaapi_encode_free_output_buffer,
  1007. avctx, AV_BUFFER_FLAG_READONLY);
  1008. if (!ref) {
  1009. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  1010. return NULL;
  1011. }
  1012. return ref;
  1013. }
  1014. static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
  1015. {
  1016. VAAPIEncodeContext *ctx = avctx->priv_data;
  1017. AVVAAPIHWConfig *hwconfig = NULL;
  1018. AVHWFramesConstraints *constraints = NULL;
  1019. enum AVPixelFormat recon_format;
  1020. int err, i;
  1021. hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
  1022. if (!hwconfig) {
  1023. err = AVERROR(ENOMEM);
  1024. goto fail;
  1025. }
  1026. hwconfig->config_id = ctx->va_config;
  1027. constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
  1028. hwconfig);
  1029. if (!constraints) {
  1030. err = AVERROR(ENOMEM);
  1031. goto fail;
  1032. }
  1033. // Probably we can use the input surface format as the surface format
  1034. // of the reconstructed frames. If not, we just pick the first (only?)
  1035. // format in the valid list and hope that it all works.
  1036. recon_format = AV_PIX_FMT_NONE;
  1037. if (constraints->valid_sw_formats) {
  1038. for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
  1039. if (ctx->input_frames->sw_format ==
  1040. constraints->valid_sw_formats[i]) {
  1041. recon_format = ctx->input_frames->sw_format;
  1042. break;
  1043. }
  1044. }
  1045. if (recon_format == AV_PIX_FMT_NONE) {
  1046. // No match. Just use the first in the supported list and
  1047. // hope for the best.
  1048. recon_format = constraints->valid_sw_formats[0];
  1049. }
  1050. } else {
  1051. // No idea what to use; copy input format.
  1052. recon_format = ctx->input_frames->sw_format;
  1053. }
  1054. av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
  1055. "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
  1056. if (ctx->surface_width < constraints->min_width ||
  1057. ctx->surface_height < constraints->min_height ||
  1058. ctx->surface_width > constraints->max_width ||
  1059. ctx->surface_height > constraints->max_height) {
  1060. av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
  1061. "size %dx%d (constraints: width %d-%d height %d-%d).\n",
  1062. ctx->surface_width, ctx->surface_height,
  1063. constraints->min_width, constraints->max_width,
  1064. constraints->min_height, constraints->max_height);
  1065. err = AVERROR(EINVAL);
  1066. goto fail;
  1067. }
  1068. av_freep(&hwconfig);
  1069. av_hwframe_constraints_free(&constraints);
  1070. ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
  1071. if (!ctx->recon_frames_ref) {
  1072. err = AVERROR(ENOMEM);
  1073. goto fail;
  1074. }
  1075. ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
  1076. ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
  1077. ctx->recon_frames->sw_format = recon_format;
  1078. ctx->recon_frames->width = ctx->surface_width;
  1079. ctx->recon_frames->height = ctx->surface_height;
  1080. ctx->recon_frames->initial_pool_size =
  1081. avctx->max_b_frames + 3;
  1082. err = av_hwframe_ctx_init(ctx->recon_frames_ref);
  1083. if (err < 0) {
  1084. av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
  1085. "frame context: %d.\n", err);
  1086. goto fail;
  1087. }
  1088. err = 0;
  1089. fail:
  1090. av_freep(&hwconfig);
  1091. av_hwframe_constraints_free(&constraints);
  1092. return err;
  1093. }
  1094. av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
  1095. {
  1096. VAAPIEncodeContext *ctx = avctx->priv_data;
  1097. AVVAAPIFramesContext *recon_hwctx = NULL;
  1098. VAStatus vas;
  1099. int err;
  1100. if (!avctx->hw_frames_ctx) {
  1101. av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
  1102. "required to associate the encoding device.\n");
  1103. return AVERROR(EINVAL);
  1104. }
  1105. ctx->codec_options = ctx->codec_options_data;
  1106. ctx->va_config = VA_INVALID_ID;
  1107. ctx->va_context = VA_INVALID_ID;
  1108. ctx->priv_data = av_mallocz(ctx->codec->priv_data_size);
  1109. if (!ctx->priv_data) {
  1110. err = AVERROR(ENOMEM);
  1111. goto fail;
  1112. }
  1113. ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
  1114. if (!ctx->input_frames_ref) {
  1115. err = AVERROR(ENOMEM);
  1116. goto fail;
  1117. }
  1118. ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
  1119. ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
  1120. if (!ctx->device_ref) {
  1121. err = AVERROR(ENOMEM);
  1122. goto fail;
  1123. }
  1124. ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
  1125. ctx->hwctx = ctx->device->hwctx;
  1126. err = vaapi_encode_config_attributes(avctx);
  1127. if (err < 0)
  1128. goto fail;
  1129. vas = vaCreateConfig(ctx->hwctx->display,
  1130. ctx->va_profile, ctx->va_entrypoint,
  1131. ctx->config_attributes, ctx->nb_config_attributes,
  1132. &ctx->va_config);
  1133. if (vas != VA_STATUS_SUCCESS) {
  1134. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  1135. "configuration: %d (%s).\n", vas, vaErrorStr(vas));
  1136. err = AVERROR(EIO);
  1137. goto fail;
  1138. }
  1139. err = vaapi_encode_create_recon_frames(avctx);
  1140. if (err < 0)
  1141. goto fail;
  1142. recon_hwctx = ctx->recon_frames->hwctx;
  1143. vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
  1144. ctx->surface_width, ctx->surface_height,
  1145. VA_PROGRESSIVE,
  1146. recon_hwctx->surface_ids,
  1147. recon_hwctx->nb_surfaces,
  1148. &ctx->va_context);
  1149. if (vas != VA_STATUS_SUCCESS) {
  1150. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  1151. "context: %d (%s).\n", vas, vaErrorStr(vas));
  1152. err = AVERROR(EIO);
  1153. goto fail;
  1154. }
  1155. ctx->output_buffer_pool =
  1156. av_buffer_pool_init2(sizeof(VABufferID), avctx,
  1157. &vaapi_encode_alloc_output_buffer, NULL);
  1158. if (!ctx->output_buffer_pool) {
  1159. err = AVERROR(ENOMEM);
  1160. goto fail;
  1161. }
  1162. if (ctx->va_rc_mode & ~VA_RC_CQP) {
  1163. err = vaapi_encode_init_rate_control(avctx);
  1164. if (err < 0)
  1165. goto fail;
  1166. }
  1167. if (ctx->codec->configure) {
  1168. err = ctx->codec->configure(avctx);
  1169. if (err < 0)
  1170. goto fail;
  1171. }
  1172. ctx->input_order = 0;
  1173. ctx->output_delay = avctx->max_b_frames;
  1174. ctx->decode_delay = 1;
  1175. ctx->output_order = - ctx->output_delay - 1;
  1176. // Currently we never generate I frames, only IDR.
  1177. ctx->i_per_idr = 0;
  1178. ctx->p_per_i = ((avctx->gop_size + avctx->max_b_frames) /
  1179. (avctx->max_b_frames + 1));
  1180. ctx->b_per_p = avctx->max_b_frames;
  1181. if (ctx->codec->sequence_params_size > 0) {
  1182. ctx->codec_sequence_params =
  1183. av_mallocz(ctx->codec->sequence_params_size);
  1184. if (!ctx->codec_sequence_params) {
  1185. err = AVERROR(ENOMEM);
  1186. goto fail;
  1187. }
  1188. }
  1189. if (ctx->codec->picture_params_size > 0) {
  1190. ctx->codec_picture_params =
  1191. av_mallocz(ctx->codec->picture_params_size);
  1192. if (!ctx->codec_picture_params) {
  1193. err = AVERROR(ENOMEM);
  1194. goto fail;
  1195. }
  1196. }
  1197. if (ctx->codec->init_sequence_params) {
  1198. err = ctx->codec->init_sequence_params(avctx);
  1199. if (err < 0) {
  1200. av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
  1201. "failed: %d.\n", err);
  1202. goto fail;
  1203. }
  1204. }
  1205. // This should be configurable somehow. (Needs testing on a machine
  1206. // where it actually overlaps properly, though.)
  1207. ctx->issue_mode = ISSUE_MODE_MAXIMISE_THROUGHPUT;
  1208. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
  1209. ctx->codec->write_sequence_header) {
  1210. char data[MAX_PARAM_BUFFER_SIZE];
  1211. size_t bit_len = 8 * sizeof(data);
  1212. err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
  1213. if (err < 0) {
  1214. av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
  1215. "for extradata: %d.\n", err);
  1216. goto fail;
  1217. } else {
  1218. avctx->extradata_size = (bit_len + 7) / 8;
  1219. avctx->extradata = av_mallocz(avctx->extradata_size +
  1220. AV_INPUT_BUFFER_PADDING_SIZE);
  1221. if (!avctx->extradata) {
  1222. err = AVERROR(ENOMEM);
  1223. goto fail;
  1224. }
  1225. memcpy(avctx->extradata, data, avctx->extradata_size);
  1226. }
  1227. }
  1228. return 0;
  1229. fail:
  1230. ff_vaapi_encode_close(avctx);
  1231. return err;
  1232. }
  1233. av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
  1234. {
  1235. VAAPIEncodeContext *ctx = avctx->priv_data;
  1236. VAAPIEncodePicture *pic, *next;
  1237. for (pic = ctx->pic_start; pic; pic = next) {
  1238. next = pic->next;
  1239. vaapi_encode_free(avctx, pic);
  1240. }
  1241. if (ctx->va_context != VA_INVALID_ID) {
  1242. vaDestroyContext(ctx->hwctx->display, ctx->va_context);
  1243. ctx->va_context = VA_INVALID_ID;
  1244. }
  1245. if (ctx->va_config != VA_INVALID_ID) {
  1246. vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
  1247. ctx->va_config = VA_INVALID_ID;
  1248. }
  1249. av_buffer_pool_uninit(&ctx->output_buffer_pool);
  1250. av_freep(&ctx->codec_sequence_params);
  1251. av_freep(&ctx->codec_picture_params);
  1252. av_buffer_unref(&ctx->recon_frames_ref);
  1253. av_buffer_unref(&ctx->input_frames_ref);
  1254. av_buffer_unref(&ctx->device_ref);
  1255. av_freep(&ctx->priv_data);
  1256. return 0;
  1257. }