Browse code

lavfi: port libmpcodecs remove-logo filter

The code is based on the remove-logo filter in MPlayer/libmpcodecs, by
Robert Edele, relicensed to LGPL with consent of the author.

Address trac issue #249.

Stefano Sabatini authored on 2012/03/10 22:01:28
Showing 11 changed files
... ...
@@ -21,6 +21,8 @@ version next:
21 21
 - tile video filter
22 22
 - Metal Gear Solid: The Twin Snakes demuxer
23 23
 - OpenEXR image decoder
24
+- removelogo filter
25
+
24 26
 
25 27
 version 0.10:
26 28
 - Fixes: CVE-2011-3929, CVE-2011-3934, CVE-2011-3935, CVE-2011-3936,
... ...
@@ -1688,6 +1688,7 @@ mptestsrc_filter_deps="gpl"
1688 1688
 negate_filter_deps="lut_filter"
1689 1689
 ocv_filter_deps="libopencv"
1690 1690
 pan_filter_deps="swresample"
1691
+removelogo_filter_deps="avcodec avformat swscale"
1691 1692
 scale_filter_deps="swscale"
1692 1693
 tinterlace_filter_deps="gpl"
1693 1694
 yadif_filter_deps="gpl"
... ...
@@ -2237,6 +2237,32 @@ format=monow, pixdesctest
2237 2237
 
2238 2238
 can be used to test the monowhite pixel format descriptor definition.
2239 2239
 
2240
+@section removelogo
2241
+
2242
+Suppress a TV station logo, using an image file to determine which
2243
+pixels comprise the logo. It works by filling in the pixels that
2244
+comprise the logo with neighboring pixels.
2245
+
2246
+This filter requires one argument which specifies the filter bitmap
2247
+file, which can be any image format supported by libavformat. The
2248
+width and height of the image file must match those of the video
2249
+stream being processed.
2250
+
2251
+Pixels in the provided bitmap image with a value of zero are not
2252
+considered part of the logo, non-zero pixels are considered part of
2253
+the logo. If you use white (255) for the logo and black (0) for the
2254
+rest, you will be safe. For making the filter bitmap, it is
2255
+recommended to take a screen capture of a black frame with the logo
2256
+visible, and then using a threshold filter followed by the erode
2257
+filter once or twice.
2258
+
2259
+If needed, little splotches can be fixed manually. Remember that if
2260
+logo pixels are not covered, the filter quality will be much
2261
+reduced. Marking too many pixels as part of the logo does not hurt as
2262
+much, but it will increase the amount of blurring needed to cover over
2263
+the image and will destroy more information than necessary, and extra
2264
+pixels will slow things down on a large logo.
2265
+
2240 2266
 @section scale
2241 2267
 
2242 2268
 Scale the input video to @var{width}:@var{height}[:@var{interl}=@{1|-1@}] and/or convert the image format.
... ...
@@ -8,6 +8,7 @@ FFLIBS-$(CONFIG_AMOVIE_FILTER)               += avformat avcodec
8 8
 FFLIBS-$(CONFIG_ARESAMPLE_FILTER)            += swresample
9 9
 FFLIBS-$(CONFIG_MOVIE_FILTER)                += avformat avcodec
10 10
 FFLIBS-$(CONFIG_PAN_FILTER)                  += swresample
11
+FFLIBS-$(CONFIG_REMOVELOGO_FILTER)           += swscale avformat avcodec
11 12
 FFLIBS-$(CONFIG_SCALE_FILTER)                += swscale
12 13
 FFLIBS-$(CONFIG_MP_FILTER)                   += avcodec postproc
13 14
 
... ...
@@ -25,6 +26,8 @@ OBJS = allfilters.o                                                     \
25 25
        vsrc_buffer.o
26 26
 
27 27
 OBJS-$(CONFIG_AVCODEC)                       += avcodec.o
28
+OBJS-$(CONFIG_AVFORMAT)                      += lavfutils.o
29
+OBJS-$(CONFIG_SWSCALE)                       += lswsutils.o
28 30
 
29 31
 OBJS-$(CONFIG_ACONVERT_FILTER)               += af_aconvert.o
30 32
 OBJS-$(CONFIG_AFORMAT_FILTER)                += af_aformat.o
... ...
@@ -80,6 +83,7 @@ OBJS-$(CONFIG_OCV_FILTER)                    += vf_libopencv.o
80 80
 OBJS-$(CONFIG_OVERLAY_FILTER)                += vf_overlay.o
81 81
 OBJS-$(CONFIG_PAD_FILTER)                    += vf_pad.o
82 82
 OBJS-$(CONFIG_PIXDESCTEST_FILTER)            += vf_pixdesctest.o
83
+OBJS-$(CONFIG_REMOVELOGO_FILTER)             += bbox.o lswsutils.o lavfutils.o vf_removelogo.o
83 84
 OBJS-$(CONFIG_SCALE_FILTER)                  += vf_scale.o
84 85
 OBJS-$(CONFIG_SELECT_FILTER)                 += vf_select.o
85 86
 OBJS-$(CONFIG_SETDAR_FILTER)                 += vf_aspect.o
... ...
@@ -88,6 +88,7 @@ void avfilter_register_all(void)
88 88
     REGISTER_FILTER (OVERLAY,     overlay,     vf);
89 89
     REGISTER_FILTER (PAD,         pad,         vf);
90 90
     REGISTER_FILTER (PIXDESCTEST, pixdesctest, vf);
91
+    REGISTER_FILTER (REMOVELOGO,  removelogo,  vf);
91 92
     REGISTER_FILTER (SCALE,       scale,       vf);
92 93
     REGISTER_FILTER (SELECT,      select,      vf);
93 94
     REGISTER_FILTER (SETDAR,      setdar,      vf);
94 95
new file mode 100644
... ...
@@ -0,0 +1,95 @@
0
+/*
1
+ * This file is part of FFmpeg.
2
+ *
3
+ * FFmpeg is free software; you can redistribute it and/or
4
+ * modify it under the terms of the GNU Lesser General Public
5
+ * License as published by the Free Software Foundation; either
6
+ * version 2.1 of the License, or (at your option) any later version.
7
+ *
8
+ * FFmpeg is distributed in the hope that it will be useful,
9
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11
+ * Lesser General Public License for more details.
12
+ *
13
+ * You should have received a copy of the GNU Lesser General Public
14
+ * License along with FFmpeg; if not, write to the Free Software
15
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
+ */
17
+
18
+#include "libavutil/imgutils.h"
19
+#include "lavfutils.h"
20
+
21
+int ff_load_image(uint8_t *data[4], int linesize[4],
22
+                  int *w, int *h, enum PixelFormat *pix_fmt,
23
+                  const char *filename, void *log_ctx)
24
+{
25
+    AVInputFormat *iformat = NULL;
26
+    AVFormatContext *format_ctx;
27
+    AVCodec *codec;
28
+    AVCodecContext *codec_ctx;
29
+    AVFrame *frame;
30
+    int frame_decoded, ret = 0;
31
+    AVPacket pkt;
32
+
33
+    av_register_all();
34
+
35
+    iformat = av_find_input_format("image2");
36
+    if ((ret = avformat_open_input(&format_ctx, filename, iformat, NULL)) < 0) {
37
+        av_log(log_ctx, AV_LOG_ERROR,
38
+               "Failed to open input file '%s'\n", filename);
39
+        return ret;
40
+    }
41
+
42
+    codec_ctx = format_ctx->streams[0]->codec;
43
+    codec = avcodec_find_decoder(codec_ctx->codec_id);
44
+    if (!codec) {
45
+        av_log(log_ctx, AV_LOG_ERROR, "Failed to find codec\n");
46
+        ret = AVERROR(EINVAL);
47
+        goto end;
48
+    }
49
+
50
+    if ((ret = avcodec_open2(codec_ctx, codec, NULL)) < 0) {
51
+        av_log(log_ctx, AV_LOG_ERROR, "Failed to open codec\n");
52
+        goto end;
53
+    }
54
+
55
+    if (!(frame = avcodec_alloc_frame()) ) {
56
+        av_log(log_ctx, AV_LOG_ERROR, "Failed to alloc frame\n");
57
+        ret = AVERROR(ENOMEM);
58
+        goto end;
59
+    }
60
+
61
+    ret = av_read_frame(format_ctx, &pkt);
62
+    if (ret < 0) {
63
+        av_log(log_ctx, AV_LOG_ERROR, "Failed to read frame from file\n");
64
+        goto end;
65
+    }
66
+
67
+    ret = avcodec_decode_video2(codec_ctx, frame, &frame_decoded, &pkt);
68
+    if (ret < 0 || !frame_decoded) {
69
+        av_log(log_ctx, AV_LOG_ERROR, "Failed to decode image from file\n");
70
+        goto end;
71
+    }
72
+    ret = 0;
73
+
74
+    *w       = frame->width;
75
+    *h       = frame->height;
76
+    *pix_fmt = frame->format;
77
+
78
+    if ((ret = av_image_alloc(data, linesize, *w, *h, *pix_fmt, 16)) < 0)
79
+        goto end;
80
+    ret = 0;
81
+
82
+    av_image_copy(data, linesize, frame->data, frame->linesize, *pix_fmt, *w, *h);
83
+
84
+end:
85
+    if (codec_ctx)
86
+        avcodec_close(codec_ctx);
87
+    if (format_ctx)
88
+        avformat_close_input(&format_ctx);
89
+    av_freep(&frame);
90
+
91
+    if (ret < 0)
92
+        av_log(log_ctx, AV_LOG_ERROR, "Error loading image file '%s'\n", filename);
93
+    return ret;
94
+}
0 95
new file mode 100644
... ...
@@ -0,0 +1,43 @@
0
+/*
1
+ * This file is part of FFmpeg.
2
+ *
3
+ * FFmpeg is free software; you can redistribute it and/or
4
+ * modify it under the terms of the GNU Lesser General Public
5
+ * License as published by the Free Software Foundation; either
6
+ * version 2.1 of the License, or (at your option) any later version.
7
+ *
8
+ * FFmpeg is distributed in the hope that it will be useful,
9
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11
+ * Lesser General Public License for more details.
12
+ *
13
+ * You should have received a copy of the GNU Lesser General Public
14
+ * License along with FFmpeg; if not, write to the Free Software
15
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
+ */
17
+
18
+/**
19
+ * @file
20
+ * Miscellaneous utilities which make use of the libavformat library
21
+ */
22
+
23
+#ifndef AVFILTER_LAVFUTILS_H
24
+#define AVFILTER_LAVFUTILS_H
25
+
26
+#include "libavformat/avformat.h"
27
+
28
+/**
29
+ * Load image from filename and put the resulting image in data.
30
+ *
31
+ * @param w pointer to the width of the loaded image
32
+ * @param h pointer to the height of the loaded image
33
+ * @param pix_fmt pointer to the pixel format of the loaded image
34
+ * @param filename the name of the image file to load
35
+ * @param log_ctx log context
36
+ * @return 0 in case of success, a negative error code otherwise.
37
+ */
38
+int ff_load_image(uint8_t *data[4], int linesize[4],
39
+                  int *w, int *h, enum PixelFormat *pix_fmt,
40
+                  const char *filename, void *log_ctx);
41
+
42
+#endif  /* AVFILTER_LAVFUTILS_H */
0 43
new file mode 100644
... ...
@@ -0,0 +1,50 @@
0
+/*
1
+ * This file is part of FFmpeg.
2
+ *
3
+ * FFmpeg is free software; you can redistribute it and/or
4
+ * modify it under the terms of the GNU Lesser General Public
5
+ * License as published by the Free Software Foundation; either
6
+ * version 2.1 of the License, or (at your option) any later version.
7
+ *
8
+ * FFmpeg is distributed in the hope that it will be useful,
9
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11
+ * Lesser General Public License for more details.
12
+ *
13
+ * You should have received a copy of the GNU Lesser General Public
14
+ * License along with FFmpeg; if not, write to the Free Software
15
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
+ */
17
+
18
+#include "libavutil/imgutils.h"
19
+#include "lswsutils.h"
20
+
21
+int ff_scale_image(uint8_t *dst_data[4], int dst_linesize[4],
22
+                   int dst_w, int dst_h, enum PixelFormat dst_pix_fmt,
23
+                   uint8_t * const src_data[4], int src_linesize[4],
24
+                   int src_w, int src_h, enum PixelFormat src_pix_fmt,
25
+                   void *log_ctx)
26
+{
27
+    int ret;
28
+    struct SwsContext *sws_ctx = sws_getContext(src_w, src_h, src_pix_fmt,
29
+                                                dst_w, dst_h, dst_pix_fmt,
30
+                                                SWS_BILINEAR, NULL, NULL, NULL);
31
+    if (!sws_ctx) {
32
+        av_log(log_ctx, AV_LOG_ERROR,
33
+               "Impossible to create scale context for the conversion "
34
+               "fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n",
35
+               av_get_pix_fmt_name(src_pix_fmt), src_w, src_h,
36
+               av_get_pix_fmt_name(dst_pix_fmt), dst_w, dst_h);
37
+        ret = AVERROR(EINVAL);
38
+        goto end;
39
+    }
40
+
41
+    if ((ret = av_image_alloc(dst_data, dst_linesize, dst_w, dst_h, dst_pix_fmt, 16)) < 0)
42
+        goto end;
43
+    ret = 0;
44
+    sws_scale(sws_ctx, src_data, src_linesize, 0, src_h, dst_data, dst_linesize);
45
+
46
+end:
47
+    sws_freeContext(sws_ctx);
48
+    return ret;
49
+}
0 50
new file mode 100644
... ...
@@ -0,0 +1,38 @@
0
+/*
1
+ * This file is part of FFmpeg.
2
+ *
3
+ * FFmpeg is free software; you can redistribute it and/or
4
+ * modify it under the terms of the GNU Lesser General Public
5
+ * License as published by the Free Software Foundation; either
6
+ * version 2.1 of the License, or (at your option) any later version.
7
+ *
8
+ * FFmpeg is distributed in the hope that it will be useful,
9
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11
+ * Lesser General Public License for more details.
12
+ *
13
+ * You should have received a copy of the GNU Lesser General Public
14
+ * License along with FFmpeg; if not, write to the Free Software
15
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
+ */
17
+
18
+/**
19
+ * @file
20
+ * Miscellaneous utilities which make use of the libswscale library
21
+ */
22
+
23
+#ifndef AVFILTER_LSWSUTILS_H
24
+#define AVFILTER_LSWSUTILS_H
25
+
26
+#include "libswscale/swscale.h"
27
+
28
+/**
29
+ * Scale image using libswscale.
30
+ */
31
+int ff_scale_image(uint8_t *dst_data[4], int dst_linesize[4],
32
+                   int dst_w, int dst_h, enum PixelFormat dst_pix_fmt,
33
+                   uint8_t *const src_data[4], int src_linesize[4],
34
+                   int src_w, int src_h, enum PixelFormat src_pix_fmt,
35
+                   void *log_ctx);
36
+
37
+#endif  /* AVFILTER_LSWSUTILS_H */
... ...
@@ -29,8 +29,8 @@
29 29
 #include "libavutil/avutil.h"
30 30
 
31 31
 #define LIBAVFILTER_VERSION_MAJOR  2
32
-#define LIBAVFILTER_VERSION_MINOR 66
33
-#define LIBAVFILTER_VERSION_MICRO 101
32
+#define LIBAVFILTER_VERSION_MINOR 67
33
+#define LIBAVFILTER_VERSION_MICRO 100
34 34
 
35 35
 #define LIBAVFILTER_VERSION_INT AV_VERSION_INT(LIBAVFILTER_VERSION_MAJOR, \
36 36
                                                LIBAVFILTER_VERSION_MINOR, \
37 37
new file mode 100644
... ...
@@ -0,0 +1,570 @@
0
+/*
1
+ * Copyright (c) 2005 Robert Edele <yartrebo@earthlink.net>
2
+ * Copyright (c) 2012 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
+/**
22
+ * @file advanced blur-based logo removing filter
23
+ *
24
+ * This filter loads an image mask file showing where a logo is and
25
+ * uses a blur transform to remove the logo.
26
+ *
27
+ * Based on the libmpcodecs remove-logo filter by Robert Edele.
28
+ */
29
+
30
+/**
31
+ * This code implements a filter to remove annoying TV logos and other annoying
32
+ * images placed onto a video stream. It works by filling in the pixels that
33
+ * comprise the logo with neighboring pixels. The transform is very loosely
34
+ * based on a gaussian blur, but it is different enough to merit its own
35
+ * paragraph later on. It is a major improvement on the old delogo filter as it
36
+ * both uses a better blurring algorithm and uses a bitmap to use an arbitrary
37
+ * and generally much tighter fitting shape than a rectangle.
38
+ *
39
+ * The logo removal algorithm has two key points. The first is that it
40
+ * distinguishes between pixels in the logo and those not in the logo by using
41
+ * the passed-in bitmap. Pixels not in the logo are copied over directly without
42
+ * being modified and they also serve as source pixels for the logo
43
+ * fill-in. Pixels inside the logo have the mask applied.
44
+ *
45
+ * At init-time the bitmap is reprocessed internally, and the distance to the
46
+ * nearest edge of the logo (Manhattan distance), along with a little extra to
47
+ * remove rough edges, is stored in each pixel. This is done using an in-place
48
+ * erosion algorithm, and incrementing each pixel that survives any given
49
+ * erosion.  Once every pixel is eroded, the maximum value is recorded, and a
50
+ * set of masks from size 0 to this size are generaged. The masks are circular
51
+ * binary masks, where each pixel within a radius N (where N is the size of the
52
+ * mask) is a 1, and all other pixels are a 0. Although a gaussian mask would be
53
+ * more mathematically accurate, a binary mask works better in practice because
54
+ * we generally do not use the central pixels in the mask (because they are in
55
+ * the logo region), and thus a gaussian mask will cause too little blur and
56
+ * thus a very unstable image.
57
+ *
58
+ * The mask is applied in a special way. Namely, only pixels in the mask that
59
+ * line up to pixels outside the logo are used. The dynamic mask size means that
60
+ * the mask is just big enough so that the edges touch pixels outside the logo,
61
+ * so the blurring is kept to a minimum and at least the first boundary
62
+ * condition is met (that the image function itself is continuous), even if the
63
+ * second boundary condition (that the derivative of the image function is
64
+ * continuous) is not met. A masking algorithm that does preserve the second
65
+ * boundary coundition (perhaps something based on a highly-modified bi-cubic
66
+ * algorithm) should offer even better results on paper, but the noise in a
67
+ * typical TV signal should make anything based on derivatives hopelessly noisy.
68
+ */
69
+
70
+#include "libavutil/imgutils.h"
71
+#include "avfilter.h"
72
+#include "bbox.h"
73
+#include "lavfutils.h"
74
+#include "lswsutils.h"
75
+
76
+typedef struct {
77
+    /* Stores our collection of masks. The first is for an array of
78
+       the second for the y axis, and the third for the x axis. */
79
+    int ***mask;
80
+    int max_mask_size;
81
+    int mask_w, mask_h;
82
+
83
+    uint8_t      *full_mask_data;
84
+    FFBoundingBox full_mask_bbox;
85
+    uint8_t      *half_mask_data;
86
+    FFBoundingBox half_mask_bbox;
87
+} RemovelogoContext;
88
+
89
+/**
90
+ * Choose a slightly larger mask size to improve performance.
91
+ *
92
+ * This function maps the absolute minimum mask size needed to the
93
+ * mask size we'll actually use. f(x) = x (the smallest that will
94
+ * work) will produce the sharpest results, but will be quite
95
+ * jittery. f(x) = 1.25x (what I'm using) is a good tradeoff in my
96
+ * opinion. This will calculate only at init-time, so you can put a
97
+ * long expression here without effecting performance.
98
+ */
99
+#define apply_mask_fudge_factor(x) (((x) >> 2) + x)
100
+
101
+/**
102
+ * Pre-process an image to give distance information.
103
+ *
104
+ * This function takes a bitmap image and converts it in place into a
105
+ * distance image. A distance image is zero for pixels outside of the
106
+ * logo and is the Manhattan distance (|dx| + |dy|) from the logo edge
107
+ * for pixels inside of the logo. This will overestimate the distance,
108
+ * but that is safe, and is far easier to implement than a proper
109
+ * pythagorean distance since I'm using a modified erosion algorithm
110
+ * to compute the distances.
111
+ *
112
+ * @param mask image which will be converted from a greyscale image
113
+ * into a distance image.
114
+ */
115
+static void convert_mask_to_strength_mask(uint8_t *data, int linesize,
116
+                                          int w, int h, int min_val,
117
+                                          int *max_mask_size)
118
+{
119
+    int x, y;
120
+
121
+    /* How many times we've gone through the loop. Used in the
122
+       in-place erosion algorithm and to get us max_mask_size later on. */
123
+    int current_pass = 0;
124
+
125
+    /* set all non-zero values to 1 */
126
+    for (y = 0; y < h; y++)
127
+        for (x = 0; x < w; x++)
128
+            data[y*linesize + x] = data[y*linesize + x] > min_val;
129
+
130
+    /* For each pass, if a pixel is itself the same value as the
131
+       current pass, and its four neighbors are too, then it is
132
+       incremented. If no pixels are incremented by the end of the
133
+       pass, then we go again. Edge pixels are counted as always
134
+       excluded (this should be true anyway for any sane mask, but if
135
+       it isn't this will ensure that we eventually exit). */
136
+    while (1) {
137
+        /* If this doesn't get set by the end of this pass, then we're done. */
138
+        int has_anything_changed = 0;
139
+        uint8_t *current_pixel0 = data, *current_pixel;
140
+        current_pass++;
141
+
142
+        for (y = 1; y < h-1; y++) {
143
+            current_pixel = current_pixel0;
144
+            for (x = 1; x < w-1; x++) {
145
+                /* Apply the in-place erosion transform. It is based
146
+                   on the following two premises:
147
+                   1 - Any pixel that fails 1 erosion will fail all
148
+                       future erosions.
149
+
150
+                   2 - Only pixels having survived all erosions up to
151
+                       the present will be >= to current_pass.
152
+                   It doesn't matter if it survived the current pass,
153
+                   failed it, or hasn't been tested yet.  By using >=
154
+                   instead of ==, we allow the algorithm to work in
155
+                   place. */
156
+                if ( *current_pixel      >= current_pass &&
157
+                    *(current_pixel + 1) >= current_pass &&
158
+                    *(current_pixel - 1) >= current_pass &&
159
+                    *(current_pixel + w) >= current_pass &&
160
+                    *(current_pixel - w) >= current_pass) {
161
+                    /* Increment the value since it still has not been
162
+                     * eroded, as evidenced by the if statement that
163
+                     * just evaluated to true. */
164
+                    (*current_pixel)++;
165
+                    has_anything_changed = 1;
166
+                }
167
+                current_pixel++;
168
+            }
169
+            current_pixel0 += linesize;
170
+        }
171
+        if (!has_anything_changed)
172
+            break;
173
+    }
174
+
175
+    /* Apply the fudge factor, which will increase the size of the
176
+     * mask a little to reduce jitter at the cost of more blur. */
177
+    for (y = 1; y < h - 1; y++)
178
+        for (x = 1; x < w - 1; x++)
179
+            data[(y * linesize) + x] = apply_mask_fudge_factor(data[(y * linesize) + x]);
180
+
181
+    /* As a side-effect, we now know the maximum mask size, which
182
+     * we'll use to generate our masks. */
183
+    /* Apply the fudge factor to this number too, since we must ensure
184
+     * that enough masks are generated. */
185
+    *max_mask_size = apply_mask_fudge_factor(current_pass + 1);
186
+}
187
+
188
+static int query_formats(AVFilterContext *ctx)
189
+{
190
+    enum PixelFormat pix_fmts[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
191
+    avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
192
+    return 0;
193
+}
194
+
195
+static int load_mask(uint8_t **mask, int *w, int *h,
196
+                     const char *filename, void *log_ctx)
197
+{
198
+    int ret;
199
+    enum PixelFormat pix_fmt;
200
+    uint8_t *src_data[4], *gray_data[4];
201
+    int src_linesize[4], gray_linesize[4];
202
+
203
+    /* load image from file */
204
+    if ((ret = ff_load_image(src_data, src_linesize, w, h, &pix_fmt, filename, log_ctx)) < 0)
205
+        return ret;
206
+
207
+    /* convert the image to GRAY8 */
208
+    if ((ret = ff_scale_image(gray_data, gray_linesize, *w, *h, PIX_FMT_GRAY8,
209
+                              src_data, src_linesize, *w, *h, pix_fmt,
210
+                              log_ctx)) < 0)
211
+        goto end;
212
+
213
+    /* copy mask to a newly allocated array */
214
+    *mask = av_malloc(*w * *h);
215
+    if (!*mask)
216
+        ret = AVERROR(ENOMEM);
217
+    av_image_copy_plane(*mask, *w, gray_data[0], gray_linesize[0], *w, *h);
218
+
219
+end:
220
+    av_free(src_data[0]);
221
+    av_free(gray_data[0]);
222
+    return ret;
223
+}
224
+
225
+/**
226
+ * Generate a scaled down image with half width, height, and intensity.
227
+ *
228
+ * This function not only scales down an image, but halves the value
229
+ * in each pixel too. The purpose of this is to produce a chroma
230
+ * filter image out of a luma filter image. The pixel values store the
231
+ * distance to the edge of the logo and halving the dimensions halves
232
+ * the distance. This function rounds up, because a downwards rounding
233
+ * error could cause the filter to fail, but an upwards rounding error
234
+ * will only cause a minor amount of excess blur in the chroma planes.
235
+ */
236
+static void generate_half_size_image(const uint8_t *src_data, int src_linesize,
237
+                                     uint8_t *dst_data, int dst_linesize,
238
+                                     int src_w, int src_h,
239
+                                     int *max_mask_size)
240
+{
241
+    int x, y;
242
+
243
+    /* Copy over the image data, using the average of 4 pixels for to
244
+     * calculate each downsampled pixel. */
245
+    for (y = 0; y < src_h/2; y++) {
246
+        for (x = 0; x < src_w/2; x++) {
247
+            /* Set the pixel if there exists a non-zero value in the
248
+             * source pixels, else clear it. */
249
+            dst_data[(y * dst_linesize) + x] =
250
+                src_data[((y << 1) * src_linesize) + (x << 1)] ||
251
+                src_data[((y << 1) * src_linesize) + (x << 1) + 1] ||
252
+                src_data[(((y << 1) + 1) * src_linesize) + (x << 1)] ||
253
+                src_data[(((y << 1) + 1) * src_linesize) + (x << 1) + 1];
254
+            dst_data[(y * dst_linesize) + x] = FFMIN(1, dst_data[(y * dst_linesize) + x]);
255
+        }
256
+    }
257
+
258
+    convert_mask_to_strength_mask(dst_data, dst_linesize,
259
+                                  src_w/2, src_h/2, 0, max_mask_size);
260
+}
261
+
262
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
263
+{
264
+    RemovelogoContext *removelogo = ctx->priv;
265
+    int ***mask;
266
+    int ret = 0;
267
+    int a, b, c, w, h;
268
+    int full_max_mask_size, half_max_mask_size;
269
+
270
+    if (!args) {
271
+        av_log(ctx, AV_LOG_ERROR, "An image file must be specified as argument\n");
272
+        return AVERROR(EINVAL);
273
+    }
274
+
275
+    /* Load our mask image. */
276
+    if ((ret = load_mask(&removelogo->full_mask_data, &w, &h, args, ctx)) < 0)
277
+        return ret;
278
+    removelogo->mask_w = w;
279
+    removelogo->mask_h = h;
280
+
281
+    convert_mask_to_strength_mask(removelogo->full_mask_data, w, w, h,
282
+                                  16, &full_max_mask_size);
283
+
284
+    /* Create the scaled down mask image for the chroma planes. */
285
+    if (!(removelogo->half_mask_data = av_mallocz(w/2 * h/2)))
286
+        return AVERROR(ENOMEM);
287
+    generate_half_size_image(removelogo->full_mask_data, w,
288
+                             removelogo->half_mask_data, w/2,
289
+                             w, h, &half_max_mask_size);
290
+
291
+    removelogo->max_mask_size = FFMAX(full_max_mask_size, half_max_mask_size);
292
+
293
+    /* Create a circular mask for each size up to max_mask_size. When
294
+       the filter is applied, the mask size is determined on a pixel
295
+       by pixel basis, with pixels nearer the edge of the logo getting
296
+       smaller mask sizes. */
297
+    mask = (int ***)av_malloc(sizeof(int **) * (removelogo->max_mask_size + 1));
298
+    if (!mask)
299
+        return AVERROR(ENOMEM);
300
+
301
+    for (a = 0; a <= removelogo->max_mask_size; a++) {
302
+        mask[a] = (int **)av_malloc(sizeof(int *) * ((a * 2) + 1));
303
+        if (!mask[a])
304
+            return AVERROR(ENOMEM);
305
+        for (b = -a; b <= a; b++) {
306
+            mask[a][b + a] = (int *)av_malloc(sizeof(int) * ((a * 2) + 1));
307
+            if (!mask[a][b + a])
308
+                return AVERROR(ENOMEM);
309
+            for (c = -a; c <= a; c++) {
310
+                if ((b * b) + (c * c) <= (a * a)) /* Circular 0/1 mask. */
311
+                    mask[a][b + a][c + a] = 1;
312
+                else
313
+                    mask[a][b + a][c + a] = 0;
314
+            }
315
+        }
316
+    }
317
+    removelogo->mask = mask;
318
+
319
+    /* Calculate our bounding rectangles, which determine in what
320
+     * region the logo resides for faster processing. */
321
+    ff_calculate_bounding_box(&removelogo->full_mask_bbox, removelogo->full_mask_data, w, w, h, 0);
322
+    ff_calculate_bounding_box(&removelogo->half_mask_bbox, removelogo->half_mask_data, w/2, w/2, h/2, 0);
323
+
324
+#define SHOW_LOGO_INFO(mask_type)                                       \
325
+    av_log(ctx, AV_LOG_INFO, #mask_type " x1:%d x2:%d y1:%d y2:%d max_mask_size:%d\n", \
326
+           removelogo->mask_type##_mask_bbox.x1, removelogo->mask_type##_mask_bbox.x2, \
327
+           removelogo->mask_type##_mask_bbox.y1, removelogo->mask_type##_mask_bbox.y2, \
328
+           mask_type##_max_mask_size);
329
+    SHOW_LOGO_INFO(full);
330
+    SHOW_LOGO_INFO(half);
331
+
332
+    return 0;
333
+}
334
+
335
+static int config_props_input(AVFilterLink *inlink)
336
+{
337
+    AVFilterContext *ctx = inlink->dst;
338
+    RemovelogoContext *removelogo = ctx->priv;
339
+
340
+    if (inlink->w != removelogo->mask_w || inlink->h != removelogo->mask_h) {
341
+        av_log(ctx, AV_LOG_INFO,
342
+               "Mask image size %dx%d does not match with the input video size %dx%d\n",
343
+               removelogo->mask_w, removelogo->mask_h, inlink->w, inlink->h);
344
+        return AVERROR(EINVAL);
345
+    }
346
+
347
+    return 0;
348
+}
349
+
350
+/**
351
+ * Blur image.
352
+ *
353
+ * It takes a pixel that is inside the mask and blurs it. It does so
354
+ * by finding the average of all the pixels within the mask and
355
+ * outside of the mask.
356
+ *
357
+ * @param mask_data  the mask plane to use for averaging
358
+ * @param image_data the image plane to blur
359
+ * @param w width of the image
360
+ * @param h height of the image
361
+ * @param x x-coordinate of the pixel to blur
362
+ * @param y y-coordinate of the pixel to blur
363
+ */
364
+static unsigned int blur_pixel(int ***mask,
365
+                               const uint8_t *mask_data, int mask_linesize,
366
+                               uint8_t       *image_data, int image_linesize,
367
+                               int w, int h, int x, int y)
368
+{
369
+    /* Mask size tells how large a circle to use. The radius is about
370
+     * (slightly larger than) mask size. */
371
+    int mask_size;
372
+    int start_posx, start_posy, end_posx, end_posy;
373
+    int i, j;
374
+    unsigned int accumulator = 0, divisor = 0;
375
+    /* What pixel we are reading out of the circular blur mask. */
376
+    const uint8_t *image_read_position;
377
+    /* What pixel we are reading out of the filter image. */
378
+    const uint8_t *mask_read_position;
379
+
380
+    /* Prepare our bounding rectangle and clip it if need be. */
381
+    mask_size  = mask_data[y * mask_linesize + x];
382
+    start_posx = FFMAX(0, x - mask_size);
383
+    start_posy = FFMAX(0, y - mask_size);
384
+    end_posx   = FFMIN(w - 1, x + mask_size);
385
+    end_posy   = FFMIN(h - 1, y + mask_size);
386
+
387
+    image_read_position = image_data + image_linesize * start_posy + start_posx;
388
+    mask_read_position  = mask_data  + mask_linesize  * start_posy + start_posx;
389
+
390
+    for (j = start_posy; j <= end_posy; j++) {
391
+        for (i = start_posx; i <= end_posx; i++) {
392
+            /* Check if this pixel is in the mask or not. Only use the
393
+             * pixel if it is not. */
394
+            if (!(*mask_read_position) && mask[mask_size][i - start_posx][j - start_posy]) {
395
+                accumulator += *image_read_position;
396
+                divisor++;
397
+            }
398
+
399
+            image_read_position++;
400
+            mask_read_position++;
401
+        }
402
+
403
+        image_read_position += (image_linesize - ((end_posx + 1) - start_posx));
404
+        mask_read_position  += (mask_linesize - ((end_posx + 1) - start_posx));
405
+    }
406
+
407
+    /* If divisor is 0, it means that not a single pixel is outside of
408
+       the logo, so we have no data.  Else we need to normalise the
409
+       data using the divisor. */
410
+    return divisor == 0 ? 255:
411
+        (accumulator + (divisor / 2)) / divisor;  /* divide, taking into account average rounding error */
412
+}
413
+
414
+/**
415
+ * Blur image plane using a mask.
416
+ *
417
+ * @param source The image to have it's logo removed.
418
+ * @param destination Where the output image will be stored.
419
+ * @param source_stride How far apart (in memory) two consecutive lines are.
420
+ * @param destination Same as source_stride, but for the destination image.
421
+ * @param width Width of the image. This is the same for source and destination.
422
+ * @param height Height of the image. This is the same for source and destination.
423
+ * @param is_image_direct If the image is direct, then source and destination are
424
+ *        the same and we can save a lot of time by not copying pixels that
425
+ *        haven't changed.
426
+ * @param filter The image that stores the distance to the edge of the logo for
427
+ *        each pixel.
428
+ * @param logo_start_x smallest x-coordinate that contains at least 1 logo pixel.
429
+ * @param logo_start_y smallest y-coordinate that contains at least 1 logo pixel.
430
+ * @param logo_end_x   largest x-coordinate that contains at least 1 logo pixel.
431
+ * @param logo_end_y   largest y-coordinate that contains at least 1 logo pixel.
432
+ *
433
+ * This function processes an entire plane. Pixels outside of the logo are copied
434
+ * to the output without change, and pixels inside the logo have the de-blurring
435
+ * function applied.
436
+ */
437
+static void blur_image(int ***mask,
438
+                       const uint8_t *src_data,  int src_linesize,
439
+                             uint8_t *dst_data,  int dst_linesize,
440
+                       const uint8_t *mask_data, int mask_linesize,
441
+                       int w, int h, int direct,
442
+                       FFBoundingBox *bbox)
443
+{
444
+    int x, y;
445
+    uint8_t *dst_line;
446
+    const uint8_t *src_line;
447
+
448
+    if (!direct)
449
+        av_image_copy_plane(dst_data, dst_linesize, src_data, src_linesize, w, h);
450
+
451
+    for (y = bbox->y1; y <= bbox->y2; y++) {
452
+        src_line = src_data + src_linesize * y;
453
+        dst_line = dst_data + dst_linesize * y;
454
+
455
+        for (x = bbox->x1; x <= bbox->x2; x++) {
456
+             if (mask_data[y * mask_linesize + x]) {
457
+                /* Only process if we are in the mask. */
458
+                 dst_line[x] = blur_pixel(mask,
459
+                                          mask_data, mask_linesize,
460
+                                          dst_data, dst_linesize,
461
+                                          w, h, x, y);
462
+            } else {
463
+                /* Else just copy the data. */
464
+                if (!direct)
465
+                    dst_line[x] = src_line[x];
466
+            }
467
+        }
468
+    }
469
+}
470
+
471
+static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
472
+{
473
+    AVFilterLink *outlink = inlink->dst->outputs[0];
474
+    AVFilterBufferRef *outpicref;
475
+
476
+    if (inpicref->perms & AV_PERM_PRESERVE) {
477
+        outpicref = avfilter_get_video_buffer(outlink, AV_PERM_WRITE,
478
+                                              outlink->w, outlink->h);
479
+        avfilter_copy_buffer_ref_props(outpicref, inpicref);
480
+        outpicref->video->w = outlink->w;
481
+        outpicref->video->h = outlink->h;
482
+    } else
483
+        outpicref = inpicref;
484
+
485
+    outlink->out_buf = outpicref;
486
+    avfilter_start_frame(outlink, avfilter_ref_buffer(outpicref, ~0));
487
+}
488
+
489
+static void end_frame(AVFilterLink *inlink)
490
+{
491
+    RemovelogoContext *removelogo = inlink->dst->priv;
492
+    AVFilterLink *outlink = inlink->dst->outputs[0];
493
+    AVFilterBufferRef *inpicref  = inlink ->cur_buf;
494
+    AVFilterBufferRef *outpicref = outlink->out_buf;
495
+    int direct = inpicref == outpicref;
496
+
497
+    blur_image(removelogo->mask,
498
+               inpicref ->data[0], inpicref ->linesize[0],
499
+               outpicref->data[0], outpicref->linesize[0],
500
+               removelogo->full_mask_data, inlink->w,
501
+               inlink->w, inlink->h, direct, &removelogo->full_mask_bbox);
502
+    blur_image(removelogo->mask,
503
+               inpicref ->data[1], inpicref ->linesize[1],
504
+               outpicref->data[1], outpicref->linesize[1],
505
+               removelogo->half_mask_data, inlink->w/2,
506
+               inlink->w/2, inlink->h/2, direct, &removelogo->half_mask_bbox);
507
+    blur_image(removelogo->mask,
508
+               inpicref ->data[2], inpicref ->linesize[2],
509
+               outpicref->data[2], outpicref->linesize[2],
510
+               removelogo->half_mask_data, inlink->w/2,
511
+               inlink->w/2, inlink->h/2, direct, &removelogo->half_mask_bbox);
512
+
513
+    avfilter_draw_slice(outlink, 0, inlink->h, 1);
514
+    avfilter_end_frame(outlink);
515
+    avfilter_unref_buffer(inpicref);
516
+    if (!direct)
517
+        avfilter_unref_buffer(outpicref);
518
+}
519
+
520
+static void uninit(AVFilterContext *ctx)
521
+{
522
+    RemovelogoContext *removelogo = ctx->priv;
523
+    int a, b;
524
+
525
+    av_freep(&removelogo->full_mask_data);
526
+    av_freep(&removelogo->half_mask_data);
527
+
528
+    if (removelogo->mask) {
529
+        /* Loop through each mask. */
530
+        for (a = 0; a <= removelogo->max_mask_size; a++) {
531
+            /* Loop through each scanline in a mask. */
532
+            for (b = -a; b <= a; b++) {
533
+                av_free(removelogo->mask[a][b + a]); /* Free a scanline. */
534
+            }
535
+            av_free(removelogo->mask[a]);
536
+        }
537
+        /* Free the array of pointers pointing to the masks. */
538
+        av_freep(&removelogo->mask);
539
+    }
540
+}
541
+
542
+static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
543
+
544
+AVFilter avfilter_vf_removelogo = {
545
+    .name          = "removelogo",
546
+    .description   = NULL_IF_CONFIG_SMALL("Remove a TV logo based on a mask image."),
547
+    .priv_size     = sizeof(RemovelogoContext),
548
+    .init          = init,
549
+    .uninit        = uninit,
550
+    .query_formats = query_formats,
551
+
552
+    .inputs = (const AVFilterPad[]) {
553
+        { .name             = "default",
554
+          .type             = AVMEDIA_TYPE_VIDEO,
555
+          .get_video_buffer = avfilter_null_get_video_buffer,
556
+          .config_props     = config_props_input,
557
+          .draw_slice       = null_draw_slice,
558
+          .start_frame      = start_frame,
559
+          .end_frame        = end_frame,
560
+          .min_perms        = AV_PERM_WRITE | AV_PERM_READ,
561
+          .rej_perms        = AV_PERM_PRESERVE },
562
+        { .name = NULL }
563
+    },
564
+    .outputs = (const AVFilterPad[]) {
565
+        { .name             = "default",
566
+          .type             = AVMEDIA_TYPE_VIDEO, },
567
+        { .name = NULL }
568
+    },
569
+};