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.

1030 lines
33KB

  1. /*
  2. * This file is part of FFmpeg.
  3. *
  4. * FFmpeg is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * FFmpeg is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with FFmpeg; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include "config.h"
  19. #if HAVE_VAAPI_X11
  20. # include <va/va_x11.h>
  21. #endif
  22. #if HAVE_VAAPI_DRM
  23. # include <va/va_drm.h>
  24. #endif
  25. #include <fcntl.h>
  26. #if HAVE_UNISTD_H
  27. # include <unistd.h>
  28. #endif
  29. #include "avassert.h"
  30. #include "buffer.h"
  31. #include "common.h"
  32. #include "hwcontext.h"
  33. #include "hwcontext_internal.h"
  34. #include "hwcontext_vaapi.h"
  35. #include "mem.h"
  36. #include "pixdesc.h"
  37. #include "pixfmt.h"
  38. typedef struct VAAPIDevicePriv {
  39. #if HAVE_VAAPI_X11
  40. Display *x11_display;
  41. #endif
  42. int drm_fd;
  43. } VAAPIDevicePriv;
  44. typedef struct VAAPISurfaceFormat {
  45. enum AVPixelFormat pix_fmt;
  46. VAImageFormat image_format;
  47. } VAAPISurfaceFormat;
  48. typedef struct VAAPIDeviceContext {
  49. // Surface formats which can be used with this device.
  50. VAAPISurfaceFormat *formats;
  51. int nb_formats;
  52. } VAAPIDeviceContext;
  53. typedef struct VAAPIFramesContext {
  54. // Surface attributes set at create time.
  55. VASurfaceAttrib *attributes;
  56. int nb_attributes;
  57. // RT format of the underlying surface (Intel driver ignores this anyway).
  58. unsigned int rt_format;
  59. // Whether vaDeriveImage works.
  60. int derive_works;
  61. } VAAPIFramesContext;
  62. typedef struct VAAPIMapping {
  63. // Handle to the derived or copied image which is mapped.
  64. VAImage image;
  65. // The mapping flags actually used.
  66. int flags;
  67. } VAAPIMapping;
  68. #define MAP(va, rt, av) { \
  69. VA_FOURCC_ ## va, \
  70. VA_RT_FORMAT_ ## rt, \
  71. AV_PIX_FMT_ ## av \
  72. }
  73. // The map fourcc <-> pix_fmt isn't bijective because of the annoying U/V
  74. // plane swap cases. The frame handling below tries to hide these.
  75. static struct {
  76. unsigned int fourcc;
  77. unsigned int rt_format;
  78. enum AVPixelFormat pix_fmt;
  79. } vaapi_format_map[] = {
  80. MAP(NV12, YUV420, NV12),
  81. MAP(YV12, YUV420, YUV420P), // With U/V planes swapped.
  82. MAP(IYUV, YUV420, YUV420P),
  83. //MAP(I420, YUV420, YUV420P), // Not in libva but used by Intel driver.
  84. #ifdef VA_FOURCC_YV16
  85. MAP(YV16, YUV422, YUV422P), // With U/V planes swapped.
  86. #endif
  87. MAP(422H, YUV422, YUV422P),
  88. MAP(UYVY, YUV422, UYVY422),
  89. MAP(YUY2, YUV422, YUYV422),
  90. MAP(Y800, YUV400, GRAY8),
  91. #ifdef VA_FOURCC_P010
  92. MAP(P010, YUV420_10BPP, P010),
  93. #endif
  94. MAP(BGRA, RGB32, BGRA),
  95. MAP(BGRX, RGB32, BGR0),
  96. MAP(RGBA, RGB32, RGBA),
  97. MAP(RGBX, RGB32, RGB0),
  98. #ifdef VA_FOURCC_ABGR
  99. MAP(ABGR, RGB32, ABGR),
  100. MAP(XBGR, RGB32, 0BGR),
  101. #endif
  102. MAP(ARGB, RGB32, ARGB),
  103. MAP(XRGB, RGB32, 0RGB),
  104. };
  105. #undef MAP
  106. static enum AVPixelFormat vaapi_pix_fmt_from_fourcc(unsigned int fourcc)
  107. {
  108. int i;
  109. for (i = 0; i < FF_ARRAY_ELEMS(vaapi_format_map); i++)
  110. if (vaapi_format_map[i].fourcc == fourcc)
  111. return vaapi_format_map[i].pix_fmt;
  112. return AV_PIX_FMT_NONE;
  113. }
  114. static int vaapi_get_image_format(AVHWDeviceContext *hwdev,
  115. enum AVPixelFormat pix_fmt,
  116. VAImageFormat **image_format)
  117. {
  118. VAAPIDeviceContext *ctx = hwdev->internal->priv;
  119. int i;
  120. for (i = 0; i < ctx->nb_formats; i++) {
  121. if (ctx->formats[i].pix_fmt == pix_fmt) {
  122. if (image_format)
  123. *image_format = &ctx->formats[i].image_format;
  124. return 0;
  125. }
  126. }
  127. return AVERROR(EINVAL);
  128. }
  129. static int vaapi_frames_get_constraints(AVHWDeviceContext *hwdev,
  130. const void *hwconfig,
  131. AVHWFramesConstraints *constraints)
  132. {
  133. AVVAAPIDeviceContext *hwctx = hwdev->hwctx;
  134. const AVVAAPIHWConfig *config = hwconfig;
  135. VAAPIDeviceContext *ctx = hwdev->internal->priv;
  136. VASurfaceAttrib *attr_list = NULL;
  137. VAStatus vas;
  138. enum AVPixelFormat pix_fmt;
  139. unsigned int fourcc;
  140. int err, i, j, attr_count, pix_fmt_count;
  141. if (config &&
  142. !(hwctx->driver_quirks & AV_VAAPI_DRIVER_QUIRK_SURFACE_ATTRIBUTES)) {
  143. attr_count = 0;
  144. vas = vaQuerySurfaceAttributes(hwctx->display, config->config_id,
  145. 0, &attr_count);
  146. if (vas != VA_STATUS_SUCCESS) {
  147. av_log(hwdev, AV_LOG_ERROR, "Failed to query surface attributes: "
  148. "%d (%s).\n", vas, vaErrorStr(vas));
  149. err = AVERROR(ENOSYS);
  150. goto fail;
  151. }
  152. attr_list = av_malloc(attr_count * sizeof(*attr_list));
  153. if (!attr_list) {
  154. err = AVERROR(ENOMEM);
  155. goto fail;
  156. }
  157. vas = vaQuerySurfaceAttributes(hwctx->display, config->config_id,
  158. attr_list, &attr_count);
  159. if (vas != VA_STATUS_SUCCESS) {
  160. av_log(hwdev, AV_LOG_ERROR, "Failed to query surface attributes: "
  161. "%d (%s).\n", vas, vaErrorStr(vas));
  162. err = AVERROR(ENOSYS);
  163. goto fail;
  164. }
  165. pix_fmt_count = 0;
  166. for (i = 0; i < attr_count; i++) {
  167. switch (attr_list[i].type) {
  168. case VASurfaceAttribPixelFormat:
  169. fourcc = attr_list[i].value.value.i;
  170. pix_fmt = vaapi_pix_fmt_from_fourcc(fourcc);
  171. if (pix_fmt != AV_PIX_FMT_NONE) {
  172. ++pix_fmt_count;
  173. } else {
  174. // Something unsupported - ignore.
  175. }
  176. break;
  177. case VASurfaceAttribMinWidth:
  178. constraints->min_width = attr_list[i].value.value.i;
  179. break;
  180. case VASurfaceAttribMinHeight:
  181. constraints->min_height = attr_list[i].value.value.i;
  182. break;
  183. case VASurfaceAttribMaxWidth:
  184. constraints->max_width = attr_list[i].value.value.i;
  185. break;
  186. case VASurfaceAttribMaxHeight:
  187. constraints->max_height = attr_list[i].value.value.i;
  188. break;
  189. }
  190. }
  191. if (pix_fmt_count == 0) {
  192. // Nothing usable found. Presumably there exists something which
  193. // works, so leave the set null to indicate unknown.
  194. constraints->valid_sw_formats = NULL;
  195. } else {
  196. constraints->valid_sw_formats = av_malloc_array(pix_fmt_count + 1,
  197. sizeof(pix_fmt));
  198. if (!constraints->valid_sw_formats) {
  199. err = AVERROR(ENOMEM);
  200. goto fail;
  201. }
  202. for (i = j = 0; i < attr_count; i++) {
  203. if (attr_list[i].type != VASurfaceAttribPixelFormat)
  204. continue;
  205. fourcc = attr_list[i].value.value.i;
  206. pix_fmt = vaapi_pix_fmt_from_fourcc(fourcc);
  207. if (pix_fmt != AV_PIX_FMT_NONE)
  208. constraints->valid_sw_formats[j++] = pix_fmt;
  209. }
  210. av_assert0(j == pix_fmt_count);
  211. constraints->valid_sw_formats[j] = AV_PIX_FMT_NONE;
  212. }
  213. } else {
  214. // No configuration supplied.
  215. // Return the full set of image formats known by the implementation.
  216. constraints->valid_sw_formats = av_malloc_array(ctx->nb_formats + 1,
  217. sizeof(pix_fmt));
  218. if (!constraints->valid_sw_formats) {
  219. err = AVERROR(ENOMEM);
  220. goto fail;
  221. }
  222. for (i = 0; i < ctx->nb_formats; i++)
  223. constraints->valid_sw_formats[i] = ctx->formats[i].pix_fmt;
  224. constraints->valid_sw_formats[i] = AV_PIX_FMT_NONE;
  225. }
  226. constraints->valid_hw_formats = av_malloc_array(2, sizeof(pix_fmt));
  227. if (!constraints->valid_hw_formats) {
  228. err = AVERROR(ENOMEM);
  229. goto fail;
  230. }
  231. constraints->valid_hw_formats[0] = AV_PIX_FMT_VAAPI;
  232. constraints->valid_hw_formats[1] = AV_PIX_FMT_NONE;
  233. err = 0;
  234. fail:
  235. av_freep(&attr_list);
  236. return err;
  237. }
  238. static const struct {
  239. const char *friendly_name;
  240. const char *match_string;
  241. unsigned int quirks;
  242. } vaapi_driver_quirks_table[] = {
  243. {
  244. "Intel i965 (Quick Sync)",
  245. "i965",
  246. AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS,
  247. },
  248. {
  249. "Intel iHD",
  250. "ubit",
  251. AV_VAAPI_DRIVER_QUIRK_ATTRIB_MEMTYPE,
  252. },
  253. {
  254. "VDPAU wrapper",
  255. "Splitted-Desktop Systems VDPAU backend for VA-API",
  256. AV_VAAPI_DRIVER_QUIRK_SURFACE_ATTRIBUTES,
  257. },
  258. };
  259. static int vaapi_device_init(AVHWDeviceContext *hwdev)
  260. {
  261. VAAPIDeviceContext *ctx = hwdev->internal->priv;
  262. AVVAAPIDeviceContext *hwctx = hwdev->hwctx;
  263. VAImageFormat *image_list = NULL;
  264. VAStatus vas;
  265. const char *vendor_string;
  266. int err, i, image_count;
  267. enum AVPixelFormat pix_fmt;
  268. unsigned int fourcc;
  269. image_count = vaMaxNumImageFormats(hwctx->display);
  270. if (image_count <= 0) {
  271. err = AVERROR(EIO);
  272. goto fail;
  273. }
  274. image_list = av_malloc(image_count * sizeof(*image_list));
  275. if (!image_list) {
  276. err = AVERROR(ENOMEM);
  277. goto fail;
  278. }
  279. vas = vaQueryImageFormats(hwctx->display, image_list, &image_count);
  280. if (vas != VA_STATUS_SUCCESS) {
  281. err = AVERROR(EIO);
  282. goto fail;
  283. }
  284. ctx->formats = av_malloc(image_count * sizeof(*ctx->formats));
  285. if (!ctx->formats) {
  286. err = AVERROR(ENOMEM);
  287. goto fail;
  288. }
  289. ctx->nb_formats = 0;
  290. for (i = 0; i < image_count; i++) {
  291. fourcc = image_list[i].fourcc;
  292. pix_fmt = vaapi_pix_fmt_from_fourcc(fourcc);
  293. if (pix_fmt == AV_PIX_FMT_NONE) {
  294. av_log(hwdev, AV_LOG_DEBUG, "Format %#x -> unknown.\n",
  295. fourcc);
  296. } else {
  297. av_log(hwdev, AV_LOG_DEBUG, "Format %#x -> %s.\n",
  298. fourcc, av_get_pix_fmt_name(pix_fmt));
  299. ctx->formats[ctx->nb_formats].pix_fmt = pix_fmt;
  300. ctx->formats[ctx->nb_formats].image_format = image_list[i];
  301. ++ctx->nb_formats;
  302. }
  303. }
  304. if (hwctx->driver_quirks & AV_VAAPI_DRIVER_QUIRK_USER_SET) {
  305. av_log(hwdev, AV_LOG_VERBOSE, "Not detecting driver: "
  306. "quirks set by user.\n");
  307. } else {
  308. // Detect the driver in use and set quirk flags if necessary.
  309. vendor_string = vaQueryVendorString(hwctx->display);
  310. hwctx->driver_quirks = 0;
  311. if (vendor_string) {
  312. for (i = 0; i < FF_ARRAY_ELEMS(vaapi_driver_quirks_table); i++) {
  313. if (strstr(vendor_string,
  314. vaapi_driver_quirks_table[i].match_string)) {
  315. av_log(hwdev, AV_LOG_VERBOSE, "Matched \"%s\" as known "
  316. "driver \"%s\".\n", vendor_string,
  317. vaapi_driver_quirks_table[i].friendly_name);
  318. hwctx->driver_quirks |=
  319. vaapi_driver_quirks_table[i].quirks;
  320. break;
  321. }
  322. }
  323. if (!(i < FF_ARRAY_ELEMS(vaapi_driver_quirks_table))) {
  324. av_log(hwdev, AV_LOG_VERBOSE, "Unknown driver \"%s\", "
  325. "assuming standard behaviour.\n", vendor_string);
  326. }
  327. }
  328. }
  329. av_free(image_list);
  330. return 0;
  331. fail:
  332. av_freep(&ctx->formats);
  333. av_free(image_list);
  334. return err;
  335. }
  336. static void vaapi_device_uninit(AVHWDeviceContext *hwdev)
  337. {
  338. VAAPIDeviceContext *ctx = hwdev->internal->priv;
  339. av_freep(&ctx->formats);
  340. }
  341. static void vaapi_buffer_free(void *opaque, uint8_t *data)
  342. {
  343. AVHWFramesContext *hwfc = opaque;
  344. AVVAAPIDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  345. VASurfaceID surface_id;
  346. VAStatus vas;
  347. surface_id = (VASurfaceID)(uintptr_t)data;
  348. vas = vaDestroySurfaces(hwctx->display, &surface_id, 1);
  349. if (vas != VA_STATUS_SUCCESS) {
  350. av_log(hwfc, AV_LOG_ERROR, "Failed to destroy surface %#x: "
  351. "%d (%s).\n", surface_id, vas, vaErrorStr(vas));
  352. }
  353. }
  354. static AVBufferRef *vaapi_pool_alloc(void *opaque, int size)
  355. {
  356. AVHWFramesContext *hwfc = opaque;
  357. VAAPIFramesContext *ctx = hwfc->internal->priv;
  358. AVVAAPIDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  359. AVVAAPIFramesContext *avfc = hwfc->hwctx;
  360. VASurfaceID surface_id;
  361. VAStatus vas;
  362. AVBufferRef *ref;
  363. if (hwfc->initial_pool_size > 0 &&
  364. avfc->nb_surfaces >= hwfc->initial_pool_size)
  365. return NULL;
  366. vas = vaCreateSurfaces(hwctx->display, ctx->rt_format,
  367. hwfc->width, hwfc->height,
  368. &surface_id, 1,
  369. ctx->attributes, ctx->nb_attributes);
  370. if (vas != VA_STATUS_SUCCESS) {
  371. av_log(hwfc, AV_LOG_ERROR, "Failed to create surface: "
  372. "%d (%s).\n", vas, vaErrorStr(vas));
  373. return NULL;
  374. }
  375. av_log(hwfc, AV_LOG_DEBUG, "Created surface %#x.\n", surface_id);
  376. ref = av_buffer_create((uint8_t*)(uintptr_t)surface_id,
  377. sizeof(surface_id), &vaapi_buffer_free,
  378. hwfc, AV_BUFFER_FLAG_READONLY);
  379. if (!ref) {
  380. vaDestroySurfaces(hwctx->display, &surface_id, 1);
  381. return NULL;
  382. }
  383. if (hwfc->initial_pool_size > 0) {
  384. // This is a fixed-size pool, so we must still be in the initial
  385. // allocation sequence.
  386. av_assert0(avfc->nb_surfaces < hwfc->initial_pool_size);
  387. avfc->surface_ids[avfc->nb_surfaces] = surface_id;
  388. ++avfc->nb_surfaces;
  389. }
  390. return ref;
  391. }
  392. static int vaapi_frames_init(AVHWFramesContext *hwfc)
  393. {
  394. AVVAAPIFramesContext *avfc = hwfc->hwctx;
  395. VAAPIFramesContext *ctx = hwfc->internal->priv;
  396. AVVAAPIDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  397. VAImageFormat *expected_format;
  398. AVBufferRef *test_surface = NULL;
  399. VASurfaceID test_surface_id;
  400. VAImage test_image;
  401. VAStatus vas;
  402. int err, i;
  403. unsigned int fourcc, rt_format;
  404. for (i = 0; i < FF_ARRAY_ELEMS(vaapi_format_map); i++) {
  405. if (vaapi_format_map[i].pix_fmt == hwfc->sw_format) {
  406. fourcc = vaapi_format_map[i].fourcc;
  407. rt_format = vaapi_format_map[i].rt_format;
  408. break;
  409. }
  410. }
  411. if (i >= FF_ARRAY_ELEMS(vaapi_format_map)) {
  412. av_log(hwfc, AV_LOG_ERROR, "Unsupported format: %s.\n",
  413. av_get_pix_fmt_name(hwfc->sw_format));
  414. return AVERROR(EINVAL);
  415. }
  416. if (!hwfc->pool) {
  417. if (!(hwctx->driver_quirks & AV_VAAPI_DRIVER_QUIRK_SURFACE_ATTRIBUTES)) {
  418. int need_memory_type = !(hwctx->driver_quirks & AV_VAAPI_DRIVER_QUIRK_ATTRIB_MEMTYPE);
  419. int need_pixel_format = 1;
  420. for (i = 0; i < avfc->nb_attributes; i++) {
  421. if (ctx->attributes[i].type == VASurfaceAttribMemoryType)
  422. need_memory_type = 0;
  423. if (ctx->attributes[i].type == VASurfaceAttribPixelFormat)
  424. need_pixel_format = 0;
  425. }
  426. ctx->nb_attributes =
  427. avfc->nb_attributes + need_memory_type + need_pixel_format;
  428. ctx->attributes = av_malloc(ctx->nb_attributes *
  429. sizeof(*ctx->attributes));
  430. if (!ctx->attributes) {
  431. err = AVERROR(ENOMEM);
  432. goto fail;
  433. }
  434. for (i = 0; i < avfc->nb_attributes; i++)
  435. ctx->attributes[i] = avfc->attributes[i];
  436. if (need_memory_type) {
  437. ctx->attributes[i++] = (VASurfaceAttrib) {
  438. .type = VASurfaceAttribMemoryType,
  439. .flags = VA_SURFACE_ATTRIB_SETTABLE,
  440. .value.type = VAGenericValueTypeInteger,
  441. .value.value.i = VA_SURFACE_ATTRIB_MEM_TYPE_VA,
  442. };
  443. }
  444. if (need_pixel_format) {
  445. ctx->attributes[i++] = (VASurfaceAttrib) {
  446. .type = VASurfaceAttribPixelFormat,
  447. .flags = VA_SURFACE_ATTRIB_SETTABLE,
  448. .value.type = VAGenericValueTypeInteger,
  449. .value.value.i = fourcc,
  450. };
  451. }
  452. av_assert0(i == ctx->nb_attributes);
  453. } else {
  454. ctx->attributes = NULL;
  455. ctx->nb_attributes = 0;
  456. }
  457. ctx->rt_format = rt_format;
  458. if (hwfc->initial_pool_size > 0) {
  459. // This pool will be usable as a render target, so we need to store
  460. // all of the surface IDs somewhere that vaCreateContext() calls
  461. // will be able to access them.
  462. avfc->nb_surfaces = 0;
  463. avfc->surface_ids = av_malloc(hwfc->initial_pool_size *
  464. sizeof(*avfc->surface_ids));
  465. if (!avfc->surface_ids) {
  466. err = AVERROR(ENOMEM);
  467. goto fail;
  468. }
  469. } else {
  470. // This pool allows dynamic sizing, and will not be usable as a
  471. // render target.
  472. avfc->nb_surfaces = 0;
  473. avfc->surface_ids = NULL;
  474. }
  475. hwfc->internal->pool_internal =
  476. av_buffer_pool_init2(sizeof(VASurfaceID), hwfc,
  477. &vaapi_pool_alloc, NULL);
  478. if (!hwfc->internal->pool_internal) {
  479. av_log(hwfc, AV_LOG_ERROR, "Failed to create VAAPI surface pool.\n");
  480. err = AVERROR(ENOMEM);
  481. goto fail;
  482. }
  483. }
  484. // Allocate a single surface to test whether vaDeriveImage() is going
  485. // to work for the specific configuration.
  486. if (hwfc->pool) {
  487. test_surface = av_buffer_pool_get(hwfc->pool);
  488. if (!test_surface) {
  489. av_log(hwfc, AV_LOG_ERROR, "Unable to allocate a surface from "
  490. "user-configured buffer pool.\n");
  491. err = AVERROR(ENOMEM);
  492. goto fail;
  493. }
  494. } else {
  495. test_surface = av_buffer_pool_get(hwfc->internal->pool_internal);
  496. if (!test_surface) {
  497. av_log(hwfc, AV_LOG_ERROR, "Unable to allocate a surface from "
  498. "internal buffer pool.\n");
  499. err = AVERROR(ENOMEM);
  500. goto fail;
  501. }
  502. }
  503. test_surface_id = (VASurfaceID)(uintptr_t)test_surface->data;
  504. ctx->derive_works = 0;
  505. err = vaapi_get_image_format(hwfc->device_ctx,
  506. hwfc->sw_format, &expected_format);
  507. if (err == 0) {
  508. vas = vaDeriveImage(hwctx->display, test_surface_id, &test_image);
  509. if (vas == VA_STATUS_SUCCESS) {
  510. if (expected_format->fourcc == test_image.format.fourcc) {
  511. av_log(hwfc, AV_LOG_DEBUG, "Direct mapping possible.\n");
  512. ctx->derive_works = 1;
  513. } else {
  514. av_log(hwfc, AV_LOG_DEBUG, "Direct mapping disabled: "
  515. "derived image format %08x does not match "
  516. "expected format %08x.\n",
  517. expected_format->fourcc, test_image.format.fourcc);
  518. }
  519. vaDestroyImage(hwctx->display, test_image.image_id);
  520. } else {
  521. av_log(hwfc, AV_LOG_DEBUG, "Direct mapping disabled: "
  522. "deriving image does not work: "
  523. "%d (%s).\n", vas, vaErrorStr(vas));
  524. }
  525. } else {
  526. av_log(hwfc, AV_LOG_DEBUG, "Direct mapping disabled: "
  527. "image format is not supported.\n");
  528. }
  529. av_buffer_unref(&test_surface);
  530. return 0;
  531. fail:
  532. av_buffer_unref(&test_surface);
  533. av_freep(&avfc->surface_ids);
  534. av_freep(&ctx->attributes);
  535. return err;
  536. }
  537. static void vaapi_frames_uninit(AVHWFramesContext *hwfc)
  538. {
  539. AVVAAPIFramesContext *avfc = hwfc->hwctx;
  540. VAAPIFramesContext *ctx = hwfc->internal->priv;
  541. av_freep(&avfc->surface_ids);
  542. av_freep(&ctx->attributes);
  543. }
  544. static int vaapi_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
  545. {
  546. frame->buf[0] = av_buffer_pool_get(hwfc->pool);
  547. if (!frame->buf[0])
  548. return AVERROR(ENOMEM);
  549. frame->data[3] = frame->buf[0]->data;
  550. frame->format = AV_PIX_FMT_VAAPI;
  551. frame->width = hwfc->width;
  552. frame->height = hwfc->height;
  553. return 0;
  554. }
  555. static int vaapi_transfer_get_formats(AVHWFramesContext *hwfc,
  556. enum AVHWFrameTransferDirection dir,
  557. enum AVPixelFormat **formats)
  558. {
  559. VAAPIDeviceContext *ctx = hwfc->device_ctx->internal->priv;
  560. enum AVPixelFormat *pix_fmts, preferred_format;
  561. int i, k;
  562. preferred_format = hwfc->sw_format;
  563. pix_fmts = av_malloc((ctx->nb_formats + 1) * sizeof(*pix_fmts));
  564. if (!pix_fmts)
  565. return AVERROR(ENOMEM);
  566. pix_fmts[0] = preferred_format;
  567. k = 1;
  568. for (i = 0; i < ctx->nb_formats; i++) {
  569. if (ctx->formats[i].pix_fmt == preferred_format)
  570. continue;
  571. av_assert0(k < ctx->nb_formats);
  572. pix_fmts[k++] = ctx->formats[i].pix_fmt;
  573. }
  574. av_assert0(k == ctx->nb_formats);
  575. pix_fmts[k] = AV_PIX_FMT_NONE;
  576. *formats = pix_fmts;
  577. return 0;
  578. }
  579. static void vaapi_unmap_frame(AVHWFramesContext *hwfc,
  580. HWMapDescriptor *hwmap)
  581. {
  582. AVVAAPIDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  583. VAAPIMapping *map = hwmap->priv;
  584. VASurfaceID surface_id;
  585. VAStatus vas;
  586. surface_id = (VASurfaceID)(uintptr_t)hwmap->source->data[3];
  587. av_log(hwfc, AV_LOG_DEBUG, "Unmap surface %#x.\n", surface_id);
  588. vas = vaUnmapBuffer(hwctx->display, map->image.buf);
  589. if (vas != VA_STATUS_SUCCESS) {
  590. av_log(hwfc, AV_LOG_ERROR, "Failed to unmap image from surface "
  591. "%#x: %d (%s).\n", surface_id, vas, vaErrorStr(vas));
  592. }
  593. if ((map->flags & AV_HWFRAME_MAP_WRITE) &&
  594. !(map->flags & AV_HWFRAME_MAP_DIRECT)) {
  595. vas = vaPutImage(hwctx->display, surface_id, map->image.image_id,
  596. 0, 0, hwfc->width, hwfc->height,
  597. 0, 0, hwfc->width, hwfc->height);
  598. if (vas != VA_STATUS_SUCCESS) {
  599. av_log(hwfc, AV_LOG_ERROR, "Failed to write image to surface "
  600. "%#x: %d (%s).\n", surface_id, vas, vaErrorStr(vas));
  601. }
  602. }
  603. vas = vaDestroyImage(hwctx->display, map->image.image_id);
  604. if (vas != VA_STATUS_SUCCESS) {
  605. av_log(hwfc, AV_LOG_ERROR, "Failed to destroy image from surface "
  606. "%#x: %d (%s).\n", surface_id, vas, vaErrorStr(vas));
  607. }
  608. av_free(map);
  609. }
  610. static int vaapi_map_frame(AVHWFramesContext *hwfc,
  611. AVFrame *dst, const AVFrame *src, int flags)
  612. {
  613. AVVAAPIDeviceContext *hwctx = hwfc->device_ctx->hwctx;
  614. VAAPIFramesContext *ctx = hwfc->internal->priv;
  615. VASurfaceID surface_id;
  616. VAImageFormat *image_format;
  617. VAAPIMapping *map;
  618. VAStatus vas;
  619. void *address = NULL;
  620. int err, i;
  621. surface_id = (VASurfaceID)(uintptr_t)src->data[3];
  622. av_log(hwfc, AV_LOG_DEBUG, "Map surface %#x.\n", surface_id);
  623. if (!ctx->derive_works && (flags & AV_HWFRAME_MAP_DIRECT)) {
  624. // Requested direct mapping but it is not possible.
  625. return AVERROR(EINVAL);
  626. }
  627. if (dst->format == AV_PIX_FMT_NONE)
  628. dst->format = hwfc->sw_format;
  629. if (dst->format != hwfc->sw_format && (flags & AV_HWFRAME_MAP_DIRECT)) {
  630. // Requested direct mapping but the formats do not match.
  631. return AVERROR(EINVAL);
  632. }
  633. err = vaapi_get_image_format(hwfc->device_ctx, dst->format, &image_format);
  634. if (err < 0) {
  635. // Requested format is not a valid output format.
  636. return AVERROR(EINVAL);
  637. }
  638. map = av_malloc(sizeof(*map));
  639. if (!map)
  640. return AVERROR(ENOMEM);
  641. map->flags = flags;
  642. map->image.image_id = VA_INVALID_ID;
  643. vas = vaSyncSurface(hwctx->display, surface_id);
  644. if (vas != VA_STATUS_SUCCESS) {
  645. av_log(hwfc, AV_LOG_ERROR, "Failed to sync surface "
  646. "%#x: %d (%s).\n", surface_id, vas, vaErrorStr(vas));
  647. err = AVERROR(EIO);
  648. goto fail;
  649. }
  650. // The memory which we map using derive need not be connected to the CPU
  651. // in a way conducive to fast access. On Gen7-Gen9 Intel graphics, the
  652. // memory is mappable but not cached, so normal memcpy()-like access is
  653. // very slow to read it (but writing is ok). It is possible to read much
  654. // faster with a copy routine which is aware of the limitation, but we
  655. // assume for now that the user is not aware of that and would therefore
  656. // prefer not to be given direct-mapped memory if they request read access.
  657. if (ctx->derive_works && dst->format == hwfc->sw_format &&
  658. ((flags & AV_HWFRAME_MAP_DIRECT) || !(flags & AV_HWFRAME_MAP_READ))) {
  659. vas = vaDeriveImage(hwctx->display, surface_id, &map->image);
  660. if (vas != VA_STATUS_SUCCESS) {
  661. av_log(hwfc, AV_LOG_ERROR, "Failed to derive image from "
  662. "surface %#x: %d (%s).\n",
  663. surface_id, vas, vaErrorStr(vas));
  664. err = AVERROR(EIO);
  665. goto fail;
  666. }
  667. if (map->image.format.fourcc != image_format->fourcc) {
  668. av_log(hwfc, AV_LOG_ERROR, "Derive image of surface %#x "
  669. "is in wrong format: expected %#08x, got %#08x.\n",
  670. surface_id, image_format->fourcc, map->image.format.fourcc);
  671. err = AVERROR(EIO);
  672. goto fail;
  673. }
  674. map->flags |= AV_HWFRAME_MAP_DIRECT;
  675. } else {
  676. vas = vaCreateImage(hwctx->display, image_format,
  677. hwfc->width, hwfc->height, &map->image);
  678. if (vas != VA_STATUS_SUCCESS) {
  679. av_log(hwfc, AV_LOG_ERROR, "Failed to create image for "
  680. "surface %#x: %d (%s).\n",
  681. surface_id, vas, vaErrorStr(vas));
  682. err = AVERROR(EIO);
  683. goto fail;
  684. }
  685. if (!(flags & AV_HWFRAME_MAP_OVERWRITE)) {
  686. vas = vaGetImage(hwctx->display, surface_id, 0, 0,
  687. hwfc->width, hwfc->height, map->image.image_id);
  688. if (vas != VA_STATUS_SUCCESS) {
  689. av_log(hwfc, AV_LOG_ERROR, "Failed to read image from "
  690. "surface %#x: %d (%s).\n",
  691. surface_id, vas, vaErrorStr(vas));
  692. err = AVERROR(EIO);
  693. goto fail;
  694. }
  695. }
  696. }
  697. vas = vaMapBuffer(hwctx->display, map->image.buf, &address);
  698. if (vas != VA_STATUS_SUCCESS) {
  699. av_log(hwfc, AV_LOG_ERROR, "Failed to map image from surface "
  700. "%#x: %d (%s).\n", surface_id, vas, vaErrorStr(vas));
  701. err = AVERROR(EIO);
  702. goto fail;
  703. }
  704. err = ff_hwframe_map_create(src->hw_frames_ctx,
  705. dst, src, &vaapi_unmap_frame, map);
  706. if (err < 0)
  707. goto fail;
  708. dst->width = src->width;
  709. dst->height = src->height;
  710. for (i = 0; i < map->image.num_planes; i++) {
  711. dst->data[i] = (uint8_t*)address + map->image.offsets[i];
  712. dst->linesize[i] = map->image.pitches[i];
  713. }
  714. if (
  715. #ifdef VA_FOURCC_YV16
  716. map->image.format.fourcc == VA_FOURCC_YV16 ||
  717. #endif
  718. map->image.format.fourcc == VA_FOURCC_YV12) {
  719. // Chroma planes are YVU rather than YUV, so swap them.
  720. FFSWAP(uint8_t*, dst->data[1], dst->data[2]);
  721. }
  722. return 0;
  723. fail:
  724. if (map) {
  725. if (address)
  726. vaUnmapBuffer(hwctx->display, map->image.buf);
  727. if (map->image.image_id != VA_INVALID_ID)
  728. vaDestroyImage(hwctx->display, map->image.image_id);
  729. av_free(map);
  730. }
  731. return err;
  732. }
  733. static int vaapi_transfer_data_from(AVHWFramesContext *hwfc,
  734. AVFrame *dst, const AVFrame *src)
  735. {
  736. AVFrame *map;
  737. int err;
  738. if (dst->width > hwfc->width || dst->height > hwfc->height)
  739. return AVERROR(EINVAL);
  740. map = av_frame_alloc();
  741. if (!map)
  742. return AVERROR(ENOMEM);
  743. map->format = dst->format;
  744. err = vaapi_map_frame(hwfc, map, src, AV_HWFRAME_MAP_READ);
  745. if (err)
  746. goto fail;
  747. map->width = dst->width;
  748. map->height = dst->height;
  749. err = av_frame_copy(dst, map);
  750. if (err)
  751. goto fail;
  752. err = 0;
  753. fail:
  754. av_frame_free(&map);
  755. return err;
  756. }
  757. static int vaapi_transfer_data_to(AVHWFramesContext *hwfc,
  758. AVFrame *dst, const AVFrame *src)
  759. {
  760. AVFrame *map;
  761. int err;
  762. if (src->width > hwfc->width || src->height > hwfc->height)
  763. return AVERROR(EINVAL);
  764. map = av_frame_alloc();
  765. if (!map)
  766. return AVERROR(ENOMEM);
  767. map->format = src->format;
  768. err = vaapi_map_frame(hwfc, map, dst, AV_HWFRAME_MAP_WRITE | AV_HWFRAME_MAP_OVERWRITE);
  769. if (err)
  770. goto fail;
  771. map->width = src->width;
  772. map->height = src->height;
  773. err = av_frame_copy(map, src);
  774. if (err)
  775. goto fail;
  776. err = 0;
  777. fail:
  778. av_frame_free(&map);
  779. return err;
  780. }
  781. static int vaapi_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
  782. const AVFrame *src, int flags)
  783. {
  784. int err;
  785. if (dst->format != AV_PIX_FMT_NONE) {
  786. err = vaapi_get_image_format(hwfc->device_ctx, dst->format, NULL);
  787. if (err < 0)
  788. return AVERROR(ENOSYS);
  789. }
  790. err = vaapi_map_frame(hwfc, dst, src, flags);
  791. if (err)
  792. return err;
  793. err = av_frame_copy_props(dst, src);
  794. if (err)
  795. return err;
  796. return 0;
  797. }
  798. static void vaapi_device_free(AVHWDeviceContext *ctx)
  799. {
  800. AVVAAPIDeviceContext *hwctx = ctx->hwctx;
  801. VAAPIDevicePriv *priv = ctx->user_opaque;
  802. if (hwctx->display)
  803. vaTerminate(hwctx->display);
  804. #if HAVE_VAAPI_X11
  805. if (priv->x11_display)
  806. XCloseDisplay(priv->x11_display);
  807. #endif
  808. if (priv->drm_fd >= 0)
  809. close(priv->drm_fd);
  810. av_freep(&priv);
  811. }
  812. static int vaapi_device_create(AVHWDeviceContext *ctx, const char *device,
  813. AVDictionary *opts, int flags)
  814. {
  815. AVVAAPIDeviceContext *hwctx = ctx->hwctx;
  816. VAAPIDevicePriv *priv;
  817. VADisplay display = 0;
  818. VAStatus vas;
  819. int major, minor;
  820. priv = av_mallocz(sizeof(*priv));
  821. if (!priv)
  822. return AVERROR(ENOMEM);
  823. priv->drm_fd = -1;
  824. ctx->user_opaque = priv;
  825. ctx->free = vaapi_device_free;
  826. #if HAVE_VAAPI_X11
  827. if (!display && !(device && device[0] == '/')) {
  828. // Try to open the device as an X11 display.
  829. priv->x11_display = XOpenDisplay(device);
  830. if (!priv->x11_display) {
  831. av_log(ctx, AV_LOG_VERBOSE, "Cannot open X11 display "
  832. "%s.\n", XDisplayName(device));
  833. } else {
  834. display = vaGetDisplay(priv->x11_display);
  835. if (!display) {
  836. av_log(ctx, AV_LOG_ERROR, "Cannot open a VA display "
  837. "from X11 display %s.\n", XDisplayName(device));
  838. return AVERROR_UNKNOWN;
  839. }
  840. av_log(ctx, AV_LOG_VERBOSE, "Opened VA display via "
  841. "X11 display %s.\n", XDisplayName(device));
  842. }
  843. }
  844. #endif
  845. #if HAVE_VAAPI_DRM
  846. if (!display) {
  847. // Try to open the device as a DRM path.
  848. // Default to using the first render node if the user did not
  849. // supply a path.
  850. const char *path = device ? device : "/dev/dri/renderD128";
  851. priv->drm_fd = open(path, O_RDWR);
  852. if (priv->drm_fd < 0) {
  853. av_log(ctx, AV_LOG_VERBOSE, "Cannot open DRM device %s.\n",
  854. path);
  855. } else {
  856. display = vaGetDisplayDRM(priv->drm_fd);
  857. if (!display) {
  858. av_log(ctx, AV_LOG_ERROR, "Cannot open a VA display "
  859. "from DRM device %s.\n", path);
  860. return AVERROR_UNKNOWN;
  861. }
  862. av_log(ctx, AV_LOG_VERBOSE, "Opened VA display via "
  863. "DRM device %s.\n", path);
  864. }
  865. }
  866. #endif
  867. if (!display) {
  868. av_log(ctx, AV_LOG_ERROR, "No VA display found for "
  869. "device: %s.\n", device ? device : "");
  870. return AVERROR(EINVAL);
  871. }
  872. hwctx->display = display;
  873. vas = vaInitialize(display, &major, &minor);
  874. if (vas != VA_STATUS_SUCCESS) {
  875. av_log(ctx, AV_LOG_ERROR, "Failed to initialise VAAPI "
  876. "connection: %d (%s).\n", vas, vaErrorStr(vas));
  877. return AVERROR(EIO);
  878. }
  879. av_log(ctx, AV_LOG_VERBOSE, "Initialised VAAPI connection: "
  880. "version %d.%d\n", major, minor);
  881. return 0;
  882. }
  883. const HWContextType ff_hwcontext_type_vaapi = {
  884. .type = AV_HWDEVICE_TYPE_VAAPI,
  885. .name = "VAAPI",
  886. .device_hwctx_size = sizeof(AVVAAPIDeviceContext),
  887. .device_priv_size = sizeof(VAAPIDeviceContext),
  888. .device_hwconfig_size = sizeof(AVVAAPIHWConfig),
  889. .frames_hwctx_size = sizeof(AVVAAPIFramesContext),
  890. .frames_priv_size = sizeof(VAAPIFramesContext),
  891. .device_create = &vaapi_device_create,
  892. .device_init = &vaapi_device_init,
  893. .device_uninit = &vaapi_device_uninit,
  894. .frames_get_constraints = &vaapi_frames_get_constraints,
  895. .frames_init = &vaapi_frames_init,
  896. .frames_uninit = &vaapi_frames_uninit,
  897. .frames_get_buffer = &vaapi_get_buffer,
  898. .transfer_get_formats = &vaapi_transfer_get_formats,
  899. .transfer_data_to = &vaapi_transfer_data_to,
  900. .transfer_data_from = &vaapi_transfer_data_from,
  901. .map_to = NULL,
  902. .map_from = &vaapi_map_from,
  903. .pix_fmts = (const enum AVPixelFormat[]) {
  904. AV_PIX_FMT_VAAPI,
  905. AV_PIX_FMT_NONE
  906. },
  907. };