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.

1418 lines
47KB

  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 "formats.h"
  19. #include "vulkan.h"
  20. #include "glslang.h"
  21. /* Generic macro for creating contexts which need to keep their addresses
  22. * if another context is created. */
  23. #define FN_CREATING(ctx, type, shortname, array, num) \
  24. static av_always_inline type *create_ ##shortname(ctx *dctx) \
  25. { \
  26. type **array, *sctx = av_mallocz(sizeof(*sctx)); \
  27. if (!sctx) \
  28. return NULL; \
  29. \
  30. array = av_realloc_array(dctx->array, sizeof(*dctx->array), dctx->num + 1);\
  31. if (!array) { \
  32. av_free(sctx); \
  33. return NULL; \
  34. } \
  35. \
  36. dctx->array = array; \
  37. dctx->array[dctx->num++] = sctx; \
  38. \
  39. return sctx; \
  40. }
  41. const VkComponentMapping ff_comp_identity_map = {
  42. .r = VK_COMPONENT_SWIZZLE_IDENTITY,
  43. .g = VK_COMPONENT_SWIZZLE_IDENTITY,
  44. .b = VK_COMPONENT_SWIZZLE_IDENTITY,
  45. .a = VK_COMPONENT_SWIZZLE_IDENTITY,
  46. };
  47. /* Converts return values to strings */
  48. const char *ff_vk_ret2str(VkResult res)
  49. {
  50. #define CASE(VAL) case VAL: return #VAL
  51. switch (res) {
  52. CASE(VK_SUCCESS);
  53. CASE(VK_NOT_READY);
  54. CASE(VK_TIMEOUT);
  55. CASE(VK_EVENT_SET);
  56. CASE(VK_EVENT_RESET);
  57. CASE(VK_INCOMPLETE);
  58. CASE(VK_ERROR_OUT_OF_HOST_MEMORY);
  59. CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY);
  60. CASE(VK_ERROR_INITIALIZATION_FAILED);
  61. CASE(VK_ERROR_DEVICE_LOST);
  62. CASE(VK_ERROR_MEMORY_MAP_FAILED);
  63. CASE(VK_ERROR_LAYER_NOT_PRESENT);
  64. CASE(VK_ERROR_EXTENSION_NOT_PRESENT);
  65. CASE(VK_ERROR_FEATURE_NOT_PRESENT);
  66. CASE(VK_ERROR_INCOMPATIBLE_DRIVER);
  67. CASE(VK_ERROR_TOO_MANY_OBJECTS);
  68. CASE(VK_ERROR_FORMAT_NOT_SUPPORTED);
  69. CASE(VK_ERROR_FRAGMENTED_POOL);
  70. CASE(VK_ERROR_SURFACE_LOST_KHR);
  71. CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR);
  72. CASE(VK_SUBOPTIMAL_KHR);
  73. CASE(VK_ERROR_OUT_OF_DATE_KHR);
  74. CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR);
  75. CASE(VK_ERROR_VALIDATION_FAILED_EXT);
  76. CASE(VK_ERROR_INVALID_SHADER_NV);
  77. CASE(VK_ERROR_OUT_OF_POOL_MEMORY);
  78. CASE(VK_ERROR_INVALID_EXTERNAL_HANDLE);
  79. CASE(VK_ERROR_NOT_PERMITTED_EXT);
  80. default: return "Unknown error";
  81. }
  82. #undef CASE
  83. }
  84. static int vk_alloc_mem(AVFilterContext *avctx, VkMemoryRequirements *req,
  85. VkMemoryPropertyFlagBits req_flags, void *alloc_extension,
  86. VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
  87. {
  88. VkResult ret;
  89. int index = -1;
  90. VkPhysicalDeviceProperties props;
  91. VkPhysicalDeviceMemoryProperties mprops;
  92. VulkanFilterContext *s = avctx->priv;
  93. VkMemoryAllocateInfo alloc_info = {
  94. .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
  95. .pNext = alloc_extension,
  96. };
  97. vkGetPhysicalDeviceProperties(s->hwctx->phys_dev, &props);
  98. vkGetPhysicalDeviceMemoryProperties(s->hwctx->phys_dev, &mprops);
  99. /* Align if we need to */
  100. if (req_flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
  101. req->size = FFALIGN(req->size, props.limits.minMemoryMapAlignment);
  102. alloc_info.allocationSize = req->size;
  103. /* The vulkan spec requires memory types to be sorted in the "optimal"
  104. * order, so the first matching type we find will be the best/fastest one */
  105. for (int i = 0; i < mprops.memoryTypeCount; i++) {
  106. /* The memory type must be supported by the requirements (bitfield) */
  107. if (!(req->memoryTypeBits & (1 << i)))
  108. continue;
  109. /* The memory type flags must include our properties */
  110. if ((mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
  111. continue;
  112. /* Found a suitable memory type */
  113. index = i;
  114. break;
  115. }
  116. if (index < 0) {
  117. av_log(avctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
  118. req_flags);
  119. return AVERROR(EINVAL);
  120. }
  121. alloc_info.memoryTypeIndex = index;
  122. ret = vkAllocateMemory(s->hwctx->act_dev, &alloc_info,
  123. s->hwctx->alloc, mem);
  124. if (ret != VK_SUCCESS) {
  125. av_log(avctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
  126. ff_vk_ret2str(ret));
  127. return AVERROR(ENOMEM);
  128. }
  129. *mem_flags |= mprops.memoryTypes[index].propertyFlags;
  130. return 0;
  131. }
  132. int ff_vk_create_buf(AVFilterContext *avctx, FFVkBuffer *buf, size_t size,
  133. VkBufferUsageFlags usage, VkMemoryPropertyFlagBits flags)
  134. {
  135. int err;
  136. VkResult ret;
  137. VkMemoryRequirements req;
  138. VulkanFilterContext *s = avctx->priv;
  139. VkBufferCreateInfo buf_spawn = {
  140. .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
  141. .pNext = NULL,
  142. .usage = usage,
  143. .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
  144. .size = size, /* Gets FFALIGNED during alloc if host visible
  145. but should be ok */
  146. };
  147. ret = vkCreateBuffer(s->hwctx->act_dev, &buf_spawn, NULL, &buf->buf);
  148. if (ret != VK_SUCCESS) {
  149. av_log(avctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
  150. ff_vk_ret2str(ret));
  151. return AVERROR_EXTERNAL;
  152. }
  153. vkGetBufferMemoryRequirements(s->hwctx->act_dev, buf->buf, &req);
  154. err = vk_alloc_mem(avctx, &req, flags, NULL, &buf->flags, &buf->mem);
  155. if (err)
  156. return err;
  157. ret = vkBindBufferMemory(s->hwctx->act_dev, buf->buf, buf->mem, 0);
  158. if (ret != VK_SUCCESS) {
  159. av_log(avctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
  160. ff_vk_ret2str(ret));
  161. return AVERROR_EXTERNAL;
  162. }
  163. return 0;
  164. }
  165. int ff_vk_map_buffers(AVFilterContext *avctx, FFVkBuffer *buf, uint8_t *mem[],
  166. int nb_buffers, int invalidate)
  167. {
  168. VkResult ret;
  169. VulkanFilterContext *s = avctx->priv;
  170. VkMappedMemoryRange *inval_list = NULL;
  171. int inval_count = 0;
  172. for (int i = 0; i < nb_buffers; i++) {
  173. ret = vkMapMemory(s->hwctx->act_dev, buf[i].mem, 0,
  174. VK_WHOLE_SIZE, 0, (void **)&mem[i]);
  175. if (ret != VK_SUCCESS) {
  176. av_log(avctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
  177. ff_vk_ret2str(ret));
  178. return AVERROR_EXTERNAL;
  179. }
  180. }
  181. if (!invalidate)
  182. return 0;
  183. for (int i = 0; i < nb_buffers; i++) {
  184. const VkMappedMemoryRange ival_buf = {
  185. .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
  186. .memory = buf[i].mem,
  187. .size = VK_WHOLE_SIZE,
  188. };
  189. if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
  190. continue;
  191. inval_list = av_fast_realloc(s->scratch, &s->scratch_size,
  192. (++inval_count)*sizeof(*inval_list));
  193. if (!inval_list)
  194. return AVERROR(ENOMEM);
  195. inval_list[inval_count - 1] = ival_buf;
  196. }
  197. if (inval_count) {
  198. ret = vkInvalidateMappedMemoryRanges(s->hwctx->act_dev, inval_count,
  199. inval_list);
  200. if (ret != VK_SUCCESS) {
  201. av_log(avctx, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
  202. ff_vk_ret2str(ret));
  203. return AVERROR_EXTERNAL;
  204. }
  205. }
  206. return 0;
  207. }
  208. int ff_vk_unmap_buffers(AVFilterContext *avctx, FFVkBuffer *buf, int nb_buffers,
  209. int flush)
  210. {
  211. int err = 0;
  212. VkResult ret;
  213. VulkanFilterContext *s = avctx->priv;
  214. VkMappedMemoryRange *flush_list = NULL;
  215. int flush_count = 0;
  216. if (flush) {
  217. for (int i = 0; i < nb_buffers; i++) {
  218. const VkMappedMemoryRange flush_buf = {
  219. .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
  220. .memory = buf[i].mem,
  221. .size = VK_WHOLE_SIZE,
  222. };
  223. if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
  224. continue;
  225. flush_list = av_fast_realloc(s->scratch, &s->scratch_size,
  226. (++flush_count)*sizeof(*flush_list));
  227. if (!flush_list)
  228. return AVERROR(ENOMEM);
  229. flush_list[flush_count - 1] = flush_buf;
  230. }
  231. }
  232. if (flush_count) {
  233. ret = vkFlushMappedMemoryRanges(s->hwctx->act_dev, flush_count,
  234. flush_list);
  235. if (ret != VK_SUCCESS) {
  236. av_log(avctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
  237. ff_vk_ret2str(ret));
  238. err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
  239. }
  240. }
  241. for (int i = 0; i < nb_buffers; i++)
  242. vkUnmapMemory(s->hwctx->act_dev, buf[i].mem);
  243. return err;
  244. }
  245. void ff_vk_free_buf(AVFilterContext *avctx, FFVkBuffer *buf)
  246. {
  247. VulkanFilterContext *s = avctx->priv;
  248. if (!buf)
  249. return;
  250. if (buf->buf != VK_NULL_HANDLE)
  251. vkDestroyBuffer(s->hwctx->act_dev, buf->buf, s->hwctx->alloc);
  252. if (buf->mem != VK_NULL_HANDLE)
  253. vkFreeMemory(s->hwctx->act_dev, buf->mem, s->hwctx->alloc);
  254. }
  255. int ff_vk_add_push_constant(AVFilterContext *avctx, VulkanPipeline *pl,
  256. int offset, int size, VkShaderStageFlagBits stage)
  257. {
  258. VkPushConstantRange *pc;
  259. pl->push_consts = av_realloc_array(pl->push_consts, sizeof(*pl->push_consts),
  260. pl->push_consts_num + 1);
  261. if (!pl->push_consts)
  262. return AVERROR(ENOMEM);
  263. pc = &pl->push_consts[pl->push_consts_num++];
  264. memset(pc, 0, sizeof(*pc));
  265. pc->stageFlags = stage;
  266. pc->offset = offset;
  267. pc->size = size;
  268. return 0;
  269. }
  270. FN_CREATING(VulkanFilterContext, FFVkExecContext, exec_ctx, exec_ctx, exec_ctx_num)
  271. int ff_vk_create_exec_ctx(AVFilterContext *avctx, FFVkExecContext **ctx)
  272. {
  273. VkResult ret;
  274. FFVkExecContext *e;
  275. VulkanFilterContext *s = avctx->priv;
  276. int queue_family = s->queue_family_idx;
  277. int nb_queues = s->queue_count;
  278. VkCommandPoolCreateInfo cqueue_create = {
  279. .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
  280. .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
  281. .queueFamilyIndex = queue_family,
  282. };
  283. VkCommandBufferAllocateInfo cbuf_create = {
  284. .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
  285. .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
  286. .commandBufferCount = nb_queues,
  287. };
  288. e = create_exec_ctx(s);
  289. if (!e)
  290. return AVERROR(ENOMEM);
  291. e->queues = av_mallocz(nb_queues * sizeof(*e->queues));
  292. if (!e->queues)
  293. return AVERROR(ENOMEM);
  294. e->bufs = av_mallocz(nb_queues * sizeof(*e->bufs));
  295. if (!e->bufs)
  296. return AVERROR(ENOMEM);
  297. /* Create command pool */
  298. ret = vkCreateCommandPool(s->hwctx->act_dev, &cqueue_create,
  299. s->hwctx->alloc, &e->pool);
  300. if (ret != VK_SUCCESS) {
  301. av_log(avctx, AV_LOG_ERROR, "Command pool creation failure: %s\n",
  302. ff_vk_ret2str(ret));
  303. return AVERROR_EXTERNAL;
  304. }
  305. cbuf_create.commandPool = e->pool;
  306. /* Allocate command buffer */
  307. ret = vkAllocateCommandBuffers(s->hwctx->act_dev, &cbuf_create, e->bufs);
  308. if (ret != VK_SUCCESS) {
  309. av_log(avctx, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
  310. ff_vk_ret2str(ret));
  311. return AVERROR_EXTERNAL;
  312. }
  313. for (int i = 0; i < nb_queues; i++) {
  314. FFVkQueueCtx *q = &e->queues[i];
  315. vkGetDeviceQueue(s->hwctx->act_dev, queue_family, i, &q->queue);
  316. }
  317. *ctx = e;
  318. return 0;
  319. }
  320. void ff_vk_discard_exec_deps(AVFilterContext *avctx, FFVkExecContext *e)
  321. {
  322. VulkanFilterContext *s = avctx->priv;
  323. FFVkQueueCtx *q = &e->queues[s->cur_queue_idx];
  324. for (int j = 0; j < q->nb_buf_deps; j++)
  325. av_buffer_unref(&q->buf_deps[j]);
  326. q->nb_buf_deps = 0;
  327. for (int j = 0; j < q->nb_frame_deps; j++)
  328. av_frame_free(&q->frame_deps[j]);
  329. q->nb_frame_deps = 0;
  330. e->sem_wait_cnt = 0;
  331. e->sem_sig_cnt = 0;
  332. }
  333. int ff_vk_start_exec_recording(AVFilterContext *avctx, FFVkExecContext *e)
  334. {
  335. VkResult ret;
  336. VulkanFilterContext *s = avctx->priv;
  337. FFVkQueueCtx *q = &e->queues[s->cur_queue_idx];
  338. VkCommandBufferBeginInfo cmd_start = {
  339. .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  340. .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
  341. };
  342. /* Create the fence and don't wait for it initially */
  343. if (!q->fence) {
  344. VkFenceCreateInfo fence_spawn = {
  345. .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
  346. };
  347. ret = vkCreateFence(s->hwctx->act_dev, &fence_spawn, s->hwctx->alloc,
  348. &q->fence);
  349. if (ret != VK_SUCCESS) {
  350. av_log(avctx, AV_LOG_ERROR, "Failed to queue frame fence: %s\n",
  351. ff_vk_ret2str(ret));
  352. return AVERROR_EXTERNAL;
  353. }
  354. } else {
  355. vkWaitForFences(s->hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
  356. vkResetFences(s->hwctx->act_dev, 1, &q->fence);
  357. }
  358. /* Discard queue dependencies */
  359. ff_vk_discard_exec_deps(avctx, e);
  360. ret = vkBeginCommandBuffer(e->bufs[s->cur_queue_idx], &cmd_start);
  361. if (ret != VK_SUCCESS) {
  362. av_log(avctx, AV_LOG_ERROR, "Failed to start command recoding: %s\n",
  363. ff_vk_ret2str(ret));
  364. return AVERROR_EXTERNAL;
  365. }
  366. return 0;
  367. }
  368. VkCommandBuffer ff_vk_get_exec_buf(AVFilterContext *avctx, FFVkExecContext *e)
  369. {
  370. VulkanFilterContext *s = avctx->priv;
  371. return e->bufs[s->cur_queue_idx];
  372. }
  373. int ff_vk_add_exec_dep(AVFilterContext *avctx, FFVkExecContext *e,
  374. AVFrame *frame, VkPipelineStageFlagBits in_wait_dst_flag)
  375. {
  376. AVFrame **dst;
  377. VulkanFilterContext *s = avctx->priv;
  378. AVVkFrame *f = (AVVkFrame *)frame->data[0];
  379. FFVkQueueCtx *q = &e->queues[s->cur_queue_idx];
  380. AVHWFramesContext *fc = (AVHWFramesContext *)frame->hw_frames_ctx->data;
  381. int planes = av_pix_fmt_count_planes(fc->sw_format);
  382. for (int i = 0; i < planes; i++) {
  383. e->sem_wait = av_fast_realloc(e->sem_wait, &e->sem_wait_alloc,
  384. (e->sem_wait_cnt + 1)*sizeof(*e->sem_wait));
  385. if (!e->sem_wait) {
  386. ff_vk_discard_exec_deps(avctx, e);
  387. return AVERROR(ENOMEM);
  388. }
  389. e->sem_wait_dst = av_fast_realloc(e->sem_wait_dst, &e->sem_wait_dst_alloc,
  390. (e->sem_wait_cnt + 1)*sizeof(*e->sem_wait_dst));
  391. if (!e->sem_wait_dst) {
  392. ff_vk_discard_exec_deps(avctx, e);
  393. return AVERROR(ENOMEM);
  394. }
  395. e->sem_sig = av_fast_realloc(e->sem_sig, &e->sem_sig_alloc,
  396. (e->sem_sig_cnt + 1)*sizeof(*e->sem_sig));
  397. if (!e->sem_sig) {
  398. ff_vk_discard_exec_deps(avctx, e);
  399. return AVERROR(ENOMEM);
  400. }
  401. e->sem_wait[e->sem_wait_cnt] = f->sem[i];
  402. e->sem_wait_dst[e->sem_wait_cnt] = in_wait_dst_flag;
  403. e->sem_wait_cnt++;
  404. e->sem_sig[e->sem_sig_cnt] = f->sem[i];
  405. e->sem_sig_cnt++;
  406. }
  407. dst = av_fast_realloc(q->frame_deps, &q->frame_deps_alloc_size,
  408. (q->nb_frame_deps + 1) * sizeof(*dst));
  409. if (!dst) {
  410. ff_vk_discard_exec_deps(avctx, e);
  411. return AVERROR(ENOMEM);
  412. }
  413. q->frame_deps = dst;
  414. q->frame_deps[q->nb_frame_deps] = av_frame_clone(frame);
  415. if (!q->frame_deps[q->nb_frame_deps]) {
  416. ff_vk_discard_exec_deps(avctx, e);
  417. return AVERROR(ENOMEM);
  418. }
  419. q->nb_frame_deps++;
  420. return 0;
  421. }
  422. int ff_vk_submit_exec_queue(AVFilterContext *avctx, FFVkExecContext *e)
  423. {
  424. VkResult ret;
  425. VulkanFilterContext *s = avctx->priv;
  426. FFVkQueueCtx *q = &e->queues[s->cur_queue_idx];
  427. VkSubmitInfo s_info = {
  428. .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
  429. .commandBufferCount = 1,
  430. .pCommandBuffers = &e->bufs[s->cur_queue_idx],
  431. .pWaitSemaphores = e->sem_wait,
  432. .pWaitDstStageMask = e->sem_wait_dst,
  433. .waitSemaphoreCount = e->sem_wait_cnt,
  434. .pSignalSemaphores = e->sem_sig,
  435. .signalSemaphoreCount = e->sem_sig_cnt,
  436. };
  437. ret = vkEndCommandBuffer(e->bufs[s->cur_queue_idx]);
  438. if (ret != VK_SUCCESS) {
  439. av_log(avctx, AV_LOG_ERROR, "Unable to finish command buffer: %s\n",
  440. ff_vk_ret2str(ret));
  441. return AVERROR_EXTERNAL;
  442. }
  443. ret = vkQueueSubmit(q->queue, 1, &s_info, q->fence);
  444. if (ret != VK_SUCCESS) {
  445. av_log(avctx, AV_LOG_ERROR, "Unable to submit command buffer: %s\n",
  446. ff_vk_ret2str(ret));
  447. return AVERROR_EXTERNAL;
  448. }
  449. /* Rotate queues */
  450. s->cur_queue_idx = (s->cur_queue_idx + 1) % s->queue_count;
  451. return 0;
  452. }
  453. int ff_vk_add_dep_exec_ctx(AVFilterContext *avctx, FFVkExecContext *e,
  454. AVBufferRef **deps, int nb_deps)
  455. {
  456. AVBufferRef **dst;
  457. VulkanFilterContext *s = avctx->priv;
  458. FFVkQueueCtx *q = &e->queues[s->cur_queue_idx];
  459. if (!deps || !nb_deps)
  460. return 0;
  461. dst = av_fast_realloc(q->buf_deps, &q->buf_deps_alloc_size,
  462. (q->nb_buf_deps + nb_deps) * sizeof(*dst));
  463. if (!dst)
  464. goto err;
  465. q->buf_deps = dst;
  466. for (int i = 0; i < nb_deps; i++) {
  467. q->buf_deps[q->nb_buf_deps] = deps[i];
  468. if (!q->buf_deps[q->nb_buf_deps])
  469. goto err;
  470. q->nb_buf_deps++;
  471. }
  472. return 0;
  473. err:
  474. ff_vk_discard_exec_deps(avctx, e);
  475. return AVERROR(ENOMEM);
  476. }
  477. int ff_vk_filter_query_formats(AVFilterContext *avctx)
  478. {
  479. static const enum AVPixelFormat pixel_formats[] = {
  480. AV_PIX_FMT_VULKAN, AV_PIX_FMT_NONE,
  481. };
  482. AVFilterFormats *pix_fmts = ff_make_format_list(pixel_formats);
  483. if (!pix_fmts)
  484. return AVERROR(ENOMEM);
  485. return ff_set_common_formats(avctx, pix_fmts);
  486. }
  487. static int vulkan_filter_set_device(AVFilterContext *avctx,
  488. AVBufferRef *device)
  489. {
  490. VulkanFilterContext *s = avctx->priv;
  491. av_buffer_unref(&s->device_ref);
  492. s->device_ref = av_buffer_ref(device);
  493. if (!s->device_ref)
  494. return AVERROR(ENOMEM);
  495. s->device = (AVHWDeviceContext*)s->device_ref->data;
  496. s->hwctx = s->device->hwctx;
  497. return 0;
  498. }
  499. static int vulkan_filter_set_frames(AVFilterContext *avctx,
  500. AVBufferRef *frames)
  501. {
  502. VulkanFilterContext *s = avctx->priv;
  503. av_buffer_unref(&s->frames_ref);
  504. s->frames_ref = av_buffer_ref(frames);
  505. if (!s->frames_ref)
  506. return AVERROR(ENOMEM);
  507. return 0;
  508. }
  509. int ff_vk_filter_config_input(AVFilterLink *inlink)
  510. {
  511. int err;
  512. AVFilterContext *avctx = inlink->dst;
  513. VulkanFilterContext *s = avctx->priv;
  514. AVHWFramesContext *input_frames;
  515. if (!inlink->hw_frames_ctx) {
  516. av_log(avctx, AV_LOG_ERROR, "Vulkan filtering requires a "
  517. "hardware frames context on the input.\n");
  518. return AVERROR(EINVAL);
  519. }
  520. /* Extract the device and default output format from the first input. */
  521. if (avctx->inputs[0] != inlink)
  522. return 0;
  523. input_frames = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
  524. if (input_frames->format != AV_PIX_FMT_VULKAN)
  525. return AVERROR(EINVAL);
  526. err = vulkan_filter_set_device(avctx, input_frames->device_ref);
  527. if (err < 0)
  528. return err;
  529. err = vulkan_filter_set_frames(avctx, inlink->hw_frames_ctx);
  530. if (err < 0)
  531. return err;
  532. /* Default output parameters match input parameters. */
  533. s->input_format = input_frames->sw_format;
  534. if (s->output_format == AV_PIX_FMT_NONE)
  535. s->output_format = input_frames->sw_format;
  536. if (!s->output_width)
  537. s->output_width = inlink->w;
  538. if (!s->output_height)
  539. s->output_height = inlink->h;
  540. return 0;
  541. }
  542. int ff_vk_filter_config_output_inplace(AVFilterLink *outlink)
  543. {
  544. int err;
  545. AVFilterContext *avctx = outlink->src;
  546. VulkanFilterContext *s = avctx->priv;
  547. av_buffer_unref(&outlink->hw_frames_ctx);
  548. if (!s->device_ref) {
  549. if (!avctx->hw_device_ctx) {
  550. av_log(avctx, AV_LOG_ERROR, "Vulkan filtering requires a "
  551. "Vulkan device.\n");
  552. return AVERROR(EINVAL);
  553. }
  554. err = vulkan_filter_set_device(avctx, avctx->hw_device_ctx);
  555. if (err < 0)
  556. return err;
  557. }
  558. outlink->hw_frames_ctx = av_buffer_ref(s->frames_ref);
  559. if (!outlink->hw_frames_ctx)
  560. return AVERROR(ENOMEM);
  561. outlink->w = s->output_width;
  562. outlink->h = s->output_height;
  563. return 0;
  564. }
  565. int ff_vk_filter_config_output(AVFilterLink *outlink)
  566. {
  567. int err;
  568. AVFilterContext *avctx = outlink->src;
  569. VulkanFilterContext *s = avctx->priv;
  570. AVBufferRef *output_frames_ref;
  571. AVHWFramesContext *output_frames;
  572. av_buffer_unref(&outlink->hw_frames_ctx);
  573. if (!s->device_ref) {
  574. if (!avctx->hw_device_ctx) {
  575. av_log(avctx, AV_LOG_ERROR, "Vulkan filtering requires a "
  576. "Vulkan device.\n");
  577. return AVERROR(EINVAL);
  578. }
  579. err = vulkan_filter_set_device(avctx, avctx->hw_device_ctx);
  580. if (err < 0)
  581. return err;
  582. }
  583. output_frames_ref = av_hwframe_ctx_alloc(s->device_ref);
  584. if (!output_frames_ref) {
  585. err = AVERROR(ENOMEM);
  586. goto fail;
  587. }
  588. output_frames = (AVHWFramesContext*)output_frames_ref->data;
  589. output_frames->format = AV_PIX_FMT_VULKAN;
  590. output_frames->sw_format = s->output_format;
  591. output_frames->width = s->output_width;
  592. output_frames->height = s->output_height;
  593. err = av_hwframe_ctx_init(output_frames_ref);
  594. if (err < 0) {
  595. av_log(avctx, AV_LOG_ERROR, "Failed to initialise output "
  596. "frames: %d.\n", err);
  597. goto fail;
  598. }
  599. outlink->hw_frames_ctx = output_frames_ref;
  600. outlink->w = s->output_width;
  601. outlink->h = s->output_height;
  602. return 0;
  603. fail:
  604. av_buffer_unref(&output_frames_ref);
  605. return err;
  606. }
  607. int ff_vk_filter_init(AVFilterContext *avctx)
  608. {
  609. VulkanFilterContext *s = avctx->priv;
  610. s->output_format = AV_PIX_FMT_NONE;
  611. if (glslang_init())
  612. return AVERROR_EXTERNAL;
  613. return 0;
  614. }
  615. FN_CREATING(VulkanFilterContext, VkSampler, sampler, samplers, samplers_num)
  616. VkSampler *ff_vk_init_sampler(AVFilterContext *avctx, int unnorm_coords,
  617. VkFilter filt)
  618. {
  619. VkResult ret;
  620. VulkanFilterContext *s = avctx->priv;
  621. VkSamplerCreateInfo sampler_info = {
  622. .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
  623. .magFilter = filt,
  624. .minFilter = sampler_info.magFilter,
  625. .mipmapMode = unnorm_coords ? VK_SAMPLER_MIPMAP_MODE_NEAREST :
  626. VK_SAMPLER_MIPMAP_MODE_LINEAR,
  627. .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
  628. .addressModeV = sampler_info.addressModeU,
  629. .addressModeW = sampler_info.addressModeU,
  630. .anisotropyEnable = VK_FALSE,
  631. .compareOp = VK_COMPARE_OP_NEVER,
  632. .borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK,
  633. .unnormalizedCoordinates = unnorm_coords,
  634. };
  635. VkSampler *sampler = create_sampler(s);
  636. if (!sampler)
  637. return NULL;
  638. ret = vkCreateSampler(s->hwctx->act_dev, &sampler_info,
  639. s->hwctx->alloc, sampler);
  640. if (ret != VK_SUCCESS) {
  641. av_log(avctx, AV_LOG_ERROR, "Unable to init sampler: %s\n",
  642. ff_vk_ret2str(ret));
  643. return NULL;
  644. }
  645. return sampler;
  646. }
  647. int ff_vk_mt_is_np_rgb(enum AVPixelFormat pix_fmt)
  648. {
  649. if (pix_fmt == AV_PIX_FMT_ABGR || pix_fmt == AV_PIX_FMT_BGRA ||
  650. pix_fmt == AV_PIX_FMT_RGBA || pix_fmt == AV_PIX_FMT_RGB24 ||
  651. pix_fmt == AV_PIX_FMT_BGR24 || pix_fmt == AV_PIX_FMT_RGB48 ||
  652. pix_fmt == AV_PIX_FMT_RGBA64 || pix_fmt == AV_PIX_FMT_RGB565 ||
  653. pix_fmt == AV_PIX_FMT_BGR565 || pix_fmt == AV_PIX_FMT_BGR0 ||
  654. pix_fmt == AV_PIX_FMT_0BGR || pix_fmt == AV_PIX_FMT_RGB0)
  655. return 1;
  656. return 0;
  657. }
  658. const char *ff_vk_shader_rep_fmt(enum AVPixelFormat pixfmt)
  659. {
  660. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pixfmt);
  661. const int high = desc->comp[0].depth > 8;
  662. return high ? "rgba16f" : "rgba8";
  663. }
  664. typedef struct ImageViewCtx {
  665. VkImageView view;
  666. } ImageViewCtx;
  667. static void destroy_imageview(void *opaque, uint8_t *data)
  668. {
  669. VulkanFilterContext *s = opaque;
  670. ImageViewCtx *iv = (ImageViewCtx *)data;
  671. vkDestroyImageView(s->hwctx->act_dev, iv->view, s->hwctx->alloc);
  672. av_free(iv);
  673. }
  674. int ff_vk_create_imageview(AVFilterContext *avctx, FFVkExecContext *e,
  675. VkImageView *v, VkImage img, VkFormat fmt,
  676. const VkComponentMapping map)
  677. {
  678. int err;
  679. AVBufferRef *buf;
  680. VulkanFilterContext *s = avctx->priv;
  681. VkImageViewCreateInfo imgview_spawn = {
  682. .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
  683. .pNext = NULL,
  684. .image = img,
  685. .viewType = VK_IMAGE_VIEW_TYPE_2D,
  686. .format = fmt,
  687. .components = map,
  688. .subresourceRange = {
  689. .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
  690. .baseMipLevel = 0,
  691. .levelCount = 1,
  692. .baseArrayLayer = 0,
  693. .layerCount = 1,
  694. },
  695. };
  696. ImageViewCtx *iv = av_mallocz(sizeof(*iv));
  697. VkResult ret = vkCreateImageView(s->hwctx->act_dev, &imgview_spawn,
  698. s->hwctx->alloc, &iv->view);
  699. if (ret != VK_SUCCESS) {
  700. av_log(avctx, AV_LOG_ERROR, "Failed to create imageview: %s\n",
  701. ff_vk_ret2str(ret));
  702. return AVERROR_EXTERNAL;
  703. }
  704. buf = av_buffer_create((uint8_t *)iv, sizeof(*iv), destroy_imageview, s, 0);
  705. if (!buf) {
  706. destroy_imageview(s, (uint8_t *)iv);
  707. return AVERROR(ENOMEM);
  708. }
  709. /* Add to queue dependencies */
  710. err = ff_vk_add_dep_exec_ctx(avctx, e, &buf, 1);
  711. if (err) {
  712. av_buffer_unref(&buf);
  713. return err;
  714. }
  715. *v = iv->view;
  716. return 0;
  717. }
  718. FN_CREATING(VulkanPipeline, SPIRVShader, shader, shaders, shaders_num)
  719. SPIRVShader *ff_vk_init_shader(AVFilterContext *avctx, VulkanPipeline *pl,
  720. const char *name, VkShaderStageFlags stage)
  721. {
  722. SPIRVShader *shd = create_shader(pl);
  723. if (!shd)
  724. return NULL;
  725. av_bprint_init(&shd->src, 0, AV_BPRINT_SIZE_UNLIMITED);
  726. shd->shader.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  727. shd->shader.stage = stage;
  728. shd->name = name;
  729. GLSLF(0, #version %i ,460);
  730. GLSLC(0, #define IS_WITHIN(v1, v2) ((v1.x < v2.x) && (v1.y < v2.y)) );
  731. GLSLC(0, );
  732. return shd;
  733. }
  734. void ff_vk_set_compute_shader_sizes(AVFilterContext *avctx, SPIRVShader *shd,
  735. int local_size[3])
  736. {
  737. shd->local_size[0] = local_size[0];
  738. shd->local_size[1] = local_size[1];
  739. shd->local_size[2] = local_size[2];
  740. av_bprintf(&shd->src, "layout (local_size_x = %i, "
  741. "local_size_y = %i, local_size_z = %i) in;\n\n",
  742. shd->local_size[0], shd->local_size[1], shd->local_size[2]);
  743. }
  744. static void print_shader(AVFilterContext *avctx, SPIRVShader *shd, int prio)
  745. {
  746. int line = 0;
  747. const char *p = shd->src.str;
  748. const char *start = p;
  749. AVBPrint buf;
  750. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
  751. for (int i = 0; i < strlen(p); i++) {
  752. if (p[i] == '\n') {
  753. av_bprintf(&buf, "%i\t", ++line);
  754. av_bprint_append_data(&buf, start, &p[i] - start + 1);
  755. start = &p[i + 1];
  756. }
  757. }
  758. av_log(avctx, prio, "Shader %s: \n%s", shd->name, buf.str);
  759. av_bprint_finalize(&buf, NULL);
  760. }
  761. int ff_vk_compile_shader(AVFilterContext *avctx, SPIRVShader *shd,
  762. const char *entrypoint)
  763. {
  764. VkResult ret;
  765. VulkanFilterContext *s = avctx->priv;
  766. VkShaderModuleCreateInfo shader_create;
  767. GLSlangResult *res;
  768. static const enum GLSlangStage emap[] = {
  769. [VK_SHADER_STAGE_VERTEX_BIT] = GLSLANG_VERTEX,
  770. [VK_SHADER_STAGE_FRAGMENT_BIT] = GLSLANG_FRAGMENT,
  771. [VK_SHADER_STAGE_COMPUTE_BIT] = GLSLANG_COMPUTE,
  772. };
  773. shd->shader.pName = entrypoint;
  774. res = glslang_compile(shd->src.str, emap[shd->shader.stage]);
  775. if (!res)
  776. return AVERROR(ENOMEM);
  777. if (res->rval) {
  778. av_log(avctx, AV_LOG_ERROR, "Error compiling shader %s: %s!\n",
  779. shd->name, av_err2str(res->rval));
  780. print_shader(avctx, shd, AV_LOG_ERROR);
  781. if (res->error_msg)
  782. av_log(avctx, AV_LOG_ERROR, "%s", res->error_msg);
  783. av_free(res->error_msg);
  784. return res->rval;
  785. }
  786. print_shader(avctx, shd, AV_LOG_VERBOSE);
  787. shader_create.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  788. shader_create.pNext = NULL;
  789. shader_create.codeSize = res->size;
  790. shader_create.flags = 0;
  791. shader_create.pCode = res->data;
  792. ret = vkCreateShaderModule(s->hwctx->act_dev, &shader_create, NULL,
  793. &shd->shader.module);
  794. /* Free the GLSlangResult struct */
  795. av_free(res->data);
  796. av_free(res);
  797. if (ret != VK_SUCCESS) {
  798. av_log(avctx, AV_LOG_ERROR, "Unable to create shader module: %s\n",
  799. ff_vk_ret2str(ret));
  800. return AVERROR_EXTERNAL;
  801. }
  802. av_log(avctx, AV_LOG_VERBOSE, "Shader %s linked! Size: %zu bytes\n",
  803. shd->name, shader_create.codeSize);
  804. return 0;
  805. }
  806. static const struct descriptor_props {
  807. size_t struct_size; /* Size of the opaque which updates the descriptor */
  808. const char *type;
  809. int is_uniform;
  810. int mem_quali; /* Can use a memory qualifier */
  811. int dim_needed; /* Must indicate dimension */
  812. int buf_content; /* Must indicate buffer contents */
  813. } descriptor_props[] = {
  814. [VK_DESCRIPTOR_TYPE_SAMPLER] = { sizeof(VkDescriptorImageInfo), "sampler", 1, 0, 0, 0, },
  815. [VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE] = { sizeof(VkDescriptorImageInfo), "texture", 1, 0, 1, 0, },
  816. [VK_DESCRIPTOR_TYPE_STORAGE_IMAGE] = { sizeof(VkDescriptorImageInfo), "image", 1, 1, 1, 0, },
  817. [VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT] = { sizeof(VkDescriptorImageInfo), "subpassInput", 1, 0, 0, 0, },
  818. [VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER] = { sizeof(VkDescriptorImageInfo), "sampler", 1, 0, 1, 0, },
  819. [VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER] = { sizeof(VkDescriptorBufferInfo), NULL, 1, 0, 0, 1, },
  820. [VK_DESCRIPTOR_TYPE_STORAGE_BUFFER] = { sizeof(VkDescriptorBufferInfo), "buffer", 0, 1, 0, 1, },
  821. [VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC] = { sizeof(VkDescriptorBufferInfo), NULL, 1, 0, 0, 1, },
  822. [VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC] = { sizeof(VkDescriptorBufferInfo), "buffer", 0, 1, 0, 1, },
  823. [VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER] = { sizeof(VkBufferView), "samplerBuffer", 1, 0, 0, 0, },
  824. [VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER] = { sizeof(VkBufferView), "imageBuffer", 1, 0, 0, 0, },
  825. };
  826. int ff_vk_add_descriptor_set(AVFilterContext *avctx, VulkanPipeline *pl,
  827. SPIRVShader *shd, VulkanDescriptorSetBinding *desc,
  828. int num, int only_print_to_shader)
  829. {
  830. VkResult ret;
  831. VkDescriptorSetLayout *layout;
  832. VulkanFilterContext *s = avctx->priv;
  833. if (only_print_to_shader)
  834. goto print;
  835. pl->desc_layout = av_realloc_array(pl->desc_layout, sizeof(*pl->desc_layout),
  836. pl->desc_layout_num + 1);
  837. if (!pl->desc_layout)
  838. return AVERROR(ENOMEM);
  839. layout = &pl->desc_layout[pl->desc_layout_num];
  840. memset(layout, 0, sizeof(*layout));
  841. { /* Create descriptor set layout descriptions */
  842. VkDescriptorSetLayoutCreateInfo desc_create_layout = { 0 };
  843. VkDescriptorSetLayoutBinding *desc_binding;
  844. desc_binding = av_mallocz(sizeof(*desc_binding)*num);
  845. if (!desc_binding)
  846. return AVERROR(ENOMEM);
  847. for (int i = 0; i < num; i++) {
  848. desc_binding[i].binding = i;
  849. desc_binding[i].descriptorType = desc[i].type;
  850. desc_binding[i].descriptorCount = FFMAX(desc[i].elems, 1);
  851. desc_binding[i].stageFlags = desc[i].stages;
  852. desc_binding[i].pImmutableSamplers = desc[i].samplers;
  853. }
  854. desc_create_layout.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  855. desc_create_layout.pBindings = desc_binding;
  856. desc_create_layout.bindingCount = num;
  857. ret = vkCreateDescriptorSetLayout(s->hwctx->act_dev, &desc_create_layout,
  858. s->hwctx->alloc, layout);
  859. av_free(desc_binding);
  860. if (ret != VK_SUCCESS) {
  861. av_log(avctx, AV_LOG_ERROR, "Unable to init descriptor set "
  862. "layout: %s\n", ff_vk_ret2str(ret));
  863. return AVERROR_EXTERNAL;
  864. }
  865. }
  866. { /* Pool each descriptor by type and update pool counts */
  867. for (int i = 0; i < num; i++) {
  868. int j;
  869. for (j = 0; j < pl->pool_size_desc_num; j++)
  870. if (pl->pool_size_desc[j].type == desc[i].type)
  871. break;
  872. if (j >= pl->pool_size_desc_num) {
  873. pl->pool_size_desc = av_realloc_array(pl->pool_size_desc,
  874. sizeof(*pl->pool_size_desc),
  875. ++pl->pool_size_desc_num);
  876. if (!pl->pool_size_desc)
  877. return AVERROR(ENOMEM);
  878. memset(&pl->pool_size_desc[j], 0, sizeof(VkDescriptorPoolSize));
  879. }
  880. pl->pool_size_desc[j].type = desc[i].type;
  881. pl->pool_size_desc[j].descriptorCount += FFMAX(desc[i].elems, 1);
  882. }
  883. }
  884. { /* Create template creation struct */
  885. VkDescriptorUpdateTemplateCreateInfo *dt;
  886. VkDescriptorUpdateTemplateEntry *des_entries;
  887. /* Freed after descriptor set initialization */
  888. des_entries = av_mallocz(num*sizeof(VkDescriptorUpdateTemplateEntry));
  889. if (!des_entries)
  890. return AVERROR(ENOMEM);
  891. for (int i = 0; i < num; i++) {
  892. des_entries[i].dstBinding = i;
  893. des_entries[i].descriptorType = desc[i].type;
  894. des_entries[i].descriptorCount = FFMAX(desc[i].elems, 1);
  895. des_entries[i].dstArrayElement = 0;
  896. des_entries[i].offset = ((uint8_t *)desc[i].updater) - (uint8_t *)s;
  897. des_entries[i].stride = descriptor_props[desc[i].type].struct_size;
  898. }
  899. pl->desc_template_info = av_realloc_array(pl->desc_template_info,
  900. sizeof(*pl->desc_template_info),
  901. pl->desc_layout_num + 1);
  902. if (!pl->desc_template_info)
  903. return AVERROR(ENOMEM);
  904. dt = &pl->desc_template_info[pl->desc_layout_num];
  905. memset(dt, 0, sizeof(*dt));
  906. dt->sType = VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO;
  907. dt->templateType = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET;
  908. dt->descriptorSetLayout = *layout;
  909. dt->pDescriptorUpdateEntries = des_entries;
  910. dt->descriptorUpdateEntryCount = num;
  911. }
  912. pl->desc_layout_num++;
  913. print:
  914. /* Write shader info */
  915. for (int i = 0; i < num; i++) {
  916. const struct descriptor_props *prop = &descriptor_props[desc[i].type];
  917. GLSLA("layout (set = %i, binding = %i", pl->desc_layout_num - 1, i);
  918. if (desc[i].mem_layout)
  919. GLSLA(", %s", desc[i].mem_layout);
  920. GLSLA(")");
  921. if (prop->is_uniform)
  922. GLSLA(" uniform");
  923. if (prop->mem_quali && desc[i].mem_quali)
  924. GLSLA(" %s", desc[i].mem_quali);
  925. if (prop->type)
  926. GLSLA(" %s", prop->type);
  927. if (prop->dim_needed)
  928. GLSLA("%iD", desc[i].dimensions);
  929. GLSLA(" %s", desc[i].name);
  930. if (prop->buf_content)
  931. GLSLA(" {\n %s\n}", desc[i].buf_content);
  932. else if (desc[i].elems > 0)
  933. GLSLA("[%i]", desc[i].elems);
  934. GLSLA(";\n");
  935. }
  936. GLSLA("\n");
  937. return 0;
  938. }
  939. void ff_vk_update_descriptor_set(AVFilterContext *avctx, VulkanPipeline *pl,
  940. int set_id)
  941. {
  942. VulkanFilterContext *s = avctx->priv;
  943. vkUpdateDescriptorSetWithTemplate(s->hwctx->act_dev,
  944. pl->desc_set[set_id * s->cur_queue_idx],
  945. pl->desc_template[set_id],
  946. s);
  947. }
  948. void ff_vk_update_push_exec(AVFilterContext *avctx, FFVkExecContext *e,
  949. VkShaderStageFlagBits stage, int offset,
  950. size_t size, void *src)
  951. {
  952. VulkanFilterContext *s = avctx->priv;
  953. vkCmdPushConstants(e->bufs[s->cur_queue_idx], e->bound_pl->pipeline_layout,
  954. stage, offset, size, src);
  955. }
  956. int ff_vk_init_pipeline_layout(AVFilterContext *avctx, VulkanPipeline *pl)
  957. {
  958. VkResult ret;
  959. VulkanFilterContext *s = avctx->priv;
  960. int queues_count = 1;
  961. pl->descriptor_sets_num = pl->desc_layout_num * queues_count;
  962. { /* Init descriptor set pool */
  963. VkDescriptorPoolCreateInfo pool_create_info = {
  964. .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
  965. .poolSizeCount = pl->pool_size_desc_num,
  966. .pPoolSizes = pl->pool_size_desc,
  967. .maxSets = pl->descriptor_sets_num,
  968. };
  969. ret = vkCreateDescriptorPool(s->hwctx->act_dev, &pool_create_info,
  970. s->hwctx->alloc, &pl->desc_pool);
  971. av_freep(&pl->pool_size_desc);
  972. if (ret != VK_SUCCESS) {
  973. av_log(avctx, AV_LOG_ERROR, "Unable to init descriptor set "
  974. "pool: %s\n", ff_vk_ret2str(ret));
  975. return AVERROR_EXTERNAL;
  976. }
  977. }
  978. { /* Allocate descriptor sets */
  979. VkDescriptorSetAllocateInfo alloc_info = {
  980. .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
  981. .descriptorPool = pl->desc_pool,
  982. .descriptorSetCount = pl->descriptor_sets_num,
  983. .pSetLayouts = pl->desc_layout,
  984. };
  985. pl->desc_set = av_malloc(pl->descriptor_sets_num*sizeof(*pl->desc_set));
  986. if (!pl->desc_set)
  987. return AVERROR(ENOMEM);
  988. ret = vkAllocateDescriptorSets(s->hwctx->act_dev, &alloc_info,
  989. pl->desc_set);
  990. if (ret != VK_SUCCESS) {
  991. av_log(avctx, AV_LOG_ERROR, "Unable to allocate descriptor set: %s\n",
  992. ff_vk_ret2str(ret));
  993. return AVERROR_EXTERNAL;
  994. }
  995. }
  996. { /* Finally create the pipeline layout */
  997. VkPipelineLayoutCreateInfo spawn_pipeline_layout = {
  998. .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
  999. .setLayoutCount = pl->desc_layout_num,
  1000. .pSetLayouts = pl->desc_layout,
  1001. .pushConstantRangeCount = pl->push_consts_num,
  1002. .pPushConstantRanges = pl->push_consts,
  1003. };
  1004. ret = vkCreatePipelineLayout(s->hwctx->act_dev, &spawn_pipeline_layout,
  1005. s->hwctx->alloc, &pl->pipeline_layout);
  1006. av_freep(&pl->push_consts);
  1007. pl->push_consts_num = 0;
  1008. if (ret != VK_SUCCESS) {
  1009. av_log(avctx, AV_LOG_ERROR, "Unable to init pipeline layout: %s\n",
  1010. ff_vk_ret2str(ret));
  1011. return AVERROR_EXTERNAL;
  1012. }
  1013. }
  1014. { /* Descriptor template (for tightly packed descriptors) */
  1015. VkDescriptorUpdateTemplateCreateInfo *desc_template_info;
  1016. pl->desc_template = av_malloc(pl->descriptor_sets_num*sizeof(*pl->desc_template));
  1017. if (!pl->desc_template)
  1018. return AVERROR(ENOMEM);
  1019. /* Create update templates for the descriptor sets */
  1020. for (int i = 0; i < pl->descriptor_sets_num; i++) {
  1021. desc_template_info = &pl->desc_template_info[i % pl->desc_layout_num];
  1022. desc_template_info->pipelineLayout = pl->pipeline_layout;
  1023. ret = vkCreateDescriptorUpdateTemplate(s->hwctx->act_dev,
  1024. desc_template_info,
  1025. s->hwctx->alloc,
  1026. &pl->desc_template[i]);
  1027. av_free((void *)desc_template_info->pDescriptorUpdateEntries);
  1028. if (ret != VK_SUCCESS) {
  1029. av_log(avctx, AV_LOG_ERROR, "Unable to init descriptor "
  1030. "template: %s\n", ff_vk_ret2str(ret));
  1031. return AVERROR_EXTERNAL;
  1032. }
  1033. }
  1034. av_freep(&pl->desc_template_info);
  1035. }
  1036. return 0;
  1037. }
  1038. FN_CREATING(VulkanFilterContext, VulkanPipeline, pipeline, pipelines, pipelines_num)
  1039. VulkanPipeline *ff_vk_create_pipeline(AVFilterContext *avctx)
  1040. {
  1041. return create_pipeline(avctx->priv);
  1042. }
  1043. int ff_vk_init_compute_pipeline(AVFilterContext *avctx, VulkanPipeline *pl)
  1044. {
  1045. int i;
  1046. VkResult ret;
  1047. VulkanFilterContext *s = avctx->priv;
  1048. VkComputePipelineCreateInfo pipe = {
  1049. .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
  1050. .layout = pl->pipeline_layout,
  1051. };
  1052. for (i = 0; i < pl->shaders_num; i++) {
  1053. if (pl->shaders[i]->shader.stage & VK_SHADER_STAGE_COMPUTE_BIT) {
  1054. pipe.stage = pl->shaders[i]->shader;
  1055. break;
  1056. }
  1057. }
  1058. if (i == pl->shaders_num) {
  1059. av_log(avctx, AV_LOG_ERROR, "Can't init compute pipeline, no shader\n");
  1060. return AVERROR(EINVAL);
  1061. }
  1062. ret = vkCreateComputePipelines(s->hwctx->act_dev, VK_NULL_HANDLE, 1, &pipe,
  1063. s->hwctx->alloc, &pl->pipeline);
  1064. if (ret != VK_SUCCESS) {
  1065. av_log(avctx, AV_LOG_ERROR, "Unable to init compute pipeline: %s\n",
  1066. ff_vk_ret2str(ret));
  1067. return AVERROR_EXTERNAL;
  1068. }
  1069. pl->bind_point = VK_PIPELINE_BIND_POINT_COMPUTE;
  1070. return 0;
  1071. }
  1072. void ff_vk_bind_pipeline_exec(AVFilterContext *avctx, FFVkExecContext *e,
  1073. VulkanPipeline *pl)
  1074. {
  1075. VulkanFilterContext *s = avctx->priv;
  1076. vkCmdBindPipeline(e->bufs[s->cur_queue_idx], pl->bind_point, pl->pipeline);
  1077. vkCmdBindDescriptorSets(e->bufs[s->cur_queue_idx], pl->bind_point,
  1078. pl->pipeline_layout, 0, pl->descriptor_sets_num,
  1079. pl->desc_set, 0, 0);
  1080. e->bound_pl = pl;
  1081. }
  1082. static void free_exec_ctx(VulkanFilterContext *s, FFVkExecContext *e)
  1083. {
  1084. /* Make sure all queues have finished executing */
  1085. for (int i = 0; i < s->queue_count; i++) {
  1086. FFVkQueueCtx *q = &e->queues[i];
  1087. if (q->fence) {
  1088. vkWaitForFences(s->hwctx->act_dev, 1, &q->fence, VK_TRUE, UINT64_MAX);
  1089. vkResetFences(s->hwctx->act_dev, 1, &q->fence);
  1090. }
  1091. /* Free the fence */
  1092. if (q->fence)
  1093. vkDestroyFence(s->hwctx->act_dev, q->fence, s->hwctx->alloc);
  1094. /* Free buffer dependencies */
  1095. for (int j = 0; j < q->nb_buf_deps; j++)
  1096. av_buffer_unref(&q->buf_deps[j]);
  1097. av_free(q->buf_deps);
  1098. /* Free frame dependencies */
  1099. for (int j = 0; j < q->nb_frame_deps; j++)
  1100. av_frame_free(&q->frame_deps[j]);
  1101. av_free(q->frame_deps);
  1102. }
  1103. if (e->bufs)
  1104. vkFreeCommandBuffers(s->hwctx->act_dev, e->pool, s->queue_count, e->bufs);
  1105. if (e->pool)
  1106. vkDestroyCommandPool(s->hwctx->act_dev, e->pool, s->hwctx->alloc);
  1107. av_freep(&e->bufs);
  1108. av_freep(&e->queues);
  1109. av_freep(&e->sem_sig);
  1110. av_freep(&e->sem_wait);
  1111. av_freep(&e->sem_wait_dst);
  1112. av_free(e);
  1113. }
  1114. static void free_pipeline(VulkanFilterContext *s, VulkanPipeline *pl)
  1115. {
  1116. for (int i = 0; i < pl->shaders_num; i++) {
  1117. SPIRVShader *shd = pl->shaders[i];
  1118. av_bprint_finalize(&shd->src, NULL);
  1119. vkDestroyShaderModule(s->hwctx->act_dev, shd->shader.module,
  1120. s->hwctx->alloc);
  1121. av_free(shd);
  1122. }
  1123. vkDestroyPipeline(s->hwctx->act_dev, pl->pipeline, s->hwctx->alloc);
  1124. vkDestroyPipelineLayout(s->hwctx->act_dev, pl->pipeline_layout,
  1125. s->hwctx->alloc);
  1126. for (int i = 0; i < pl->desc_layout_num; i++) {
  1127. if (pl->desc_template && pl->desc_template[i])
  1128. vkDestroyDescriptorUpdateTemplate(s->hwctx->act_dev, pl->desc_template[i],
  1129. s->hwctx->alloc);
  1130. if (pl->desc_layout && pl->desc_layout[i])
  1131. vkDestroyDescriptorSetLayout(s->hwctx->act_dev, pl->desc_layout[i],
  1132. s->hwctx->alloc);
  1133. }
  1134. /* Also frees the descriptor sets */
  1135. if (pl->desc_pool)
  1136. vkDestroyDescriptorPool(s->hwctx->act_dev, pl->desc_pool,
  1137. s->hwctx->alloc);
  1138. av_freep(&pl->desc_set);
  1139. av_freep(&pl->shaders);
  1140. av_freep(&pl->desc_layout);
  1141. av_freep(&pl->desc_template);
  1142. av_freep(&pl->push_consts);
  1143. pl->push_consts_num = 0;
  1144. /* Only freed in case of failure */
  1145. av_freep(&pl->pool_size_desc);
  1146. if (pl->desc_template_info) {
  1147. for (int i = 0; i < pl->descriptor_sets_num; i++)
  1148. av_free((void *)pl->desc_template_info[i].pDescriptorUpdateEntries);
  1149. av_freep(&pl->desc_template_info);
  1150. }
  1151. av_free(pl);
  1152. }
  1153. void ff_vk_filter_uninit(AVFilterContext *avctx)
  1154. {
  1155. VulkanFilterContext *s = avctx->priv;
  1156. glslang_uninit();
  1157. for (int i = 0; i < s->exec_ctx_num; i++)
  1158. free_exec_ctx(s, s->exec_ctx[i]);
  1159. av_freep(&s->exec_ctx);
  1160. for (int i = 0; i < s->samplers_num; i++) {
  1161. vkDestroySampler(s->hwctx->act_dev, *s->samplers[i], s->hwctx->alloc);
  1162. av_free(s->samplers[i]);
  1163. }
  1164. av_freep(&s->samplers);
  1165. for (int i = 0; i < s->pipelines_num; i++)
  1166. free_pipeline(s, s->pipelines[i]);
  1167. av_freep(&s->pipelines);
  1168. av_freep(&s->scratch);
  1169. s->scratch_size = 0;
  1170. av_buffer_unref(&s->device_ref);
  1171. av_buffer_unref(&s->frames_ref);
  1172. }