[FFmpeg-devel] [PATCH] lavfi: add erosion_opencl, dilation_opencl filters

Danil Iashchenko danyaschenko at gmail.com
Thu Aug 9 03:20:53 EEST 2018


Add erosion_opencl, dilation_opencl filters. Behave like existing erosion and dilation filters.

---
 configure                        |   1 +
 libavfilter/Makefile             |   4 +
 libavfilter/allfilters.c         |   2 +
 libavfilter/opencl/neighbor.cl   |  87 +++++++++++
 libavfilter/opencl_source.h      |   1 +
 libavfilter/vf_neighbor_opencl.c | 327 +++++++++++++++++++++++++++++++++++++++
 6 files changed, 422 insertions(+)
 create mode 100644 libavfilter/opencl/neighbor.cl
 create mode 100644 libavfilter/vf_neighbor_opencl.c

diff --git a/configure b/configure
index 5783407..211f05f 100755
--- a/configure
+++ b/configure
@@ -3363,6 +3363,7 @@ mpdecimate_filter_deps="gpl"
 mpdecimate_filter_select="pixelutils"
 mptestsrc_filter_deps="gpl"
 negate_filter_deps="lut_filter"
+neighbor_opencl_filter_deps="opencl"
 nnedi_filter_deps="gpl"
 ocr_filter_deps="libtesseract"
 ocv_filter_deps="libopencv"
diff --git a/libavfilter/Makefile b/libavfilter/Makefile
index 5d4549e..03df93b 100644
--- a/libavfilter/Makefile
+++ b/libavfilter/Makefile
@@ -196,6 +196,8 @@ OBJS-$(CONFIG_DESHAKE_FILTER)                += vf_deshake.o
 OBJS-$(CONFIG_DESPILL_FILTER)                += vf_despill.o
 OBJS-$(CONFIG_DETELECINE_FILTER)             += vf_detelecine.o
 OBJS-$(CONFIG_DILATION_FILTER)               += vf_neighbor.o
+OBJS-$(CONFIG_DILATION_OPENCL_FILTER)        += vf_neighbor_opencl.o opencl.o \
+                                                opencl/neighbor.o
 OBJS-$(CONFIG_DISPLACE_FILTER)               += vf_displace.o framesync.o
 OBJS-$(CONFIG_DOUBLEWEAVE_FILTER)            += vf_weave.o
 OBJS-$(CONFIG_DRAWBOX_FILTER)                += vf_drawbox.o
@@ -207,6 +209,8 @@ OBJS-$(CONFIG_ELBG_FILTER)                   += vf_elbg.o
 OBJS-$(CONFIG_ENTROPY_FILTER)                += vf_entropy.o
 OBJS-$(CONFIG_EQ_FILTER)                     += vf_eq.o
 OBJS-$(CONFIG_EROSION_FILTER)                += vf_neighbor.o
+OBJS-$(CONFIG_EROSION_OPENCL_FILTER)         += vf_neighbor_opencl.o opencl.o \
+                                                opencl/neighbor.o
 OBJS-$(CONFIG_EXTRACTPLANES_FILTER)          += vf_extractplanes.o
 OBJS-$(CONFIG_FADE_FILTER)                   += vf_fade.o
 OBJS-$(CONFIG_FFTDNOIZ_FILTER)               += vf_fftdnoiz.o
diff --git a/libavfilter/allfilters.c b/libavfilter/allfilters.c
index 521bc53..f33129c 100644
--- a/libavfilter/allfilters.c
+++ b/libavfilter/allfilters.c
@@ -185,6 +185,7 @@ extern AVFilter ff_vf_deshake;
 extern AVFilter ff_vf_despill;
 extern AVFilter ff_vf_detelecine;
 extern AVFilter ff_vf_dilation;
+extern AVFilter ff_vf_dilation_opencl;
 extern AVFilter ff_vf_displace;
 extern AVFilter ff_vf_doubleweave;
 extern AVFilter ff_vf_drawbox;
@@ -196,6 +197,7 @@ extern AVFilter ff_vf_elbg;
 extern AVFilter ff_vf_entropy;
 extern AVFilter ff_vf_eq;
 extern AVFilter ff_vf_erosion;
+extern AVFilter ff_vf_erosion_opencl;
 extern AVFilter ff_vf_extractplanes;
 extern AVFilter ff_vf_fade;
 extern AVFilter ff_vf_fftdnoiz;
diff --git a/libavfilter/opencl/neighbor.cl b/libavfilter/opencl/neighbor.cl
new file mode 100644
index 0000000..2235e3e
--- /dev/null
+++ b/libavfilter/opencl/neighbor.cl
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2018 Danil Iashchenko
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+
+__kernel void erosion_global(__write_only image2d_t dst,
+                             __read_only  image2d_t src,
+                             float threshold,
+                             __constant int *coord)
+{
+    const sampler_t sampler = (CLK_NORMALIZED_COORDS_FALSE |
+                            CLK_ADDRESS_CLAMP_TO_EDGE   |
+                            CLK_FILTER_NEAREST);
+
+    int2 loc = (int2)(get_global_id(0), get_global_id(1));
+
+    float4 px = read_imagef(src, sampler, loc);
+    float limit = px.x - threshold;
+    if (limit < 0) {
+        limit = 0;
+    }
+
+    for (int i = -1; i <= 1; i++) {
+        for (int j = -1; j <= 1; j++) {
+            if (coord[(j + 1) * 3 + (i + 1)] == 1) {
+                float4 cur = read_imagef(src, sampler, loc + (int2)(i, j));
+                if (cur.x < px.x) {
+                    px = cur;
+                }
+            }
+        }
+    }
+    if (limit > px.x) {
+        px = (float4)(limit);
+    }
+    write_imagef(dst, loc, px);
+}
+
+
+__kernel void dilation_global(__write_only image2d_t dst,
+                             __read_only  image2d_t src,
+                             float threshold,
+                             __constant int *coord)
+{
+    const sampler_t sampler = (CLK_NORMALIZED_COORDS_FALSE |
+                            CLK_ADDRESS_CLAMP_TO_EDGE   |
+                            CLK_FILTER_NEAREST);
+
+    int2 loc = (int2)(get_global_id(0), get_global_id(1));
+
+    float4 px = read_imagef(src, sampler, loc);
+    float limit = px.x + threshold;
+    if (limit > 1) {
+        limit = 1;
+    }
+
+    for (int i = -1; i <= 1; i++) {
+        for (int j = -1; j <= 1; j++) {
+            if (coord[(j + 1) * 3 + (i + 1)] == 1) {
+                float4 cur = read_imagef(src, sampler, loc + (int2)(i, j));
+                if (cur.x > px.x) {
+                    px = cur;
+                }
+            }
+        }
+    }
+    if (limit < px.x) {
+        px = (float4)(limit);
+    }
+    write_imagef(dst, loc, px);
+}
diff --git a/libavfilter/opencl_source.h b/libavfilter/opencl_source.h
index de4e66e..2f67d89 100644
--- a/libavfilter/opencl_source.h
+++ b/libavfilter/opencl_source.h
@@ -22,6 +22,7 @@
 extern const char *ff_opencl_source_avgblur;
 extern const char *ff_opencl_source_colorspace_common;
 extern const char *ff_opencl_source_convolution;
+extern const char *ff_opencl_source_neighbor;
 extern const char *ff_opencl_source_overlay;
 extern const char *ff_opencl_source_tonemap;
 extern const char *ff_opencl_source_unsharp;
diff --git a/libavfilter/vf_neighbor_opencl.c b/libavfilter/vf_neighbor_opencl.c
new file mode 100644
index 0000000..7ba759b
--- /dev/null
+++ b/libavfilter/vf_neighbor_opencl.c
@@ -0,0 +1,327 @@
+/*
+ * Copyright (c) 2018 Danil Iashchenko
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/common.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/mem.h"
+#include "libavutil/opt.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/avstring.h"
+
+
+#include "avfilter.h"
+#include "internal.h"
+#include "opencl.h"
+#include "opencl_source.h"
+#include "video.h"
+
+typedef struct NeighborOpenCLContext {
+    OpenCLFilterContext ocf;
+
+    int              initialised;
+    cl_kernel        kernel;
+    cl_command_queue command_queue;
+
+    char *matrix_str[4];
+
+    cl_float threshold[4];
+    cl_int coordinates;
+    cl_mem coord;
+
+} NeighborOpenCLContext;
+
+static int neighbor_opencl_init(AVFilterContext *avctx)
+{
+    NeighborOpenCLContext *ctx = avctx->priv;
+    const char *kernel_name;
+    cl_int cle;
+    int err;
+
+    err = ff_opencl_filter_load_program(avctx, &ff_opencl_source_neighbor, 1);
+    if (err < 0)
+        goto fail;
+
+    ctx->command_queue = clCreateCommandQueue(ctx->ocf.hwctx->context,
+                                              ctx->ocf.hwctx->device_id,
+                                              0, &cle);
+    CL_FAIL_ON_ERROR(AVERROR(EIO), "Failed to create OpenCL "
+                     "command queue %d.\n", cle);
+
+    if (!strcmp(avctx->filter->name, "erosion_opencl")){
+        kernel_name = "erosion_global";
+    } else if (!strcmp(avctx->filter->name, "dilation_opencl")){
+        kernel_name = "dilation_global";
+    }
+    ctx->kernel = clCreateKernel(ctx->ocf.program, kernel_name, &cle);
+    CL_FAIL_ON_ERROR(AVERROR(EIO), "Failed to create "
+                     "kernel %d.\n", cle);
+
+    ctx->initialised = 1;
+    return 0;
+
+fail:
+    if (ctx->command_queue)
+        clReleaseCommandQueue(ctx->command_queue);
+    if (ctx->kernel)
+        clReleaseKernel(ctx->kernel);
+    return err;
+}
+
+static int neighbor_opencl_make_filter_params(AVFilterContext *avctx)
+{
+    NeighborOpenCLContext *ctx = avctx->priv;
+    int *matrix = NULL;
+    size_t matrix_bytes;
+    cl_mem buffer;
+    cl_int cle;
+    int i;
+
+    for (i = 0; i < 4; i++) {
+        ctx->threshold[i] /= 255.0;
+    }
+    for (i = 0; i < 9; i++) {
+        matrix_bytes = sizeof(float)*9;
+        matrix = av_malloc(matrix_bytes);
+    }
+    if (!matrix) {
+        av_freep(&matrix);
+        return AVERROR(ENOMEM);
+    }
+    matrix[4] = 0;
+    for (i = 0; i < 8; i++) {
+        if (ctx->coordinates & (1 << i)) {
+            matrix[i > 3 ? i + 1: i] = 1;
+        }
+    }
+    buffer = clCreateBuffer(ctx->ocf.hwctx->context,
+                            CL_MEM_READ_ONLY |
+                            CL_MEM_COPY_HOST_PTR |
+                            CL_MEM_HOST_NO_ACCESS,
+                            matrix_bytes, matrix, &cle);
+    if (!buffer) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to create matrix buffer: "
+               "%d.\n", cle);
+        av_freep(&matrix);
+        return AVERROR(EIO);
+    }
+    ctx->coord = buffer;
+    av_freep(&matrix);
+
+    return 0;
+}
+
+
+static int neighbor_opencl_filter_frame(AVFilterLink *inlink, AVFrame *input)
+{
+    AVFilterContext *avctx = inlink->dst;
+    AVFilterLink *outlink = avctx->outputs[0];
+    NeighborOpenCLContext *ctx = avctx->priv;
+    AVFrame *output = NULL;
+    cl_int cle;
+    size_t global_work[2];
+    cl_mem src, dst;
+    int err, p;
+    size_t origin[3] = {0, 0, 0};
+    size_t region[3] = {0, 0, 1};
+
+    av_log(ctx, AV_LOG_DEBUG, "Filter input: %s, %ux%u (%"PRId64").\n",
+           av_get_pix_fmt_name(input->format),
+           input->width, input->height, input->pts);
+
+    if (!input->hw_frames_ctx)
+        return AVERROR(EINVAL);
+
+    if (!ctx->initialised) {
+        err = neighbor_opencl_init(avctx);
+        if (err < 0)
+            goto fail;
+
+        err = neighbor_opencl_make_filter_params(avctx);
+        if (err < 0)
+            goto fail;
+
+    }
+
+    output = ff_get_video_buffer(outlink, outlink->w, outlink->h);
+    if (!output) {
+        err = AVERROR(ENOMEM);
+        goto fail;
+    }
+
+    for (p = 0; p < FF_ARRAY_ELEMS(output->data); p++) {
+        src = (cl_mem) input->data[p];
+        dst = (cl_mem)output->data[p];
+
+        if (!dst)
+            break;
+
+        if (ctx->threshold[p] == 0) {
+            err = ff_opencl_filter_work_size_from_image(avctx, region, output, p, 0);
+            if (err < 0)
+                goto fail;
+
+            cle = clEnqueueCopyImage(ctx->command_queue, src, dst,
+                                     origin, origin, region, 0, NULL, NULL);
+            CL_FAIL_ON_ERROR(AVERROR(EIO), "Failed to copy plane %d: %d.\n",
+                             p, cle);
+        } else {
+            CL_SET_KERNEL_ARG(ctx->kernel, 0, cl_mem,   &dst);
+            CL_SET_KERNEL_ARG(ctx->kernel, 1, cl_mem,   &src);
+            CL_SET_KERNEL_ARG(ctx->kernel, 2, cl_float, &ctx->threshold[p]);
+            CL_SET_KERNEL_ARG(ctx->kernel, 3, cl_mem,   &ctx->coord);
+
+            err = ff_opencl_filter_work_size_from_image(avctx, global_work, output, p, 0);
+            if (err < 0)
+                goto fail;
+
+            av_log(avctx, AV_LOG_DEBUG, "Run kernel on plane %d "
+                   "(%"SIZE_SPECIFIER"x%"SIZE_SPECIFIER").\n",
+                   p, global_work[0], global_work[1]);
+
+            cle = clEnqueueNDRangeKernel(ctx->command_queue, ctx->kernel, 2, NULL,
+                                         global_work, NULL,
+                                         0, NULL, NULL);
+            CL_FAIL_ON_ERROR(AVERROR(EIO), "Failed to enqueue "
+                             "kernel: %d.\n", cle);
+        }
+    }
+
+    cle = clFinish(ctx->command_queue);
+    CL_FAIL_ON_ERROR(AVERROR(EIO), "Failed to finish command queue: %d.\n", cle);
+
+    err = av_frame_copy_props(output, input);
+    if (err < 0)
+        goto fail;
+
+    av_frame_free(&input);
+
+    av_log(ctx, AV_LOG_DEBUG, "Filter output: %s, %ux%u (%"PRId64").\n",
+           av_get_pix_fmt_name(output->format),
+           output->width, output->height, output->pts);
+
+    return ff_filter_frame(outlink, output);
+
+fail:
+    clFinish(ctx->command_queue);
+    av_frame_free(&input);
+    av_frame_free(&output);
+    return err;
+}
+
+static av_cold void neighbor_opencl_uninit(AVFilterContext *avctx)
+{
+    NeighborOpenCLContext *ctx = avctx->priv;
+    cl_int cle;
+
+    if (ctx->kernel) {
+        cle = clReleaseKernel(ctx->kernel);
+        if (cle != CL_SUCCESS)
+            av_log(avctx, AV_LOG_ERROR, "Failed to release "
+                   "kernel: %d.\n", cle);
+    }
+
+    if (ctx->command_queue) {
+        cle = clReleaseCommandQueue(ctx->command_queue);
+        if (cle != CL_SUCCESS)
+            av_log(avctx, AV_LOG_ERROR, "Failed to release "
+                   "command queue: %d.\n", cle);
+    }
+
+    ff_opencl_filter_uninit(avctx);
+}
+
+static const AVFilterPad neighbor_opencl_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = &neighbor_opencl_filter_frame,
+        .config_props = &ff_opencl_filter_config_input,
+    },
+    { NULL }
+};
+
+static const AVFilterPad neighbor_opencl_outputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = &ff_opencl_filter_config_output,
+    },
+    { NULL }
+};
+
+#define OFFSET(x) offsetof(NeighborOpenCLContext, x)
+#define FLAGS (AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM)
+
+#if CONFIG_EROSION_OPENCL_FILTER
+
+static const AVOption erosion_opencl_options[] = {
+    { "threshold0",  "set threshold for 1st plane",   OFFSET(threshold[0]),   AV_OPT_TYPE_FLOAT, {.dbl=65535.0}, 0.0, 65535, FLAGS },
+    { "threshold1",  "set threshold for 2nd plane",   OFFSET(threshold[1]),   AV_OPT_TYPE_FLOAT, {.dbl=65535.0}, 0.0, 65535, FLAGS },
+    { "threshold2",  "set threshold for 3rd plane",   OFFSET(threshold[2]),   AV_OPT_TYPE_FLOAT, {.dbl=65535.0}, 0.0, 65535, FLAGS },
+    { "threshold3",  "set threshold for 4th plane",   OFFSET(threshold[3]),   AV_OPT_TYPE_FLOAT, {.dbl=65535.0}, 0.0, 65535, FLAGS },
+    { "coordinates", "set coordinates",               OFFSET(coordinates),    AV_OPT_TYPE_INT,   {.i64=255},     0,   255,   FLAGS },
+    { NULL }
+};
+
+AVFILTER_DEFINE_CLASS(erosion_opencl);
+
+AVFilter ff_vf_erosion_opencl = {
+    .name           = "erosion_opencl",
+    .description    = NULL_IF_CONFIG_SMALL("Apply erosion effect"),
+    .priv_size      = sizeof(NeighborOpenCLContext),
+    .priv_class     = &erosion_opencl_class,
+    .init           = &ff_opencl_filter_init,
+    .uninit         = &neighbor_opencl_uninit,
+    .query_formats  = &ff_opencl_filter_query_formats,
+    .inputs         = neighbor_opencl_inputs,
+    .outputs        = neighbor_opencl_outputs,
+    .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,
+};
+
+#endif /* CONFIG_EROSION_OPENCL_FILTER */
+
+#if CONFIG_DILATION_OPENCL_FILTER
+
+static const AVOption dilation_opencl_options[] = {
+    { "threshold0",  "set threshold for 1st plane",   OFFSET(threshold[0]),   AV_OPT_TYPE_FLOAT, {.dbl=65535.0}, 0.0, 65535, FLAGS },
+    { "threshold1",  "set threshold for 2nd plane",   OFFSET(threshold[1]),   AV_OPT_TYPE_FLOAT, {.dbl=65535.0}, 0.0, 65535, FLAGS },
+    { "threshold2",  "set threshold for 3rd plane",   OFFSET(threshold[2]),   AV_OPT_TYPE_FLOAT, {.dbl=65535.0}, 0.0, 65535, FLAGS },
+    { "threshold3",  "set threshold for 4th plane",   OFFSET(threshold[3]),   AV_OPT_TYPE_FLOAT, {.dbl=65535.0}, 0.0, 65535, FLAGS },
+    { "coordinates", "set coordinates",               OFFSET(coordinates),    AV_OPT_TYPE_INT,   {.i64=255},     0,   255,   FLAGS },
+    { NULL }
+};
+
+AVFILTER_DEFINE_CLASS(dilation_opencl);
+
+AVFilter ff_vf_dilation_opencl = {
+    .name           = "dilation_opencl",
+    .description    = NULL_IF_CONFIG_SMALL("Apply dilation effect"),
+    .priv_size      = sizeof(NeighborOpenCLContext),
+    .priv_class     = &dilation_opencl_class,
+    .init           = &ff_opencl_filter_init,
+    .uninit         = &neighbor_opencl_uninit,
+    .query_formats  = &ff_opencl_filter_query_formats,
+    .inputs         = neighbor_opencl_inputs,
+    .outputs        = neighbor_opencl_outputs,
+    .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,
+};
+
+#endif /* CONFIG_DILATION_OPENCL_FILTER */
+
-- 
2.7.4



More information about the ffmpeg-devel mailing list