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.

1237 lines
41KB

  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, int queue)
  272. {
  273. VkResult ret;
  274. FFVkExecContext *e;
  275. VulkanFilterContext *s = avctx->priv;
  276. VkCommandPoolCreateInfo cqueue_create = {
  277. .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
  278. .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
  279. .queueFamilyIndex = queue,
  280. };
  281. VkCommandBufferAllocateInfo cbuf_create = {
  282. .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
  283. .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
  284. .commandBufferCount = 1,
  285. };
  286. VkFenceCreateInfo fence_spawn = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
  287. e = create_exec_ctx(s);
  288. if (!e)
  289. return AVERROR(ENOMEM);
  290. ret = vkCreateCommandPool(s->hwctx->act_dev, &cqueue_create,
  291. s->hwctx->alloc, &e->pool);
  292. if (ret != VK_SUCCESS) {
  293. av_log(avctx, AV_LOG_ERROR, "Command pool creation failure: %s\n",
  294. ff_vk_ret2str(ret));
  295. return 1;
  296. }
  297. cbuf_create.commandPool = e->pool;
  298. ret = vkAllocateCommandBuffers(s->hwctx->act_dev, &cbuf_create, &e->buf);
  299. if (ret != VK_SUCCESS) {
  300. av_log(avctx, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
  301. ff_vk_ret2str(ret));
  302. return 1;
  303. }
  304. ret = vkCreateFence(s->hwctx->act_dev, &fence_spawn,
  305. s->hwctx->alloc, &e->fence);
  306. if (ret != VK_SUCCESS) {
  307. av_log(avctx, AV_LOG_ERROR, "Failed to create frame fence: %s\n",
  308. ff_vk_ret2str(ret));
  309. return 1;
  310. }
  311. vkGetDeviceQueue(s->hwctx->act_dev, queue, 0, &e->queue);
  312. *ctx = e;
  313. return 0;
  314. }
  315. int ff_vk_start_exec_recording(AVFilterContext *avctx, FFVkExecContext *e)
  316. {
  317. VkResult ret;
  318. VkCommandBufferBeginInfo cmd_start = {
  319. .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  320. .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
  321. };
  322. e->sem_wait_cnt = 0;
  323. e->sem_sig_cnt = 0;
  324. ret = vkBeginCommandBuffer(e->buf, &cmd_start);
  325. if (ret != VK_SUCCESS) {
  326. av_log(avctx, AV_LOG_ERROR, "Failed to start command recoding: %s\n",
  327. ff_vk_ret2str(ret));
  328. return AVERROR_EXTERNAL;
  329. }
  330. return 0;
  331. }
  332. int ff_vk_add_exec_dep(AVFilterContext *avctx, FFVkExecContext *e,
  333. AVFrame *frame, VkPipelineStageFlagBits in_wait_dst_flag)
  334. {
  335. AVVkFrame *f = (AVVkFrame *)frame->data[0];
  336. AVHWFramesContext *fc = (AVHWFramesContext *)frame->hw_frames_ctx->data;
  337. int planes = av_pix_fmt_count_planes(fc->sw_format);
  338. for (int i = 0; i < planes; i++) {
  339. e->sem_wait = av_fast_realloc(e->sem_wait, &e->sem_wait_alloc,
  340. (e->sem_wait_cnt + 1)*sizeof(*e->sem_wait));
  341. if (!e->sem_wait)
  342. return AVERROR(ENOMEM);
  343. e->sem_wait_dst = av_fast_realloc(e->sem_wait_dst, &e->sem_wait_dst_alloc,
  344. (e->sem_wait_cnt + 1)*sizeof(*e->sem_wait_dst));
  345. if (!e->sem_wait_dst)
  346. return AVERROR(ENOMEM);
  347. e->sem_sig = av_fast_realloc(e->sem_sig, &e->sem_sig_alloc,
  348. (e->sem_sig_cnt + 1)*sizeof(*e->sem_sig));
  349. if (!e->sem_sig)
  350. return AVERROR(ENOMEM);
  351. e->sem_wait[e->sem_wait_cnt] = f->sem[i];
  352. e->sem_wait_dst[e->sem_wait_cnt] = in_wait_dst_flag;
  353. e->sem_wait_cnt++;
  354. e->sem_sig[e->sem_sig_cnt] = f->sem[i];
  355. e->sem_sig_cnt++;
  356. }
  357. return 0;
  358. }
  359. int ff_vk_submit_exec_queue(AVFilterContext *avctx, FFVkExecContext *e)
  360. {
  361. VkResult ret;
  362. VulkanFilterContext *s = avctx->priv;
  363. VkSubmitInfo s_info = {
  364. .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
  365. .commandBufferCount = 1,
  366. .pCommandBuffers = &e->buf,
  367. .pWaitSemaphores = e->sem_wait,
  368. .pWaitDstStageMask = e->sem_wait_dst,
  369. .waitSemaphoreCount = e->sem_wait_cnt,
  370. .pSignalSemaphores = e->sem_sig,
  371. .signalSemaphoreCount = e->sem_sig_cnt,
  372. };
  373. vkEndCommandBuffer(e->buf);
  374. ret = vkQueueSubmit(e->queue, 1, &s_info, e->fence);
  375. if (ret != VK_SUCCESS) {
  376. av_log(avctx, AV_LOG_ERROR, "Unable to submit command buffer: %s\n",
  377. ff_vk_ret2str(ret));
  378. return AVERROR_EXTERNAL;
  379. }
  380. vkWaitForFences(s->hwctx->act_dev, 1, &e->fence, VK_TRUE, UINT64_MAX);
  381. vkResetFences(s->hwctx->act_dev, 1, &e->fence);
  382. return 0;
  383. }
  384. int ff_vk_filter_query_formats(AVFilterContext *avctx)
  385. {
  386. static const enum AVPixelFormat pixel_formats[] = {
  387. AV_PIX_FMT_VULKAN, AV_PIX_FMT_NONE,
  388. };
  389. AVFilterFormats *pix_fmts = ff_make_format_list(pixel_formats);
  390. if (!pix_fmts)
  391. return AVERROR(ENOMEM);
  392. return ff_set_common_formats(avctx, pix_fmts);
  393. }
  394. static int vulkan_filter_set_device(AVFilterContext *avctx,
  395. AVBufferRef *device)
  396. {
  397. VulkanFilterContext *s = avctx->priv;
  398. av_buffer_unref(&s->device_ref);
  399. s->device_ref = av_buffer_ref(device);
  400. if (!s->device_ref)
  401. return AVERROR(ENOMEM);
  402. s->device = (AVHWDeviceContext*)s->device_ref->data;
  403. s->hwctx = s->device->hwctx;
  404. return 0;
  405. }
  406. static int vulkan_filter_set_frames(AVFilterContext *avctx,
  407. AVBufferRef *frames)
  408. {
  409. VulkanFilterContext *s = avctx->priv;
  410. av_buffer_unref(&s->frames_ref);
  411. s->frames_ref = av_buffer_ref(frames);
  412. if (!s->frames_ref)
  413. return AVERROR(ENOMEM);
  414. return 0;
  415. }
  416. int ff_vk_filter_config_input(AVFilterLink *inlink)
  417. {
  418. int err;
  419. AVFilterContext *avctx = inlink->dst;
  420. VulkanFilterContext *s = avctx->priv;
  421. AVHWFramesContext *input_frames;
  422. if (!inlink->hw_frames_ctx) {
  423. av_log(avctx, AV_LOG_ERROR, "Vulkan filtering requires a "
  424. "hardware frames context on the input.\n");
  425. return AVERROR(EINVAL);
  426. }
  427. /* Extract the device and default output format from the first input. */
  428. if (avctx->inputs[0] != inlink)
  429. return 0;
  430. input_frames = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
  431. if (input_frames->format != AV_PIX_FMT_VULKAN)
  432. return AVERROR(EINVAL);
  433. err = vulkan_filter_set_device(avctx, input_frames->device_ref);
  434. if (err < 0)
  435. return err;
  436. err = vulkan_filter_set_frames(avctx, inlink->hw_frames_ctx);
  437. if (err < 0)
  438. return err;
  439. /* Default output parameters match input parameters. */
  440. s->input_format = input_frames->sw_format;
  441. if (s->output_format == AV_PIX_FMT_NONE)
  442. s->output_format = input_frames->sw_format;
  443. if (!s->output_width)
  444. s->output_width = inlink->w;
  445. if (!s->output_height)
  446. s->output_height = inlink->h;
  447. return 0;
  448. }
  449. int ff_vk_filter_config_output_inplace(AVFilterLink *outlink)
  450. {
  451. int err;
  452. AVFilterContext *avctx = outlink->src;
  453. VulkanFilterContext *s = avctx->priv;
  454. av_buffer_unref(&outlink->hw_frames_ctx);
  455. if (!s->device_ref) {
  456. if (!avctx->hw_device_ctx) {
  457. av_log(avctx, AV_LOG_ERROR, "Vulkan filtering requires a "
  458. "Vulkan device.\n");
  459. return AVERROR(EINVAL);
  460. }
  461. err = vulkan_filter_set_device(avctx, avctx->hw_device_ctx);
  462. if (err < 0)
  463. return err;
  464. }
  465. outlink->hw_frames_ctx = av_buffer_ref(s->frames_ref);
  466. if (!outlink->hw_frames_ctx)
  467. return AVERROR(ENOMEM);
  468. outlink->w = s->output_width;
  469. outlink->h = s->output_height;
  470. return 0;
  471. }
  472. int ff_vk_filter_config_output(AVFilterLink *outlink)
  473. {
  474. int err;
  475. AVFilterContext *avctx = outlink->src;
  476. VulkanFilterContext *s = avctx->priv;
  477. AVBufferRef *output_frames_ref;
  478. AVHWFramesContext *output_frames;
  479. av_buffer_unref(&outlink->hw_frames_ctx);
  480. if (!s->device_ref) {
  481. if (!avctx->hw_device_ctx) {
  482. av_log(avctx, AV_LOG_ERROR, "Vulkan filtering requires a "
  483. "Vulkan device.\n");
  484. return AVERROR(EINVAL);
  485. }
  486. err = vulkan_filter_set_device(avctx, avctx->hw_device_ctx);
  487. if (err < 0)
  488. return err;
  489. }
  490. output_frames_ref = av_hwframe_ctx_alloc(s->device_ref);
  491. if (!output_frames_ref) {
  492. err = AVERROR(ENOMEM);
  493. goto fail;
  494. }
  495. output_frames = (AVHWFramesContext*)output_frames_ref->data;
  496. output_frames->format = AV_PIX_FMT_VULKAN;
  497. output_frames->sw_format = s->output_format;
  498. output_frames->width = s->output_width;
  499. output_frames->height = s->output_height;
  500. err = av_hwframe_ctx_init(output_frames_ref);
  501. if (err < 0) {
  502. av_log(avctx, AV_LOG_ERROR, "Failed to initialise output "
  503. "frames: %d.\n", err);
  504. goto fail;
  505. }
  506. outlink->hw_frames_ctx = output_frames_ref;
  507. outlink->w = s->output_width;
  508. outlink->h = s->output_height;
  509. return 0;
  510. fail:
  511. av_buffer_unref(&output_frames_ref);
  512. return err;
  513. }
  514. int ff_vk_filter_init(AVFilterContext *avctx)
  515. {
  516. VulkanFilterContext *s = avctx->priv;
  517. s->output_format = AV_PIX_FMT_NONE;
  518. if (glslang_init())
  519. return AVERROR_EXTERNAL;
  520. return 0;
  521. }
  522. FN_CREATING(VulkanFilterContext, VkSampler, sampler, samplers, samplers_num)
  523. VkSampler *ff_vk_init_sampler(AVFilterContext *avctx, int unnorm_coords,
  524. VkFilter filt)
  525. {
  526. VkResult ret;
  527. VulkanFilterContext *s = avctx->priv;
  528. VkSamplerCreateInfo sampler_info = {
  529. .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
  530. .magFilter = filt,
  531. .minFilter = sampler_info.magFilter,
  532. .mipmapMode = unnorm_coords ? VK_SAMPLER_MIPMAP_MODE_NEAREST :
  533. VK_SAMPLER_MIPMAP_MODE_LINEAR,
  534. .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
  535. .addressModeV = sampler_info.addressModeU,
  536. .addressModeW = sampler_info.addressModeU,
  537. .anisotropyEnable = VK_FALSE,
  538. .compareOp = VK_COMPARE_OP_NEVER,
  539. .borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK,
  540. .unnormalizedCoordinates = unnorm_coords,
  541. };
  542. VkSampler *sampler = create_sampler(s);
  543. if (!sampler)
  544. return NULL;
  545. ret = vkCreateSampler(s->hwctx->act_dev, &sampler_info,
  546. s->hwctx->alloc, sampler);
  547. if (ret != VK_SUCCESS) {
  548. av_log(avctx, AV_LOG_ERROR, "Unable to init sampler: %s\n",
  549. ff_vk_ret2str(ret));
  550. return NULL;
  551. }
  552. return sampler;
  553. }
  554. const char *ff_vk_shader_rep_fmt(enum AVPixelFormat pixfmt)
  555. {
  556. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pixfmt);
  557. const int high = desc->comp[0].depth > 8;
  558. return high ? "rgba16f" : "rgba8";
  559. }
  560. int ff_vk_create_imageview(AVFilterContext *avctx, VkImageView *v, VkImage img,
  561. VkFormat fmt, const VkComponentMapping map)
  562. {
  563. VulkanFilterContext *s = avctx->priv;
  564. VkImageViewCreateInfo imgview_spawn = {
  565. .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
  566. .pNext = NULL,
  567. .image = img,
  568. .viewType = VK_IMAGE_VIEW_TYPE_2D,
  569. .format = fmt,
  570. .components = map,
  571. .subresourceRange = {
  572. .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
  573. .baseMipLevel = 0,
  574. .levelCount = 1,
  575. .baseArrayLayer = 0,
  576. .layerCount = 1,
  577. },
  578. };
  579. VkResult ret = vkCreateImageView(s->hwctx->act_dev, &imgview_spawn,
  580. s->hwctx->alloc, v);
  581. if (ret != VK_SUCCESS) {
  582. av_log(s, AV_LOG_ERROR, "Failed to create imageview: %s\n",
  583. ff_vk_ret2str(ret));
  584. return AVERROR_EXTERNAL;
  585. }
  586. return 0;
  587. }
  588. void ff_vk_destroy_imageview(AVFilterContext *avctx, VkImageView *v)
  589. {
  590. VulkanFilterContext *s = avctx->priv;
  591. if (v && *v) {
  592. vkDestroyImageView(s->hwctx->act_dev, *v, s->hwctx->alloc);
  593. *v = NULL;
  594. }
  595. }
  596. FN_CREATING(VulkanPipeline, SPIRVShader, shader, shaders, shaders_num)
  597. SPIRVShader *ff_vk_init_shader(AVFilterContext *avctx, VulkanPipeline *pl,
  598. const char *name, VkShaderStageFlags stage)
  599. {
  600. SPIRVShader *shd = create_shader(pl);
  601. if (!shd)
  602. return NULL;
  603. av_bprint_init(&shd->src, 0, AV_BPRINT_SIZE_UNLIMITED);
  604. shd->shader.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  605. shd->shader.stage = stage;
  606. shd->name = name;
  607. GLSLF(0, #version %i ,460);
  608. GLSLC(0, #define IS_WITHIN(v1, v2) ((v1.x < v2.x) && (v1.y < v2.y)) );
  609. GLSLC(0, );
  610. return shd;
  611. }
  612. void ff_vk_set_compute_shader_sizes(AVFilterContext *avctx, SPIRVShader *shd,
  613. int local_size[3])
  614. {
  615. shd->local_size[0] = local_size[0];
  616. shd->local_size[1] = local_size[1];
  617. shd->local_size[2] = local_size[2];
  618. av_bprintf(&shd->src, "layout (local_size_x = %i, "
  619. "local_size_y = %i, local_size_z = %i) in;\n\n",
  620. shd->local_size[0], shd->local_size[1], shd->local_size[2]);
  621. }
  622. static void print_shader(AVFilterContext *avctx, SPIRVShader *shd, int prio)
  623. {
  624. int line = 0;
  625. const char *p = shd->src.str;
  626. const char *start = p;
  627. AVBPrint buf;
  628. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
  629. for (int i = 0; i < strlen(p); i++) {
  630. if (p[i] == '\n') {
  631. av_bprintf(&buf, "%i\t", ++line);
  632. av_bprint_append_data(&buf, start, &p[i] - start + 1);
  633. start = &p[i + 1];
  634. }
  635. }
  636. av_log(avctx, prio, "Shader %s: \n%s", shd->name, buf.str);
  637. av_bprint_finalize(&buf, NULL);
  638. }
  639. int ff_vk_compile_shader(AVFilterContext *avctx, SPIRVShader *shd,
  640. const char *entrypoint)
  641. {
  642. VkResult ret;
  643. VulkanFilterContext *s = avctx->priv;
  644. VkShaderModuleCreateInfo shader_create;
  645. GLSlangResult *res;
  646. static const enum GLSlangStage emap[] = {
  647. [VK_SHADER_STAGE_VERTEX_BIT] = GLSLANG_VERTEX,
  648. [VK_SHADER_STAGE_FRAGMENT_BIT] = GLSLANG_FRAGMENT,
  649. [VK_SHADER_STAGE_COMPUTE_BIT] = GLSLANG_COMPUTE,
  650. };
  651. shd->shader.pName = entrypoint;
  652. res = glslang_compile(shd->src.str, emap[shd->shader.stage]);
  653. if (!res)
  654. return AVERROR(ENOMEM);
  655. if (res->rval) {
  656. av_log(avctx, AV_LOG_ERROR, "Error compiling shader %s: %s!\n",
  657. shd->name, av_err2str(res->rval));
  658. print_shader(avctx, shd, AV_LOG_ERROR);
  659. if (res->error_msg)
  660. av_log(avctx, AV_LOG_ERROR, "%s", res->error_msg);
  661. av_free(res->error_msg);
  662. return res->rval;
  663. }
  664. print_shader(avctx, shd, AV_LOG_VERBOSE);
  665. shader_create.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  666. shader_create.pNext = NULL;
  667. shader_create.codeSize = res->size;
  668. shader_create.flags = 0;
  669. shader_create.pCode = res->data;
  670. ret = vkCreateShaderModule(s->hwctx->act_dev, &shader_create, NULL,
  671. &shd->shader.module);
  672. /* Free the GLSlangResult struct */
  673. av_free(res);
  674. if (ret != VK_SUCCESS) {
  675. av_log(avctx, AV_LOG_ERROR, "Unable to create shader module: %s\n",
  676. ff_vk_ret2str(ret));
  677. return AVERROR_EXTERNAL;
  678. }
  679. av_log(avctx, AV_LOG_VERBOSE, "Shader %s linked! Size: %zu bytes\n",
  680. shd->name, shader_create.codeSize);
  681. return 0;
  682. }
  683. static const struct descriptor_props {
  684. size_t struct_size; /* Size of the opaque which updates the descriptor */
  685. const char *type;
  686. int is_uniform;
  687. int mem_quali; /* Can use a memory qualifier */
  688. int dim_needed; /* Must indicate dimension */
  689. int buf_content; /* Must indicate buffer contents */
  690. } descriptor_props[] = {
  691. [VK_DESCRIPTOR_TYPE_SAMPLER] = { sizeof(VkDescriptorImageInfo), "sampler", 1, 0, 0, 0, },
  692. [VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE] = { sizeof(VkDescriptorImageInfo), "texture", 1, 0, 1, 0, },
  693. [VK_DESCRIPTOR_TYPE_STORAGE_IMAGE] = { sizeof(VkDescriptorImageInfo), "image", 1, 1, 1, 0, },
  694. [VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT] = { sizeof(VkDescriptorImageInfo), "subpassInput", 1, 0, 0, 0, },
  695. [VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER] = { sizeof(VkDescriptorImageInfo), "sampler", 1, 0, 1, 0, },
  696. [VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER] = { sizeof(VkDescriptorBufferInfo), NULL, 1, 0, 0, 1, },
  697. [VK_DESCRIPTOR_TYPE_STORAGE_BUFFER] = { sizeof(VkDescriptorBufferInfo), "buffer", 0, 1, 0, 1, },
  698. [VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC] = { sizeof(VkDescriptorBufferInfo), NULL, 1, 0, 0, 1, },
  699. [VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC] = { sizeof(VkDescriptorBufferInfo), "buffer", 0, 1, 0, 1, },
  700. [VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER] = { sizeof(VkBufferView), "samplerBuffer", 1, 0, 0, 0, },
  701. [VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER] = { sizeof(VkBufferView), "imageBuffer", 1, 0, 0, 0, },
  702. };
  703. int ff_vk_add_descriptor_set(AVFilterContext *avctx, VulkanPipeline *pl,
  704. SPIRVShader *shd, VulkanDescriptorSetBinding *desc,
  705. int num, int only_print_to_shader)
  706. {
  707. VkResult ret;
  708. VkDescriptorSetLayout *layout;
  709. VulkanFilterContext *s = avctx->priv;
  710. if (only_print_to_shader)
  711. goto print;
  712. pl->desc_layout = av_realloc_array(pl->desc_layout, sizeof(*pl->desc_layout),
  713. pl->descriptor_sets_num + 1);
  714. if (!pl->desc_layout)
  715. return AVERROR(ENOMEM);
  716. layout = &pl->desc_layout[pl->descriptor_sets_num];
  717. memset(layout, 0, sizeof(*layout));
  718. { /* Create descriptor set layout descriptions */
  719. VkDescriptorSetLayoutCreateInfo desc_create_layout = { 0 };
  720. VkDescriptorSetLayoutBinding *desc_binding;
  721. desc_binding = av_mallocz(sizeof(*desc_binding)*num);
  722. if (!desc_binding)
  723. return AVERROR(ENOMEM);
  724. for (int i = 0; i < num; i++) {
  725. desc_binding[i].binding = i;
  726. desc_binding[i].descriptorType = desc[i].type;
  727. desc_binding[i].descriptorCount = FFMAX(desc[i].elems, 1);
  728. desc_binding[i].stageFlags = desc[i].stages;
  729. desc_binding[i].pImmutableSamplers = desc[i].samplers;
  730. }
  731. desc_create_layout.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  732. desc_create_layout.pBindings = desc_binding;
  733. desc_create_layout.bindingCount = num;
  734. ret = vkCreateDescriptorSetLayout(s->hwctx->act_dev, &desc_create_layout,
  735. s->hwctx->alloc, layout);
  736. av_free(desc_binding);
  737. if (ret != VK_SUCCESS) {
  738. av_log(avctx, AV_LOG_ERROR, "Unable to init descriptor set "
  739. "layout: %s\n", ff_vk_ret2str(ret));
  740. return AVERROR_EXTERNAL;
  741. }
  742. }
  743. { /* Pool each descriptor by type and update pool counts */
  744. for (int i = 0; i < num; i++) {
  745. int j;
  746. for (j = 0; j < pl->pool_size_desc_num; j++)
  747. if (pl->pool_size_desc[j].type == desc[i].type)
  748. break;
  749. if (j >= pl->pool_size_desc_num) {
  750. pl->pool_size_desc = av_realloc_array(pl->pool_size_desc,
  751. sizeof(*pl->pool_size_desc),
  752. ++pl->pool_size_desc_num);
  753. if (!pl->pool_size_desc)
  754. return AVERROR(ENOMEM);
  755. memset(&pl->pool_size_desc[j], 0, sizeof(VkDescriptorPoolSize));
  756. }
  757. pl->pool_size_desc[j].type = desc[i].type;
  758. pl->pool_size_desc[j].descriptorCount += FFMAX(desc[i].elems, 1);
  759. }
  760. }
  761. { /* Create template creation struct */
  762. VkDescriptorUpdateTemplateCreateInfo *dt;
  763. VkDescriptorUpdateTemplateEntry *des_entries;
  764. /* Freed after descriptor set initialization */
  765. des_entries = av_mallocz(num*sizeof(VkDescriptorUpdateTemplateEntry));
  766. if (!des_entries)
  767. return AVERROR(ENOMEM);
  768. for (int i = 0; i < num; i++) {
  769. des_entries[i].dstBinding = i;
  770. des_entries[i].descriptorType = desc[i].type;
  771. des_entries[i].descriptorCount = FFMAX(desc[i].elems, 1);
  772. des_entries[i].dstArrayElement = 0;
  773. des_entries[i].offset = ((uint8_t *)desc[i].updater) - (uint8_t *)s;
  774. des_entries[i].stride = descriptor_props[desc[i].type].struct_size;
  775. }
  776. pl->desc_template_info = av_realloc_array(pl->desc_template_info,
  777. sizeof(*pl->desc_template_info),
  778. pl->descriptor_sets_num + 1);
  779. if (!pl->desc_template_info)
  780. return AVERROR(ENOMEM);
  781. dt = &pl->desc_template_info[pl->descriptor_sets_num];
  782. memset(dt, 0, sizeof(*dt));
  783. dt->sType = VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO;
  784. dt->templateType = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET;
  785. dt->descriptorSetLayout = *layout;
  786. dt->pDescriptorUpdateEntries = des_entries;
  787. dt->descriptorUpdateEntryCount = num;
  788. }
  789. pl->descriptor_sets_num++;
  790. print:
  791. /* Write shader info */
  792. for (int i = 0; i < num; i++) {
  793. const struct descriptor_props *prop = &descriptor_props[desc[i].type];
  794. GLSLA("layout (set = %i, binding = %i", pl->descriptor_sets_num - 1, i);
  795. if (desc[i].mem_layout)
  796. GLSLA(", %s", desc[i].mem_layout);
  797. GLSLA(")");
  798. if (prop->is_uniform)
  799. GLSLA(" uniform");
  800. if (prop->mem_quali && desc[i].mem_quali)
  801. GLSLA(" %s", desc[i].mem_quali);
  802. if (prop->type)
  803. GLSLA(" %s", prop->type);
  804. if (prop->dim_needed)
  805. GLSLA("%iD", desc[i].dimensions);
  806. GLSLA(" %s", desc[i].name);
  807. if (prop->buf_content)
  808. GLSLA(" {\n %s\n}", desc[i].buf_content);
  809. else if (desc[i].elems > 0)
  810. GLSLA("[%i]", desc[i].elems);
  811. GLSLA(";\n");
  812. }
  813. GLSLA("\n");
  814. return 0;
  815. }
  816. void ff_vk_update_descriptor_set(AVFilterContext *avctx, VulkanPipeline *pl,
  817. int set_id)
  818. {
  819. VulkanFilterContext *s = avctx->priv;
  820. vkUpdateDescriptorSetWithTemplate(s->hwctx->act_dev,
  821. pl->desc_set[set_id],
  822. pl->desc_template[set_id], s);
  823. }
  824. void ff_vk_update_push_exec(AVFilterContext *avctx, FFVkExecContext *e,
  825. VkShaderStageFlagBits stage, int offset,
  826. size_t size, void *src)
  827. {
  828. vkCmdPushConstants(e->buf, e->bound_pl->pipeline_layout,
  829. stage, offset, size, src);
  830. }
  831. int ff_vk_init_pipeline_layout(AVFilterContext *avctx, VulkanPipeline *pl)
  832. {
  833. VkResult ret;
  834. VulkanFilterContext *s = avctx->priv;
  835. { /* Init descriptor set pool */
  836. VkDescriptorPoolCreateInfo pool_create_info = {
  837. .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
  838. .poolSizeCount = pl->pool_size_desc_num,
  839. .pPoolSizes = pl->pool_size_desc,
  840. .maxSets = pl->descriptor_sets_num,
  841. };
  842. ret = vkCreateDescriptorPool(s->hwctx->act_dev, &pool_create_info,
  843. s->hwctx->alloc, &pl->desc_pool);
  844. av_freep(&pl->pool_size_desc);
  845. if (ret != VK_SUCCESS) {
  846. av_log(avctx, AV_LOG_ERROR, "Unable to init descriptor set "
  847. "pool: %s\n", ff_vk_ret2str(ret));
  848. return AVERROR_EXTERNAL;
  849. }
  850. }
  851. { /* Allocate descriptor sets */
  852. VkDescriptorSetAllocateInfo alloc_info = {
  853. .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
  854. .descriptorPool = pl->desc_pool,
  855. .descriptorSetCount = pl->descriptor_sets_num,
  856. .pSetLayouts = pl->desc_layout,
  857. };
  858. pl->desc_set = av_malloc(pl->descriptor_sets_num*sizeof(*pl->desc_set));
  859. if (!pl->desc_set)
  860. return AVERROR(ENOMEM);
  861. ret = vkAllocateDescriptorSets(s->hwctx->act_dev, &alloc_info,
  862. pl->desc_set);
  863. if (ret != VK_SUCCESS) {
  864. av_log(avctx, AV_LOG_ERROR, "Unable to allocate descriptor set: %s\n",
  865. ff_vk_ret2str(ret));
  866. return AVERROR_EXTERNAL;
  867. }
  868. }
  869. { /* Finally create the pipeline layout */
  870. VkPipelineLayoutCreateInfo spawn_pipeline_layout = {
  871. .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
  872. .setLayoutCount = pl->descriptor_sets_num,
  873. .pSetLayouts = pl->desc_layout,
  874. .pushConstantRangeCount = pl->push_consts_num,
  875. .pPushConstantRanges = pl->push_consts,
  876. };
  877. ret = vkCreatePipelineLayout(s->hwctx->act_dev, &spawn_pipeline_layout,
  878. s->hwctx->alloc, &pl->pipeline_layout);
  879. av_freep(&pl->push_consts);
  880. pl->push_consts_num = 0;
  881. if (ret != VK_SUCCESS) {
  882. av_log(avctx, AV_LOG_ERROR, "Unable to init pipeline layout: %s\n",
  883. ff_vk_ret2str(ret));
  884. return AVERROR_EXTERNAL;
  885. }
  886. }
  887. { /* Descriptor template (for tightly packed descriptors) */
  888. VkDescriptorUpdateTemplateCreateInfo *desc_template_info;
  889. pl->desc_template = av_malloc(pl->descriptor_sets_num*sizeof(*pl->desc_template));
  890. if (!pl->desc_template)
  891. return AVERROR(ENOMEM);
  892. /* Create update templates for the descriptor sets */
  893. for (int i = 0; i < pl->descriptor_sets_num; i++) {
  894. desc_template_info = &pl->desc_template_info[i];
  895. desc_template_info->pipelineLayout = pl->pipeline_layout;
  896. ret = vkCreateDescriptorUpdateTemplate(s->hwctx->act_dev,
  897. desc_template_info,
  898. s->hwctx->alloc,
  899. &pl->desc_template[i]);
  900. av_free((void *)desc_template_info->pDescriptorUpdateEntries);
  901. if (ret != VK_SUCCESS) {
  902. av_log(avctx, AV_LOG_ERROR, "Unable to init descriptor "
  903. "template: %s\n", ff_vk_ret2str(ret));
  904. return AVERROR_EXTERNAL;
  905. }
  906. }
  907. av_freep(&pl->desc_template_info);
  908. }
  909. return 0;
  910. }
  911. FN_CREATING(VulkanFilterContext, VulkanPipeline, pipeline, pipelines, pipelines_num)
  912. VulkanPipeline *ff_vk_create_pipeline(AVFilterContext *avctx)
  913. {
  914. return create_pipeline(avctx->priv);
  915. }
  916. int ff_vk_init_compute_pipeline(AVFilterContext *avctx, VulkanPipeline *pl)
  917. {
  918. int i;
  919. VkResult ret;
  920. VulkanFilterContext *s = avctx->priv;
  921. VkComputePipelineCreateInfo pipe = {
  922. .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
  923. .layout = pl->pipeline_layout,
  924. };
  925. for (i = 0; i < pl->shaders_num; i++) {
  926. if (pl->shaders[i]->shader.stage & VK_SHADER_STAGE_COMPUTE_BIT) {
  927. pipe.stage = pl->shaders[i]->shader;
  928. break;
  929. }
  930. }
  931. if (i == pl->shaders_num) {
  932. av_log(avctx, AV_LOG_ERROR, "Can't init compute pipeline, no shader\n");
  933. return AVERROR(EINVAL);
  934. }
  935. ret = vkCreateComputePipelines(s->hwctx->act_dev, VK_NULL_HANDLE, 1, &pipe,
  936. s->hwctx->alloc, &pl->pipeline);
  937. if (ret != VK_SUCCESS) {
  938. av_log(avctx, AV_LOG_ERROR, "Unable to init compute pipeline: %s\n",
  939. ff_vk_ret2str(ret));
  940. return AVERROR_EXTERNAL;
  941. }
  942. pl->bind_point = VK_PIPELINE_BIND_POINT_COMPUTE;
  943. return 0;
  944. }
  945. void ff_vk_bind_pipeline_exec(AVFilterContext *avctx, FFVkExecContext *e,
  946. VulkanPipeline *pl)
  947. {
  948. vkCmdBindPipeline(e->buf, pl->bind_point, pl->pipeline);
  949. vkCmdBindDescriptorSets(e->buf, pl->bind_point, pl->pipeline_layout, 0,
  950. pl->descriptor_sets_num, pl->desc_set, 0, 0);
  951. e->bound_pl = pl;
  952. }
  953. static void free_exec_ctx(VulkanFilterContext *s, FFVkExecContext *e)
  954. {
  955. vkDestroyFence(s->hwctx->act_dev, e->fence, s->hwctx->alloc);
  956. if (e->buf != VK_NULL_HANDLE)
  957. vkFreeCommandBuffers(s->hwctx->act_dev, e->pool, 1, &e->buf);
  958. if (e->pool != VK_NULL_HANDLE)
  959. vkDestroyCommandPool(s->hwctx->act_dev, e->pool, s->hwctx->alloc);
  960. av_free(e->sem_wait);
  961. av_free(e->sem_wait_dst);
  962. av_free(e->sem_sig);
  963. av_free(e);
  964. }
  965. static void free_pipeline(VulkanFilterContext *s, VulkanPipeline *pl)
  966. {
  967. for (int i = 0; i < pl->shaders_num; i++) {
  968. SPIRVShader *shd = pl->shaders[i];
  969. av_bprint_finalize(&shd->src, NULL);
  970. vkDestroyShaderModule(s->hwctx->act_dev, shd->shader.module,
  971. s->hwctx->alloc);
  972. av_free(shd);
  973. }
  974. vkDestroyPipeline(s->hwctx->act_dev, pl->pipeline, s->hwctx->alloc);
  975. vkDestroyPipelineLayout(s->hwctx->act_dev, pl->pipeline_layout,
  976. s->hwctx->alloc);
  977. for (int i = 0; i < pl->descriptor_sets_num; i++) {
  978. if (pl->desc_template && pl->desc_template[i])
  979. vkDestroyDescriptorUpdateTemplate(s->hwctx->act_dev, pl->desc_template[i],
  980. s->hwctx->alloc);
  981. if (pl->desc_layout && pl->desc_layout[i])
  982. vkDestroyDescriptorSetLayout(s->hwctx->act_dev, pl->desc_layout[i],
  983. s->hwctx->alloc);
  984. }
  985. /* Also frees the descriptor sets */
  986. if (pl->desc_pool)
  987. vkDestroyDescriptorPool(s->hwctx->act_dev, pl->desc_pool,
  988. s->hwctx->alloc);
  989. av_freep(&pl->desc_set);
  990. av_freep(&pl->shaders);
  991. av_freep(&pl->desc_layout);
  992. av_freep(&pl->desc_template);
  993. av_freep(&pl->push_consts);
  994. pl->push_consts_num = 0;
  995. /* Only freed in case of failure */
  996. av_freep(&pl->pool_size_desc);
  997. if (pl->desc_template_info) {
  998. for (int i = 0; i < pl->descriptor_sets_num; i++)
  999. av_free((void *)pl->desc_template_info[i].pDescriptorUpdateEntries);
  1000. av_freep(&pl->desc_template_info);
  1001. }
  1002. av_free(pl);
  1003. }
  1004. void ff_vk_filter_uninit(AVFilterContext *avctx)
  1005. {
  1006. VulkanFilterContext *s = avctx->priv;
  1007. glslang_uninit();
  1008. for (int i = 0; i < s->samplers_num; i++)
  1009. vkDestroySampler(s->hwctx->act_dev, *s->samplers[i], s->hwctx->alloc);
  1010. av_freep(&s->samplers);
  1011. for (int i = 0; i < s->pipelines_num; i++)
  1012. free_pipeline(s, s->pipelines[i]);
  1013. av_freep(&s->pipelines);
  1014. for (int i = 0; i < s->exec_ctx_num; i++)
  1015. free_exec_ctx(s, s->exec_ctx[i]);
  1016. av_freep(&s->exec_ctx);
  1017. av_freep(&s->scratch);
  1018. s->scratch_size = 0;
  1019. av_buffer_unref(&s->device_ref);
  1020. av_buffer_unref(&s->frames_ref);
  1021. }