2 * Copyright (c) 2005 Robert Edele <yartrebo@earthlink.net>
3 * Copyright (c) 2012 Stefano Sabatini
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * Advanced blur-based logo removing filter
26 * This filter loads an image mask file showing where a logo is and
27 * uses a blur transform to remove the logo.
29 * Based on the libmpcodecs remove-logo filter by Robert Edele.
33 * This code implements a filter to remove annoying TV logos and other annoying
34 * images placed onto a video stream. It works by filling in the pixels that
35 * comprise the logo with neighboring pixels. The transform is very loosely
36 * based on a gaussian blur, but it is different enough to merit its own
37 * paragraph later on. It is a major improvement on the old delogo filter as it
38 * both uses a better blurring algorithm and uses a bitmap to use an arbitrary
39 * and generally much tighter fitting shape than a rectangle.
41 * The logo removal algorithm has two key points. The first is that it
42 * distinguishes between pixels in the logo and those not in the logo by using
43 * the passed-in bitmap. Pixels not in the logo are copied over directly without
44 * being modified and they also serve as source pixels for the logo
45 * fill-in. Pixels inside the logo have the mask applied.
47 * At init-time the bitmap is reprocessed internally, and the distance to the
48 * nearest edge of the logo (Manhattan distance), along with a little extra to
49 * remove rough edges, is stored in each pixel. This is done using an in-place
50 * erosion algorithm, and incrementing each pixel that survives any given
51 * erosion. Once every pixel is eroded, the maximum value is recorded, and a
52 * set of masks from size 0 to this size are generaged. The masks are circular
53 * binary masks, where each pixel within a radius N (where N is the size of the
54 * mask) is a 1, and all other pixels are a 0. Although a gaussian mask would be
55 * more mathematically accurate, a binary mask works better in practice because
56 * we generally do not use the central pixels in the mask (because they are in
57 * the logo region), and thus a gaussian mask will cause too little blur and
58 * thus a very unstable image.
60 * The mask is applied in a special way. Namely, only pixels in the mask that
61 * line up to pixels outside the logo are used. The dynamic mask size means that
62 * the mask is just big enough so that the edges touch pixels outside the logo,
63 * so the blurring is kept to a minimum and at least the first boundary
64 * condition is met (that the image function itself is continuous), even if the
65 * second boundary condition (that the derivative of the image function is
66 * continuous) is not met. A masking algorithm that does preserve the second
67 * boundary coundition (perhaps something based on a highly-modified bi-cubic
68 * algorithm) should offer even better results on paper, but the noise in a
69 * typical TV signal should make anything based on derivatives hopelessly noisy.
72 #include "libavutil/imgutils.h"
75 #include "lavfutils.h"
76 #include "lswsutils.h"
79 /* Stores our collection of masks. The first is for an array of
80 the second for the y axis, and the third for the x axis. */
85 uint8_t *full_mask_data;
86 FFBoundingBox full_mask_bbox;
87 uint8_t *half_mask_data;
88 FFBoundingBox half_mask_bbox;
92 * Choose a slightly larger mask size to improve performance.
94 * This function maps the absolute minimum mask size needed to the
95 * mask size we'll actually use. f(x) = x (the smallest that will
96 * work) will produce the sharpest results, but will be quite
97 * jittery. f(x) = 1.25x (what I'm using) is a good tradeoff in my
98 * opinion. This will calculate only at init-time, so you can put a
99 * long expression here without effecting performance.
101 #define apply_mask_fudge_factor(x) (((x) >> 2) + x)
104 * Pre-process an image to give distance information.
106 * This function takes a bitmap image and converts it in place into a
107 * distance image. A distance image is zero for pixels outside of the
108 * logo and is the Manhattan distance (|dx| + |dy|) from the logo edge
109 * for pixels inside of the logo. This will overestimate the distance,
110 * but that is safe, and is far easier to implement than a proper
111 * pythagorean distance since I'm using a modified erosion algorithm
112 * to compute the distances.
114 * @param mask image which will be converted from a greyscale image
115 * into a distance image.
117 static void convert_mask_to_strength_mask(uint8_t *data, int linesize,
118 int w, int h, int min_val,
123 /* How many times we've gone through the loop. Used in the
124 in-place erosion algorithm and to get us max_mask_size later on. */
125 int current_pass = 0;
127 /* set all non-zero values to 1 */
128 for (y = 0; y < h; y++)
129 for (x = 0; x < w; x++)
130 data[y*linesize + x] = data[y*linesize + x] > min_val;
132 /* For each pass, if a pixel is itself the same value as the
133 current pass, and its four neighbors are too, then it is
134 incremented. If no pixels are incremented by the end of the
135 pass, then we go again. Edge pixels are counted as always
136 excluded (this should be true anyway for any sane mask, but if
137 it isn't this will ensure that we eventually exit). */
139 /* If this doesn't get set by the end of this pass, then we're done. */
140 int has_anything_changed = 0;
141 uint8_t *current_pixel0 = data, *current_pixel;
144 for (y = 1; y < h-1; y++) {
145 current_pixel = current_pixel0;
146 for (x = 1; x < w-1; x++) {
147 /* Apply the in-place erosion transform. It is based
148 on the following two premises:
149 1 - Any pixel that fails 1 erosion will fail all
152 2 - Only pixels having survived all erosions up to
153 the present will be >= to current_pass.
154 It doesn't matter if it survived the current pass,
155 failed it, or hasn't been tested yet. By using >=
156 instead of ==, we allow the algorithm to work in
158 if ( *current_pixel >= current_pass &&
159 *(current_pixel + 1) >= current_pass &&
160 *(current_pixel - 1) >= current_pass &&
161 *(current_pixel + w) >= current_pass &&
162 *(current_pixel - w) >= current_pass) {
163 /* Increment the value since it still has not been
164 * eroded, as evidenced by the if statement that
165 * just evaluated to true. */
167 has_anything_changed = 1;
171 current_pixel0 += linesize;
173 if (!has_anything_changed)
177 /* Apply the fudge factor, which will increase the size of the
178 * mask a little to reduce jitter at the cost of more blur. */
179 for (y = 1; y < h - 1; y++)
180 for (x = 1; x < w - 1; x++)
181 data[(y * linesize) + x] = apply_mask_fudge_factor(data[(y * linesize) + x]);
183 /* As a side-effect, we now know the maximum mask size, which
184 * we'll use to generate our masks. */
185 /* Apply the fudge factor to this number too, since we must ensure
186 * that enough masks are generated. */
187 *max_mask_size = apply_mask_fudge_factor(current_pass + 1);
190 static int query_formats(AVFilterContext *ctx)
192 enum PixelFormat pix_fmts[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
193 avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
197 static int load_mask(uint8_t **mask, int *w, int *h,
198 const char *filename, void *log_ctx)
201 enum PixelFormat pix_fmt;
202 uint8_t *src_data[4], *gray_data[4];
203 int src_linesize[4], gray_linesize[4];
205 /* load image from file */
206 if ((ret = ff_load_image(src_data, src_linesize, w, h, &pix_fmt, filename, log_ctx)) < 0)
209 /* convert the image to GRAY8 */
210 if ((ret = ff_scale_image(gray_data, gray_linesize, *w, *h, PIX_FMT_GRAY8,
211 src_data, src_linesize, *w, *h, pix_fmt,
215 /* copy mask to a newly allocated array */
216 *mask = av_malloc(*w * *h);
218 ret = AVERROR(ENOMEM);
219 av_image_copy_plane(*mask, *w, gray_data[0], gray_linesize[0], *w, *h);
222 av_free(src_data[0]);
223 av_free(gray_data[0]);
228 * Generate a scaled down image with half width, height, and intensity.
230 * This function not only scales down an image, but halves the value
231 * in each pixel too. The purpose of this is to produce a chroma
232 * filter image out of a luma filter image. The pixel values store the
233 * distance to the edge of the logo and halving the dimensions halves
234 * the distance. This function rounds up, because a downwards rounding
235 * error could cause the filter to fail, but an upwards rounding error
236 * will only cause a minor amount of excess blur in the chroma planes.
238 static void generate_half_size_image(const uint8_t *src_data, int src_linesize,
239 uint8_t *dst_data, int dst_linesize,
240 int src_w, int src_h,
245 /* Copy over the image data, using the average of 4 pixels for to
246 * calculate each downsampled pixel. */
247 for (y = 0; y < src_h/2; y++) {
248 for (x = 0; x < src_w/2; x++) {
249 /* Set the pixel if there exists a non-zero value in the
250 * source pixels, else clear it. */
251 dst_data[(y * dst_linesize) + x] =
252 src_data[((y << 1) * src_linesize) + (x << 1)] ||
253 src_data[((y << 1) * src_linesize) + (x << 1) + 1] ||
254 src_data[(((y << 1) + 1) * src_linesize) + (x << 1)] ||
255 src_data[(((y << 1) + 1) * src_linesize) + (x << 1) + 1];
256 dst_data[(y * dst_linesize) + x] = FFMIN(1, dst_data[(y * dst_linesize) + x]);
260 convert_mask_to_strength_mask(dst_data, dst_linesize,
261 src_w/2, src_h/2, 0, max_mask_size);
264 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
266 RemovelogoContext *removelogo = ctx->priv;
270 int full_max_mask_size, half_max_mask_size;
273 av_log(ctx, AV_LOG_ERROR, "An image file must be specified as argument\n");
274 return AVERROR(EINVAL);
277 /* Load our mask image. */
278 if ((ret = load_mask(&removelogo->full_mask_data, &w, &h, args, ctx)) < 0)
280 removelogo->mask_w = w;
281 removelogo->mask_h = h;
283 convert_mask_to_strength_mask(removelogo->full_mask_data, w, w, h,
284 16, &full_max_mask_size);
286 /* Create the scaled down mask image for the chroma planes. */
287 if (!(removelogo->half_mask_data = av_mallocz(w/2 * h/2)))
288 return AVERROR(ENOMEM);
289 generate_half_size_image(removelogo->full_mask_data, w,
290 removelogo->half_mask_data, w/2,
291 w, h, &half_max_mask_size);
293 removelogo->max_mask_size = FFMAX(full_max_mask_size, half_max_mask_size);
295 /* Create a circular mask for each size up to max_mask_size. When
296 the filter is applied, the mask size is determined on a pixel
297 by pixel basis, with pixels nearer the edge of the logo getting
298 smaller mask sizes. */
299 mask = (int ***)av_malloc(sizeof(int **) * (removelogo->max_mask_size + 1));
301 return AVERROR(ENOMEM);
303 for (a = 0; a <= removelogo->max_mask_size; a++) {
304 mask[a] = (int **)av_malloc(sizeof(int *) * ((a * 2) + 1));
306 return AVERROR(ENOMEM);
307 for (b = -a; b <= a; b++) {
308 mask[a][b + a] = (int *)av_malloc(sizeof(int) * ((a * 2) + 1));
310 return AVERROR(ENOMEM);
311 for (c = -a; c <= a; c++) {
312 if ((b * b) + (c * c) <= (a * a)) /* Circular 0/1 mask. */
313 mask[a][b + a][c + a] = 1;
315 mask[a][b + a][c + a] = 0;
319 removelogo->mask = mask;
321 /* Calculate our bounding rectangles, which determine in what
322 * region the logo resides for faster processing. */
323 ff_calculate_bounding_box(&removelogo->full_mask_bbox, removelogo->full_mask_data, w, w, h, 0);
324 ff_calculate_bounding_box(&removelogo->half_mask_bbox, removelogo->half_mask_data, w/2, w/2, h/2, 0);
326 #define SHOW_LOGO_INFO(mask_type) \
327 av_log(ctx, AV_LOG_INFO, #mask_type " x1:%d x2:%d y1:%d y2:%d max_mask_size:%d\n", \
328 removelogo->mask_type##_mask_bbox.x1, removelogo->mask_type##_mask_bbox.x2, \
329 removelogo->mask_type##_mask_bbox.y1, removelogo->mask_type##_mask_bbox.y2, \
330 mask_type##_max_mask_size);
331 SHOW_LOGO_INFO(full);
332 SHOW_LOGO_INFO(half);
337 static int config_props_input(AVFilterLink *inlink)
339 AVFilterContext *ctx = inlink->dst;
340 RemovelogoContext *removelogo = ctx->priv;
342 if (inlink->w != removelogo->mask_w || inlink->h != removelogo->mask_h) {
343 av_log(ctx, AV_LOG_INFO,
344 "Mask image size %dx%d does not match with the input video size %dx%d\n",
345 removelogo->mask_w, removelogo->mask_h, inlink->w, inlink->h);
346 return AVERROR(EINVAL);
355 * It takes a pixel that is inside the mask and blurs it. It does so
356 * by finding the average of all the pixels within the mask and
357 * outside of the mask.
359 * @param mask_data the mask plane to use for averaging
360 * @param image_data the image plane to blur
361 * @param w width of the image
362 * @param h height of the image
363 * @param x x-coordinate of the pixel to blur
364 * @param y y-coordinate of the pixel to blur
366 static unsigned int blur_pixel(int ***mask,
367 const uint8_t *mask_data, int mask_linesize,
368 uint8_t *image_data, int image_linesize,
369 int w, int h, int x, int y)
371 /* Mask size tells how large a circle to use. The radius is about
372 * (slightly larger than) mask size. */
374 int start_posx, start_posy, end_posx, end_posy;
376 unsigned int accumulator = 0, divisor = 0;
377 /* What pixel we are reading out of the circular blur mask. */
378 const uint8_t *image_read_position;
379 /* What pixel we are reading out of the filter image. */
380 const uint8_t *mask_read_position;
382 /* Prepare our bounding rectangle and clip it if need be. */
383 mask_size = mask_data[y * mask_linesize + x];
384 start_posx = FFMAX(0, x - mask_size);
385 start_posy = FFMAX(0, y - mask_size);
386 end_posx = FFMIN(w - 1, x + mask_size);
387 end_posy = FFMIN(h - 1, y + mask_size);
389 image_read_position = image_data + image_linesize * start_posy + start_posx;
390 mask_read_position = mask_data + mask_linesize * start_posy + start_posx;
392 for (j = start_posy; j <= end_posy; j++) {
393 for (i = start_posx; i <= end_posx; i++) {
394 /* Check if this pixel is in the mask or not. Only use the
395 * pixel if it is not. */
396 if (!(*mask_read_position) && mask[mask_size][i - start_posx][j - start_posy]) {
397 accumulator += *image_read_position;
401 image_read_position++;
402 mask_read_position++;
405 image_read_position += (image_linesize - ((end_posx + 1) - start_posx));
406 mask_read_position += (mask_linesize - ((end_posx + 1) - start_posx));
409 /* If divisor is 0, it means that not a single pixel is outside of
410 the logo, so we have no data. Else we need to normalise the
411 data using the divisor. */
412 return divisor == 0 ? 255:
413 (accumulator + (divisor / 2)) / divisor; /* divide, taking into account average rounding error */
417 * Blur image plane using a mask.
419 * @param source The image to have it's logo removed.
420 * @param destination Where the output image will be stored.
421 * @param source_stride How far apart (in memory) two consecutive lines are.
422 * @param destination Same as source_stride, but for the destination image.
423 * @param width Width of the image. This is the same for source and destination.
424 * @param height Height of the image. This is the same for source and destination.
425 * @param is_image_direct If the image is direct, then source and destination are
426 * the same and we can save a lot of time by not copying pixels that
428 * @param filter The image that stores the distance to the edge of the logo for
430 * @param logo_start_x smallest x-coordinate that contains at least 1 logo pixel.
431 * @param logo_start_y smallest y-coordinate that contains at least 1 logo pixel.
432 * @param logo_end_x largest x-coordinate that contains at least 1 logo pixel.
433 * @param logo_end_y largest y-coordinate that contains at least 1 logo pixel.
435 * This function processes an entire plane. Pixels outside of the logo are copied
436 * to the output without change, and pixels inside the logo have the de-blurring
439 static void blur_image(int ***mask,
440 const uint8_t *src_data, int src_linesize,
441 uint8_t *dst_data, int dst_linesize,
442 const uint8_t *mask_data, int mask_linesize,
443 int w, int h, int direct,
448 const uint8_t *src_line;
451 av_image_copy_plane(dst_data, dst_linesize, src_data, src_linesize, w, h);
453 for (y = bbox->y1; y <= bbox->y2; y++) {
454 src_line = src_data + src_linesize * y;
455 dst_line = dst_data + dst_linesize * y;
457 for (x = bbox->x1; x <= bbox->x2; x++) {
458 if (mask_data[y * mask_linesize + x]) {
459 /* Only process if we are in the mask. */
460 dst_line[x] = blur_pixel(mask,
461 mask_data, mask_linesize,
462 dst_data, dst_linesize,
465 /* Else just copy the data. */
467 dst_line[x] = src_line[x];
473 static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
475 AVFilterLink *outlink = inlink->dst->outputs[0];
476 AVFilterBufferRef *outpicref;
478 if (inpicref->perms & AV_PERM_PRESERVE) {
479 outpicref = avfilter_get_video_buffer(outlink, AV_PERM_WRITE,
480 outlink->w, outlink->h);
481 avfilter_copy_buffer_ref_props(outpicref, inpicref);
482 outpicref->video->w = outlink->w;
483 outpicref->video->h = outlink->h;
485 outpicref = inpicref;
487 outlink->out_buf = outpicref;
488 avfilter_start_frame(outlink, avfilter_ref_buffer(outpicref, ~0));
491 static void end_frame(AVFilterLink *inlink)
493 RemovelogoContext *removelogo = inlink->dst->priv;
494 AVFilterLink *outlink = inlink->dst->outputs[0];
495 AVFilterBufferRef *inpicref = inlink ->cur_buf;
496 AVFilterBufferRef *outpicref = outlink->out_buf;
497 int direct = inpicref == outpicref;
499 blur_image(removelogo->mask,
500 inpicref ->data[0], inpicref ->linesize[0],
501 outpicref->data[0], outpicref->linesize[0],
502 removelogo->full_mask_data, inlink->w,
503 inlink->w, inlink->h, direct, &removelogo->full_mask_bbox);
504 blur_image(removelogo->mask,
505 inpicref ->data[1], inpicref ->linesize[1],
506 outpicref->data[1], outpicref->linesize[1],
507 removelogo->half_mask_data, inlink->w/2,
508 inlink->w/2, inlink->h/2, direct, &removelogo->half_mask_bbox);
509 blur_image(removelogo->mask,
510 inpicref ->data[2], inpicref ->linesize[2],
511 outpicref->data[2], outpicref->linesize[2],
512 removelogo->half_mask_data, inlink->w/2,
513 inlink->w/2, inlink->h/2, direct, &removelogo->half_mask_bbox);
515 avfilter_draw_slice(outlink, 0, inlink->h, 1);
516 avfilter_end_frame(outlink);
517 avfilter_unref_buffer(inpicref);
519 avfilter_unref_buffer(outpicref);
522 static void uninit(AVFilterContext *ctx)
524 RemovelogoContext *removelogo = ctx->priv;
527 av_freep(&removelogo->full_mask_data);
528 av_freep(&removelogo->half_mask_data);
530 if (removelogo->mask) {
531 /* Loop through each mask. */
532 for (a = 0; a <= removelogo->max_mask_size; a++) {
533 /* Loop through each scanline in a mask. */
534 for (b = -a; b <= a; b++) {
535 av_free(removelogo->mask[a][b + a]); /* Free a scanline. */
537 av_free(removelogo->mask[a]);
539 /* Free the array of pointers pointing to the masks. */
540 av_freep(&removelogo->mask);
544 static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
546 AVFilter avfilter_vf_removelogo = {
547 .name = "removelogo",
548 .description = NULL_IF_CONFIG_SMALL("Remove a TV logo based on a mask image."),
549 .priv_size = sizeof(RemovelogoContext),
552 .query_formats = query_formats,
554 .inputs = (const AVFilterPad[]) {
556 .type = AVMEDIA_TYPE_VIDEO,
557 .get_video_buffer = avfilter_null_get_video_buffer,
558 .config_props = config_props_input,
559 .draw_slice = null_draw_slice,
560 .start_frame = start_frame,
561 .end_frame = end_frame,
562 .min_perms = AV_PERM_WRITE | AV_PERM_READ,
563 .rej_perms = AV_PERM_PRESERVE },
566 .outputs = (const AVFilterPad[]) {
568 .type = AVMEDIA_TYPE_VIDEO, },