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.

983 lines
32KB

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