]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_libopencv.c
Merge commit '4521645b1aee9e9ad8f5cea7b2392cd5f6ffcd26'
[ffmpeg] / libavfilter / vf_libopencv.c
1 /*
2  * Copyright (c) 2010 Stefano Sabatini
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 /**
22  * @file
23  * libopencv wrapper functions
24  */
25
26 /* #define DEBUG */
27
28 #include <opencv/cv.h>
29 #include <opencv/cxcore.h>
30 #include "libavutil/avstring.h"
31 #include "libavutil/common.h"
32 #include "libavutil/file.h"
33 #include "avfilter.h"
34 #include "formats.h"
35 #include "video.h"
36
37 static void fill_iplimage_from_picref(IplImage *img, const AVFilterBufferRef *picref, enum AVPixelFormat pixfmt)
38 {
39     IplImage *tmpimg;
40     int depth, channels_nb;
41
42     if      (pixfmt == AV_PIX_FMT_GRAY8) { depth = IPL_DEPTH_8U;  channels_nb = 1; }
43     else if (pixfmt == AV_PIX_FMT_BGRA)  { depth = IPL_DEPTH_8U;  channels_nb = 4; }
44     else if (pixfmt == AV_PIX_FMT_BGR24) { depth = IPL_DEPTH_8U;  channels_nb = 3; }
45     else return;
46
47     tmpimg = cvCreateImageHeader((CvSize){picref->video->w, picref->video->h}, depth, channels_nb);
48     *img = *tmpimg;
49     img->imageData = img->imageDataOrigin = picref->data[0];
50     img->dataOrder = IPL_DATA_ORDER_PIXEL;
51     img->origin    = IPL_ORIGIN_TL;
52     img->widthStep = picref->linesize[0];
53 }
54
55 static void fill_picref_from_iplimage(AVFilterBufferRef *picref, const IplImage *img, enum AVPixelFormat pixfmt)
56 {
57     picref->linesize[0] = img->widthStep;
58     picref->data[0]     = img->imageData;
59 }
60
61 static int query_formats(AVFilterContext *ctx)
62 {
63     static const enum AVPixelFormat pix_fmts[] = {
64         AV_PIX_FMT_BGR24, AV_PIX_FMT_BGRA, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE
65     };
66
67     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
68     return 0;
69 }
70
71 static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
72 {
73     return 0;
74 }
75
76 typedef struct {
77     const char *name;
78     int (*init)(AVFilterContext *ctx, const char *args);
79     void (*uninit)(AVFilterContext *ctx);
80     void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
81     void *priv;
82 } OCVContext;
83
84 typedef struct {
85     int type;
86     int    param1, param2;
87     double param3, param4;
88 } SmoothContext;
89
90 static av_cold int smooth_init(AVFilterContext *ctx, const char *args)
91 {
92     OCVContext *ocv = ctx->priv;
93     SmoothContext *smooth = ocv->priv;
94     char type_str[128] = "gaussian";
95
96     smooth->param1 = 3;
97     smooth->param2 = 0;
98     smooth->param3 = 0.0;
99     smooth->param4 = 0.0;
100
101     if (args)
102         sscanf(args, "%127[^:]:%d:%d:%lf:%lf", type_str, &smooth->param1, &smooth->param2, &smooth->param3, &smooth->param4);
103
104     if      (!strcmp(type_str, "blur"         )) smooth->type = CV_BLUR;
105     else if (!strcmp(type_str, "blur_no_scale")) smooth->type = CV_BLUR_NO_SCALE;
106     else if (!strcmp(type_str, "median"       )) smooth->type = CV_MEDIAN;
107     else if (!strcmp(type_str, "gaussian"     )) smooth->type = CV_GAUSSIAN;
108     else if (!strcmp(type_str, "bilateral"    )) smooth->type = CV_BILATERAL;
109     else {
110         av_log(ctx, AV_LOG_ERROR, "Smoothing type '%s' unknown.\n", type_str);
111         return AVERROR(EINVAL);
112     }
113
114     if (smooth->param1 < 0 || !(smooth->param1%2)) {
115         av_log(ctx, AV_LOG_ERROR,
116                "Invalid value '%d' for param1, it has to be a positive odd number\n",
117                smooth->param1);
118         return AVERROR(EINVAL);
119     }
120     if ((smooth->type == CV_BLUR || smooth->type == CV_BLUR_NO_SCALE || smooth->type == CV_GAUSSIAN) &&
121         (smooth->param2 < 0 || (smooth->param2 && !(smooth->param2%2)))) {
122         av_log(ctx, AV_LOG_ERROR,
123                "Invalid value '%d' for param2, it has to be zero or a positive odd number\n",
124                smooth->param2);
125         return AVERROR(EINVAL);
126     }
127
128     av_log(ctx, AV_LOG_VERBOSE, "type:%s param1:%d param2:%d param3:%f param4:%f\n",
129            type_str, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
130     return 0;
131 }
132
133 static void smooth_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
134 {
135     OCVContext *ocv = ctx->priv;
136     SmoothContext *smooth = ocv->priv;
137     cvSmooth(inimg, outimg, smooth->type, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
138 }
139
140 static int read_shape_from_file(int *cols, int *rows, int **values, const char *filename,
141                                 void *log_ctx)
142 {
143     uint8_t *buf, *p, *pend;
144     size_t size;
145     int ret, i, j, w;
146
147     if ((ret = av_file_map(filename, &buf, &size, 0, log_ctx)) < 0)
148         return ret;
149
150     /* prescan file to get the number of lines and the maximum width */
151     w = 0;
152     for (i = 0; i < size; i++) {
153         if (buf[i] == '\n') {
154             if (*rows == INT_MAX) {
155                 av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of rows in the file\n");
156                 return AVERROR_INVALIDDATA;
157             }
158             ++(*rows);
159             *cols = FFMAX(*cols, w);
160             w = 0;
161         } else if (w == INT_MAX) {
162             av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of columns in the file\n");
163             return AVERROR_INVALIDDATA;
164         }
165         w++;
166     }
167     if (*rows > (SIZE_MAX / sizeof(int) / *cols)) {
168         av_log(log_ctx, AV_LOG_ERROR, "File with size %dx%d is too big\n",
169                *rows, *cols);
170         return AVERROR_INVALIDDATA;
171     }
172     if (!(*values = av_mallocz(sizeof(int) * *rows * *cols)))
173         return AVERROR(ENOMEM);
174
175     /* fill *values */
176     p    = buf;
177     pend = buf + size-1;
178     for (i = 0; i < *rows; i++) {
179         for (j = 0;; j++) {
180             if (p > pend || *p == '\n') {
181                 p++;
182                 break;
183             } else
184                 (*values)[*cols*i + j] = !!isgraph(*(p++));
185         }
186     }
187     av_file_unmap(buf, size);
188
189 #ifdef DEBUG
190     {
191         char *line;
192         if (!(line = av_malloc(*cols + 1)))
193             return AVERROR(ENOMEM);
194         for (i = 0; i < *rows; i++) {
195             for (j = 0; j < *cols; j++)
196                 line[j] = (*values)[i * *cols + j] ? '@' : ' ';
197             line[j] = 0;
198             av_log(log_ctx, AV_LOG_DEBUG, "%3d: %s\n", i, line);
199         }
200         av_free(line);
201     }
202 #endif
203
204     return 0;
205 }
206
207 static int parse_iplconvkernel(IplConvKernel **kernel, char *buf, void *log_ctx)
208 {
209     char shape_filename[128] = "", shape_str[32] = "rect";
210     int cols = 0, rows = 0, anchor_x = 0, anchor_y = 0, shape = CV_SHAPE_RECT;
211     int *values = NULL, ret;
212
213     sscanf(buf, "%dx%d+%dx%d/%32[^=]=%127s", &cols, &rows, &anchor_x, &anchor_y, shape_str, shape_filename);
214
215     if      (!strcmp(shape_str, "rect"   )) shape = CV_SHAPE_RECT;
216     else if (!strcmp(shape_str, "cross"  )) shape = CV_SHAPE_CROSS;
217     else if (!strcmp(shape_str, "ellipse")) shape = CV_SHAPE_ELLIPSE;
218     else if (!strcmp(shape_str, "custom" )) {
219         shape = CV_SHAPE_CUSTOM;
220         if ((ret = read_shape_from_file(&cols, &rows, &values, shape_filename, log_ctx)) < 0)
221             return ret;
222     } else {
223         av_log(log_ctx, AV_LOG_ERROR,
224                "Shape unspecified or type '%s' unknown.\n", shape_str);
225         return AVERROR(EINVAL);
226     }
227
228     if (rows <= 0 || cols <= 0) {
229         av_log(log_ctx, AV_LOG_ERROR,
230                "Invalid non-positive values for shape size %dx%d\n", cols, rows);
231         return AVERROR(EINVAL);
232     }
233
234     if (anchor_x < 0 || anchor_y < 0 || anchor_x >= cols || anchor_y >= rows) {
235         av_log(log_ctx, AV_LOG_ERROR,
236                "Shape anchor %dx%d is not inside the rectangle with size %dx%d.\n",
237                anchor_x, anchor_y, cols, rows);
238         return AVERROR(EINVAL);
239     }
240
241     *kernel = cvCreateStructuringElementEx(cols, rows, anchor_x, anchor_y, shape, values);
242     av_freep(&values);
243     if (!*kernel)
244         return AVERROR(ENOMEM);
245
246     av_log(log_ctx, AV_LOG_VERBOSE, "Structuring element: w:%d h:%d x:%d y:%d shape:%s\n",
247            rows, cols, anchor_x, anchor_y, shape_str);
248     return 0;
249 }
250
251 typedef struct {
252     int nb_iterations;
253     IplConvKernel *kernel;
254 } DilateContext;
255
256 static av_cold int dilate_init(AVFilterContext *ctx, const char *args)
257 {
258     OCVContext *ocv = ctx->priv;
259     DilateContext *dilate = ocv->priv;
260     char default_kernel_str[] = "3x3+0x0/rect";
261     char *kernel_str;
262     const char *buf = args;
263     int ret;
264
265     dilate->nb_iterations = 1;
266
267     if (args)
268         kernel_str = av_get_token(&buf, ":");
269     if ((ret = parse_iplconvkernel(&dilate->kernel,
270                                    *kernel_str ? kernel_str : default_kernel_str,
271                                    ctx)) < 0)
272         return ret;
273     av_free(kernel_str);
274
275     sscanf(buf, ":%d", &dilate->nb_iterations);
276     av_log(ctx, AV_LOG_VERBOSE, "iterations_nb:%d\n", dilate->nb_iterations);
277     if (dilate->nb_iterations <= 0) {
278         av_log(ctx, AV_LOG_ERROR, "Invalid non-positive value '%d' for nb_iterations\n",
279                dilate->nb_iterations);
280         return AVERROR(EINVAL);
281     }
282     return 0;
283 }
284
285 static av_cold void dilate_uninit(AVFilterContext *ctx)
286 {
287     OCVContext *ocv = ctx->priv;
288     DilateContext *dilate = ocv->priv;
289
290     cvReleaseStructuringElement(&dilate->kernel);
291 }
292
293 static void dilate_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
294 {
295     OCVContext *ocv = ctx->priv;
296     DilateContext *dilate = ocv->priv;
297     cvDilate(inimg, outimg, dilate->kernel, dilate->nb_iterations);
298 }
299
300 static void erode_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
301 {
302     OCVContext *ocv = ctx->priv;
303     DilateContext *dilate = ocv->priv;
304     cvErode(inimg, outimg, dilate->kernel, dilate->nb_iterations);
305 }
306
307 typedef struct {
308     const char *name;
309     size_t priv_size;
310     int  (*init)(AVFilterContext *ctx, const char *args);
311     void (*uninit)(AVFilterContext *ctx);
312     void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
313 } OCVFilterEntry;
314
315 static OCVFilterEntry ocv_filter_entries[] = {
316     { "dilate", sizeof(DilateContext), dilate_init, dilate_uninit, dilate_end_frame_filter },
317     { "erode",  sizeof(DilateContext), dilate_init, dilate_uninit, erode_end_frame_filter  },
318     { "smooth", sizeof(SmoothContext), smooth_init, NULL, smooth_end_frame_filter },
319 };
320
321 static av_cold int init(AVFilterContext *ctx, const char *args)
322 {
323     OCVContext *ocv = ctx->priv;
324     char name[128], priv_args[1024];
325     int i;
326     char c;
327
328     sscanf(args, "%127[^=:]%c%1023s", name, &c, priv_args);
329
330     for (i = 0; i < FF_ARRAY_ELEMS(ocv_filter_entries); i++) {
331         OCVFilterEntry *entry = &ocv_filter_entries[i];
332         if (!strcmp(name, entry->name)) {
333             ocv->name             = entry->name;
334             ocv->init             = entry->init;
335             ocv->uninit           = entry->uninit;
336             ocv->end_frame_filter = entry->end_frame_filter;
337
338             if (!(ocv->priv = av_mallocz(entry->priv_size)))
339                 return AVERROR(ENOMEM);
340             return ocv->init(ctx, priv_args);
341         }
342     }
343
344     av_log(ctx, AV_LOG_ERROR, "No libopencv filter named '%s'\n", name);
345     return AVERROR(EINVAL);
346 }
347
348 static av_cold void uninit(AVFilterContext *ctx)
349 {
350     OCVContext *ocv = ctx->priv;
351
352     if (ocv->uninit)
353         ocv->uninit(ctx);
354     av_free(ocv->priv);
355     memset(ocv, 0, sizeof(*ocv));
356 }
357
358 static int end_frame(AVFilterLink *inlink)
359 {
360     AVFilterContext *ctx = inlink->dst;
361     OCVContext *ocv = ctx->priv;
362     AVFilterLink *outlink= inlink->dst->outputs[0];
363     AVFilterBufferRef *inpicref  = inlink ->cur_buf;
364     AVFilterBufferRef *outpicref = outlink->out_buf;
365     IplImage inimg, outimg;
366     int ret;
367
368     fill_iplimage_from_picref(&inimg , inpicref , inlink->format);
369     fill_iplimage_from_picref(&outimg, outpicref, inlink->format);
370     ocv->end_frame_filter(ctx, &inimg, &outimg);
371     fill_picref_from_iplimage(outpicref, &outimg, inlink->format);
372
373     if ((ret = ff_draw_slice(outlink, 0, outlink->h, 1)) < 0 ||
374         (ret = ff_end_frame(outlink)) < 0)
375         return ret;
376     return 0;
377 }
378
379 static const AVFilterPad avfilter_vf_ocv_inputs[] = {
380     {
381         .name       = "default",
382         .type       = AVMEDIA_TYPE_VIDEO,
383         .draw_slice = null_draw_slice,
384         .end_frame  = end_frame,
385         .min_perms  = AV_PERM_READ
386     },
387     { NULL }
388 };
389
390 static const AVFilterPad avfilter_vf_ocv_outputs[] = {
391     {
392         .name = "default",
393         .type = AVMEDIA_TYPE_VIDEO,
394     },
395     { NULL }
396 };
397
398 AVFilter avfilter_vf_ocv = {
399     .name        = "ocv",
400     .description = NULL_IF_CONFIG_SMALL("Apply transform using libopencv."),
401
402     .priv_size = sizeof(OCVContext),
403
404     .query_formats = query_formats,
405     .init = init,
406     .uninit = uninit,
407
408     .inputs    = avfilter_vf_ocv_inputs,
409
410     .outputs   = avfilter_vf_ocv_outputs,
411 };