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