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