]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_avgblur_vulkan.c
lavfi/vulkan: use all enabled queues in the queue family
[ffmpeg] / libavfilter / vf_avgblur_vulkan.c
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
19 #include "libavutil/opt.h"
20 #include "vulkan.h"
21 #include "internal.h"
22
23 #define CGS 32
24
25 typedef struct AvgBlurVulkanContext {
26     VulkanFilterContext vkctx;
27
28     int initialized;
29     FFVkExecContext *exec;
30     VulkanPipeline *pl_hor;
31     VulkanPipeline *pl_ver;
32
33     /* Shader updators, must be in the main filter struct */
34     VkDescriptorImageInfo input_images[3];
35     VkDescriptorImageInfo tmp_images[3];
36     VkDescriptorImageInfo output_images[3];
37
38     int size_x;
39     int size_y;
40     int planes;
41 } AvgBlurVulkanContext;
42
43 static const char blur_kernel[] = {
44     C(0, shared vec4 cache[DIR(gl_WorkGroupSize) + FILTER_RADIUS*2 + 1];           )
45     C(0,                                                                           )
46     C(0, void distort(const ivec2 pos, const int idx)                              )
47     C(0, {                                                                         )
48     C(1,     const uint cp = DIR(gl_LocalInvocationID) + FILTER_RADIUS;            )
49     C(0,                                                                           )
50     C(1,     cache[cp] = texture(input_img[idx], pos);                             )
51     C(0,                                                                           )
52     C(1,     const ivec2 loc_l = pos - INC(FILTER_RADIUS);                         )
53     C(1,     cache[cp - FILTER_RADIUS] = texture(input_img[idx], loc_l);           )
54     C(0,                                                                           )
55     C(1,     const ivec2 loc_h = pos + INC(DIR(gl_WorkGroupSize));                 )
56     C(1,     cache[cp + DIR(gl_WorkGroupSize)] = texture(input_img[idx], loc_h);   )
57     C(0,                                                                           )
58     C(1,     barrier();                                                            )
59     C(0,                                                                           )
60     C(1,     vec4 sum = vec4(0);                                                   )
61     C(1,     for (int p = -FILTER_RADIUS; p <= FILTER_RADIUS; p++)                 )
62     C(2,         sum += cache[cp + p];                                             )
63     C(0,                                                                           )
64     C(1,     sum /= vec4(FILTER_RADIUS*2 + 1);                                     )
65     C(1,     imageStore(output_img[idx], pos, sum);                                )
66     C(0, }                                                                         )
67 };
68
69 static av_cold int init_filter(AVFilterContext *ctx, AVFrame *in)
70 {
71     int err;
72     SPIRVShader *shd;
73     AvgBlurVulkanContext *s = ctx->priv;
74     const int planes = av_pix_fmt_count_planes(s->vkctx.output_format);
75     VkSampler *sampler = ff_vk_init_sampler(ctx, 1, VK_FILTER_LINEAR);
76
77     VulkanDescriptorSetBinding desc_i[2] = {
78         {
79             .name       = "input_img",
80             .type       = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
81             .dimensions = 2,
82             .elems      = planes,
83             .stages     = VK_SHADER_STAGE_COMPUTE_BIT,
84             .samplers   = DUP_SAMPLER_ARRAY4(*sampler),
85         },
86         {
87             .name       = "output_img",
88             .type       = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
89             .mem_layout = ff_vk_shader_rep_fmt(s->vkctx.output_format),
90             .mem_quali  = "writeonly",
91             .dimensions = 2,
92             .elems      = planes,
93             .stages     = VK_SHADER_STAGE_COMPUTE_BIT,
94         },
95     };
96
97     if (!sampler)
98         return AVERROR_EXTERNAL;
99
100     s->vkctx.queue_family_idx = s->vkctx.hwctx->queue_family_comp_index;
101     s->vkctx.queue_count = GET_QUEUE_COUNT(s->vkctx.hwctx, 0, 1, 0);
102     s->vkctx.cur_queue_idx = rand() % s->vkctx.queue_count;
103
104     { /* Create shader for the horizontal pass */
105         desc_i[0].updater = s->input_images;
106         desc_i[1].updater = s->tmp_images;
107
108         s->pl_hor = ff_vk_create_pipeline(ctx);
109         if (!s->pl_hor)
110             return AVERROR(ENOMEM);
111
112         shd = ff_vk_init_shader(ctx, s->pl_hor, "avgblur_compute_hor",
113                                 VK_SHADER_STAGE_COMPUTE_BIT);
114
115         ff_vk_set_compute_shader_sizes(ctx, shd, (int [3]){ CGS, 1, 1 });
116
117         RET(ff_vk_add_descriptor_set(ctx, s->pl_hor, shd, desc_i, 2, 0));
118
119         GLSLF(0, #define FILTER_RADIUS (%i)                     ,s->size_x - 1);
120         GLSLC(0, #define INC(x) (ivec2(x, 0))                                 );
121         GLSLC(0, #define DIR(var) (var.x)                                     );
122         GLSLD(   blur_kernel                                                  );
123         GLSLC(0, void main()                                                  );
124         GLSLC(0, {                                                            );
125         GLSLC(1,     ivec2 size;                                              );
126         GLSLC(1,     const ivec2 pos = ivec2(gl_GlobalInvocationID.xy);       );
127         for (int i = 0; i < planes; i++) {
128             GLSLC(0,                                                          );
129             GLSLF(1,  size = imageSize(output_img[%i]);                     ,i);
130             GLSLC(1,  if (IS_WITHIN(pos, size)) {                             );
131             if (s->planes & (1 << i)) {
132                 GLSLF(2, distort(pos, %i);                                  ,i);
133             } else {
134                 GLSLF(2, vec4 res = texture(input_img[%i], pos);            ,i);
135                 GLSLF(2, imageStore(output_img[%i], pos, res);              ,i);
136             }
137             GLSLC(1, }                                                        );
138         }
139         GLSLC(0, }                                                            );
140
141         RET(ff_vk_compile_shader(ctx, shd, "main"));
142
143         RET(ff_vk_init_pipeline_layout(ctx, s->pl_hor));
144         RET(ff_vk_init_compute_pipeline(ctx, s->pl_hor));
145     }
146
147     { /* Create shader for the vertical pass */
148         desc_i[0].updater = s->tmp_images;
149         desc_i[1].updater = s->output_images;
150
151         s->pl_ver = ff_vk_create_pipeline(ctx);
152         if (!s->pl_ver)
153             return AVERROR(ENOMEM);
154
155         shd = ff_vk_init_shader(ctx, s->pl_ver, "avgblur_compute_ver",
156                                 VK_SHADER_STAGE_COMPUTE_BIT);
157
158         ff_vk_set_compute_shader_sizes(ctx, shd, (int [3]){ 1, CGS, 1 });
159
160         RET(ff_vk_add_descriptor_set(ctx, s->pl_ver, shd, desc_i, 2, 0));
161
162         GLSLF(0, #define FILTER_RADIUS (%i)                     ,s->size_y - 1);
163         GLSLC(0, #define INC(x) (ivec2(0, x))                                 );
164         GLSLC(0, #define DIR(var) (var.y)                                     );
165         GLSLD(   blur_kernel                                                  );
166         GLSLC(0, void main()                                                  );
167         GLSLC(0, {                                                            );
168         GLSLC(1,     ivec2 size;                                              );
169         GLSLC(1,     const ivec2 pos = ivec2(gl_GlobalInvocationID.xy);       );
170         for (int i = 0; i < planes; i++) {
171             GLSLC(0,                                                          );
172             GLSLF(1,  size = imageSize(output_img[%i]);                     ,i);
173             GLSLC(1,  if (IS_WITHIN(pos, size)) {                             );
174             if (s->planes & (1 << i)) {
175                 GLSLF(2, distort(pos, %i);                                  ,i);
176             } else {
177                 GLSLF(2, vec4 res = texture(input_img[%i], pos);            ,i);
178                 GLSLF(2, imageStore(output_img[%i], pos, res);              ,i);
179             }
180             GLSLC(1, }                                                        );
181         }
182         GLSLC(0, }                                                            );
183
184         RET(ff_vk_compile_shader(ctx, shd, "main"));
185
186         RET(ff_vk_init_pipeline_layout(ctx, s->pl_ver));
187         RET(ff_vk_init_compute_pipeline(ctx, s->pl_ver));
188     }
189
190     /* Execution context */
191     RET(ff_vk_create_exec_ctx(ctx, &s->exec));
192
193     s->initialized = 1;
194
195     return 0;
196
197 fail:
198     return err;
199 }
200
201 static int process_frames(AVFilterContext *avctx, AVFrame *out_f, AVFrame *tmp_f, AVFrame *in_f)
202 {
203     int err;
204     VkCommandBuffer cmd_buf;
205     AvgBlurVulkanContext *s = avctx->priv;
206     AVVkFrame *in = (AVVkFrame *)in_f->data[0];
207     AVVkFrame *tmp = (AVVkFrame *)tmp_f->data[0];
208     AVVkFrame *out = (AVVkFrame *)out_f->data[0];
209     int planes = av_pix_fmt_count_planes(s->vkctx.output_format);
210
211     /* Update descriptors and init the exec context */
212     ff_vk_start_exec_recording(avctx, s->exec);
213     cmd_buf = ff_vk_get_exec_buf(avctx, s->exec);
214
215     for (int i = 0; i < planes; i++) {
216         RET(ff_vk_create_imageview(avctx, s->exec, &s->input_images[i].imageView,
217                                    in->img[i],
218                                    av_vkfmt_from_pixfmt(s->vkctx.input_format)[i],
219                                    ff_comp_identity_map));
220
221         RET(ff_vk_create_imageview(avctx, s->exec, &s->tmp_images[i].imageView,
222                                    tmp->img[i],
223                                    av_vkfmt_from_pixfmt(s->vkctx.output_format)[i],
224                                    ff_comp_identity_map));
225
226         RET(ff_vk_create_imageview(avctx, s->exec, &s->output_images[i].imageView,
227                                    out->img[i],
228                                    av_vkfmt_from_pixfmt(s->vkctx.output_format)[i],
229                                    ff_comp_identity_map));
230
231         s->input_images[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
232         s->tmp_images[i].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
233         s->output_images[i].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
234     }
235
236     ff_vk_update_descriptor_set(avctx, s->pl_hor, 0);
237     ff_vk_update_descriptor_set(avctx, s->pl_ver, 0);
238
239     for (int i = 0; i < planes; i++) {
240         VkImageMemoryBarrier bar[] = {
241             {
242                 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
243                 .srcAccessMask = 0,
244                 .dstAccessMask = VK_ACCESS_SHADER_READ_BIT,
245                 .oldLayout = in->layout[i],
246                 .newLayout = s->input_images[i].imageLayout,
247                 .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
248                 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
249                 .image = in->img[i],
250                 .subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
251                 .subresourceRange.levelCount = 1,
252                 .subresourceRange.layerCount = 1,
253             },
254             {
255                 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
256                 .srcAccessMask = 0,
257                 .dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT,
258                 .oldLayout = tmp->layout[i],
259                 .newLayout = s->tmp_images[i].imageLayout,
260                 .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
261                 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
262                 .image = tmp->img[i],
263                 .subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
264                 .subresourceRange.levelCount = 1,
265                 .subresourceRange.layerCount = 1,
266             },
267             {
268                 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
269                 .srcAccessMask = 0,
270                 .dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT,
271                 .oldLayout = out->layout[i],
272                 .newLayout = s->output_images[i].imageLayout,
273                 .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
274                 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
275                 .image = out->img[i],
276                 .subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
277                 .subresourceRange.levelCount = 1,
278                 .subresourceRange.layerCount = 1,
279             },
280         };
281
282         vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
283                              VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0,
284                              0, NULL, 0, NULL, FF_ARRAY_ELEMS(bar), bar);
285
286         in->layout[i]  = bar[0].newLayout;
287         in->access[i]  = bar[0].dstAccessMask;
288
289         tmp->layout[i] = bar[1].newLayout;
290         tmp->access[i] = bar[1].dstAccessMask;
291
292         out->layout[i] = bar[2].newLayout;
293         out->access[i] = bar[2].dstAccessMask;
294     }
295
296     ff_vk_bind_pipeline_exec(avctx, s->exec, s->pl_hor);
297
298     vkCmdDispatch(cmd_buf, FFALIGN(s->vkctx.output_width, CGS)/CGS,
299                   s->vkctx.output_height, 1);
300
301     ff_vk_bind_pipeline_exec(avctx, s->exec, s->pl_ver);
302
303     vkCmdDispatch(cmd_buf, s->vkctx.output_width,
304                   FFALIGN(s->vkctx.output_height, CGS)/CGS, 1);
305
306     ff_vk_add_exec_dep(avctx, s->exec, in_f, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
307     ff_vk_add_exec_dep(avctx, s->exec, out_f, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
308
309     err = ff_vk_submit_exec_queue(avctx, s->exec);
310     if (err)
311         return err;
312
313     return err;
314
315 fail:
316     ff_vk_discard_exec_deps(avctx, s->exec);
317     return err;
318 }
319
320 static int avgblur_vulkan_filter_frame(AVFilterLink *link, AVFrame *in)
321 {
322     int err;
323     AVFrame *tmp = NULL, *out = NULL;
324     AVFilterContext *ctx = link->dst;
325     AvgBlurVulkanContext *s = ctx->priv;
326     AVFilterLink *outlink = ctx->outputs[0];
327
328     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
329     if (!out) {
330         err = AVERROR(ENOMEM);
331         goto fail;
332     }
333
334     tmp = ff_get_video_buffer(outlink, outlink->w, outlink->h);
335     if (!out) {
336         err = AVERROR(ENOMEM);
337         goto fail;
338     }
339
340     if (!s->initialized)
341         RET(init_filter(ctx, in));
342
343     RET(process_frames(ctx, out, tmp, in));
344
345     err = av_frame_copy_props(out, in);
346     if (err < 0)
347         goto fail;
348
349     av_frame_free(&in);
350     av_frame_free(&tmp);
351
352     return ff_filter_frame(outlink, out);
353
354 fail:
355     av_frame_free(&in);
356     av_frame_free(&tmp);
357     av_frame_free(&out);
358     return err;
359 }
360
361 static void avgblur_vulkan_uninit(AVFilterContext *avctx)
362 {
363     AvgBlurVulkanContext *s = avctx->priv;
364
365     ff_vk_filter_uninit(avctx);
366
367     s->initialized = 0;
368 }
369
370 #define OFFSET(x) offsetof(AvgBlurVulkanContext, x)
371 #define FLAGS (AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM)
372 static const AVOption avgblur_vulkan_options[] = {
373     { "sizeX",  "Set horizontal radius", OFFSET(size_x), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 32, .flags = FLAGS },
374     { "planes", "Set planes to filter (bitmask)", OFFSET(planes), AV_OPT_TYPE_INT, {.i64 = 0xF}, 0, 0xF, .flags = FLAGS },
375     { "sizeY",  "Set vertical radius", OFFSET(size_y), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 32, .flags = FLAGS },
376     { NULL },
377 };
378
379 AVFILTER_DEFINE_CLASS(avgblur_vulkan);
380
381 static const AVFilterPad avgblur_vulkan_inputs[] = {
382     {
383         .name         = "default",
384         .type         = AVMEDIA_TYPE_VIDEO,
385         .filter_frame = &avgblur_vulkan_filter_frame,
386         .config_props = &ff_vk_filter_config_input,
387     },
388     { NULL }
389 };
390
391 static const AVFilterPad avgblur_vulkan_outputs[] = {
392     {
393         .name = "default",
394         .type = AVMEDIA_TYPE_VIDEO,
395         .config_props = &ff_vk_filter_config_output,
396     },
397     { NULL }
398 };
399
400 AVFilter ff_vf_avgblur_vulkan = {
401     .name           = "avgblur_vulkan",
402     .description    = NULL_IF_CONFIG_SMALL("Apply avgblur mask to input video"),
403     .priv_size      = sizeof(AvgBlurVulkanContext),
404     .init           = &ff_vk_filter_init,
405     .uninit         = &avgblur_vulkan_uninit,
406     .query_formats  = &ff_vk_filter_query_formats,
407     .inputs         = avgblur_vulkan_inputs,
408     .outputs        = avgblur_vulkan_outputs,
409     .priv_class     = &avgblur_vulkan_class,
410     .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,
411 };