2 * This file is part of FFmpeg.
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.
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.
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
23 /* Generic macro for creating contexts which need to keep their addresses
24 * if another context is created. */
25 #define FN_CREATING(ctx, type, shortname, array, num) \
26 static av_always_inline type *create_ ##shortname(ctx *dctx) \
28 type **array, *sctx = av_mallocz(sizeof(*sctx)); \
32 array = av_realloc_array(dctx->array, sizeof(*dctx->array), dctx->num + 1);\
38 dctx->array = array; \
39 dctx->array[dctx->num++] = sctx; \
44 const VkComponentMapping ff_comp_identity_map = {
45 .r = VK_COMPONENT_SWIZZLE_IDENTITY,
46 .g = VK_COMPONENT_SWIZZLE_IDENTITY,
47 .b = VK_COMPONENT_SWIZZLE_IDENTITY,
48 .a = VK_COMPONENT_SWIZZLE_IDENTITY,
51 /* Converts return values to strings */
52 const char *ff_vk_ret2str(VkResult res)
54 #define CASE(VAL) case VAL: return #VAL
62 CASE(VK_ERROR_OUT_OF_HOST_MEMORY);
63 CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY);
64 CASE(VK_ERROR_INITIALIZATION_FAILED);
65 CASE(VK_ERROR_DEVICE_LOST);
66 CASE(VK_ERROR_MEMORY_MAP_FAILED);
67 CASE(VK_ERROR_LAYER_NOT_PRESENT);
68 CASE(VK_ERROR_EXTENSION_NOT_PRESENT);
69 CASE(VK_ERROR_FEATURE_NOT_PRESENT);
70 CASE(VK_ERROR_INCOMPATIBLE_DRIVER);
71 CASE(VK_ERROR_TOO_MANY_OBJECTS);
72 CASE(VK_ERROR_FORMAT_NOT_SUPPORTED);
73 CASE(VK_ERROR_FRAGMENTED_POOL);
74 CASE(VK_ERROR_SURFACE_LOST_KHR);
75 CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR);
76 CASE(VK_SUBOPTIMAL_KHR);
77 CASE(VK_ERROR_OUT_OF_DATE_KHR);
78 CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR);
79 CASE(VK_ERROR_VALIDATION_FAILED_EXT);
80 CASE(VK_ERROR_INVALID_SHADER_NV);
81 CASE(VK_ERROR_OUT_OF_POOL_MEMORY);
82 CASE(VK_ERROR_INVALID_EXTERNAL_HANDLE);
83 CASE(VK_ERROR_NOT_PERMITTED_EXT);
84 default: return "Unknown error";
89 static int vk_alloc_mem(AVFilterContext *avctx, VkMemoryRequirements *req,
90 VkMemoryPropertyFlagBits req_flags, void *alloc_extension,
91 VkMemoryPropertyFlagBits *mem_flags, VkDeviceMemory *mem)
95 VkPhysicalDeviceProperties props;
96 VkPhysicalDeviceMemoryProperties mprops;
97 VulkanFilterContext *s = avctx->priv;
99 VkMemoryAllocateInfo alloc_info = {
100 .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
101 .pNext = alloc_extension,
104 vkGetPhysicalDeviceProperties(s->hwctx->phys_dev, &props);
105 vkGetPhysicalDeviceMemoryProperties(s->hwctx->phys_dev, &mprops);
107 /* Align if we need to */
108 if (req_flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
109 req->size = FFALIGN(req->size, props.limits.minMemoryMapAlignment);
111 alloc_info.allocationSize = req->size;
113 /* The vulkan spec requires memory types to be sorted in the "optimal"
114 * order, so the first matching type we find will be the best/fastest one */
115 for (int i = 0; i < mprops.memoryTypeCount; i++) {
116 /* The memory type must be supported by the requirements (bitfield) */
117 if (!(req->memoryTypeBits & (1 << i)))
120 /* The memory type flags must include our properties */
121 if ((mprops.memoryTypes[i].propertyFlags & req_flags) != req_flags)
124 /* Found a suitable memory type */
130 av_log(avctx, AV_LOG_ERROR, "No memory type found for flags 0x%x\n",
132 return AVERROR(EINVAL);
135 alloc_info.memoryTypeIndex = index;
137 ret = vkAllocateMemory(s->hwctx->act_dev, &alloc_info,
138 s->hwctx->alloc, mem);
139 if (ret != VK_SUCCESS) {
140 av_log(avctx, AV_LOG_ERROR, "Failed to allocate memory: %s\n",
142 return AVERROR(ENOMEM);
145 *mem_flags |= mprops.memoryTypes[index].propertyFlags;
150 int ff_vk_create_buf(AVFilterContext *avctx, FFVkBuffer *buf, size_t size,
151 VkBufferUsageFlags usage, VkMemoryPropertyFlagBits flags)
155 VkMemoryRequirements req;
156 VulkanFilterContext *s = avctx->priv;
158 VkBufferCreateInfo buf_spawn = {
159 .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
162 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
163 .size = size, /* Gets FFALIGNED during alloc if host visible
167 ret = vkCreateBuffer(s->hwctx->act_dev, &buf_spawn, NULL, &buf->buf);
168 if (ret != VK_SUCCESS) {
169 av_log(avctx, AV_LOG_ERROR, "Failed to create buffer: %s\n",
171 return AVERROR_EXTERNAL;
174 vkGetBufferMemoryRequirements(s->hwctx->act_dev, buf->buf, &req);
176 err = vk_alloc_mem(avctx, &req, flags, NULL, &buf->flags, &buf->mem);
180 ret = vkBindBufferMemory(s->hwctx->act_dev, buf->buf, buf->mem, 0);
181 if (ret != VK_SUCCESS) {
182 av_log(avctx, AV_LOG_ERROR, "Failed to bind memory to buffer: %s\n",
184 return AVERROR_EXTERNAL;
190 int ff_vk_map_buffers(AVFilterContext *avctx, FFVkBuffer *buf, uint8_t *mem[],
191 int nb_buffers, int invalidate)
194 VulkanFilterContext *s = avctx->priv;
195 VkMappedMemoryRange *inval_list = NULL;
198 for (int i = 0; i < nb_buffers; i++) {
199 ret = vkMapMemory(s->hwctx->act_dev, buf[i].mem, 0,
200 VK_WHOLE_SIZE, 0, (void **)&mem[i]);
201 if (ret != VK_SUCCESS) {
202 av_log(avctx, AV_LOG_ERROR, "Failed to map buffer memory: %s\n",
204 return AVERROR_EXTERNAL;
211 for (int i = 0; i < nb_buffers; i++) {
212 const VkMappedMemoryRange ival_buf = {
213 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
214 .memory = buf[i].mem,
215 .size = VK_WHOLE_SIZE,
217 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
219 inval_list = av_fast_realloc(s->scratch, &s->scratch_size,
220 (++inval_count)*sizeof(*inval_list));
222 return AVERROR(ENOMEM);
223 inval_list[inval_count - 1] = ival_buf;
227 ret = vkInvalidateMappedMemoryRanges(s->hwctx->act_dev, inval_count,
229 if (ret != VK_SUCCESS) {
230 av_log(avctx, AV_LOG_ERROR, "Failed to invalidate memory: %s\n",
232 return AVERROR_EXTERNAL;
239 int ff_vk_unmap_buffers(AVFilterContext *avctx, FFVkBuffer *buf, int nb_buffers,
244 VulkanFilterContext *s = avctx->priv;
245 VkMappedMemoryRange *flush_list = NULL;
249 for (int i = 0; i < nb_buffers; i++) {
250 const VkMappedMemoryRange flush_buf = {
251 .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
252 .memory = buf[i].mem,
253 .size = VK_WHOLE_SIZE,
255 if (buf[i].flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
257 flush_list = av_fast_realloc(s->scratch, &s->scratch_size,
258 (++flush_count)*sizeof(*flush_list));
260 return AVERROR(ENOMEM);
261 flush_list[flush_count - 1] = flush_buf;
266 ret = vkFlushMappedMemoryRanges(s->hwctx->act_dev, flush_count,
268 if (ret != VK_SUCCESS) {
269 av_log(avctx, AV_LOG_ERROR, "Failed to flush memory: %s\n",
271 err = AVERROR_EXTERNAL; /* We still want to try to unmap them */
275 for (int i = 0; i < nb_buffers; i++)
276 vkUnmapMemory(s->hwctx->act_dev, buf[i].mem);
281 void ff_vk_free_buf(AVFilterContext *avctx, FFVkBuffer *buf)
283 VulkanFilterContext *s = avctx->priv;
287 if (buf->buf != VK_NULL_HANDLE)
288 vkDestroyBuffer(s->hwctx->act_dev, buf->buf, s->hwctx->alloc);
289 if (buf->mem != VK_NULL_HANDLE)
290 vkFreeMemory(s->hwctx->act_dev, buf->mem, s->hwctx->alloc);
293 int ff_vk_add_push_constant(AVFilterContext *avctx, VulkanPipeline *pl,
294 int offset, int size, VkShaderStageFlagBits stage)
296 VkPushConstantRange *pc;
298 pl->push_consts = av_realloc_array(pl->push_consts, sizeof(*pl->push_consts),
299 pl->push_consts_num + 1);
300 if (!pl->push_consts)
301 return AVERROR(ENOMEM);
303 pc = &pl->push_consts[pl->push_consts_num++];
304 memset(pc, 0, sizeof(*pc));
306 pc->stageFlags = stage;
313 FN_CREATING(VulkanFilterContext, FFVkExecContext, exec_ctx, exec_ctx, exec_ctx_num)
314 int ff_vk_create_exec_ctx(AVFilterContext *avctx, FFVkExecContext **ctx, int queue)
318 VulkanFilterContext *s = avctx->priv;
320 VkCommandPoolCreateInfo cqueue_create = {
321 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
322 .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
323 .queueFamilyIndex = queue,
325 VkCommandBufferAllocateInfo cbuf_create = {
326 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
327 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
328 .commandBufferCount = 1,
330 VkFenceCreateInfo fence_spawn = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
332 e = create_exec_ctx(s);
334 return AVERROR(ENOMEM);
336 ret = vkCreateCommandPool(s->hwctx->act_dev, &cqueue_create,
337 s->hwctx->alloc, &e->pool);
338 if (ret != VK_SUCCESS) {
339 av_log(avctx, AV_LOG_ERROR, "Command pool creation failure: %s\n",
344 cbuf_create.commandPool = e->pool;
346 ret = vkAllocateCommandBuffers(s->hwctx->act_dev, &cbuf_create, &e->buf);
347 if (ret != VK_SUCCESS) {
348 av_log(avctx, AV_LOG_ERROR, "Command buffer alloc failure: %s\n",
353 ret = vkCreateFence(s->hwctx->act_dev, &fence_spawn,
354 s->hwctx->alloc, &e->fence);
355 if (ret != VK_SUCCESS) {
356 av_log(avctx, AV_LOG_ERROR, "Failed to create frame fence: %s\n",
361 vkGetDeviceQueue(s->hwctx->act_dev, queue, 0, &e->queue);
368 int ff_vk_start_exec_recording(AVFilterContext *avctx, FFVkExecContext *e)
371 VkCommandBufferBeginInfo cmd_start = {
372 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
373 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
379 ret = vkBeginCommandBuffer(e->buf, &cmd_start);
380 if (ret != VK_SUCCESS) {
381 av_log(avctx, AV_LOG_ERROR, "Failed to start command recoding: %s\n",
383 return AVERROR_EXTERNAL;
389 int ff_vk_add_exec_dep(AVFilterContext *avctx, FFVkExecContext *e,
390 AVFrame *frame, VkPipelineStageFlagBits in_wait_dst_flag)
392 AVVkFrame *f = (AVVkFrame *)frame->data[0];
393 AVHWFramesContext *fc = (AVHWFramesContext *)frame->hw_frames_ctx->data;
394 int planes = av_pix_fmt_count_planes(fc->sw_format);
396 for (int i = 0; i < planes; i++) {
397 e->sem_wait = av_fast_realloc(e->sem_wait, &e->sem_wait_alloc,
398 (e->sem_wait_cnt + 1)*sizeof(*e->sem_wait));
400 return AVERROR(ENOMEM);
402 e->sem_wait_dst = av_fast_realloc(e->sem_wait_dst, &e->sem_wait_dst_alloc,
403 (e->sem_wait_cnt + 1)*sizeof(*e->sem_wait_dst));
404 if (!e->sem_wait_dst)
405 return AVERROR(ENOMEM);
407 e->sem_sig = av_fast_realloc(e->sem_sig, &e->sem_sig_alloc,
408 (e->sem_sig_cnt + 1)*sizeof(*e->sem_sig));
410 return AVERROR(ENOMEM);
412 e->sem_wait[e->sem_wait_cnt] = f->sem[i];
413 e->sem_wait_dst[e->sem_wait_cnt] = in_wait_dst_flag;
416 e->sem_sig[e->sem_sig_cnt] = f->sem[i];
423 int ff_vk_submit_exec_queue(AVFilterContext *avctx, FFVkExecContext *e)
426 VulkanFilterContext *s = avctx->priv;
428 VkSubmitInfo s_info = {
429 .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
430 .commandBufferCount = 1,
431 .pCommandBuffers = &e->buf,
433 .pWaitSemaphores = e->sem_wait,
434 .pWaitDstStageMask = e->sem_wait_dst,
435 .waitSemaphoreCount = e->sem_wait_cnt,
437 .pSignalSemaphores = e->sem_sig,
438 .signalSemaphoreCount = e->sem_sig_cnt,
441 vkEndCommandBuffer(e->buf);
443 ret = vkQueueSubmit(e->queue, 1, &s_info, e->fence);
444 if (ret != VK_SUCCESS) {
445 av_log(avctx, AV_LOG_ERROR, "Unable to submit command buffer: %s\n",
447 return AVERROR_EXTERNAL;
450 vkWaitForFences(s->hwctx->act_dev, 1, &e->fence, VK_TRUE, UINT64_MAX);
451 vkResetFences(s->hwctx->act_dev, 1, &e->fence);
456 int ff_vk_filter_query_formats(AVFilterContext *avctx)
458 static const enum AVPixelFormat pixel_formats[] = {
459 AV_PIX_FMT_VULKAN, AV_PIX_FMT_NONE,
461 AVFilterFormats *pix_fmts = ff_make_format_list(pixel_formats);
463 return AVERROR(ENOMEM);
465 return ff_set_common_formats(avctx, pix_fmts);
468 static int vulkan_filter_set_device(AVFilterContext *avctx,
471 VulkanFilterContext *s = avctx->priv;
473 av_buffer_unref(&s->device_ref);
475 s->device_ref = av_buffer_ref(device);
477 return AVERROR(ENOMEM);
479 s->device = (AVHWDeviceContext*)s->device_ref->data;
480 s->hwctx = s->device->hwctx;
485 static int vulkan_filter_set_frames(AVFilterContext *avctx,
488 VulkanFilterContext *s = avctx->priv;
490 av_buffer_unref(&s->frames_ref);
492 s->frames_ref = av_buffer_ref(frames);
494 return AVERROR(ENOMEM);
499 int ff_vk_filter_config_input(AVFilterLink *inlink)
502 AVFilterContext *avctx = inlink->dst;
503 VulkanFilterContext *s = avctx->priv;
504 AVHWFramesContext *input_frames;
506 if (!inlink->hw_frames_ctx) {
507 av_log(avctx, AV_LOG_ERROR, "Vulkan filtering requires a "
508 "hardware frames context on the input.\n");
509 return AVERROR(EINVAL);
512 /* Extract the device and default output format from the first input. */
513 if (avctx->inputs[0] != inlink)
516 input_frames = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
517 if (input_frames->format != AV_PIX_FMT_VULKAN)
518 return AVERROR(EINVAL);
520 err = vulkan_filter_set_device(avctx, input_frames->device_ref);
523 err = vulkan_filter_set_frames(avctx, inlink->hw_frames_ctx);
527 /* Default output parameters match input parameters. */
528 s->input_format = input_frames->sw_format;
529 if (s->output_format == AV_PIX_FMT_NONE)
530 s->output_format = input_frames->sw_format;
531 if (!s->output_width)
532 s->output_width = inlink->w;
533 if (!s->output_height)
534 s->output_height = inlink->h;
539 int ff_vk_filter_config_output_inplace(AVFilterLink *outlink)
542 AVFilterContext *avctx = outlink->src;
543 VulkanFilterContext *s = avctx->priv;
545 av_buffer_unref(&outlink->hw_frames_ctx);
547 if (!s->device_ref) {
548 if (!avctx->hw_device_ctx) {
549 av_log(avctx, AV_LOG_ERROR, "Vulkan filtering requires a "
551 return AVERROR(EINVAL);
554 err = vulkan_filter_set_device(avctx, avctx->hw_device_ctx);
559 outlink->hw_frames_ctx = av_buffer_ref(s->frames_ref);
560 if (!outlink->hw_frames_ctx)
561 return AVERROR(ENOMEM);
563 outlink->w = s->output_width;
564 outlink->h = s->output_height;
569 int ff_vk_filter_config_output(AVFilterLink *outlink)
572 AVFilterContext *avctx = outlink->src;
573 VulkanFilterContext *s = avctx->priv;
574 AVBufferRef *output_frames_ref;
575 AVHWFramesContext *output_frames;
577 av_buffer_unref(&outlink->hw_frames_ctx);
579 if (!s->device_ref) {
580 if (!avctx->hw_device_ctx) {
581 av_log(avctx, AV_LOG_ERROR, "Vulkan filtering requires a "
583 return AVERROR(EINVAL);
586 err = vulkan_filter_set_device(avctx, avctx->hw_device_ctx);
591 output_frames_ref = av_hwframe_ctx_alloc(s->device_ref);
592 if (!output_frames_ref) {
593 err = AVERROR(ENOMEM);
596 output_frames = (AVHWFramesContext*)output_frames_ref->data;
598 output_frames->format = AV_PIX_FMT_VULKAN;
599 output_frames->sw_format = s->output_format;
600 output_frames->width = s->output_width;
601 output_frames->height = s->output_height;
603 err = av_hwframe_ctx_init(output_frames_ref);
605 av_log(avctx, AV_LOG_ERROR, "Failed to initialise output "
606 "frames: %d.\n", err);
610 outlink->hw_frames_ctx = output_frames_ref;
611 outlink->w = s->output_width;
612 outlink->h = s->output_height;
616 av_buffer_unref(&output_frames_ref);
620 int ff_vk_filter_init(AVFilterContext *avctx)
622 VulkanFilterContext *s = avctx->priv;
624 s->output_format = AV_PIX_FMT_NONE;
627 return AVERROR_EXTERNAL;
632 FN_CREATING(VulkanFilterContext, VkSampler, sampler, samplers, samplers_num)
633 VkSampler *ff_vk_init_sampler(AVFilterContext *avctx, int unnorm_coords,
637 VulkanFilterContext *s = avctx->priv;
639 VkSamplerCreateInfo sampler_info = {
640 .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
642 .minFilter = sampler_info.magFilter,
643 .mipmapMode = unnorm_coords ? VK_SAMPLER_MIPMAP_MODE_NEAREST :
644 VK_SAMPLER_MIPMAP_MODE_LINEAR,
645 .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
646 .addressModeV = sampler_info.addressModeU,
647 .addressModeW = sampler_info.addressModeU,
648 .anisotropyEnable = VK_FALSE,
649 .compareOp = VK_COMPARE_OP_NEVER,
650 .borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK,
651 .unnormalizedCoordinates = unnorm_coords,
654 VkSampler *sampler = create_sampler(s);
658 ret = vkCreateSampler(s->hwctx->act_dev, &sampler_info,
659 s->hwctx->alloc, sampler);
660 if (ret != VK_SUCCESS) {
661 av_log(avctx, AV_LOG_ERROR, "Unable to init sampler: %s\n",
669 int ff_vk_mt_is_np_rgb(enum AVPixelFormat pix_fmt)
671 if (pix_fmt == AV_PIX_FMT_ABGR || pix_fmt == AV_PIX_FMT_BGRA ||
672 pix_fmt == AV_PIX_FMT_RGBA || pix_fmt == AV_PIX_FMT_RGB24 ||
673 pix_fmt == AV_PIX_FMT_BGR24 || pix_fmt == AV_PIX_FMT_RGB48 ||
674 pix_fmt == AV_PIX_FMT_RGBA64 || pix_fmt == AV_PIX_FMT_RGB565 ||
675 pix_fmt == AV_PIX_FMT_BGR565 || pix_fmt == AV_PIX_FMT_BGR0 ||
676 pix_fmt == AV_PIX_FMT_0BGR || pix_fmt == AV_PIX_FMT_RGB0)
681 const char *ff_vk_shader_rep_fmt(enum AVPixelFormat pixfmt)
683 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pixfmt);
684 const int high = desc->comp[0].depth > 8;
685 return high ? "rgba16f" : "rgba8";
688 int ff_vk_create_imageview(AVFilterContext *avctx, VkImageView *v, VkImage img,
689 VkFormat fmt, const VkComponentMapping map)
691 VulkanFilterContext *s = avctx->priv;
692 VkImageViewCreateInfo imgview_spawn = {
693 .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
696 .viewType = VK_IMAGE_VIEW_TYPE_2D,
699 .subresourceRange = {
700 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
708 VkResult ret = vkCreateImageView(s->hwctx->act_dev, &imgview_spawn,
710 if (ret != VK_SUCCESS) {
711 av_log(s, AV_LOG_ERROR, "Failed to create imageview: %s\n",
713 return AVERROR_EXTERNAL;
719 void ff_vk_destroy_imageview(AVFilterContext *avctx, VkImageView *v)
721 VulkanFilterContext *s = avctx->priv;
723 vkDestroyImageView(s->hwctx->act_dev, *v, s->hwctx->alloc);
728 FN_CREATING(VulkanPipeline, SPIRVShader, shader, shaders, shaders_num)
729 SPIRVShader *ff_vk_init_shader(AVFilterContext *avctx, VulkanPipeline *pl,
730 const char *name, VkShaderStageFlags stage)
732 SPIRVShader *shd = create_shader(pl);
736 av_bprint_init(&shd->src, 0, AV_BPRINT_SIZE_UNLIMITED);
738 shd->shader.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
739 shd->shader.stage = stage;
743 GLSLF(0, #version %i ,460);
744 GLSLC(0, #define IS_WITHIN(v1, v2) ((v1.x < v2.x) && (v1.y < v2.y)) );
750 void ff_vk_set_compute_shader_sizes(AVFilterContext *avctx, SPIRVShader *shd,
753 shd->local_size[0] = local_size[0];
754 shd->local_size[1] = local_size[1];
755 shd->local_size[2] = local_size[2];
757 av_bprintf(&shd->src, "layout (local_size_x = %i, "
758 "local_size_y = %i, local_size_z = %i) in;\n\n",
759 shd->local_size[0], shd->local_size[1], shd->local_size[2]);
762 static void print_shader(AVFilterContext *avctx, SPIRVShader *shd, int prio)
765 const char *p = shd->src.str;
766 const char *start = p;
769 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
771 for (int i = 0; i < strlen(p); i++) {
773 av_bprintf(&buf, "%i\t", ++line);
774 av_bprint_append_data(&buf, start, &p[i] - start + 1);
779 av_log(avctx, prio, "Shader %s: \n%s", shd->name, buf.str);
780 av_bprint_finalize(&buf, NULL);
783 int ff_vk_compile_shader(AVFilterContext *avctx, SPIRVShader *shd,
784 const char *entrypoint)
787 VulkanFilterContext *s = avctx->priv;
788 VkShaderModuleCreateInfo shader_create;
791 static const enum GLSlangStage emap[] = {
792 [VK_SHADER_STAGE_VERTEX_BIT] = GLSLANG_VERTEX,
793 [VK_SHADER_STAGE_FRAGMENT_BIT] = GLSLANG_FRAGMENT,
794 [VK_SHADER_STAGE_COMPUTE_BIT] = GLSLANG_COMPUTE,
797 shd->shader.pName = entrypoint;
799 res = glslang_compile(shd->src.str, emap[shd->shader.stage]);
801 return AVERROR(ENOMEM);
804 av_log(avctx, AV_LOG_ERROR, "Error compiling shader %s: %s!\n",
805 shd->name, av_err2str(res->rval));
806 print_shader(avctx, shd, AV_LOG_ERROR);
808 av_log(avctx, AV_LOG_ERROR, "%s", res->error_msg);
809 av_free(res->error_msg);
813 print_shader(avctx, shd, AV_LOG_VERBOSE);
815 shader_create.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
816 shader_create.pNext = NULL;
817 shader_create.codeSize = res->size;
818 shader_create.flags = 0;
819 shader_create.pCode = res->data;
821 ret = vkCreateShaderModule(s->hwctx->act_dev, &shader_create, NULL,
822 &shd->shader.module);
824 /* Free the GLSlangResult struct */
827 if (ret != VK_SUCCESS) {
828 av_log(avctx, AV_LOG_ERROR, "Unable to create shader module: %s\n",
830 return AVERROR_EXTERNAL;
833 av_log(avctx, AV_LOG_VERBOSE, "Shader %s linked! Size: %zu bytes\n",
834 shd->name, shader_create.codeSize);
839 static const struct descriptor_props {
840 size_t struct_size; /* Size of the opaque which updates the descriptor */
843 int mem_quali; /* Can use a memory qualifier */
844 int dim_needed; /* Must indicate dimension */
845 int buf_content; /* Must indicate buffer contents */
846 } descriptor_props[] = {
847 [VK_DESCRIPTOR_TYPE_SAMPLER] = { sizeof(VkDescriptorImageInfo), "sampler", 1, 0, 0, 0, },
848 [VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE] = { sizeof(VkDescriptorImageInfo), "texture", 1, 0, 1, 0, },
849 [VK_DESCRIPTOR_TYPE_STORAGE_IMAGE] = { sizeof(VkDescriptorImageInfo), "image", 1, 1, 1, 0, },
850 [VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT] = { sizeof(VkDescriptorImageInfo), "subpassInput", 1, 0, 0, 0, },
851 [VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER] = { sizeof(VkDescriptorImageInfo), "sampler", 1, 0, 1, 0, },
852 [VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER] = { sizeof(VkDescriptorBufferInfo), NULL, 1, 0, 0, 1, },
853 [VK_DESCRIPTOR_TYPE_STORAGE_BUFFER] = { sizeof(VkDescriptorBufferInfo), "buffer", 0, 1, 0, 1, },
854 [VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC] = { sizeof(VkDescriptorBufferInfo), NULL, 1, 0, 0, 1, },
855 [VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC] = { sizeof(VkDescriptorBufferInfo), "buffer", 0, 1, 0, 1, },
856 [VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER] = { sizeof(VkBufferView), "samplerBuffer", 1, 0, 0, 0, },
857 [VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER] = { sizeof(VkBufferView), "imageBuffer", 1, 0, 0, 0, },
860 int ff_vk_add_descriptor_set(AVFilterContext *avctx, VulkanPipeline *pl,
861 SPIRVShader *shd, VulkanDescriptorSetBinding *desc,
862 int num, int only_print_to_shader)
865 VkDescriptorSetLayout *layout;
866 VulkanFilterContext *s = avctx->priv;
868 if (only_print_to_shader)
871 pl->desc_layout = av_realloc_array(pl->desc_layout, sizeof(*pl->desc_layout),
872 pl->descriptor_sets_num + 1);
873 if (!pl->desc_layout)
874 return AVERROR(ENOMEM);
876 layout = &pl->desc_layout[pl->descriptor_sets_num];
877 memset(layout, 0, sizeof(*layout));
879 { /* Create descriptor set layout descriptions */
880 VkDescriptorSetLayoutCreateInfo desc_create_layout = { 0 };
881 VkDescriptorSetLayoutBinding *desc_binding;
883 desc_binding = av_mallocz(sizeof(*desc_binding)*num);
885 return AVERROR(ENOMEM);
887 for (int i = 0; i < num; i++) {
888 desc_binding[i].binding = i;
889 desc_binding[i].descriptorType = desc[i].type;
890 desc_binding[i].descriptorCount = FFMAX(desc[i].elems, 1);
891 desc_binding[i].stageFlags = desc[i].stages;
892 desc_binding[i].pImmutableSamplers = desc[i].samplers;
895 desc_create_layout.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
896 desc_create_layout.pBindings = desc_binding;
897 desc_create_layout.bindingCount = num;
899 ret = vkCreateDescriptorSetLayout(s->hwctx->act_dev, &desc_create_layout,
900 s->hwctx->alloc, layout);
901 av_free(desc_binding);
902 if (ret != VK_SUCCESS) {
903 av_log(avctx, AV_LOG_ERROR, "Unable to init descriptor set "
904 "layout: %s\n", ff_vk_ret2str(ret));
905 return AVERROR_EXTERNAL;
909 { /* Pool each descriptor by type and update pool counts */
910 for (int i = 0; i < num; i++) {
912 for (j = 0; j < pl->pool_size_desc_num; j++)
913 if (pl->pool_size_desc[j].type == desc[i].type)
915 if (j >= pl->pool_size_desc_num) {
916 pl->pool_size_desc = av_realloc_array(pl->pool_size_desc,
917 sizeof(*pl->pool_size_desc),
918 ++pl->pool_size_desc_num);
919 if (!pl->pool_size_desc)
920 return AVERROR(ENOMEM);
921 memset(&pl->pool_size_desc[j], 0, sizeof(VkDescriptorPoolSize));
923 pl->pool_size_desc[j].type = desc[i].type;
924 pl->pool_size_desc[j].descriptorCount += FFMAX(desc[i].elems, 1);
928 { /* Create template creation struct */
929 VkDescriptorUpdateTemplateCreateInfo *dt;
930 VkDescriptorUpdateTemplateEntry *des_entries;
932 /* Freed after descriptor set initialization */
933 des_entries = av_mallocz(num*sizeof(VkDescriptorUpdateTemplateEntry));
935 return AVERROR(ENOMEM);
937 for (int i = 0; i < num; i++) {
938 des_entries[i].dstBinding = i;
939 des_entries[i].descriptorType = desc[i].type;
940 des_entries[i].descriptorCount = FFMAX(desc[i].elems, 1);
941 des_entries[i].dstArrayElement = 0;
942 des_entries[i].offset = ((uint8_t *)desc[i].updater) - (uint8_t *)s;
943 des_entries[i].stride = descriptor_props[desc[i].type].struct_size;
946 pl->desc_template_info = av_realloc_array(pl->desc_template_info,
947 sizeof(*pl->desc_template_info),
948 pl->descriptor_sets_num + 1);
949 if (!pl->desc_template_info)
950 return AVERROR(ENOMEM);
952 dt = &pl->desc_template_info[pl->descriptor_sets_num];
953 memset(dt, 0, sizeof(*dt));
955 dt->sType = VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO;
956 dt->templateType = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET;
957 dt->descriptorSetLayout = *layout;
958 dt->pDescriptorUpdateEntries = des_entries;
959 dt->descriptorUpdateEntryCount = num;
962 pl->descriptor_sets_num++;
965 /* Write shader info */
966 for (int i = 0; i < num; i++) {
967 const struct descriptor_props *prop = &descriptor_props[desc[i].type];
968 GLSLA("layout (set = %i, binding = %i", pl->descriptor_sets_num - 1, i);
970 if (desc[i].mem_layout)
971 GLSLA(", %s", desc[i].mem_layout);
974 if (prop->is_uniform)
977 if (prop->mem_quali && desc[i].mem_quali)
978 GLSLA(" %s", desc[i].mem_quali);
981 GLSLA(" %s", prop->type);
983 if (prop->dim_needed)
984 GLSLA("%iD", desc[i].dimensions);
986 GLSLA(" %s", desc[i].name);
988 if (prop->buf_content)
989 GLSLA(" {\n %s\n}", desc[i].buf_content);
990 else if (desc[i].elems > 0)
991 GLSLA("[%i]", desc[i].elems);
1000 void ff_vk_update_descriptor_set(AVFilterContext *avctx, VulkanPipeline *pl,
1003 VulkanFilterContext *s = avctx->priv;
1005 vkUpdateDescriptorSetWithTemplate(s->hwctx->act_dev,
1006 pl->desc_set[set_id],
1007 pl->desc_template[set_id], s);
1010 void ff_vk_update_push_exec(AVFilterContext *avctx, FFVkExecContext *e,
1011 VkShaderStageFlagBits stage, int offset,
1012 size_t size, void *src)
1014 vkCmdPushConstants(e->buf, e->bound_pl->pipeline_layout,
1015 stage, offset, size, src);
1018 int ff_vk_init_pipeline_layout(AVFilterContext *avctx, VulkanPipeline *pl)
1021 VulkanFilterContext *s = avctx->priv;
1023 { /* Init descriptor set pool */
1024 VkDescriptorPoolCreateInfo pool_create_info = {
1025 .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
1026 .poolSizeCount = pl->pool_size_desc_num,
1027 .pPoolSizes = pl->pool_size_desc,
1028 .maxSets = pl->descriptor_sets_num,
1031 ret = vkCreateDescriptorPool(s->hwctx->act_dev, &pool_create_info,
1032 s->hwctx->alloc, &pl->desc_pool);
1033 av_freep(&pl->pool_size_desc);
1034 if (ret != VK_SUCCESS) {
1035 av_log(avctx, AV_LOG_ERROR, "Unable to init descriptor set "
1036 "pool: %s\n", ff_vk_ret2str(ret));
1037 return AVERROR_EXTERNAL;
1041 { /* Allocate descriptor sets */
1042 VkDescriptorSetAllocateInfo alloc_info = {
1043 .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
1044 .descriptorPool = pl->desc_pool,
1045 .descriptorSetCount = pl->descriptor_sets_num,
1046 .pSetLayouts = pl->desc_layout,
1049 pl->desc_set = av_malloc(pl->descriptor_sets_num*sizeof(*pl->desc_set));
1051 return AVERROR(ENOMEM);
1053 ret = vkAllocateDescriptorSets(s->hwctx->act_dev, &alloc_info,
1055 if (ret != VK_SUCCESS) {
1056 av_log(avctx, AV_LOG_ERROR, "Unable to allocate descriptor set: %s\n",
1057 ff_vk_ret2str(ret));
1058 return AVERROR_EXTERNAL;
1062 { /* Finally create the pipeline layout */
1063 VkPipelineLayoutCreateInfo spawn_pipeline_layout = {
1064 .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
1065 .setLayoutCount = pl->descriptor_sets_num,
1066 .pSetLayouts = pl->desc_layout,
1067 .pushConstantRangeCount = pl->push_consts_num,
1068 .pPushConstantRanges = pl->push_consts,
1071 ret = vkCreatePipelineLayout(s->hwctx->act_dev, &spawn_pipeline_layout,
1072 s->hwctx->alloc, &pl->pipeline_layout);
1073 av_freep(&pl->push_consts);
1074 pl->push_consts_num = 0;
1075 if (ret != VK_SUCCESS) {
1076 av_log(avctx, AV_LOG_ERROR, "Unable to init pipeline layout: %s\n",
1077 ff_vk_ret2str(ret));
1078 return AVERROR_EXTERNAL;
1082 { /* Descriptor template (for tightly packed descriptors) */
1083 VkDescriptorUpdateTemplateCreateInfo *desc_template_info;
1085 pl->desc_template = av_malloc(pl->descriptor_sets_num*sizeof(*pl->desc_template));
1086 if (!pl->desc_template)
1087 return AVERROR(ENOMEM);
1089 /* Create update templates for the descriptor sets */
1090 for (int i = 0; i < pl->descriptor_sets_num; i++) {
1091 desc_template_info = &pl->desc_template_info[i];
1092 desc_template_info->pipelineLayout = pl->pipeline_layout;
1093 ret = vkCreateDescriptorUpdateTemplate(s->hwctx->act_dev,
1096 &pl->desc_template[i]);
1097 av_free((void *)desc_template_info->pDescriptorUpdateEntries);
1098 if (ret != VK_SUCCESS) {
1099 av_log(avctx, AV_LOG_ERROR, "Unable to init descriptor "
1100 "template: %s\n", ff_vk_ret2str(ret));
1101 return AVERROR_EXTERNAL;
1105 av_freep(&pl->desc_template_info);
1111 FN_CREATING(VulkanFilterContext, VulkanPipeline, pipeline, pipelines, pipelines_num)
1112 VulkanPipeline *ff_vk_create_pipeline(AVFilterContext *avctx)
1114 return create_pipeline(avctx->priv);
1117 int ff_vk_init_compute_pipeline(AVFilterContext *avctx, VulkanPipeline *pl)
1121 VulkanFilterContext *s = avctx->priv;
1123 VkComputePipelineCreateInfo pipe = {
1124 .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
1125 .layout = pl->pipeline_layout,
1128 for (i = 0; i < pl->shaders_num; i++) {
1129 if (pl->shaders[i]->shader.stage & VK_SHADER_STAGE_COMPUTE_BIT) {
1130 pipe.stage = pl->shaders[i]->shader;
1134 if (i == pl->shaders_num) {
1135 av_log(avctx, AV_LOG_ERROR, "Can't init compute pipeline, no shader\n");
1136 return AVERROR(EINVAL);
1139 ret = vkCreateComputePipelines(s->hwctx->act_dev, VK_NULL_HANDLE, 1, &pipe,
1140 s->hwctx->alloc, &pl->pipeline);
1141 if (ret != VK_SUCCESS) {
1142 av_log(avctx, AV_LOG_ERROR, "Unable to init compute pipeline: %s\n",
1143 ff_vk_ret2str(ret));
1144 return AVERROR_EXTERNAL;
1147 pl->bind_point = VK_PIPELINE_BIND_POINT_COMPUTE;
1152 void ff_vk_bind_pipeline_exec(AVFilterContext *avctx, FFVkExecContext *e,
1155 vkCmdBindPipeline(e->buf, pl->bind_point, pl->pipeline);
1157 vkCmdBindDescriptorSets(e->buf, pl->bind_point, pl->pipeline_layout, 0,
1158 pl->descriptor_sets_num, pl->desc_set, 0, 0);
1163 static void free_exec_ctx(VulkanFilterContext *s, FFVkExecContext *e)
1165 vkDestroyFence(s->hwctx->act_dev, e->fence, s->hwctx->alloc);
1167 if (e->buf != VK_NULL_HANDLE)
1168 vkFreeCommandBuffers(s->hwctx->act_dev, e->pool, 1, &e->buf);
1169 if (e->pool != VK_NULL_HANDLE)
1170 vkDestroyCommandPool(s->hwctx->act_dev, e->pool, s->hwctx->alloc);
1172 av_free(e->sem_wait);
1173 av_free(e->sem_wait_dst);
1174 av_free(e->sem_sig);
1179 static void free_pipeline(VulkanFilterContext *s, VulkanPipeline *pl)
1181 for (int i = 0; i < pl->shaders_num; i++) {
1182 SPIRVShader *shd = pl->shaders[i];
1183 av_bprint_finalize(&shd->src, NULL);
1184 vkDestroyShaderModule(s->hwctx->act_dev, shd->shader.module,
1189 vkDestroyPipeline(s->hwctx->act_dev, pl->pipeline, s->hwctx->alloc);
1190 vkDestroyPipelineLayout(s->hwctx->act_dev, pl->pipeline_layout,
1193 for (int i = 0; i < pl->descriptor_sets_num; i++) {
1194 if (pl->desc_template && pl->desc_template[i])
1195 vkDestroyDescriptorUpdateTemplate(s->hwctx->act_dev, pl->desc_template[i],
1197 if (pl->desc_layout && pl->desc_layout[i])
1198 vkDestroyDescriptorSetLayout(s->hwctx->act_dev, pl->desc_layout[i],
1202 /* Also frees the descriptor sets */
1204 vkDestroyDescriptorPool(s->hwctx->act_dev, pl->desc_pool,
1207 av_freep(&pl->desc_set);
1208 av_freep(&pl->shaders);
1209 av_freep(&pl->desc_layout);
1210 av_freep(&pl->desc_template);
1211 av_freep(&pl->push_consts);
1212 pl->push_consts_num = 0;
1214 /* Only freed in case of failure */
1215 av_freep(&pl->pool_size_desc);
1216 if (pl->desc_template_info) {
1217 for (int i = 0; i < pl->descriptor_sets_num; i++)
1218 av_free((void *)pl->desc_template_info[i].pDescriptorUpdateEntries);
1219 av_freep(&pl->desc_template_info);
1225 void ff_vk_filter_uninit(AVFilterContext *avctx)
1227 VulkanFilterContext *s = avctx->priv;
1231 for (int i = 0; i < s->samplers_num; i++)
1232 vkDestroySampler(s->hwctx->act_dev, *s->samplers[i], s->hwctx->alloc);
1233 av_freep(&s->samplers);
1235 for (int i = 0; i < s->pipelines_num; i++)
1236 free_pipeline(s, s->pipelines[i]);
1237 av_freep(&s->pipelines);
1239 for (int i = 0; i < s->exec_ctx_num; i++)
1240 free_exec_ctx(s, s->exec_ctx[i]);
1241 av_freep(&s->exec_ctx);
1243 av_freep(&s->scratch);
1244 s->scratch_size = 0;
1246 av_buffer_unref(&s->device_ref);
1247 av_buffer_unref(&s->frames_ref);