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
19 #include "libavutil/random_seed.h"
20 #include "libavutil/opt.h"
22 #include "scale_eval.h"
24 #include "colorspace.h"
26 #define CGROUPS (int [3]){ 32, 32, 1 }
35 typedef struct ScaleVulkanContext {
36 VulkanFilterContext vkctx;
39 FFVkExecContext *exec;
41 FFVkBuffer params_buf;
43 /* Shader updators, must be in the main filter struct */
44 VkDescriptorImageInfo input_images[3];
45 VkDescriptorImageInfo output_images[3];
46 VkDescriptorBufferInfo params_desc;
48 enum ScalerFunc scaler;
49 char *out_format_string;
50 enum AVColorRange out_range;
55 static const char scale_bilinear[] = {
56 C(0, vec4 scale_bilinear(int idx, ivec2 pos, vec2 crop_range, vec2 crop_off))
58 C(1, vec2 npos = (vec2(pos) + 0.5f) / imageSize(output_img[idx]); )
59 C(1, npos *= crop_range; /* Reduce the range */ )
60 C(1, npos += crop_off; /* Offset the start */ )
61 C(1, return texture(input_img[idx], npos); )
65 static const char rgb2yuv[] = {
66 C(0, vec4 rgb2yuv(vec4 src, int fullrange) )
68 C(1, src *= yuv_matrix; )
69 C(1, if (fullrange == 1) { )
70 C(2, src += vec4(0.0, 0.5, 0.5, 0.0); )
72 C(2, src *= vec4(219.0 / 255.0, 224.0 / 255.0, 224.0 / 255.0, 1.0); )
73 C(2, src += vec4(16.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 0.0); )
79 static const char write_nv12[] = {
80 C(0, void write_nv12(vec4 src, ivec2 pos) )
82 C(1, imageStore(output_img[0], pos, vec4(src.r, 0.0, 0.0, 0.0)); )
83 C(1, pos /= ivec2(2); )
84 C(1, imageStore(output_img[1], pos, vec4(src.g, src.b, 0.0, 0.0)); )
88 static const char write_420[] = {
89 C(0, void write_420(vec4 src, ivec2 pos) )
91 C(1, imageStore(output_img[0], pos, vec4(src.r, 0.0, 0.0, 0.0)); )
92 C(1, pos /= ivec2(2); )
93 C(1, imageStore(output_img[1], pos, vec4(src.g, 0.0, 0.0, 0.0)); )
94 C(1, imageStore(output_img[2], pos, vec4(src.b, 0.0, 0.0, 0.0)); )
98 static const char write_444[] = {
99 C(0, void write_444(vec4 src, ivec2 pos) )
101 C(1, imageStore(output_img[0], pos, vec4(src.r, 0.0, 0.0, 0.0)); )
102 C(1, imageStore(output_img[1], pos, vec4(src.g, 0.0, 0.0, 0.0)); )
103 C(1, imageStore(output_img[2], pos, vec4(src.b, 0.0, 0.0, 0.0)); )
107 static av_cold int init_filter(AVFilterContext *ctx, AVFrame *in)
111 VkFilter sampler_mode;
112 ScaleVulkanContext *s = ctx->priv;
114 int crop_x = in->crop_left;
115 int crop_y = in->crop_top;
116 int crop_w = in->width - (in->crop_left + in->crop_right);
117 int crop_h = in->height - (in->crop_top + in->crop_bottom);
119 s->vkctx.queue_family_idx = s->vkctx.hwctx->queue_family_comp_index;
120 s->vkctx.queue_count = GET_QUEUE_COUNT(s->vkctx.hwctx, 0, 1, 0);
121 s->vkctx.cur_queue_idx = av_get_random_seed() % s->vkctx.queue_count;
125 sampler_mode = VK_FILTER_NEAREST;
128 sampler_mode = VK_FILTER_LINEAR;
132 /* Create a sampler */
133 sampler = ff_vk_init_sampler(ctx, 0, sampler_mode);
135 return AVERROR_EXTERNAL;
137 s->pl = ff_vk_create_pipeline(ctx);
139 return AVERROR(ENOMEM);
141 { /* Create the shader */
142 VulkanDescriptorSetBinding desc_i[2] = {
145 .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
147 .elems = av_pix_fmt_count_planes(s->vkctx.input_format),
148 .stages = VK_SHADER_STAGE_COMPUTE_BIT,
149 .updater = s->input_images,
150 .samplers = DUP_SAMPLER_ARRAY4(*sampler),
153 .name = "output_img",
154 .type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
155 .mem_layout = ff_vk_shader_rep_fmt(s->vkctx.output_format),
156 .mem_quali = "writeonly",
158 .elems = av_pix_fmt_count_planes(s->vkctx.output_format),
159 .stages = VK_SHADER_STAGE_COMPUTE_BIT,
160 .updater = s->output_images,
164 VulkanDescriptorSetBinding desc_b = {
166 .type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
167 .mem_quali = "readonly",
168 .mem_layout = "std430",
169 .stages = VK_SHADER_STAGE_COMPUTE_BIT,
170 .updater = &s->params_desc,
171 .buf_content = "mat4 yuv_matrix;",
174 SPIRVShader *shd = ff_vk_init_shader(ctx, s->pl, "scale_compute",
175 VK_SHADER_STAGE_COMPUTE_BIT);
177 return AVERROR(ENOMEM);
179 ff_vk_set_compute_shader_sizes(ctx, shd, CGROUPS);
181 RET(ff_vk_add_descriptor_set(ctx, s->pl, shd, desc_i, 2, 0)); /* set 0 */
182 RET(ff_vk_add_descriptor_set(ctx, s->pl, shd, &desc_b, 1, 0)); /* set 0 */
184 GLSLD( scale_bilinear );
186 if (s->vkctx.output_format != s->vkctx.input_format) {
190 switch (s->vkctx.output_format) {
191 case AV_PIX_FMT_NV12: GLSLD(write_nv12); break;
192 case AV_PIX_FMT_YUV420P: GLSLD( write_420); break;
193 case AV_PIX_FMT_YUV444P: GLSLD( write_444); break;
197 GLSLC(0, void main() );
199 GLSLC(1, ivec2 size; );
200 GLSLC(1, ivec2 pos = ivec2(gl_GlobalInvocationID.xy); );
201 GLSLF(1, vec2 in_d = vec2(%i, %i); ,in->width, in->height);
202 GLSLF(1, vec2 c_r = vec2(%i, %i) / in_d; ,crop_w, crop_h);
203 GLSLF(1, vec2 c_o = vec2(%i, %i) / in_d; ,crop_x,crop_y);
206 if (s->vkctx.output_format == s->vkctx.input_format) {
207 for (int i = 0; i < desc_i[1].elems; i++) {
208 GLSLF(1, size = imageSize(output_img[%i]); ,i);
209 GLSLC(1, if (IS_WITHIN(pos, size)) { );
213 GLSLF(2, vec4 res = scale_bilinear(%i, pos, c_r, c_o); ,i);
214 GLSLF(2, imageStore(output_img[%i], pos, res); ,i);
220 GLSLC(1, vec4 res = scale_bilinear(0, pos, c_r, c_o); );
221 GLSLF(1, res = rgb2yuv(res, %i); ,s->out_range == AVCOL_RANGE_JPEG);
222 switch (s->vkctx.output_format) {
223 case AV_PIX_FMT_NV12: GLSLC(1, write_nv12(res, pos); ); break;
224 case AV_PIX_FMT_YUV420P: GLSLC(1, write_420(res, pos); ); break;
225 case AV_PIX_FMT_YUV444P: GLSLC(1, write_444(res, pos); ); break;
226 default: return AVERROR(EINVAL);
232 RET(ff_vk_compile_shader(ctx, shd, "main"));
235 RET(ff_vk_init_pipeline_layout(ctx, s->pl));
236 RET(ff_vk_init_compute_pipeline(ctx, s->pl));
238 if (s->vkctx.output_format != s->vkctx.input_format) {
239 const struct LumaCoefficients *lcoeffs;
240 double tmp_mat[3][3];
243 float yuv_matrix[4][4];
246 lcoeffs = ff_get_luma_coefficients(in->colorspace);
248 av_log(ctx, AV_LOG_ERROR, "Unsupported colorspace\n");
249 return AVERROR(EINVAL);
252 err = ff_vk_create_buf(ctx, &s->params_buf,
254 VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
255 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
259 err = ff_vk_map_buffers(ctx, &s->params_buf, (uint8_t **)&par, 1, 0);
263 ff_fill_rgb2yuv_table(lcoeffs, tmp_mat);
265 memset(par, 0, sizeof(*par));
267 for (int y = 0; y < 3; y++)
268 for (int x = 0; x < 3; x++)
269 par->yuv_matrix[x][y] = tmp_mat[x][y];
271 par->yuv_matrix[3][3] = 1.0;
273 err = ff_vk_unmap_buffers(ctx, &s->params_buf, 1, 1);
277 s->params_desc.buffer = s->params_buf.buf;
278 s->params_desc.range = VK_WHOLE_SIZE;
280 ff_vk_update_descriptor_set(ctx, s->pl, 1);
283 /* Execution context */
284 RET(ff_vk_create_exec_ctx(ctx, &s->exec));
294 static int process_frames(AVFilterContext *avctx, AVFrame *out_f, AVFrame *in_f)
297 VkCommandBuffer cmd_buf;
298 ScaleVulkanContext *s = avctx->priv;
299 AVVkFrame *in = (AVVkFrame *)in_f->data[0];
300 AVVkFrame *out = (AVVkFrame *)out_f->data[0];
301 VkImageMemoryBarrier barriers[AV_NUM_DATA_POINTERS*2];
302 int barrier_count = 0;
304 /* Update descriptors and init the exec context */
305 ff_vk_start_exec_recording(avctx, s->exec);
306 cmd_buf = ff_vk_get_exec_buf(avctx, s->exec);
308 for (int i = 0; i < av_pix_fmt_count_planes(s->vkctx.input_format); i++) {
309 RET(ff_vk_create_imageview(avctx, s->exec, &s->input_images[i].imageView,
311 av_vkfmt_from_pixfmt(s->vkctx.input_format)[i],
312 ff_comp_identity_map));
314 s->input_images[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
317 for (int i = 0; i < av_pix_fmt_count_planes(s->vkctx.output_format); i++) {
318 RET(ff_vk_create_imageview(avctx, s->exec, &s->output_images[i].imageView,
320 av_vkfmt_from_pixfmt(s->vkctx.output_format)[i],
321 ff_comp_identity_map));
323 s->output_images[i].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
326 ff_vk_update_descriptor_set(avctx, s->pl, 0);
328 for (int i = 0; i < av_pix_fmt_count_planes(s->vkctx.input_format); i++) {
329 VkImageMemoryBarrier bar = {
330 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
332 .dstAccessMask = VK_ACCESS_SHADER_READ_BIT,
333 .oldLayout = in->layout[i],
334 .newLayout = s->input_images[i].imageLayout,
335 .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
336 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
338 .subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
339 .subresourceRange.levelCount = 1,
340 .subresourceRange.layerCount = 1,
343 memcpy(&barriers[barrier_count++], &bar, sizeof(VkImageMemoryBarrier));
345 in->layout[i] = bar.newLayout;
346 in->access[i] = bar.dstAccessMask;
349 for (int i = 0; i < av_pix_fmt_count_planes(s->vkctx.output_format); i++) {
350 VkImageMemoryBarrier bar = {
351 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
353 .dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT,
354 .oldLayout = out->layout[i],
355 .newLayout = s->output_images[i].imageLayout,
356 .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
357 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
358 .image = out->img[i],
359 .subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
360 .subresourceRange.levelCount = 1,
361 .subresourceRange.layerCount = 1,
364 memcpy(&barriers[barrier_count++], &bar, sizeof(VkImageMemoryBarrier));
366 out->layout[i] = bar.newLayout;
367 out->access[i] = bar.dstAccessMask;
370 vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
371 VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0,
372 0, NULL, 0, NULL, barrier_count, barriers);
374 ff_vk_bind_pipeline_exec(avctx, s->exec, s->pl);
376 vkCmdDispatch(cmd_buf,
377 FFALIGN(s->vkctx.output_width, CGROUPS[0])/CGROUPS[0],
378 FFALIGN(s->vkctx.output_height, CGROUPS[1])/CGROUPS[1], 1);
380 ff_vk_add_exec_dep(avctx, s->exec, in_f, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
381 ff_vk_add_exec_dep(avctx, s->exec, out_f, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
383 err = ff_vk_submit_exec_queue(avctx, s->exec);
390 ff_vk_discard_exec_deps(avctx, s->exec);
394 static int scale_vulkan_filter_frame(AVFilterLink *link, AVFrame *in)
397 AVFilterContext *ctx = link->dst;
398 ScaleVulkanContext *s = ctx->priv;
399 AVFilterLink *outlink = ctx->outputs[0];
401 AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
403 err = AVERROR(ENOMEM);
408 RET(init_filter(ctx, in));
410 RET(process_frames(ctx, out, in));
412 err = av_frame_copy_props(out, in);
416 if (s->out_range != AVCOL_RANGE_UNSPECIFIED)
417 out->color_range = s->out_range;
418 if (s->vkctx.output_format != s->vkctx.input_format)
419 out->chroma_location = AVCHROMA_LOC_TOPLEFT;
423 return ff_filter_frame(outlink, out);
431 static int scale_vulkan_config_output(AVFilterLink *outlink)
434 AVFilterContext *avctx = outlink->src;
435 ScaleVulkanContext *s = avctx->priv;
436 AVFilterLink *inlink = outlink->src->inputs[0];
438 err = ff_scale_eval_dimensions(s, s->w_expr, s->h_expr, inlink, outlink,
439 &s->vkctx.output_width,
440 &s->vkctx.output_height);
444 if (s->out_format_string) {
445 s->vkctx.output_format = av_get_pix_fmt(s->out_format_string);
446 if (s->vkctx.output_format == AV_PIX_FMT_NONE) {
447 av_log(avctx, AV_LOG_ERROR, "Invalid output format.\n");
448 return AVERROR(EINVAL);
451 s->vkctx.output_format = s->vkctx.input_format;
454 if (s->vkctx.output_format != s->vkctx.input_format) {
455 if (!ff_vk_mt_is_np_rgb(s->vkctx.input_format)) {
456 av_log(avctx, AV_LOG_ERROR, "Unsupported input format for conversion\n");
457 return AVERROR(EINVAL);
459 if (s->vkctx.output_format != AV_PIX_FMT_NV12 &&
460 s->vkctx.output_format != AV_PIX_FMT_YUV420P &&
461 s->vkctx.output_format != AV_PIX_FMT_YUV444P) {
462 av_log(avctx, AV_LOG_ERROR, "Unsupported output format\n");
463 return AVERROR(EINVAL);
465 } else if (s->out_range != AVCOL_RANGE_UNSPECIFIED) {
466 av_log(avctx, AV_LOG_ERROR, "Cannot change range without converting format\n");
467 return AVERROR(EINVAL);
470 err = ff_vk_filter_config_output(outlink);
477 static void scale_vulkan_uninit(AVFilterContext *avctx)
479 ScaleVulkanContext *s = avctx->priv;
481 ff_vk_filter_uninit(avctx);
482 ff_vk_free_buf(avctx, &s->params_buf);
487 #define OFFSET(x) offsetof(ScaleVulkanContext, x)
488 #define FLAGS (AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM)
489 static const AVOption scale_vulkan_options[] = {
490 { "w", "Output video width", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, .flags = FLAGS },
491 { "h", "Output video height", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, .flags = FLAGS },
492 { "scaler", "Scaler function", OFFSET(scaler), AV_OPT_TYPE_INT, {.i64 = F_BILINEAR}, 0, F_NB, .flags = FLAGS, "scaler" },
493 { "bilinear", "Bilinear interpolation (fastest)", 0, AV_OPT_TYPE_CONST, {.i64 = F_BILINEAR}, 0, 0, .flags = FLAGS, "scaler" },
494 { "nearest", "Nearest (useful for pixel art)", 0, AV_OPT_TYPE_CONST, {.i64 = F_NEAREST}, 0, 0, .flags = FLAGS, "scaler" },
495 { "format", "Output video format (software format of hardware frames)", OFFSET(out_format_string), AV_OPT_TYPE_STRING, .flags = FLAGS },
496 { "out_range", "Output colour range (from 0 to 2) (default 0)", OFFSET(out_range), AV_OPT_TYPE_INT, {.i64 = AVCOL_RANGE_UNSPECIFIED}, AVCOL_RANGE_UNSPECIFIED, AVCOL_RANGE_JPEG, .flags = FLAGS, "range" },
497 { "full", "Full range", 0, AV_OPT_TYPE_CONST, { .i64 = AVCOL_RANGE_JPEG }, 0, 0, FLAGS, "range" },
498 { "limited", "Limited range", 0, AV_OPT_TYPE_CONST, { .i64 = AVCOL_RANGE_MPEG }, 0, 0, FLAGS, "range" },
499 { "jpeg", "Full range", 0, AV_OPT_TYPE_CONST, { .i64 = AVCOL_RANGE_JPEG }, 0, 0, FLAGS, "range" },
500 { "mpeg", "Limited range", 0, AV_OPT_TYPE_CONST, { .i64 = AVCOL_RANGE_MPEG }, 0, 0, FLAGS, "range" },
501 { "tv", "Limited range", 0, AV_OPT_TYPE_CONST, { .i64 = AVCOL_RANGE_MPEG }, 0, 0, FLAGS, "range" },
502 { "pc", "Full range", 0, AV_OPT_TYPE_CONST, { .i64 = AVCOL_RANGE_JPEG }, 0, 0, FLAGS, "range" },
506 AVFILTER_DEFINE_CLASS(scale_vulkan);
508 static const AVFilterPad scale_vulkan_inputs[] = {
511 .type = AVMEDIA_TYPE_VIDEO,
512 .filter_frame = &scale_vulkan_filter_frame,
513 .config_props = &ff_vk_filter_config_input,
518 static const AVFilterPad scale_vulkan_outputs[] = {
521 .type = AVMEDIA_TYPE_VIDEO,
522 .config_props = &scale_vulkan_config_output,
527 const AVFilter ff_vf_scale_vulkan = {
528 .name = "scale_vulkan",
529 .description = NULL_IF_CONFIG_SMALL("Scale Vulkan frames"),
530 .priv_size = sizeof(ScaleVulkanContext),
531 .init = &ff_vk_filter_init,
532 .uninit = &scale_vulkan_uninit,
533 .query_formats = &ff_vk_filter_query_formats,
534 .inputs = scale_vulkan_inputs,
535 .outputs = scale_vulkan_outputs,
536 .priv_class = &scale_vulkan_class,
537 .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,