You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

399 lines
13KB

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