]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_convolution_opencl.c
libavfilter/opencl: Add macro for setting opencl kernel arguments
[ffmpeg] / libavfilter / vf_convolution_opencl.c
1 /*
2  * Copyright (c) 2018 Danil Iashchenko
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include "libavutil/common.h"
22 #include "libavutil/imgutils.h"
23 #include "libavutil/mem.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/pixdesc.h"
26 #include "libavutil/avstring.h"
27
28
29 #include "avfilter.h"
30 #include "internal.h"
31 #include "opencl.h"
32 #include "opencl_source.h"
33 #include "video.h"
34
35 typedef struct ConvolutionOpenCLContext {
36     OpenCLFilterContext ocf;
37
38     int              initialised;
39     cl_kernel        kernel;
40     cl_command_queue command_queue;
41
42     char *matrix_str[4];
43
44     cl_mem matrix[4];
45     cl_int matrix_sizes[4];
46     cl_int dims[4];
47     cl_float rdivs[4];
48     cl_float biases[4];
49
50 } ConvolutionOpenCLContext;
51
52
53 static int convolution_opencl_init(AVFilterContext *avctx)
54 {
55     ConvolutionOpenCLContext *ctx = avctx->priv;
56     cl_int cle;
57     int err;
58
59     err = ff_opencl_filter_load_program(avctx, &ff_opencl_source_convolution, 1);
60     if (err < 0)
61         goto fail;
62
63     ctx->command_queue = clCreateCommandQueue(ctx->ocf.hwctx->context,
64                                               ctx->ocf.hwctx->device_id,
65                                               0, &cle);
66     if (!ctx->command_queue) {
67         av_log(avctx, AV_LOG_ERROR, "Failed to create OpenCL "
68                "command queue: %d.\n", cle);
69         err = AVERROR(EIO);
70         goto fail;
71     }
72
73     ctx->kernel = clCreateKernel(ctx->ocf.program, "convolution_global", &cle);
74     if (!ctx->kernel) {
75         av_log(avctx, AV_LOG_ERROR, "Failed to create kernel: %d.\n", cle);
76         err = AVERROR(EIO);
77         goto fail;
78     }
79
80     ctx->initialised = 1;
81     return 0;
82
83 fail:
84     if (ctx->command_queue)
85         clReleaseCommandQueue(ctx->command_queue);
86     if (ctx->kernel)
87         clReleaseKernel(ctx->kernel);
88     return err;
89 }
90
91
92
93 static int convolution_opencl_make_filter_params(AVFilterContext *avctx)
94 {
95     ConvolutionOpenCLContext *ctx = avctx->priv;
96     float *matrix = NULL;
97     size_t matrix_bytes;
98     cl_mem buffer;
99     cl_int cle;
100     int i, j;
101     int sscanf_err;
102     char *p, *arg, *saveptr = NULL;
103     float input_matrix[4][49];
104
105     for (i = 0; i < 4; i++) {
106         ctx->biases[i] = ctx->biases[i] / 255.0;
107     }
108
109     for (i = 0; i < 4; i++) {
110         p = ctx->matrix_str[i];
111         while (ctx->matrix_sizes[i] < 49) {
112             arg = av_strtok(p, " ", &saveptr);
113             if (!arg) {
114                 break;
115             }
116             p = NULL;
117             sscanf_err = sscanf(arg, "%f", &input_matrix[i][ctx->matrix_sizes[i]]);
118             if (sscanf_err != 1) {
119                 av_log(ctx, AV_LOG_ERROR, "Matrix is sequence of 9, 25 or 49 signed numbers\n");
120                 return AVERROR(EINVAL);
121             }
122             ctx->matrix_sizes[i]++;
123         }
124         if (ctx->matrix_sizes[i] == 9) {
125             ctx->dims[i] = 3;
126         } else if (ctx->matrix_sizes[i] == 25) {
127             ctx->dims[i] = 5;
128         } else if (ctx->matrix_sizes[i] == 49) {
129             ctx->dims[i] = 7;
130         } else {
131             av_log(ctx, AV_LOG_ERROR, "Invalid matrix size:%d\n", ctx->matrix_sizes[i]);
132             return AVERROR(EINVAL);
133         }
134
135     }
136
137     for (j = 0; j < 4; j++) {
138         matrix_bytes = sizeof(float)*ctx->matrix_sizes[j];
139         matrix = av_malloc(matrix_bytes);
140         if (!matrix) {
141             av_freep(&matrix);
142             return AVERROR(ENOMEM);
143         }
144
145         for (i = 0; i < ctx->matrix_sizes[j]; i++)
146             matrix[i] = input_matrix[j][i];
147
148         buffer = clCreateBuffer(ctx->ocf.hwctx->context,
149                                 CL_MEM_READ_ONLY |
150                                 CL_MEM_COPY_HOST_PTR |
151                                 CL_MEM_HOST_NO_ACCESS,
152                                 matrix_bytes, matrix, &cle);
153         if (!buffer) {
154             av_log(avctx, AV_LOG_ERROR, "Failed to create matrix buffer: "
155                    "%d.\n", cle);
156             av_freep(&matrix);
157             return AVERROR(EIO);
158         }
159         ctx->matrix[j] = buffer;
160         av_freep(&matrix);
161     }
162
163     return 0;
164 }
165
166 static int convolution_opencl_filter_frame(AVFilterLink *inlink, AVFrame *input)
167 {
168     AVFilterContext *avctx = inlink->dst;
169     AVFilterLink *outlink = avctx->outputs[0];
170     ConvolutionOpenCLContext *ctx = avctx->priv;
171     AVFrame *output = NULL;
172     cl_int cle;
173     size_t global_work[2];
174     cl_mem src, dst;
175     int err, p;
176
177     av_log(ctx, AV_LOG_DEBUG, "Filter input: %s, %ux%u (%"PRId64").\n",
178            av_get_pix_fmt_name(input->format),
179            input->width, input->height, input->pts);
180
181     if (!input->hw_frames_ctx)
182         return AVERROR(EINVAL);
183
184     if (!ctx->initialised) {
185         err = convolution_opencl_init(avctx);
186         if (err < 0)
187             goto fail;
188
189         err = convolution_opencl_make_filter_params(avctx);
190         if (err < 0)
191             goto fail;
192     }
193
194     output = ff_get_video_buffer(outlink, outlink->w, outlink->h);
195     if (!output) {
196         err = AVERROR(ENOMEM);
197         goto fail;
198     }
199
200     for (p = 0; p < FF_ARRAY_ELEMS(output->data); p++) {
201         src = (cl_mem) input->data[p];
202         dst = (cl_mem)output->data[p];
203
204         if (!dst)
205             break;
206
207         CL_SET_KERNEL_ARG(ctx->kernel, 0, cl_mem,   &dst);
208         CL_SET_KERNEL_ARG(ctx->kernel, 1, cl_mem,   &src);
209         CL_SET_KERNEL_ARG(ctx->kernel, 2, cl_int,   &ctx->dims[p]);
210         CL_SET_KERNEL_ARG(ctx->kernel, 3, cl_mem,   &ctx->matrix[p]);
211         CL_SET_KERNEL_ARG(ctx->kernel, 4, cl_float, &ctx->rdivs[p]);
212         CL_SET_KERNEL_ARG(ctx->kernel, 5, cl_float, &ctx->biases[p]);
213
214         err = ff_opencl_filter_work_size_from_image(avctx, global_work, output, p, 0);
215         if (err < 0)
216             goto fail;
217
218         av_log(avctx, AV_LOG_DEBUG, "Run kernel on plane %d "
219                "(%"SIZE_SPECIFIER"x%"SIZE_SPECIFIER").\n",
220                p, global_work[0], global_work[1]);
221
222         cle = clEnqueueNDRangeKernel(ctx->command_queue, ctx->kernel, 2, NULL,
223                                      global_work, NULL,
224                                      0, NULL, NULL);
225         if (cle != CL_SUCCESS) {
226             av_log(avctx, AV_LOG_ERROR, "Failed to enqueue kernel: %d.\n",
227                    cle);
228             err = AVERROR(EIO);
229             goto fail;
230         }
231     }
232
233     cle = clFinish(ctx->command_queue);
234     if (cle != CL_SUCCESS) {
235         av_log(avctx, AV_LOG_ERROR, "Failed to finish command queue: %d.\n",
236                cle);
237         err = AVERROR(EIO);
238         goto fail;
239     }
240
241     err = av_frame_copy_props(output, input);
242     if (err < 0)
243         goto fail;
244
245     av_frame_free(&input);
246
247     av_log(ctx, AV_LOG_DEBUG, "Filter output: %s, %ux%u (%"PRId64").\n",
248            av_get_pix_fmt_name(output->format),
249            output->width, output->height, output->pts);
250
251     return ff_filter_frame(outlink, output);
252
253 fail:
254     clFinish(ctx->command_queue);
255     av_frame_free(&input);
256     av_frame_free(&output);
257     return err;
258 }
259
260 static av_cold void convolution_opencl_uninit(AVFilterContext *avctx)
261 {
262     ConvolutionOpenCLContext *ctx = avctx->priv;
263     cl_int cle;
264     int i;
265
266     for (i = 0; i < 4; i++) {
267         clReleaseMemObject(ctx->matrix[i]);
268     }
269
270     if (ctx->kernel) {
271         cle = clReleaseKernel(ctx->kernel);
272         if (cle != CL_SUCCESS)
273             av_log(avctx, AV_LOG_ERROR, "Failed to release "
274                    "kernel: %d.\n", cle);
275     }
276
277     if (ctx->command_queue) {
278         cle = clReleaseCommandQueue(ctx->command_queue);
279         if (cle != CL_SUCCESS)
280             av_log(avctx, AV_LOG_ERROR, "Failed to release "
281                    "command queue: %d.\n", cle);
282     }
283
284     ff_opencl_filter_uninit(avctx);
285 }
286
287 #define OFFSET(x) offsetof(ConvolutionOpenCLContext, x)
288 #define FLAGS (AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM)
289 static const AVOption convolution_opencl_options[] = {
290     { "0m", "set matrix for 2nd plane", OFFSET(matrix_str[0]), AV_OPT_TYPE_STRING, {.str="0 0 0 0 1 0 0 0 0"}, 0, 0, FLAGS },
291     { "1m", "set matrix for 2nd plane", OFFSET(matrix_str[1]), AV_OPT_TYPE_STRING, {.str="0 0 0 0 1 0 0 0 0"}, 0, 0, FLAGS },
292     { "2m", "set matrix for 3rd plane", OFFSET(matrix_str[2]), AV_OPT_TYPE_STRING, {.str="0 0 0 0 1 0 0 0 0"}, 0, 0, FLAGS },
293     { "3m", "set matrix for 4th plane", OFFSET(matrix_str[3]), AV_OPT_TYPE_STRING, {.str="0 0 0 0 1 0 0 0 0"}, 0, 0, FLAGS },
294     { "0rdiv", "set rdiv for 1nd plane", OFFSET(rdivs[0]), AV_OPT_TYPE_FLOAT, {.dbl=1.0}, 0.0, INT_MAX, FLAGS},
295     { "1rdiv", "set rdiv for 2nd plane", OFFSET(rdivs[1]), AV_OPT_TYPE_FLOAT, {.dbl=1.0}, 0.0, INT_MAX, FLAGS},
296     { "2rdiv", "set rdiv for 3rd plane", OFFSET(rdivs[2]), AV_OPT_TYPE_FLOAT, {.dbl=1.0}, 0.0, INT_MAX, FLAGS},
297     { "3rdiv", "set rdiv for 4th plane", OFFSET(rdivs[3]), AV_OPT_TYPE_FLOAT, {.dbl=1.0}, 0.0, INT_MAX, FLAGS},
298     { "0bias", "set bias for 1st plane", OFFSET(biases[0]), AV_OPT_TYPE_FLOAT, {.dbl=0.0}, 0.0, INT_MAX, FLAGS},
299     { "1bias", "set bias for 2nd plane", OFFSET(biases[1]), AV_OPT_TYPE_FLOAT, {.dbl=0.0}, 0.0, INT_MAX, FLAGS},
300     { "2bias", "set bias for 3rd plane", OFFSET(biases[2]), AV_OPT_TYPE_FLOAT, {.dbl=0.0}, 0.0, INT_MAX, FLAGS},
301     { "3bias", "set bias for 4th plane", OFFSET(biases[3]), AV_OPT_TYPE_FLOAT, {.dbl=0.0}, 0.0, INT_MAX, FLAGS},
302     { NULL }
303 };
304
305 AVFILTER_DEFINE_CLASS(convolution_opencl);
306
307 static const AVFilterPad convolution_opencl_inputs[] = {
308     {
309         .name         = "default",
310         .type         = AVMEDIA_TYPE_VIDEO,
311         .filter_frame = &convolution_opencl_filter_frame,
312         .config_props = &ff_opencl_filter_config_input,
313     },
314     { NULL }
315 };
316
317 static const AVFilterPad convolution_opencl_outputs[] = {
318     {
319         .name         = "default",
320         .type         = AVMEDIA_TYPE_VIDEO,
321         .config_props = &ff_opencl_filter_config_output,
322     },
323     { NULL }
324 };
325
326 AVFilter ff_vf_convolution_opencl = {
327     .name           = "convolution_opencl",
328     .description    = NULL_IF_CONFIG_SMALL("Apply convolution mask to input video"),
329     .priv_size      = sizeof(ConvolutionOpenCLContext),
330     .priv_class     = &convolution_opencl_class,
331     .init           = &ff_opencl_filter_init,
332     .uninit         = &convolution_opencl_uninit,
333     .query_formats  = &ff_opencl_filter_query_formats,
334     .inputs         = convolution_opencl_inputs,
335     .outputs        = convolution_opencl_outputs,
336     .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,
337 };