libavfilter/vf_libopencv.c
6ebf0bfc
 /*
3fa77bde
  * Copyright (c) 2010 Stefano Sabatini
6ebf0bfc
  *
  * 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
  */
 
 /**
  * @file
  * libopencv wrapper functions
  */
 
38622007
 #include "config.h"
 #if HAVE_OPENCV2_CORE_CORE_C_H
 #include <opencv2/core/core_c.h>
 #include <opencv2/imgproc/imgproc_c.h>
 #else
e6c4a417
 #include <opencv/cv.h>
f1b3f33d
 #include <opencv/cxcore.h>
38622007
 #endif
91cbb6ba
 #include "libavutil/avstring.h"
7ebe3962
 #include "libavutil/common.h"
91cbb6ba
 #include "libavutil/file.h"
ee0e8d4b
 #include "libavutil/opt.h"
6ebf0bfc
 #include "avfilter.h"
fe16ca1b
 #include "formats.h"
1f94f86a
 #include "internal.h"
fe16ca1b
 #include "video.h"
6ebf0bfc
 
7e350379
 static void fill_iplimage_from_frame(IplImage *img, const AVFrame *frame, enum AVPixelFormat pixfmt)
6ebf0bfc
 {
     IplImage *tmpimg;
     int depth, channels_nb;
 
716d413c
     if      (pixfmt == AV_PIX_FMT_GRAY8) { depth = IPL_DEPTH_8U;  channels_nb = 1; }
     else if (pixfmt == AV_PIX_FMT_BGRA)  { depth = IPL_DEPTH_8U;  channels_nb = 4; }
     else if (pixfmt == AV_PIX_FMT_BGR24) { depth = IPL_DEPTH_8U;  channels_nb = 3; }
6ebf0bfc
     else return;
 
7e350379
     tmpimg = cvCreateImageHeader((CvSize){frame->width, frame->height}, depth, channels_nb);
6ebf0bfc
     *img = *tmpimg;
7e350379
     img->imageData = img->imageDataOrigin = frame->data[0];
6ebf0bfc
     img->dataOrder = IPL_DATA_ORDER_PIXEL;
     img->origin    = IPL_ORIGIN_TL;
7e350379
     img->widthStep = frame->linesize[0];
6ebf0bfc
 }
 
7e350379
 static void fill_frame_from_iplimage(AVFrame *frame, const IplImage *img, enum AVPixelFormat pixfmt)
6ebf0bfc
 {
7e350379
     frame->linesize[0] = img->widthStep;
     frame->data[0]     = img->imageData;
6ebf0bfc
 }
 
 static int query_formats(AVFilterContext *ctx)
 {
716d413c
     static const enum AVPixelFormat pix_fmts[] = {
         AV_PIX_FMT_BGR24, AV_PIX_FMT_BGRA, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE
6ebf0bfc
     };
fd682b18
     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
     if (!fmts_list)
         return AVERROR(ENOMEM);
     return ff_set_common_formats(ctx, fmts_list);
6ebf0bfc
 }
 
58400ac1
 typedef struct OCVContext {
ee0e8d4b
     const AVClass *class;
     char *name;
     char *params;
51e71d6e
     int (*init)(AVFilterContext *ctx, const char *args);
cf69ad35
     void (*uninit)(AVFilterContext *ctx);
     void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
     void *priv;
 } OCVContext;
6ebf0bfc
 
58400ac1
 typedef struct SmoothContext {
6ebf0bfc
     int type;
     int    param1, param2;
     double param3, param4;
 } SmoothContext;
 
51e71d6e
 static av_cold int smooth_init(AVFilterContext *ctx, const char *args)
6ebf0bfc
 {
4753f802
     OCVContext *s = ctx->priv;
     SmoothContext *smooth = s->priv;
6ebf0bfc
     char type_str[128] = "gaussian";
 
     smooth->param1 = 3;
     smooth->param2 = 0;
     smooth->param3 = 0.0;
     smooth->param4 = 0.0;
 
     if (args)
ee0e8d4b
         sscanf(args, "%127[^|]|%d|%d|%lf|%lf", type_str, &smooth->param1, &smooth->param2, &smooth->param3, &smooth->param4);
6ebf0bfc
 
     if      (!strcmp(type_str, "blur"         )) smooth->type = CV_BLUR;
     else if (!strcmp(type_str, "blur_no_scale")) smooth->type = CV_BLUR_NO_SCALE;
     else if (!strcmp(type_str, "median"       )) smooth->type = CV_MEDIAN;
     else if (!strcmp(type_str, "gaussian"     )) smooth->type = CV_GAUSSIAN;
     else if (!strcmp(type_str, "bilateral"    )) smooth->type = CV_BILATERAL;
     else {
e39f6a3a
         av_log(ctx, AV_LOG_ERROR, "Smoothing type '%s' unknown.\n", type_str);
6ebf0bfc
         return AVERROR(EINVAL);
     }
 
     if (smooth->param1 < 0 || !(smooth->param1%2)) {
         av_log(ctx, AV_LOG_ERROR,
                "Invalid value '%d' for param1, it has to be a positive odd number\n",
                smooth->param1);
         return AVERROR(EINVAL);
     }
     if ((smooth->type == CV_BLUR || smooth->type == CV_BLUR_NO_SCALE || smooth->type == CV_GAUSSIAN) &&
         (smooth->param2 < 0 || (smooth->param2 && !(smooth->param2%2)))) {
         av_log(ctx, AV_LOG_ERROR,
                "Invalid value '%d' for param2, it has to be zero or a positive odd number\n",
                smooth->param2);
         return AVERROR(EINVAL);
     }
 
1a49a169
     av_log(ctx, AV_LOG_VERBOSE, "type:%s param1:%d param2:%d param3:%f param4:%f\n",
6ebf0bfc
            type_str, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
     return 0;
 }
 
cf69ad35
 static void smooth_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
6ebf0bfc
 {
4753f802
     OCVContext *s = ctx->priv;
     SmoothContext *smooth = s->priv;
cf69ad35
     cvSmooth(inimg, outimg, smooth->type, smooth->param1, smooth->param2, smooth->param3, smooth->param4);
 }
 
91cbb6ba
 static int read_shape_from_file(int *cols, int *rows, int **values, const char *filename,
                                 void *log_ctx)
 {
     uint8_t *buf, *p, *pend;
     size_t size;
     int ret, i, j, w;
 
     if ((ret = av_file_map(filename, &buf, &size, 0, log_ctx)) < 0)
         return ret;
 
     /* prescan file to get the number of lines and the maximum width */
     w = 0;
     for (i = 0; i < size; i++) {
         if (buf[i] == '\n') {
             if (*rows == INT_MAX) {
                 av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of rows in the file\n");
                 return AVERROR_INVALIDDATA;
             }
             ++(*rows);
             *cols = FFMAX(*cols, w);
             w = 0;
         } else if (w == INT_MAX) {
             av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of columns in the file\n");
             return AVERROR_INVALIDDATA;
         }
         w++;
     }
6d635148
     if (*rows > (SIZE_MAX / sizeof(int) / *cols)) {
91cbb6ba
         av_log(log_ctx, AV_LOG_ERROR, "File with size %dx%d is too big\n",
                *rows, *cols);
         return AVERROR_INVALIDDATA;
     }
4932b1e8
     if (!(*values = av_mallocz_array(sizeof(int) * *rows, *cols)))
91cbb6ba
         return AVERROR(ENOMEM);
 
     /* fill *values */
     p    = buf;
     pend = buf + size-1;
     for (i = 0; i < *rows; i++) {
         for (j = 0;; j++) {
             if (p > pend || *p == '\n') {
                 p++;
                 break;
             } else
14e240cb
                 (*values)[*cols*i + j] = !!av_isgraph(*(p++));
91cbb6ba
         }
     }
     av_file_unmap(buf, size);
 
 #ifdef DEBUG
     {
         char *line;
         if (!(line = av_malloc(*cols + 1)))
             return AVERROR(ENOMEM);
         for (i = 0; i < *rows; i++) {
             for (j = 0; j < *cols; j++)
                 line[j] = (*values)[i * *cols + j] ? '@' : ' ';
             line[j] = 0;
             av_log(log_ctx, AV_LOG_DEBUG, "%3d: %s\n", i, line);
         }
         av_free(line);
     }
 #endif
 
     return 0;
 }
 
 static int parse_iplconvkernel(IplConvKernel **kernel, char *buf, void *log_ctx)
 {
     char shape_filename[128] = "", shape_str[32] = "rect";
     int cols = 0, rows = 0, anchor_x = 0, anchor_y = 0, shape = CV_SHAPE_RECT;
8805589b
     int *values = NULL, ret = 0;
91cbb6ba
 
     sscanf(buf, "%dx%d+%dx%d/%32[^=]=%127s", &cols, &rows, &anchor_x, &anchor_y, shape_str, shape_filename);
 
     if      (!strcmp(shape_str, "rect"   )) shape = CV_SHAPE_RECT;
     else if (!strcmp(shape_str, "cross"  )) shape = CV_SHAPE_CROSS;
     else if (!strcmp(shape_str, "ellipse")) shape = CV_SHAPE_ELLIPSE;
     else if (!strcmp(shape_str, "custom" )) {
         shape = CV_SHAPE_CUSTOM;
         if ((ret = read_shape_from_file(&cols, &rows, &values, shape_filename, log_ctx)) < 0)
             return ret;
     } else {
         av_log(log_ctx, AV_LOG_ERROR,
e39f6a3a
                "Shape unspecified or type '%s' unknown.\n", shape_str);
8805589b
         ret = AVERROR(EINVAL);
         goto out;
91cbb6ba
     }
 
     if (rows <= 0 || cols <= 0) {
         av_log(log_ctx, AV_LOG_ERROR,
                "Invalid non-positive values for shape size %dx%d\n", cols, rows);
8805589b
         ret = AVERROR(EINVAL);
         goto out;
91cbb6ba
     }
 
     if (anchor_x < 0 || anchor_y < 0 || anchor_x >= cols || anchor_y >= rows) {
         av_log(log_ctx, AV_LOG_ERROR,
                "Shape anchor %dx%d is not inside the rectangle with size %dx%d.\n",
                anchor_x, anchor_y, cols, rows);
8805589b
         ret = AVERROR(EINVAL);
         goto out;
91cbb6ba
     }
 
     *kernel = cvCreateStructuringElementEx(cols, rows, anchor_x, anchor_y, shape, values);
8805589b
     if (!*kernel) {
         ret = AVERROR(ENOMEM);
         goto out;
     }
91cbb6ba
 
1a49a169
     av_log(log_ctx, AV_LOG_VERBOSE, "Structuring element: w:%d h:%d x:%d y:%d shape:%s\n",
91cbb6ba
            rows, cols, anchor_x, anchor_y, shape_str);
8805589b
 out:
     av_freep(&values);
     return ret;
91cbb6ba
 }
 
58400ac1
 typedef struct DilateContext {
91cbb6ba
     int nb_iterations;
     IplConvKernel *kernel;
 } DilateContext;
 
51e71d6e
 static av_cold int dilate_init(AVFilterContext *ctx, const char *args)
91cbb6ba
 {
4753f802
     OCVContext *s = ctx->priv;
     DilateContext *dilate = s->priv;
91cbb6ba
     char default_kernel_str[] = "3x3+0x0/rect";
a6653787
     char *kernel_str = NULL;
91cbb6ba
     const char *buf = args;
     int ret;
 
a6653787
     if (args) {
ee0e8d4b
         kernel_str = av_get_token(&buf, "|");
1dc1c4e7
 
a6653787
         if (!kernel_str)
             return AVERROR(ENOMEM);
     }
 
     ret = parse_iplconvkernel(&dilate->kernel,
                               (!kernel_str || !*kernel_str) ? default_kernel_str
                                                             : kernel_str,
                               ctx);
91cbb6ba
     av_free(kernel_str);
a6653787
     if (ret < 0)
         return ret;
91cbb6ba
 
f16a6f66
     if (!buf || sscanf(buf, "|%d", &dilate->nb_iterations) != 1)
         dilate->nb_iterations = 1;
1a49a169
     av_log(ctx, AV_LOG_VERBOSE, "iterations_nb:%d\n", dilate->nb_iterations);
91cbb6ba
     if (dilate->nb_iterations <= 0) {
         av_log(ctx, AV_LOG_ERROR, "Invalid non-positive value '%d' for nb_iterations\n",
                dilate->nb_iterations);
         return AVERROR(EINVAL);
     }
     return 0;
 }
 
 static av_cold void dilate_uninit(AVFilterContext *ctx)
 {
4753f802
     OCVContext *s = ctx->priv;
     DilateContext *dilate = s->priv;
91cbb6ba
 
     cvReleaseStructuringElement(&dilate->kernel);
 }
 
 static void dilate_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
 {
4753f802
     OCVContext *s = ctx->priv;
     DilateContext *dilate = s->priv;
91cbb6ba
     cvDilate(inimg, outimg, dilate->kernel, dilate->nb_iterations);
 }
 
17fc9493
 static void erode_end_frame_filter(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg)
 {
4753f802
     OCVContext *s = ctx->priv;
     DilateContext *dilate = s->priv;
17fc9493
     cvErode(inimg, outimg, dilate->kernel, dilate->nb_iterations);
 }
 
58400ac1
 typedef struct OCVFilterEntry {
cf69ad35
     const char *name;
     size_t priv_size;
51e71d6e
     int  (*init)(AVFilterContext *ctx, const char *args);
cf69ad35
     void (*uninit)(AVFilterContext *ctx);
     void (*end_frame_filter)(AVFilterContext *ctx, IplImage *inimg, IplImage *outimg);
 } OCVFilterEntry;
 
dc4a6e4d
 static const OCVFilterEntry ocv_filter_entries[] = {
91cbb6ba
     { "dilate", sizeof(DilateContext), dilate_init, dilate_uninit, dilate_end_frame_filter },
17fc9493
     { "erode",  sizeof(DilateContext), dilate_init, dilate_uninit, erode_end_frame_filter  },
cf69ad35
     { "smooth", sizeof(SmoothContext), smooth_init, NULL, smooth_end_frame_filter },
 };
 
d69a4177
 static av_cold int init(AVFilterContext *ctx)
cf69ad35
 {
4753f802
     OCVContext *s = ctx->priv;
cf69ad35
     int i;
 
df003cbb
     if (!s->name) {
490786c0
         av_log(ctx, AV_LOG_ERROR, "No libopencv filter name specified\n");
         return AVERROR(EINVAL);
     }
cf69ad35
     for (i = 0; i < FF_ARRAY_ELEMS(ocv_filter_entries); i++) {
dc4a6e4d
         const OCVFilterEntry *entry = &ocv_filter_entries[i];
4753f802
         if (!strcmp(s->name, entry->name)) {
             s->init             = entry->init;
             s->uninit           = entry->uninit;
             s->end_frame_filter = entry->end_frame_filter;
cf69ad35
 
4753f802
             if (!(s->priv = av_mallocz(entry->priv_size)))
cf69ad35
                 return AVERROR(ENOMEM);
4753f802
             return s->init(ctx, s->params);
cf69ad35
         }
     }
 
4753f802
     av_log(ctx, AV_LOG_ERROR, "No libopencv filter named '%s'\n", s->name);
cf69ad35
     return AVERROR(EINVAL);
 }
 
 static av_cold void uninit(AVFilterContext *ctx)
 {
4753f802
     OCVContext *s = ctx->priv;
cf69ad35
 
4753f802
     if (s->uninit)
         s->uninit(ctx);
4d48ea3c
     av_freep(&s->priv);
cf69ad35
 }
 
7e350379
 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
cf69ad35
 {
     AVFilterContext *ctx = inlink->dst;
4753f802
     OCVContext *s = ctx->priv;
cf69ad35
     AVFilterLink *outlink= inlink->dst->outputs[0];
7e350379
     AVFrame *out;
6ebf0bfc
     IplImage inimg, outimg;
 
7e350379
     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
1f94f86a
     if (!out) {
7e350379
         av_frame_free(&in);
1f94f86a
         return AVERROR(ENOMEM);
     }
7e350379
     av_frame_copy_props(out, in);
1f94f86a
 
7e350379
     fill_iplimage_from_frame(&inimg , in , inlink->format);
     fill_iplimage_from_frame(&outimg, out, inlink->format);
4753f802
     s->end_frame_filter(ctx, &inimg, &outimg);
7e350379
     fill_frame_from_iplimage(out, &outimg, inlink->format);
6ebf0bfc
 
7e350379
     av_frame_free(&in);
1f94f86a
 
     return ff_filter_frame(outlink, out);
6ebf0bfc
 }
 
ee0e8d4b
 #define OFFSET(x) offsetof(OCVContext, x)
3dedcef8
 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_FILTERING_PARAM
a1873f35
 static const AVOption ocv_options[] = {
ee0e8d4b
     { "filter_name",   NULL, OFFSET(name),   AV_OPT_TYPE_STRING, .flags = FLAGS },
     { "filter_params", NULL, OFFSET(params), AV_OPT_TYPE_STRING, .flags = FLAGS },
b211607b
     { NULL }
ee0e8d4b
 };
 
a1873f35
 AVFILTER_DEFINE_CLASS(ocv);
ee0e8d4b
 
568c70e7
 static const AVFilterPad avfilter_vf_ocv_inputs[] = {
     {
b211607b
         .name         = "default",
         .type         = AVMEDIA_TYPE_VIDEO,
1f94f86a
         .filter_frame = filter_frame,
568c70e7
     },
     { NULL }
 };
 
 static const AVFilterPad avfilter_vf_ocv_outputs[] = {
     {
         .name = "default",
         .type = AVMEDIA_TYPE_VIDEO,
     },
     { NULL }
 };
 
cd43ca04
 AVFilter ff_vf_ocv = {
b211607b
     .name          = "ocv",
     .description   = NULL_IF_CONFIG_SMALL("Apply transform using libopencv."),
     .priv_size     = sizeof(OCVContext),
     .priv_class    = &ocv_class,
6ebf0bfc
     .query_formats = query_formats,
b211607b
     .init          = init,
     .uninit        = uninit,
     .inputs        = avfilter_vf_ocv_inputs,
     .outputs       = avfilter_vf_ocv_outputs,
6ebf0bfc
 };