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.

1527 lines
50KB

  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 * 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. 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. slice->index = i;
  284. pic->slices[i] = slice;
  285. if (ctx->codec->slice_params_size > 0) {
  286. slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
  287. if (!slice->codec_slice_params) {
  288. err = AVERROR(ENOMEM);
  289. goto fail;
  290. }
  291. }
  292. if (ctx->codec->init_slice_params) {
  293. err = ctx->codec->init_slice_params(avctx, pic, slice);
  294. if (err < 0) {
  295. av_log(avctx, AV_LOG_ERROR, "Failed to initalise slice "
  296. "parameters: %d.\n", err);
  297. goto fail;
  298. }
  299. }
  300. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
  301. ctx->codec->write_slice_header) {
  302. bit_len = 8 * sizeof(data);
  303. err = ctx->codec->write_slice_header(avctx, pic, slice,
  304. data, &bit_len);
  305. if (err < 0) {
  306. av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
  307. "header: %d.\n", err);
  308. goto fail;
  309. }
  310. err = vaapi_encode_make_packed_header(avctx, pic,
  311. ctx->codec->slice_header_type,
  312. data, bit_len);
  313. if (err < 0)
  314. goto fail;
  315. }
  316. if (ctx->codec->init_slice_params) {
  317. err = vaapi_encode_make_param_buffer(avctx, pic,
  318. VAEncSliceParameterBufferType,
  319. slice->codec_slice_params,
  320. ctx->codec->slice_params_size);
  321. if (err < 0)
  322. goto fail;
  323. }
  324. }
  325. vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
  326. pic->input_surface);
  327. if (vas != VA_STATUS_SUCCESS) {
  328. av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
  329. "%d (%s).\n", vas, vaErrorStr(vas));
  330. err = AVERROR(EIO);
  331. goto fail_with_picture;
  332. }
  333. vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
  334. pic->param_buffers, pic->nb_param_buffers);
  335. if (vas != VA_STATUS_SUCCESS) {
  336. av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
  337. "%d (%s).\n", vas, vaErrorStr(vas));
  338. err = AVERROR(EIO);
  339. goto fail_with_picture;
  340. }
  341. vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
  342. if (vas != VA_STATUS_SUCCESS) {
  343. av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
  344. "%d (%s).\n", vas, vaErrorStr(vas));
  345. err = AVERROR(EIO);
  346. // vaRenderPicture() has been called here, so we should not destroy
  347. // the parameter buffers unless separate destruction is required.
  348. if (ctx->hwctx->driver_quirks &
  349. AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
  350. goto fail;
  351. else
  352. goto fail_at_end;
  353. }
  354. if (ctx->hwctx->driver_quirks &
  355. AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
  356. for (i = 0; i < pic->nb_param_buffers; i++) {
  357. vas = vaDestroyBuffer(ctx->hwctx->display,
  358. pic->param_buffers[i]);
  359. if (vas != VA_STATUS_SUCCESS) {
  360. av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
  361. "param buffer %#x: %d (%s).\n",
  362. pic->param_buffers[i], vas, vaErrorStr(vas));
  363. // And ignore.
  364. }
  365. }
  366. }
  367. pic->encode_issued = 1;
  368. if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
  369. return vaapi_encode_wait(avctx, pic);
  370. else
  371. return 0;
  372. fail_with_picture:
  373. vaEndPicture(ctx->hwctx->display, ctx->va_context);
  374. fail:
  375. for(i = 0; i < pic->nb_param_buffers; i++)
  376. vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
  377. fail_at_end:
  378. av_freep(&pic->codec_picture_params);
  379. av_frame_free(&pic->recon_image);
  380. av_buffer_unref(&pic->output_buffer_ref);
  381. pic->output_buffer = VA_INVALID_ID;
  382. return err;
  383. }
  384. static int vaapi_encode_output(AVCodecContext *avctx,
  385. VAAPIEncodePicture *pic, AVPacket *pkt)
  386. {
  387. VAAPIEncodeContext *ctx = avctx->priv_data;
  388. VACodedBufferSegment *buf_list, *buf;
  389. VAStatus vas;
  390. int err;
  391. err = vaapi_encode_wait(avctx, pic);
  392. if (err < 0)
  393. return err;
  394. buf_list = NULL;
  395. vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
  396. (void**)&buf_list);
  397. if (vas != VA_STATUS_SUCCESS) {
  398. av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
  399. "%d (%s).\n", vas, vaErrorStr(vas));
  400. err = AVERROR(EIO);
  401. goto fail;
  402. }
  403. for (buf = buf_list; buf; buf = buf->next) {
  404. av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
  405. "(status %08x).\n", buf->size, buf->status);
  406. err = av_new_packet(pkt, buf->size);
  407. if (err < 0)
  408. goto fail_mapped;
  409. memcpy(pkt->data, buf->buf, buf->size);
  410. }
  411. if (pic->type == PICTURE_TYPE_IDR)
  412. pkt->flags |= AV_PKT_FLAG_KEY;
  413. pkt->pts = pic->pts;
  414. vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
  415. if (vas != VA_STATUS_SUCCESS) {
  416. av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
  417. "%d (%s).\n", vas, vaErrorStr(vas));
  418. err = AVERROR(EIO);
  419. goto fail;
  420. }
  421. av_buffer_unref(&pic->output_buffer_ref);
  422. pic->output_buffer = VA_INVALID_ID;
  423. av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
  424. pic->display_order, pic->encode_order);
  425. return 0;
  426. fail_mapped:
  427. vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
  428. fail:
  429. av_buffer_unref(&pic->output_buffer_ref);
  430. pic->output_buffer = VA_INVALID_ID;
  431. return err;
  432. }
  433. static int vaapi_encode_discard(AVCodecContext *avctx,
  434. VAAPIEncodePicture *pic)
  435. {
  436. vaapi_encode_wait(avctx, pic);
  437. if (pic->output_buffer_ref) {
  438. av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
  439. "%"PRId64"/%"PRId64".\n",
  440. pic->display_order, pic->encode_order);
  441. av_buffer_unref(&pic->output_buffer_ref);
  442. pic->output_buffer = VA_INVALID_ID;
  443. }
  444. return 0;
  445. }
  446. static VAAPIEncodePicture *vaapi_encode_alloc(void)
  447. {
  448. VAAPIEncodePicture *pic;
  449. pic = av_mallocz(sizeof(*pic));
  450. if (!pic)
  451. return NULL;
  452. pic->input_surface = VA_INVALID_ID;
  453. pic->recon_surface = VA_INVALID_ID;
  454. pic->output_buffer = VA_INVALID_ID;
  455. return pic;
  456. }
  457. static int vaapi_encode_free(AVCodecContext *avctx,
  458. VAAPIEncodePicture *pic)
  459. {
  460. int i;
  461. if (pic->encode_issued)
  462. vaapi_encode_discard(avctx, pic);
  463. for (i = 0; i < pic->nb_slices; i++) {
  464. av_freep(&pic->slices[i]->priv_data);
  465. av_freep(&pic->slices[i]->codec_slice_params);
  466. av_freep(&pic->slices[i]);
  467. }
  468. av_freep(&pic->codec_picture_params);
  469. av_frame_free(&pic->input_image);
  470. av_frame_free(&pic->recon_image);
  471. // Output buffer should already be destroyed.
  472. av_assert0(pic->output_buffer == VA_INVALID_ID);
  473. av_freep(&pic->priv_data);
  474. av_freep(&pic->codec_picture_params);
  475. av_free(pic);
  476. return 0;
  477. }
  478. static int vaapi_encode_step(AVCodecContext *avctx,
  479. VAAPIEncodePicture *target)
  480. {
  481. VAAPIEncodeContext *ctx = avctx->priv_data;
  482. VAAPIEncodePicture *pic;
  483. int i, err;
  484. if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING ||
  485. ctx->issue_mode == ISSUE_MODE_MINIMISE_LATENCY) {
  486. // These two modes are equivalent, except that we wait for
  487. // immediate completion on each operation if serialised.
  488. if (!target) {
  489. // No target, nothing to do yet.
  490. return 0;
  491. }
  492. if (target->encode_complete) {
  493. // Already done.
  494. return 0;
  495. }
  496. pic = target;
  497. for (i = 0; i < pic->nb_refs; i++) {
  498. if (!pic->refs[i]->encode_complete) {
  499. err = vaapi_encode_step(avctx, pic->refs[i]);
  500. if (err < 0)
  501. return err;
  502. }
  503. }
  504. err = vaapi_encode_issue(avctx, pic);
  505. if (err < 0)
  506. return err;
  507. } else if (ctx->issue_mode == ISSUE_MODE_MAXIMISE_THROUGHPUT) {
  508. int activity;
  509. // Run through the list of all available pictures repeatedly
  510. // and issue the first one found which has all dependencies
  511. // available (including previously-issued but not necessarily
  512. // completed pictures).
  513. do {
  514. activity = 0;
  515. for (pic = ctx->pic_start; pic; pic = pic->next) {
  516. if (!pic->input_available || pic->encode_issued)
  517. continue;
  518. for (i = 0; i < pic->nb_refs; i++) {
  519. if (!pic->refs[i]->encode_issued)
  520. break;
  521. }
  522. if (i < pic->nb_refs)
  523. continue;
  524. err = vaapi_encode_issue(avctx, pic);
  525. if (err < 0)
  526. return err;
  527. activity = 1;
  528. // Start again from the beginning of the list,
  529. // because issuing this picture may have satisfied
  530. // forward dependencies of earlier ones.
  531. break;
  532. }
  533. } while(activity);
  534. // If we had a defined target for this step then it will
  535. // always have been issued by now.
  536. if (target) {
  537. av_assert0(target->encode_issued && "broken dependencies?");
  538. }
  539. } else {
  540. av_assert0(0);
  541. }
  542. return 0;
  543. }
  544. static int vaapi_encode_get_next(AVCodecContext *avctx,
  545. VAAPIEncodePicture **pic_out)
  546. {
  547. VAAPIEncodeContext *ctx = avctx->priv_data;
  548. VAAPIEncodePicture *start, *end, *pic;
  549. int i;
  550. for (pic = ctx->pic_start; pic; pic = pic->next) {
  551. if (pic->next)
  552. av_assert0(pic->display_order + 1 == pic->next->display_order);
  553. if (pic->display_order == ctx->input_order) {
  554. *pic_out = pic;
  555. return 0;
  556. }
  557. }
  558. pic = vaapi_encode_alloc();
  559. if (!pic)
  560. return AVERROR(ENOMEM);
  561. if (ctx->input_order == 0 || ctx->force_idr ||
  562. ctx->gop_counter >= avctx->gop_size) {
  563. pic->type = PICTURE_TYPE_IDR;
  564. ctx->force_idr = 0;
  565. ctx->gop_counter = 1;
  566. ctx->p_counter = 0;
  567. } else if (ctx->p_counter >= ctx->p_per_i) {
  568. pic->type = PICTURE_TYPE_I;
  569. ++ctx->gop_counter;
  570. ctx->p_counter = 0;
  571. } else {
  572. pic->type = PICTURE_TYPE_P;
  573. pic->refs[0] = ctx->pic_end;
  574. pic->nb_refs = 1;
  575. ++ctx->gop_counter;
  576. ++ctx->p_counter;
  577. }
  578. start = end = pic;
  579. if (pic->type != PICTURE_TYPE_IDR) {
  580. // If that was not an IDR frame, add B-frames display-before and
  581. // encode-after it, but not exceeding the GOP size.
  582. for (i = 0; i < ctx->b_per_p &&
  583. ctx->gop_counter < avctx->gop_size; i++) {
  584. pic = vaapi_encode_alloc();
  585. if (!pic)
  586. goto fail;
  587. pic->type = PICTURE_TYPE_B;
  588. pic->refs[0] = ctx->pic_end;
  589. pic->refs[1] = end;
  590. pic->nb_refs = 2;
  591. pic->next = start;
  592. pic->display_order = ctx->input_order + ctx->b_per_p - i - 1;
  593. pic->encode_order = pic->display_order + 1;
  594. start = pic;
  595. ++ctx->gop_counter;
  596. }
  597. }
  598. if (ctx->input_order == 0) {
  599. pic->display_order = 0;
  600. pic->encode_order = 0;
  601. ctx->pic_start = ctx->pic_end = pic;
  602. } else {
  603. for (i = 0, pic = start; pic; i++, pic = pic->next) {
  604. pic->display_order = ctx->input_order + i;
  605. if (end->type == PICTURE_TYPE_IDR)
  606. pic->encode_order = ctx->input_order + i;
  607. else if (pic == end)
  608. pic->encode_order = ctx->input_order;
  609. else
  610. pic->encode_order = ctx->input_order + i + 1;
  611. }
  612. av_assert0(ctx->pic_end);
  613. ctx->pic_end->next = start;
  614. ctx->pic_end = end;
  615. }
  616. *pic_out = start;
  617. av_log(avctx, AV_LOG_DEBUG, "Pictures:");
  618. for (pic = ctx->pic_start; pic; pic = pic->next) {
  619. av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
  620. picture_type_name[pic->type],
  621. pic->display_order, pic->encode_order);
  622. }
  623. av_log(avctx, AV_LOG_DEBUG, "\n");
  624. return 0;
  625. fail:
  626. while (start) {
  627. pic = start->next;
  628. vaapi_encode_free(avctx, start);
  629. start = pic;
  630. }
  631. return AVERROR(ENOMEM);
  632. }
  633. static int vaapi_encode_truncate_gop(AVCodecContext *avctx)
  634. {
  635. VAAPIEncodeContext *ctx = avctx->priv_data;
  636. VAAPIEncodePicture *pic, *last_pic, *next;
  637. // Find the last picture we actually have input for.
  638. for (pic = ctx->pic_start; pic; pic = pic->next) {
  639. if (!pic->input_available)
  640. break;
  641. last_pic = pic;
  642. }
  643. if (pic) {
  644. av_assert0(last_pic);
  645. if (last_pic->type == PICTURE_TYPE_B) {
  646. // Some fixing up is required. Change the type of this
  647. // picture to P, then modify preceding B references which
  648. // point beyond it to point at it instead.
  649. last_pic->type = PICTURE_TYPE_P;
  650. last_pic->encode_order = last_pic->refs[1]->encode_order;
  651. for (pic = ctx->pic_start; pic != last_pic; pic = pic->next) {
  652. if (pic->type == PICTURE_TYPE_B &&
  653. pic->refs[1] == last_pic->refs[1])
  654. pic->refs[1] = last_pic;
  655. }
  656. last_pic->nb_refs = 1;
  657. last_pic->refs[1] = NULL;
  658. } else {
  659. // We can use the current structure (no references point
  660. // beyond the end), but there are unused pics to discard.
  661. }
  662. // Discard all following pics, they will never be used.
  663. for (pic = last_pic->next; pic; pic = next) {
  664. next = pic->next;
  665. vaapi_encode_free(avctx, pic);
  666. }
  667. last_pic->next = NULL;
  668. ctx->pic_end = last_pic;
  669. } else {
  670. // Input is available for all pictures, so we don't need to
  671. // mangle anything.
  672. }
  673. av_log(avctx, AV_LOG_DEBUG, "Pictures ending truncated GOP:");
  674. for (pic = ctx->pic_start; pic; pic = pic->next) {
  675. av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
  676. picture_type_name[pic->type],
  677. pic->display_order, pic->encode_order);
  678. }
  679. av_log(avctx, AV_LOG_DEBUG, "\n");
  680. return 0;
  681. }
  682. static int vaapi_encode_clear_old(AVCodecContext *avctx)
  683. {
  684. VAAPIEncodeContext *ctx = avctx->priv_data;
  685. VAAPIEncodePicture *pic, *old;
  686. int i;
  687. while (ctx->pic_start != ctx->pic_end) {
  688. old = ctx->pic_start;
  689. if (old->encode_order > ctx->output_order)
  690. break;
  691. for (pic = old->next; pic; pic = pic->next) {
  692. if (pic->encode_complete)
  693. continue;
  694. for (i = 0; i < pic->nb_refs; i++) {
  695. if (pic->refs[i] == old) {
  696. // We still need this picture because it's referred to
  697. // directly by a later one, so it and all following
  698. // pictures have to stay.
  699. return 0;
  700. }
  701. }
  702. }
  703. pic = ctx->pic_start;
  704. ctx->pic_start = pic->next;
  705. vaapi_encode_free(avctx, pic);
  706. }
  707. return 0;
  708. }
  709. int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
  710. const AVFrame *input_image, int *got_packet)
  711. {
  712. VAAPIEncodeContext *ctx = avctx->priv_data;
  713. VAAPIEncodePicture *pic;
  714. int err;
  715. if (input_image) {
  716. av_log(avctx, AV_LOG_DEBUG, "Encode frame: %ux%u (%"PRId64").\n",
  717. input_image->width, input_image->height, input_image->pts);
  718. if (input_image->pict_type == AV_PICTURE_TYPE_I) {
  719. err = vaapi_encode_truncate_gop(avctx);
  720. if (err < 0)
  721. goto fail;
  722. ctx->force_idr = 1;
  723. }
  724. err = vaapi_encode_get_next(avctx, &pic);
  725. if (err) {
  726. av_log(avctx, AV_LOG_ERROR, "Input setup failed: %d.\n", err);
  727. return err;
  728. }
  729. pic->input_image = av_frame_alloc();
  730. if (!pic->input_image) {
  731. err = AVERROR(ENOMEM);
  732. goto fail;
  733. }
  734. err = av_frame_ref(pic->input_image, input_image);
  735. if (err < 0)
  736. goto fail;
  737. pic->input_surface = (VASurfaceID)(uintptr_t)input_image->data[3];
  738. pic->pts = input_image->pts;
  739. if (ctx->input_order == 0)
  740. ctx->first_pts = pic->pts;
  741. if (ctx->input_order == ctx->decode_delay)
  742. ctx->dts_pts_diff = pic->pts - ctx->first_pts;
  743. if (ctx->output_delay > 0)
  744. ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
  745. pic->input_available = 1;
  746. } else {
  747. if (!ctx->end_of_stream) {
  748. err = vaapi_encode_truncate_gop(avctx);
  749. if (err < 0)
  750. goto fail;
  751. ctx->end_of_stream = 1;
  752. }
  753. }
  754. ++ctx->input_order;
  755. ++ctx->output_order;
  756. av_assert0(ctx->output_order + ctx->output_delay + 1 == ctx->input_order);
  757. for (pic = ctx->pic_start; pic; pic = pic->next)
  758. if (pic->encode_order == ctx->output_order)
  759. break;
  760. // pic can be null here if we don't have a specific target in this
  761. // iteration. We might still issue encodes if things can be overlapped,
  762. // even though we don't intend to output anything.
  763. err = vaapi_encode_step(avctx, pic);
  764. if (err < 0) {
  765. av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
  766. goto fail;
  767. }
  768. if (!pic) {
  769. *got_packet = 0;
  770. } else {
  771. err = vaapi_encode_output(avctx, pic, pkt);
  772. if (err < 0) {
  773. av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
  774. goto fail;
  775. }
  776. if (ctx->output_delay == 0) {
  777. pkt->dts = pkt->pts;
  778. } else if (ctx->output_order < ctx->decode_delay) {
  779. if (ctx->ts_ring[ctx->output_order] < INT64_MIN + ctx->dts_pts_diff)
  780. pkt->dts = INT64_MIN;
  781. else
  782. pkt->dts = ctx->ts_ring[ctx->output_order] - ctx->dts_pts_diff;
  783. } else {
  784. pkt->dts = ctx->ts_ring[(ctx->output_order - ctx->decode_delay) %
  785. (3 * ctx->output_delay)];
  786. }
  787. *got_packet = 1;
  788. }
  789. err = vaapi_encode_clear_old(avctx);
  790. if (err < 0) {
  791. av_log(avctx, AV_LOG_ERROR, "List clearing failed: %d.\n", err);
  792. goto fail;
  793. }
  794. return 0;
  795. fail:
  796. // Unclear what to clean up on failure. There are probably some things we
  797. // could do usefully clean up here, but for now just leave them for uninit()
  798. // to do instead.
  799. return err;
  800. }
  801. static av_cold int vaapi_encode_config_attributes(AVCodecContext *avctx)
  802. {
  803. VAAPIEncodeContext *ctx = avctx->priv_data;
  804. VAStatus vas;
  805. int i, n, err;
  806. VAProfile *profiles = NULL;
  807. VAEntrypoint *entrypoints = NULL;
  808. VAConfigAttrib attr[] = {
  809. { VAConfigAttribRTFormat },
  810. { VAConfigAttribRateControl },
  811. { VAConfigAttribEncMaxRefFrames },
  812. { VAConfigAttribEncPackedHeaders },
  813. };
  814. n = vaMaxNumProfiles(ctx->hwctx->display);
  815. profiles = av_malloc_array(n, sizeof(VAProfile));
  816. if (!profiles) {
  817. err = AVERROR(ENOMEM);
  818. goto fail;
  819. }
  820. vas = vaQueryConfigProfiles(ctx->hwctx->display, profiles, &n);
  821. if (vas != VA_STATUS_SUCCESS) {
  822. av_log(ctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
  823. vas, vaErrorStr(vas));
  824. err = AVERROR(ENOSYS);
  825. goto fail;
  826. }
  827. for (i = 0; i < n; i++) {
  828. if (profiles[i] == ctx->va_profile)
  829. break;
  830. }
  831. if (i >= n) {
  832. av_log(ctx, AV_LOG_ERROR, "Encoding profile not found (%d).\n",
  833. ctx->va_profile);
  834. err = AVERROR(ENOSYS);
  835. goto fail;
  836. }
  837. n = vaMaxNumEntrypoints(ctx->hwctx->display);
  838. entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
  839. if (!entrypoints) {
  840. err = AVERROR(ENOMEM);
  841. goto fail;
  842. }
  843. vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
  844. entrypoints, &n);
  845. if (vas != VA_STATUS_SUCCESS) {
  846. av_log(ctx, AV_LOG_ERROR, "Failed to query entrypoints for "
  847. "profile %u: %d (%s).\n", ctx->va_profile,
  848. vas, vaErrorStr(vas));
  849. err = AVERROR(ENOSYS);
  850. goto fail;
  851. }
  852. for (i = 0; i < n; i++) {
  853. if (entrypoints[i] == ctx->va_entrypoint)
  854. break;
  855. }
  856. if (i >= n) {
  857. av_log(ctx, AV_LOG_ERROR, "Encoding entrypoint not found "
  858. "(%d / %d).\n", ctx->va_profile, ctx->va_entrypoint);
  859. err = AVERROR(ENOSYS);
  860. goto fail;
  861. }
  862. vas = vaGetConfigAttributes(ctx->hwctx->display,
  863. ctx->va_profile, ctx->va_entrypoint,
  864. attr, FF_ARRAY_ELEMS(attr));
  865. if (vas != VA_STATUS_SUCCESS) {
  866. av_log(avctx, AV_LOG_ERROR, "Failed to fetch config "
  867. "attributes: %d (%s).\n", vas, vaErrorStr(vas));
  868. return AVERROR(EINVAL);
  869. }
  870. for (i = 0; i < FF_ARRAY_ELEMS(attr); i++) {
  871. if (attr[i].value == VA_ATTRIB_NOT_SUPPORTED) {
  872. // Unfortunately we have to treat this as "don't know" and hope
  873. // for the best, because the Intel MJPEG encoder returns this
  874. // for all the interesting attributes.
  875. continue;
  876. }
  877. switch (attr[i].type) {
  878. case VAConfigAttribRTFormat:
  879. if (!(ctx->va_rt_format & attr[i].value)) {
  880. av_log(avctx, AV_LOG_ERROR, "Surface RT format %#x "
  881. "is not supported (mask %#x).\n",
  882. ctx->va_rt_format, attr[i].value);
  883. err = AVERROR(EINVAL);
  884. goto fail;
  885. }
  886. ctx->config_attributes[ctx->nb_config_attributes++] =
  887. (VAConfigAttrib) {
  888. .type = VAConfigAttribRTFormat,
  889. .value = ctx->va_rt_format,
  890. };
  891. break;
  892. case VAConfigAttribRateControl:
  893. // Hack for backward compatibility: CBR was the only
  894. // usable RC mode for a long time, so old drivers will
  895. // only have it. Normal default options may now choose
  896. // VBR and then fail, however, so override it here with
  897. // CBR if that is the only supported mode.
  898. if (ctx->va_rc_mode == VA_RC_VBR &&
  899. !(attr[i].value & VA_RC_VBR) &&
  900. (attr[i].value & VA_RC_CBR)) {
  901. av_log(avctx, AV_LOG_WARNING, "VBR rate control is "
  902. "not supported with this driver version; "
  903. "using CBR instead.\n");
  904. ctx->va_rc_mode = VA_RC_CBR;
  905. }
  906. if (!(ctx->va_rc_mode & attr[i].value)) {
  907. av_log(avctx, AV_LOG_ERROR, "Rate control mode %#x "
  908. "is not supported (mask: %#x).\n",
  909. ctx->va_rc_mode, attr[i].value);
  910. err = AVERROR(EINVAL);
  911. goto fail;
  912. }
  913. ctx->config_attributes[ctx->nb_config_attributes++] =
  914. (VAConfigAttrib) {
  915. .type = VAConfigAttribRateControl,
  916. .value = ctx->va_rc_mode,
  917. };
  918. break;
  919. case VAConfigAttribEncMaxRefFrames:
  920. {
  921. unsigned int ref_l0 = attr[i].value & 0xffff;
  922. unsigned int ref_l1 = (attr[i].value >> 16) & 0xffff;
  923. if (avctx->gop_size > 1 && ref_l0 < 1) {
  924. av_log(avctx, AV_LOG_ERROR, "P frames are not "
  925. "supported (%#x).\n", attr[i].value);
  926. err = AVERROR(EINVAL);
  927. goto fail;
  928. }
  929. if (avctx->max_b_frames > 0 && ref_l1 < 1) {
  930. av_log(avctx, AV_LOG_ERROR, "B frames are not "
  931. "supported (%#x).\n", attr[i].value);
  932. err = AVERROR(EINVAL);
  933. goto fail;
  934. }
  935. }
  936. break;
  937. case VAConfigAttribEncPackedHeaders:
  938. if (ctx->va_packed_headers & ~attr[i].value) {
  939. // This isn't fatal, but packed headers are always
  940. // preferable because they are under our control.
  941. // When absent, the driver is generating them and some
  942. // features may not work (e.g. VUI or SEI in H.264).
  943. av_log(avctx, AV_LOG_WARNING, "Warning: some packed "
  944. "headers are not supported (want %#x, got %#x).\n",
  945. ctx->va_packed_headers, attr[i].value);
  946. ctx->va_packed_headers &= attr[i].value;
  947. }
  948. ctx->config_attributes[ctx->nb_config_attributes++] =
  949. (VAConfigAttrib) {
  950. .type = VAConfigAttribEncPackedHeaders,
  951. .value = ctx->va_packed_headers,
  952. };
  953. break;
  954. default:
  955. av_assert0(0 && "Unexpected config attribute.");
  956. }
  957. }
  958. err = 0;
  959. fail:
  960. av_freep(&profiles);
  961. av_freep(&entrypoints);
  962. return err;
  963. }
  964. static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
  965. {
  966. VAAPIEncodeContext *ctx = avctx->priv_data;
  967. int rc_bits_per_second;
  968. int rc_target_percentage;
  969. int rc_window_size;
  970. int hrd_buffer_size;
  971. int hrd_initial_buffer_fullness;
  972. int fr_num, fr_den;
  973. if (avctx->rc_buffer_size)
  974. hrd_buffer_size = avctx->rc_buffer_size;
  975. else
  976. hrd_buffer_size = avctx->bit_rate;
  977. if (avctx->rc_initial_buffer_occupancy)
  978. hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
  979. else
  980. hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
  981. if (ctx->va_rc_mode == VA_RC_CBR) {
  982. rc_bits_per_second = avctx->bit_rate;
  983. rc_target_percentage = 100;
  984. rc_window_size = 1000;
  985. } else {
  986. if (avctx->rc_max_rate < avctx->bit_rate) {
  987. // Max rate is unset or invalid, just use the normal bitrate.
  988. rc_bits_per_second = avctx->bit_rate;
  989. rc_target_percentage = 100;
  990. } else {
  991. rc_bits_per_second = avctx->rc_max_rate;
  992. rc_target_percentage = (avctx->bit_rate * 100) / rc_bits_per_second;
  993. }
  994. rc_window_size = (hrd_buffer_size * 1000) / avctx->bit_rate;
  995. }
  996. ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
  997. ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
  998. .bits_per_second = rc_bits_per_second,
  999. .target_percentage = rc_target_percentage,
  1000. .window_size = rc_window_size,
  1001. .initial_qp = 0,
  1002. .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
  1003. .basic_unit_size = 0,
  1004. };
  1005. ctx->global_params[ctx->nb_global_params] =
  1006. &ctx->rc_params.misc;
  1007. ctx->global_params_size[ctx->nb_global_params++] =
  1008. sizeof(ctx->rc_params);
  1009. ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
  1010. ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
  1011. .initial_buffer_fullness = hrd_initial_buffer_fullness,
  1012. .buffer_size = hrd_buffer_size,
  1013. };
  1014. ctx->global_params[ctx->nb_global_params] =
  1015. &ctx->hrd_params.misc;
  1016. ctx->global_params_size[ctx->nb_global_params++] =
  1017. sizeof(ctx->hrd_params);
  1018. if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
  1019. av_reduce(&fr_num, &fr_den,
  1020. avctx->framerate.num, avctx->framerate.den, 65535);
  1021. else
  1022. av_reduce(&fr_num, &fr_den,
  1023. avctx->time_base.den, avctx->time_base.num, 65535);
  1024. ctx->fr_params.misc.type = VAEncMiscParameterTypeFrameRate;
  1025. ctx->fr_params.fr.framerate = (unsigned int)fr_den << 16 | fr_num;
  1026. #if VA_CHECK_VERSION(0, 40, 0)
  1027. ctx->global_params[ctx->nb_global_params] =
  1028. &ctx->fr_params.misc;
  1029. ctx->global_params_size[ctx->nb_global_params++] =
  1030. sizeof(ctx->fr_params);
  1031. #endif
  1032. return 0;
  1033. }
  1034. static void vaapi_encode_free_output_buffer(void *opaque,
  1035. uint8_t *data)
  1036. {
  1037. AVCodecContext *avctx = opaque;
  1038. VAAPIEncodeContext *ctx = avctx->priv_data;
  1039. VABufferID buffer_id;
  1040. buffer_id = (VABufferID)(uintptr_t)data;
  1041. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  1042. av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
  1043. }
  1044. static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
  1045. int size)
  1046. {
  1047. AVCodecContext *avctx = opaque;
  1048. VAAPIEncodeContext *ctx = avctx->priv_data;
  1049. VABufferID buffer_id;
  1050. VAStatus vas;
  1051. AVBufferRef *ref;
  1052. // The output buffer size is fixed, so it needs to be large enough
  1053. // to hold the largest possible compressed frame. We assume here
  1054. // that the uncompressed frame plus some header data is an upper
  1055. // bound on that.
  1056. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  1057. VAEncCodedBufferType,
  1058. 3 * ctx->surface_width * ctx->surface_height +
  1059. (1 << 16), 1, 0, &buffer_id);
  1060. if (vas != VA_STATUS_SUCCESS) {
  1061. av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
  1062. "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
  1063. return NULL;
  1064. }
  1065. av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
  1066. ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
  1067. sizeof(buffer_id),
  1068. &vaapi_encode_free_output_buffer,
  1069. avctx, AV_BUFFER_FLAG_READONLY);
  1070. if (!ref) {
  1071. vaDestroyBuffer(ctx->hwctx->display, buffer_id);
  1072. return NULL;
  1073. }
  1074. return ref;
  1075. }
  1076. static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
  1077. {
  1078. VAAPIEncodeContext *ctx = avctx->priv_data;
  1079. AVVAAPIHWConfig *hwconfig = NULL;
  1080. AVHWFramesConstraints *constraints = NULL;
  1081. enum AVPixelFormat recon_format;
  1082. int err, i;
  1083. hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
  1084. if (!hwconfig) {
  1085. err = AVERROR(ENOMEM);
  1086. goto fail;
  1087. }
  1088. hwconfig->config_id = ctx->va_config;
  1089. constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
  1090. hwconfig);
  1091. if (!constraints) {
  1092. err = AVERROR(ENOMEM);
  1093. goto fail;
  1094. }
  1095. // Probably we can use the input surface format as the surface format
  1096. // of the reconstructed frames. If not, we just pick the first (only?)
  1097. // format in the valid list and hope that it all works.
  1098. recon_format = AV_PIX_FMT_NONE;
  1099. if (constraints->valid_sw_formats) {
  1100. for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
  1101. if (ctx->input_frames->sw_format ==
  1102. constraints->valid_sw_formats[i]) {
  1103. recon_format = ctx->input_frames->sw_format;
  1104. break;
  1105. }
  1106. }
  1107. if (recon_format == AV_PIX_FMT_NONE) {
  1108. // No match. Just use the first in the supported list and
  1109. // hope for the best.
  1110. recon_format = constraints->valid_sw_formats[0];
  1111. }
  1112. } else {
  1113. // No idea what to use; copy input format.
  1114. recon_format = ctx->input_frames->sw_format;
  1115. }
  1116. av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
  1117. "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
  1118. if (ctx->surface_width < constraints->min_width ||
  1119. ctx->surface_height < constraints->min_height ||
  1120. ctx->surface_width > constraints->max_width ||
  1121. ctx->surface_height > constraints->max_height) {
  1122. av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
  1123. "size %dx%d (constraints: width %d-%d height %d-%d).\n",
  1124. ctx->surface_width, ctx->surface_height,
  1125. constraints->min_width, constraints->max_width,
  1126. constraints->min_height, constraints->max_height);
  1127. err = AVERROR(EINVAL);
  1128. goto fail;
  1129. }
  1130. av_freep(&hwconfig);
  1131. av_hwframe_constraints_free(&constraints);
  1132. ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
  1133. if (!ctx->recon_frames_ref) {
  1134. err = AVERROR(ENOMEM);
  1135. goto fail;
  1136. }
  1137. ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
  1138. ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
  1139. ctx->recon_frames->sw_format = recon_format;
  1140. ctx->recon_frames->width = ctx->surface_width;
  1141. ctx->recon_frames->height = ctx->surface_height;
  1142. // At most three IDR/I/P frames and two runs of B frames can be in
  1143. // flight at any one time.
  1144. ctx->recon_frames->initial_pool_size = 3 + 2 * avctx->max_b_frames;
  1145. err = av_hwframe_ctx_init(ctx->recon_frames_ref);
  1146. if (err < 0) {
  1147. av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
  1148. "frame context: %d.\n", err);
  1149. goto fail;
  1150. }
  1151. err = 0;
  1152. fail:
  1153. av_freep(&hwconfig);
  1154. av_hwframe_constraints_free(&constraints);
  1155. return err;
  1156. }
  1157. av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
  1158. {
  1159. VAAPIEncodeContext *ctx = avctx->priv_data;
  1160. AVVAAPIFramesContext *recon_hwctx = NULL;
  1161. VAStatus vas;
  1162. int err;
  1163. if (!avctx->hw_frames_ctx) {
  1164. av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
  1165. "required to associate the encoding device.\n");
  1166. return AVERROR(EINVAL);
  1167. }
  1168. ctx->codec_options = ctx->codec_options_data;
  1169. ctx->va_config = VA_INVALID_ID;
  1170. ctx->va_context = VA_INVALID_ID;
  1171. ctx->priv_data = av_mallocz(ctx->codec->priv_data_size);
  1172. if (!ctx->priv_data) {
  1173. err = AVERROR(ENOMEM);
  1174. goto fail;
  1175. }
  1176. ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
  1177. if (!ctx->input_frames_ref) {
  1178. err = AVERROR(ENOMEM);
  1179. goto fail;
  1180. }
  1181. ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
  1182. ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
  1183. if (!ctx->device_ref) {
  1184. err = AVERROR(ENOMEM);
  1185. goto fail;
  1186. }
  1187. ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
  1188. ctx->hwctx = ctx->device->hwctx;
  1189. err = vaapi_encode_config_attributes(avctx);
  1190. if (err < 0)
  1191. goto fail;
  1192. vas = vaCreateConfig(ctx->hwctx->display,
  1193. ctx->va_profile, ctx->va_entrypoint,
  1194. ctx->config_attributes, ctx->nb_config_attributes,
  1195. &ctx->va_config);
  1196. if (vas != VA_STATUS_SUCCESS) {
  1197. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  1198. "configuration: %d (%s).\n", vas, vaErrorStr(vas));
  1199. err = AVERROR(EIO);
  1200. goto fail;
  1201. }
  1202. err = vaapi_encode_create_recon_frames(avctx);
  1203. if (err < 0)
  1204. goto fail;
  1205. recon_hwctx = ctx->recon_frames->hwctx;
  1206. vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
  1207. ctx->surface_width, ctx->surface_height,
  1208. VA_PROGRESSIVE,
  1209. recon_hwctx->surface_ids,
  1210. recon_hwctx->nb_surfaces,
  1211. &ctx->va_context);
  1212. if (vas != VA_STATUS_SUCCESS) {
  1213. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  1214. "context: %d (%s).\n", vas, vaErrorStr(vas));
  1215. err = AVERROR(EIO);
  1216. goto fail;
  1217. }
  1218. ctx->output_buffer_pool =
  1219. av_buffer_pool_init2(sizeof(VABufferID), avctx,
  1220. &vaapi_encode_alloc_output_buffer, NULL);
  1221. if (!ctx->output_buffer_pool) {
  1222. err = AVERROR(ENOMEM);
  1223. goto fail;
  1224. }
  1225. if (ctx->va_rc_mode & ~VA_RC_CQP) {
  1226. err = vaapi_encode_init_rate_control(avctx);
  1227. if (err < 0)
  1228. goto fail;
  1229. }
  1230. if (ctx->codec->configure) {
  1231. err = ctx->codec->configure(avctx);
  1232. if (err < 0)
  1233. goto fail;
  1234. }
  1235. ctx->input_order = 0;
  1236. ctx->output_delay = avctx->max_b_frames;
  1237. ctx->decode_delay = 1;
  1238. ctx->output_order = - ctx->output_delay - 1;
  1239. // Currently we never generate I frames, only IDR.
  1240. ctx->p_per_i = INT_MAX;
  1241. ctx->b_per_p = avctx->max_b_frames;
  1242. if (ctx->codec->sequence_params_size > 0) {
  1243. ctx->codec_sequence_params =
  1244. av_mallocz(ctx->codec->sequence_params_size);
  1245. if (!ctx->codec_sequence_params) {
  1246. err = AVERROR(ENOMEM);
  1247. goto fail;
  1248. }
  1249. }
  1250. if (ctx->codec->picture_params_size > 0) {
  1251. ctx->codec_picture_params =
  1252. av_mallocz(ctx->codec->picture_params_size);
  1253. if (!ctx->codec_picture_params) {
  1254. err = AVERROR(ENOMEM);
  1255. goto fail;
  1256. }
  1257. }
  1258. if (ctx->codec->init_sequence_params) {
  1259. err = ctx->codec->init_sequence_params(avctx);
  1260. if (err < 0) {
  1261. av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
  1262. "failed: %d.\n", err);
  1263. goto fail;
  1264. }
  1265. }
  1266. // This should be configurable somehow. (Needs testing on a machine
  1267. // where it actually overlaps properly, though.)
  1268. ctx->issue_mode = ISSUE_MODE_MAXIMISE_THROUGHPUT;
  1269. if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
  1270. ctx->codec->write_sequence_header) {
  1271. char data[MAX_PARAM_BUFFER_SIZE];
  1272. size_t bit_len = 8 * sizeof(data);
  1273. err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
  1274. if (err < 0) {
  1275. av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
  1276. "for extradata: %d.\n", err);
  1277. goto fail;
  1278. } else {
  1279. avctx->extradata_size = (bit_len + 7) / 8;
  1280. avctx->extradata = av_mallocz(avctx->extradata_size +
  1281. AV_INPUT_BUFFER_PADDING_SIZE);
  1282. if (!avctx->extradata) {
  1283. err = AVERROR(ENOMEM);
  1284. goto fail;
  1285. }
  1286. memcpy(avctx->extradata, data, avctx->extradata_size);
  1287. }
  1288. }
  1289. return 0;
  1290. fail:
  1291. ff_vaapi_encode_close(avctx);
  1292. return err;
  1293. }
  1294. av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
  1295. {
  1296. VAAPIEncodeContext *ctx = avctx->priv_data;
  1297. VAAPIEncodePicture *pic, *next;
  1298. for (pic = ctx->pic_start; pic; pic = next) {
  1299. next = pic->next;
  1300. vaapi_encode_free(avctx, pic);
  1301. }
  1302. if (ctx->va_context != VA_INVALID_ID) {
  1303. vaDestroyContext(ctx->hwctx->display, ctx->va_context);
  1304. ctx->va_context = VA_INVALID_ID;
  1305. }
  1306. if (ctx->va_config != VA_INVALID_ID) {
  1307. vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
  1308. ctx->va_config = VA_INVALID_ID;
  1309. }
  1310. av_buffer_pool_uninit(&ctx->output_buffer_pool);
  1311. av_freep(&ctx->codec_sequence_params);
  1312. av_freep(&ctx->codec_picture_params);
  1313. av_buffer_unref(&ctx->recon_frames_ref);
  1314. av_buffer_unref(&ctx->input_frames_ref);
  1315. av_buffer_unref(&ctx->device_ref);
  1316. av_freep(&ctx->priv_data);
  1317. return 0;
  1318. }