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.

429 lines
14KB

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