From 8f383f3c2783d2a9c5096019ddf3dfebb0b726fd Mon Sep 17 00:00:00 2001
From: Ruiling Song <ruiling.song@intel.com>
Date: Tue, 27 Mar 2018 09:12:42 +0800
Subject: [PATCH] lavf: add scale_opencl filter.

Signed-off-by: Ruiling Song <ruiling.song@intel.com>
---
 configure                     |   1 +
 libavfilter/Makefile          |   2 +
 libavfilter/allfilters.c      |   1 +
 libavfilter/opencl/scale.cl   |  78 ++++++++++
 libavfilter/opencl_source.h   |   1 +
 libavfilter/vf_scale_opencl.c | 338 ++++++++++++++++++++++++++++++++++++++++++
 6 files changed, 421 insertions(+)
 create mode 100644 libavfilter/opencl/scale.cl
 create mode 100644 libavfilter/vf_scale_opencl.c

diff --git a/configure b/configure
index 5ccf3ce..bab789a 100755
--- a/configure
+++ b/configure
@@ -3330,6 +3330,7 @@ tinterlace_merge_test_deps="tinterlace_filter"
 tinterlace_pad_test_deps="tinterlace_filter"
 tonemap_filter_deps="const_nan"
 unsharp_opencl_filter_deps="opencl"
+scale_opencl_filter_deps="opencl"
 uspp_filter_deps="gpl avcodec"
 vaguedenoiser_filter_deps="gpl"
 vidstabdetect_filter_deps="libvidstab"
diff --git a/libavfilter/Makefile b/libavfilter/Makefile
index 7f2ad1f..67c480a 100644
--- a/libavfilter/Makefile
+++ b/libavfilter/Makefile
@@ -302,6 +302,8 @@ OBJS-$(CONFIG_SAB_FILTER)                    += vf_sab.o
 OBJS-$(CONFIG_SCALE_FILTER)                  += vf_scale.o scale.o
 OBJS-$(CONFIG_SCALE_CUDA_FILTER)             += vf_scale_cuda.o vf_scale_cuda.ptx.o
 OBJS-$(CONFIG_SCALE_NPP_FILTER)              += vf_scale_npp.o scale.o
+OBJS-$(CONFIG_SCALE_OPENCL_FILTER)           += vf_scale_opencl.o opencl.o \
+                                                opencl/scale.o
 OBJS-$(CONFIG_SCALE_QSV_FILTER)              += vf_scale_qsv.o
 OBJS-$(CONFIG_SCALE_VAAPI_FILTER)            += vf_scale_vaapi.o scale.o vaapi_vpp.o
 OBJS-$(CONFIG_SCALE2REF_FILTER)              += vf_scale.o scale.o
diff --git a/libavfilter/allfilters.c b/libavfilter/allfilters.c
index 1cf1340..3185b17 100644
--- a/libavfilter/allfilters.c
+++ b/libavfilter/allfilters.c
@@ -309,6 +309,7 @@ static void register_all(void)
     REGISTER_FILTER(SCALE,          scale,          vf);
     REGISTER_FILTER(SCALE_CUDA,     scale_cuda,     vf);
     REGISTER_FILTER(SCALE_NPP,      scale_npp,      vf);
+    REGISTER_FILTER(SCALE_OPENCL,   scale_opencl,   vf);
     REGISTER_FILTER(SCALE_QSV,      scale_qsv,      vf);
     REGISTER_FILTER(SCALE_VAAPI,    scale_vaapi,    vf);
     REGISTER_FILTER(SCALE2REF,      scale2ref,      vf);
diff --git a/libavfilter/opencl/scale.cl b/libavfilter/opencl/scale.cl
new file mode 100644
index 0000000..86d0015
--- /dev/null
+++ b/libavfilter/opencl/scale.cl
@@ -0,0 +1,78 @@
+/*
+ * 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 scale_bilinear_uchar(__write_only image2d_t dst,
+                                   __read_only  image2d_t src,
+                                   int dst_width,
+                                   int dst_height,
+                                   int src_width,
+                                   int src_height)
+{
+    const sampler_t sampler = (CLK_NORMALIZED_COORDS_FALSE |
+                               CLK_FILTER_NEAREST);
+    int x = get_global_id(0);
+    int y = get_global_id(1);
+    float xi = (x + 0.5f) *src_width / dst_width;
+    float yi = (y + 0.5) * src_height / dst_height;
+    float xf = floor(xi);
+    float yf = floor(yi);
+    int xl = (int)xf;
+    int yl = (int)yf;
+    float a = xf - xl;
+    float b = yf - yl;
+
+    float v1 = read_imagef(src, sampler, (int2)(xl,     yl)).x;
+    float v2 = read_imagef(src, sampler, (int2)(xl + 1, yl)).x;
+    float v3 = read_imagef(src, sampler, (int2)(xl,     yl + 1)).x;
+    float v4 = read_imagef(src, sampler, (int2)(xl+1,   yl + 1)).x;
+    float sum = v1 * (1.0f - a) * (1.0f - b) + v2 * a * (1.0f - b)
+                + v3 * b*(1.0f-a) + v4 * a * b;
+
+    write_imagef(dst, (int2)(x, y), (float4)(sum, 0.0f, 0.0f, 1.0f));
+}
+
+__kernel void scale_bilinear_uchar2(__write_only image2d_t dst,
+                                   __read_only  image2d_t src,
+                                   int dst_width,
+                                   int dst_height,
+                                   int src_width,
+                                   int src_height)
+{
+    const sampler_t sampler = (CLK_NORMALIZED_COORDS_FALSE |
+                               CLK_FILTER_NEAREST);
+    int x = get_global_id(0);
+    int y = get_global_id(1);
+    float xi = (x + 0.5f) *src_width / dst_width;
+    float yi = (y + 0.5) * src_height / dst_height;
+    float xf = floor(xi);
+    float yf = floor(yi);
+    int xl = (int)xf;
+    int yl = (int)yf;
+    float a = xf - xl;
+    float b = yf - yl;
+
+    float2 v1 = read_imagef(src, sampler, (int2)(xl,     yl)).xy;
+    float2 v2 = read_imagef(src, sampler, (int2)(xl + 1, yl)).xy;
+    float2 v3 = read_imagef(src, sampler, (int2)(xl,     yl + 1)).xy;
+    float2 v4 = read_imagef(src, sampler, (int2)(xl+1,   yl + 1)).xy;
+
+    float2 sum = v1 * (1.0f - a) * (1.0f - b) + v2 * a * (1.0f - b)
+                + v3 * b*(1.0f-a) + v4 * a * b;
+
+    write_imagef(dst, (int2)(x, y), (float4)(sum.x, sum.y, 0.0f, 1.0f));
+}
diff --git a/libavfilter/opencl_source.h b/libavfilter/opencl_source.h
index 4bb9969..10e6092 100644
--- a/libavfilter/opencl_source.h
+++ b/libavfilter/opencl_source.h
@@ -23,5 +23,6 @@ extern const char *ff_opencl_source_avgblur;
 extern const char *ff_opencl_source_convolution;
 extern const char *ff_opencl_source_overlay;
 extern const char *ff_opencl_source_unsharp;
+extern const char *ff_opencl_source_scale;
 
 #endif /* AVFILTER_OPENCL_SOURCE_H */
diff --git a/libavfilter/vf_scale_opencl.c b/libavfilter/vf_scale_opencl.c
new file mode 100644
index 0000000..7bc35bc
--- /dev/null
+++ b/libavfilter/vf_scale_opencl.c
@@ -0,0 +1,338 @@
+/*
+ * 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 "avfilter.h"
+#include "internal.h"
+#include "opencl.h"
+#include "opencl_source.h"
+#include "scale.h"
+#include "video.h"
+
+
+typedef struct ScaleOpenCLContext {
+    OpenCLFilterContext ocf;
+
+    char *w_expr;               ///< width  expression string
+    char *h_expr;               ///< height expression string
+    int              initialised;
+    cl_kernel        kernel;    ///< uchar kernel
+    cl_kernel        kernel2;   ///< uchar2 kernel
+    cl_command_queue command_queue;
+
+} ScaleOpenCLContext;
+
+static int scale_opencl_init(AVFilterContext *avctx)
+{
+    ScaleOpenCLContext *ctx = avctx->priv;
+    cl_int cle;
+    int err;
+
+    err = ff_opencl_filter_load_program(avctx, &ff_opencl_source_scale, 1);
+    if (err < 0)
+        goto fail;
+
+    ctx->command_queue = clCreateCommandQueue(ctx->ocf.hwctx->context,
+                                              ctx->ocf.hwctx->device_id,
+                                              0, &cle);
+    if (!ctx->command_queue) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to create OpenCL "
+               "command queue: %d.\n", cle);
+        err = AVERROR(EIO);
+        goto fail;
+    }
+
+    ctx->kernel = clCreateKernel(ctx->ocf.program, "scale_bilinear_uchar", &cle);
+    if (!ctx->kernel) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to create kernel: %d.\n", cle);
+        err = AVERROR(EIO);
+        goto fail;
+    }
+
+    ctx->kernel2 = clCreateKernel(ctx->ocf.program, "scale_bilinear_uchar2", &cle);
+    if (!ctx->kernel2) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to create kernel: %d.\n", cle);
+        err = AVERROR(EIO);
+        goto fail;
+    }
+    ctx->initialised = 1;
+    return 0;
+
+fail:
+    if (ctx->command_queue)
+        clReleaseCommandQueue(ctx->command_queue);
+    if (ctx->kernel)
+        clReleaseKernel(ctx->kernel);
+    return err;
+}
+
+static int scale_opencl_config_output(AVFilterLink *outlink)
+{
+    AVFilterContext *avctx = outlink->src;
+    ScaleOpenCLContext *s = avctx->priv;
+    AVFilterLink *inlink = outlink->src->inputs[0];
+    int w, h, ret;
+
+    if ((ret = ff_scale_eval_dimensions(s,
+                                        s->w_expr, s->h_expr,
+                                        inlink, outlink,
+                                        &w, &h)) < 0)
+        goto fail;
+    s->ocf.output_width = w;
+    s->ocf.output_height = h;
+    ret = ff_opencl_filter_config_output(outlink);
+    if (ret < 0)
+        return ret;
+
+    return 0;
+fail:
+    return ret;
+}
+
+static int call_resize_kernel(AVFilterContext *avctx, cl_kernel kernel,
+                              AVFrame *output, AVFrame *input, int plane,
+                              int dst_width, int dst_height,
+                              int src_width, int src_height) {
+    ScaleOpenCLContext *ctx = avctx->priv;
+    cl_mem dst = output->data[plane];
+    cl_mem src = input->data[plane];
+    int err = AVERROR(ENOSYS);
+    size_t global_work[2];
+    size_t local_work[2];
+    cl_int cle;
+
+    cle = clSetKernelArg(kernel, 0, sizeof(cl_mem), &dst);
+    if (cle != CL_SUCCESS) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to set kernel "
+               "destination image argument: %d.\n", cle);
+        return AVERROR(EINVAL);
+    }
+    cle = clSetKernelArg(kernel, 1, sizeof(cl_mem), &src);
+    if (cle != CL_SUCCESS) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to set kernel "
+               "source image argument: %d.\n", cle);
+        return AVERROR(EINVAL);
+    }
+
+    cle = clSetKernelArg(kernel, 2, sizeof(cl_int), &dst_width);
+    if (cle != CL_SUCCESS) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to set arg @2 "
+               ": %d.\n", cle);
+        return AVERROR(EINVAL);
+    }
+
+    cle = clSetKernelArg(kernel, 3, sizeof(cl_int), &dst_height);
+    if (cle != CL_SUCCESS) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to set kernel "
+               "source image argument: %d.\n", cle);
+        return AVERROR(EINVAL);
+    }
+
+    cle = clSetKernelArg(kernel, 4, sizeof(cl_int), &src_width);
+    if (cle != CL_SUCCESS) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to set kernel "
+               "source image argument: %d.\n", cle);
+        return AVERROR(EINVAL);
+    }
+
+    cle = clSetKernelArg(kernel, 5, sizeof(cl_int), &src_height);
+    if (cle != CL_SUCCESS) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to set kernel "
+               "source image argument: %d.\n", cle);
+        return AVERROR(EINVAL);
+    }
+
+    local_work[0]  = 16;
+    local_work[1]  = 16;
+    err = ff_opencl_filter_work_size_from_image(avctx, global_work, output,
+                                                plane, 16);
+    if (err < 0)
+        return err;
+
+    cle = clEnqueueNDRangeKernel(ctx->command_queue, kernel, 2, NULL,
+                                 global_work, local_work,
+                                 0, NULL, NULL);
+    if (cle != CL_SUCCESS) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to enqueue kernel: %d.\n",
+               cle);
+        return AVERROR(EIO);
+    }
+    return 0;
+}
+
+static int scale_opencl_filter_frame(AVFilterLink *inlink, AVFrame *input)
+{
+    AVFilterContext    *avctx = inlink->dst;
+    AVFilterLink     *outlink = avctx->outputs[0];
+    ScaleOpenCLContext *ctx = avctx->priv;
+    AVFrame *output = NULL;
+    cl_int cle;
+    cl_mem src, dst;
+    int err, p;
+    AVHWFramesContext *input_frames_ctx =
+        (AVHWFramesContext*)input->hw_frames_ctx->data;
+    AVHWFramesContext *output_frames_ctx =
+        (AVHWFramesContext*)input->hw_frames_ctx->data;
+
+    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 = scale_opencl_init(avctx);
+        if (err < 0)
+            goto fail;
+    }
+
+    output = ff_get_video_buffer(outlink, outlink->w, outlink->h);
+    if (!output) {
+        err = AVERROR(ENOMEM);
+        goto fail;
+    }
+
+    switch(input_frames_ctx->sw_format) {
+    case AV_PIX_FMT_YUV420P:
+        err = call_resize_kernel(avctx, ctx->kernel, output, input, 0, output->width,
+                           output->height, input->width, input->height);
+        if (err < 0) goto fail;
+        err = call_resize_kernel(avctx, ctx->kernel, output, input, 1, output->width/2,
+                           output->height/2, input->width/2, input->height/2);
+        if (err < 0) goto fail;
+        err = call_resize_kernel(avctx, ctx->kernel, output, input, 2, output->width,
+                           output->height/2, input->width/2, input->height/2);
+        if (err < 0) goto fail;
+        break;
+    case AV_PIX_FMT_NV12:
+        err = call_resize_kernel(avctx, ctx->kernel, output, input, 0, output->width,
+                           output->height, input->width, input->height);
+        if (err < 0) goto fail;
+        err = call_resize_kernel(avctx, ctx->kernel2, output, input, 1, output->width/2,
+                           output->height/2, input->width/2, input->height/2);
+        if (err < 0) goto fail;
+        break;
+    default:
+      av_log(ctx, AV_LOG_ERROR, "unsupported format in scale_opencl.\n");
+      err = AVERROR(ENOSYS);
+      goto fail;
+    }
+
+    cle = clFinish(ctx->command_queue);
+    if (cle != CL_SUCCESS) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to finish command queue: %d.\n",
+               cle);
+        err = AVERROR(EIO);
+        goto fail;
+    }
+
+    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 scale_opencl_uninit(AVFilterContext *avctx)
+{
+    ScaleOpenCLContext *ctx = avctx->priv;
+    cl_int cle;
+    int i;
+
+    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->kernel2) {
+        cle = clReleaseKernel(ctx->kernel2);
+        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);
+}
+
+#define OFFSET(x) offsetof(ScaleOpenCLContext, x)
+#define FLAGS (AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM)
+static const AVOption scale_opencl_options[] = {
+    { "w",      "Output video width",  OFFSET(w_expr),     AV_OPT_TYPE_STRING, { .str = "iw"   }, .flags = FLAGS },
+    { "h",      "Output video height", OFFSET(h_expr),     AV_OPT_TYPE_STRING, { .str = "ih"   }, .flags = FLAGS },
+    { NULL }
+};
+
+AVFILTER_DEFINE_CLASS(scale_opencl);
+
+static const AVFilterPad scale_opencl_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .filter_frame = &scale_opencl_filter_frame,
+        .config_props = &ff_opencl_filter_config_input,
+    },
+    { NULL }
+};
+
+static const AVFilterPad scale_opencl_outputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_VIDEO,
+        .config_props = &scale_opencl_config_output,
+    },
+    { NULL }
+};
+
+AVFilter ff_vf_scale_opencl = {
+    .name           = "scale_opencl",
+    .description    = NULL_IF_CONFIG_SMALL("Scale input video"),
+    .priv_size      = sizeof(ScaleOpenCLContext),
+    .priv_class     = &scale_opencl_class,
+    .init           = &ff_opencl_filter_init,
+    .uninit         = &scale_opencl_uninit,
+    .query_formats  = &ff_opencl_filter_query_formats,
+    .inputs         = scale_opencl_inputs,
+    .outputs        = scale_opencl_outputs,
+    .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,
+};
-- 
2.7.4

