]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_edgedetect.c
avfilter/vf_edgedetect: fix coverity issue
[ffmpeg] / libavfilter / vf_edgedetect.c
1 /*
2  * Copyright (c) 2012-2014 Clément Bœsch <u pkh me>
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  * Edge detection filter
24  *
25  * @see https://en.wikipedia.org/wiki/Canny_edge_detector
26  */
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/opt.h"
31 #include "avfilter.h"
32 #include "formats.h"
33 #include "internal.h"
34 #include "video.h"
35
36 #define PLANE_R 0x4
37 #define PLANE_G 0x1
38 #define PLANE_B 0x2
39 #define PLANE_Y 0x1
40 #define PLANE_U 0x2
41 #define PLANE_V 0x4
42 #define PLANE_A 0x8
43
44 enum FilterMode {
45     MODE_WIRES,
46     MODE_COLORMIX,
47     MODE_CANNY,
48     NB_MODE
49 };
50
51 struct plane_info {
52     uint8_t  *tmpbuf;
53     uint16_t *gradients;
54     char     *directions;
55     int      width, height;
56 };
57
58 typedef struct EdgeDetectContext {
59     const AVClass *class;
60     struct plane_info planes[3];
61     int filter_planes;
62     int nb_planes;
63     double   low, high;
64     uint8_t  low_u8, high_u8;
65     int mode;
66 } EdgeDetectContext;
67
68 #define OFFSET(x) offsetof(EdgeDetectContext, x)
69 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
70 static const AVOption edgedetect_options[] = {
71     { "high", "set high threshold", OFFSET(high), AV_OPT_TYPE_DOUBLE, {.dbl=50/255.}, 0, 1, FLAGS },
72     { "low",  "set low threshold",  OFFSET(low),  AV_OPT_TYPE_DOUBLE, {.dbl=20/255.}, 0, 1, FLAGS },
73     { "mode", "set mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=MODE_WIRES}, 0, NB_MODE-1, FLAGS, "mode" },
74         { "wires",    "white/gray wires on black",  0, AV_OPT_TYPE_CONST, {.i64=MODE_WIRES},    INT_MIN, INT_MAX, FLAGS, "mode" },
75         { "colormix", "mix colors",                 0, AV_OPT_TYPE_CONST, {.i64=MODE_COLORMIX}, INT_MIN, INT_MAX, FLAGS, "mode" },
76         { "canny",    "detect edges on planes",     0, AV_OPT_TYPE_CONST, {.i64=MODE_CANNY},    INT_MIN, INT_MAX, FLAGS, "mode" },
77     { "planes", "set planes to filter",  OFFSET(filter_planes), AV_OPT_TYPE_FLAGS, {.i64=7}, 1, 0x7, FLAGS, "flags" },
78         { "y", "filter luma plane",  0, AV_OPT_TYPE_CONST, {.i64=PLANE_Y}, 0, 0, FLAGS, "flags" },
79         { "u", "filter u plane",     0, AV_OPT_TYPE_CONST, {.i64=PLANE_U}, 0, 0, FLAGS, "flags" },
80         { "v", "filter v plane",     0, AV_OPT_TYPE_CONST, {.i64=PLANE_V}, 0, 0, FLAGS, "flags" },
81         { "r", "filter red plane",   0, AV_OPT_TYPE_CONST, {.i64=PLANE_R}, 0, 0, FLAGS, "flags" },
82         { "g", "filter green plane", 0, AV_OPT_TYPE_CONST, {.i64=PLANE_G}, 0, 0, FLAGS, "flags" },
83         { "b", "filter blue plane",  0, AV_OPT_TYPE_CONST, {.i64=PLANE_B}, 0, 0, FLAGS, "flags" },
84     { NULL }
85 };
86
87 AVFILTER_DEFINE_CLASS(edgedetect);
88
89 static av_cold int init(AVFilterContext *ctx)
90 {
91     EdgeDetectContext *edgedetect = ctx->priv;
92
93     edgedetect->low_u8  = edgedetect->low  * 255. + .5;
94     edgedetect->high_u8 = edgedetect->high * 255. + .5;
95     return 0;
96 }
97
98 static int query_formats(AVFilterContext *ctx)
99 {
100     const EdgeDetectContext *edgedetect = ctx->priv;
101     static const enum AVPixelFormat wires_pix_fmts[] = {AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE};
102     static const enum AVPixelFormat canny_pix_fmts[] = {AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_GBRP, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE};
103     static const enum AVPixelFormat colormix_pix_fmts[] = {AV_PIX_FMT_GBRP, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE};
104     AVFilterFormats *fmts_list;
105     const enum AVPixelFormat *pix_fmts = NULL;
106
107     if (edgedetect->mode == MODE_WIRES) {
108         pix_fmts = wires_pix_fmts;
109     } else if (edgedetect->mode == MODE_COLORMIX) {
110         pix_fmts = colormix_pix_fmts;
111     } else if (edgedetect->mode == MODE_CANNY) {
112         pix_fmts = canny_pix_fmts;
113     } else {
114         av_assert0(0);
115     }
116     fmts_list = ff_make_format_list(pix_fmts);
117     if (!fmts_list)
118         return AVERROR(ENOMEM);
119     return ff_set_common_formats(ctx, fmts_list);
120 }
121
122 static int config_props(AVFilterLink *inlink)
123 {
124     int p;
125     AVFilterContext *ctx = inlink->dst;
126     EdgeDetectContext *edgedetect = ctx->priv;
127     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
128
129     edgedetect->nb_planes = inlink->format == AV_PIX_FMT_GRAY8 ? 1 : 3;
130     for (p = 0; p < edgedetect->nb_planes; p++) {
131         struct plane_info *plane = &edgedetect->planes[p];
132         int vsub = p ? desc->log2_chroma_h : 0;
133         int hsub = p ? desc->log2_chroma_w : 0;
134
135         plane->width      = AV_CEIL_RSHIFT(inlink->w, hsub);
136         plane->height     = AV_CEIL_RSHIFT(inlink->h, vsub);
137         plane->tmpbuf     = av_malloc(plane->width * plane->height);
138         plane->gradients  = av_calloc(plane->width * plane->height, sizeof(*plane->gradients));
139         plane->directions = av_malloc(plane->width * plane->height);
140         if (!plane->tmpbuf || !plane->gradients || !plane->directions)
141             return AVERROR(ENOMEM);
142     }
143     return 0;
144 }
145
146 static void gaussian_blur(AVFilterContext *ctx, int w, int h,
147                                 uint8_t *dst, int dst_linesize,
148                           const uint8_t *src, int src_linesize)
149 {
150     int i, j;
151
152     memcpy(dst, src, w); dst += dst_linesize; src += src_linesize;
153     if (h > 1) {
154         memcpy(dst, src, w); dst += dst_linesize; src += src_linesize;
155     }
156     for (j = 2; j < h - 2; j++) {
157         dst[0] = src[0];
158         dst[1] = src[1];
159         for (i = 2; i < w - 2; i++) {
160             /* Gaussian mask of size 5x5 with sigma = 1.4 */
161             dst[i] = ((src[-2*src_linesize + i-2] + src[2*src_linesize + i-2]) * 2
162                     + (src[-2*src_linesize + i-1] + src[2*src_linesize + i-1]) * 4
163                     + (src[-2*src_linesize + i  ] + src[2*src_linesize + i  ]) * 5
164                     + (src[-2*src_linesize + i+1] + src[2*src_linesize + i+1]) * 4
165                     + (src[-2*src_linesize + i+2] + src[2*src_linesize + i+2]) * 2
166
167                     + (src[  -src_linesize + i-2] + src[  src_linesize + i-2]) *  4
168                     + (src[  -src_linesize + i-1] + src[  src_linesize + i-1]) *  9
169                     + (src[  -src_linesize + i  ] + src[  src_linesize + i  ]) * 12
170                     + (src[  -src_linesize + i+1] + src[  src_linesize + i+1]) *  9
171                     + (src[  -src_linesize + i+2] + src[  src_linesize + i+2]) *  4
172
173                     + src[i-2] *  5
174                     + src[i-1] * 12
175                     + src[i  ] * 15
176                     + src[i+1] * 12
177                     + src[i+2] *  5) / 159;
178         }
179         dst[i    ] = src[i    ];
180         dst[i + 1] = src[i + 1];
181
182         dst += dst_linesize;
183         src += src_linesize;
184     }
185     if (h > 2) {
186         memcpy(dst, src, w); dst += dst_linesize; src += src_linesize;
187     }
188     if (h > 3)
189         memcpy(dst, src, w);
190 }
191
192 enum {
193     DIRECTION_45UP,
194     DIRECTION_45DOWN,
195     DIRECTION_HORIZONTAL,
196     DIRECTION_VERTICAL,
197 };
198
199 static int get_rounded_direction(int gx, int gy)
200 {
201     /* reference angles:
202      *   tan( pi/8) = sqrt(2)-1
203      *   tan(3pi/8) = sqrt(2)+1
204      * Gy/Gx is the tangent of the angle (theta), so Gy/Gx is compared against
205      * <ref-angle>, or more simply Gy against <ref-angle>*Gx
206      *
207      * Gx and Gy bounds = [-1020;1020], using 16-bit arithmetic:
208      *   round((sqrt(2)-1) * (1<<16)) =  27146
209      *   round((sqrt(2)+1) * (1<<16)) = 158218
210      */
211     if (gx) {
212         int tanpi8gx, tan3pi8gx;
213
214         if (gx < 0)
215             gx = -gx, gy = -gy;
216         gy <<= 16;
217         tanpi8gx  =  27146 * gx;
218         tan3pi8gx = 158218 * gx;
219         if (gy > -tan3pi8gx && gy < -tanpi8gx)  return DIRECTION_45UP;
220         if (gy > -tanpi8gx  && gy <  tanpi8gx)  return DIRECTION_HORIZONTAL;
221         if (gy >  tanpi8gx  && gy <  tan3pi8gx) return DIRECTION_45DOWN;
222     }
223     return DIRECTION_VERTICAL;
224 }
225
226 static void sobel(int w, int h,
227                        uint16_t *dst, int dst_linesize,
228                          int8_t *dir, int dir_linesize,
229                   const uint8_t *src, int src_linesize)
230 {
231     int i, j;
232
233     for (j = 1; j < h - 1; j++) {
234         dst += dst_linesize;
235         dir += dir_linesize;
236         src += src_linesize;
237         for (i = 1; i < w - 1; i++) {
238             const int gx =
239                 -1*src[-src_linesize + i-1] + 1*src[-src_linesize + i+1]
240                 -2*src[                i-1] + 2*src[                i+1]
241                 -1*src[ src_linesize + i-1] + 1*src[ src_linesize + i+1];
242             const int gy =
243                 -1*src[-src_linesize + i-1] + 1*src[ src_linesize + i-1]
244                 -2*src[-src_linesize + i  ] + 2*src[ src_linesize + i  ]
245                 -1*src[-src_linesize + i+1] + 1*src[ src_linesize + i+1];
246
247             dst[i] = FFABS(gx) + FFABS(gy);
248             dir[i] = get_rounded_direction(gx, gy);
249         }
250     }
251 }
252
253 static void non_maximum_suppression(int w, int h,
254                                           uint8_t  *dst, int dst_linesize,
255                                     const  int8_t  *dir, int dir_linesize,
256                                     const uint16_t *src, int src_linesize)
257 {
258     int i, j;
259
260 #define COPY_MAXIMA(ay, ax, by, bx) do {                \
261     if (src[i] > src[(ay)*src_linesize + i+(ax)] &&     \
262         src[i] > src[(by)*src_linesize + i+(bx)])       \
263         dst[i] = av_clip_uint8(src[i]);                 \
264 } while (0)
265
266     for (j = 1; j < h - 1; j++) {
267         dst += dst_linesize;
268         dir += dir_linesize;
269         src += src_linesize;
270         for (i = 1; i < w - 1; i++) {
271             switch (dir[i]) {
272             case DIRECTION_45UP:        COPY_MAXIMA( 1, -1, -1,  1); break;
273             case DIRECTION_45DOWN:      COPY_MAXIMA(-1, -1,  1,  1); break;
274             case DIRECTION_HORIZONTAL:  COPY_MAXIMA( 0, -1,  0,  1); break;
275             case DIRECTION_VERTICAL:    COPY_MAXIMA(-1,  0,  1,  0); break;
276             }
277         }
278     }
279 }
280
281 static void double_threshold(int low, int high, int w, int h,
282                                    uint8_t *dst, int dst_linesize,
283                              const uint8_t *src, int src_linesize)
284 {
285     int i, j;
286
287     for (j = 0; j < h; j++) {
288         for (i = 0; i < w; i++) {
289             if (src[i] > high) {
290                 dst[i] = src[i];
291                 continue;
292             }
293
294             if ((!i || i == w - 1 || !j || j == h - 1) &&
295                 src[i] > low &&
296                 (src[-src_linesize + i-1] > high ||
297                  src[-src_linesize + i  ] > high ||
298                  src[-src_linesize + i+1] > high ||
299                  src[                i-1] > high ||
300                  src[                i+1] > high ||
301                  src[ src_linesize + i-1] > high ||
302                  src[ src_linesize + i  ] > high ||
303                  src[ src_linesize + i+1] > high))
304                 dst[i] = src[i];
305             else
306                 dst[i] = 0;
307         }
308         dst += dst_linesize;
309         src += src_linesize;
310     }
311 }
312
313 static void color_mix(int w, int h,
314                             uint8_t *dst, int dst_linesize,
315                       const uint8_t *src, int src_linesize)
316 {
317     int i, j;
318
319     for (j = 0; j < h; j++) {
320         for (i = 0; i < w; i++)
321             dst[i] = (dst[i] + src[i]) >> 1;
322         dst += dst_linesize;
323         src += src_linesize;
324     }
325 }
326
327 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
328 {
329     AVFilterContext *ctx = inlink->dst;
330     EdgeDetectContext *edgedetect = ctx->priv;
331     AVFilterLink *outlink = ctx->outputs[0];
332     int p, direct = 0;
333     AVFrame *out;
334
335     if (edgedetect->mode != MODE_COLORMIX && av_frame_is_writable(in)) {
336         direct = 1;
337         out = in;
338     } else {
339         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
340         if (!out) {
341             av_frame_free(&in);
342             return AVERROR(ENOMEM);
343         }
344         av_frame_copy_props(out, in);
345     }
346
347     for (p = 0; p < edgedetect->nb_planes; p++) {
348         struct plane_info *plane = &edgedetect->planes[p];
349         uint8_t  *tmpbuf     = plane->tmpbuf;
350         uint16_t *gradients  = plane->gradients;
351         int8_t   *directions = plane->directions;
352         const int width      = plane->width;
353         const int height     = plane->height;
354
355         if (!((1 << p) & edgedetect->filter_planes)) {
356             if (!direct)
357                 av_image_copy_plane(out->data[p], out->linesize[p],
358                                     in->data[p], in->linesize[p],
359                                     width, height);
360             continue;
361         }
362
363         /* gaussian filter to reduce noise  */
364         gaussian_blur(ctx, width, height,
365                       tmpbuf,      width,
366                       in->data[p], in->linesize[p]);
367
368         /* compute the 16-bits gradients and directions for the next step */
369         sobel(width, height,
370               gradients, width,
371               directions,width,
372               tmpbuf,    width);
373
374         /* non_maximum_suppression() will actually keep & clip what's necessary and
375          * ignore the rest, so we need a clean output buffer */
376         memset(tmpbuf, 0, width * height);
377         non_maximum_suppression(width, height,
378                                 tmpbuf,    width,
379                                 directions,width,
380                                 gradients, width);
381
382         /* keep high values, or low values surrounded by high values */
383         double_threshold(edgedetect->low_u8, edgedetect->high_u8,
384                          width, height,
385                          out->data[p], out->linesize[p],
386                          tmpbuf,       width);
387
388         if (edgedetect->mode == MODE_COLORMIX) {
389             color_mix(width, height,
390                       out->data[p], out->linesize[p],
391                       in->data[p], in->linesize[p]);
392         }
393     }
394
395     if (!direct)
396         av_frame_free(&in);
397     return ff_filter_frame(outlink, out);
398 }
399
400 static av_cold void uninit(AVFilterContext *ctx)
401 {
402     int p;
403     EdgeDetectContext *edgedetect = ctx->priv;
404
405     for (p = 0; p < edgedetect->nb_planes; p++) {
406         struct plane_info *plane = &edgedetect->planes[p];
407         av_freep(&plane->tmpbuf);
408         av_freep(&plane->gradients);
409         av_freep(&plane->directions);
410     }
411 }
412
413 static const AVFilterPad edgedetect_inputs[] = {
414     {
415         .name         = "default",
416         .type         = AVMEDIA_TYPE_VIDEO,
417         .config_props = config_props,
418         .filter_frame = filter_frame,
419     },
420     { NULL }
421 };
422
423 static const AVFilterPad edgedetect_outputs[] = {
424     {
425         .name = "default",
426         .type = AVMEDIA_TYPE_VIDEO,
427     },
428     { NULL }
429 };
430
431 AVFilter ff_vf_edgedetect = {
432     .name          = "edgedetect",
433     .description   = NULL_IF_CONFIG_SMALL("Detect and draw edge."),
434     .priv_size     = sizeof(EdgeDetectContext),
435     .init          = init,
436     .uninit        = uninit,
437     .query_formats = query_formats,
438     .inputs        = edgedetect_inputs,
439     .outputs       = edgedetect_outputs,
440     .priv_class    = &edgedetect_class,
441     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
442 };