]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_removelogo.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavfilter / vf_removelogo.c
1 /*
2  * Copyright (c) 2005 Robert Edele <yartrebo@earthlink.net>
3  * Copyright (c) 2012 Stefano Sabatini
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 /**
23  * @file
24  * Advanced blur-based logo removing filter
25  *
26  * This filter loads an image mask file showing where a logo is and
27  * uses a blur transform to remove the logo.
28  *
29  * Based on the libmpcodecs remove-logo filter by Robert Edele.
30  */
31
32 /**
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.
40  *
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.
46  *
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.
59  *
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.
70  */
71
72 #include "libavutil/imgutils.h"
73 #include "avfilter.h"
74 #include "formats.h"
75 #include "video.h"
76 #include "bbox.h"
77 #include "lavfutils.h"
78 #include "lswsutils.h"
79
80 typedef struct {
81     /* Stores our collection of masks. The first is for an array of
82        the second for the y axis, and the third for the x axis. */
83     int ***mask;
84     int max_mask_size;
85     int mask_w, mask_h;
86
87     uint8_t      *full_mask_data;
88     FFBoundingBox full_mask_bbox;
89     uint8_t      *half_mask_data;
90     FFBoundingBox half_mask_bbox;
91 } RemovelogoContext;
92
93 /**
94  * Choose a slightly larger mask size to improve performance.
95  *
96  * This function maps the absolute minimum mask size needed to the
97  * mask size we'll actually use. f(x) = x (the smallest that will
98  * work) will produce the sharpest results, but will be quite
99  * jittery. f(x) = 1.25x (what I'm using) is a good tradeoff in my
100  * opinion. This will calculate only at init-time, so you can put a
101  * long expression here without effecting performance.
102  */
103 #define apply_mask_fudge_factor(x) (((x) >> 2) + x)
104
105 /**
106  * Pre-process an image to give distance information.
107  *
108  * This function takes a bitmap image and converts it in place into a
109  * distance image. A distance image is zero for pixels outside of the
110  * logo and is the Manhattan distance (|dx| + |dy|) from the logo edge
111  * for pixels inside of the logo. This will overestimate the distance,
112  * but that is safe, and is far easier to implement than a proper
113  * pythagorean distance since I'm using a modified erosion algorithm
114  * to compute the distances.
115  *
116  * @param mask image which will be converted from a greyscale image
117  * into a distance image.
118  */
119 static void convert_mask_to_strength_mask(uint8_t *data, int linesize,
120                                           int w, int h, int min_val,
121                                           int *max_mask_size)
122 {
123     int x, y;
124
125     /* How many times we've gone through the loop. Used in the
126        in-place erosion algorithm and to get us max_mask_size later on. */
127     int current_pass = 0;
128
129     /* set all non-zero values to 1 */
130     for (y = 0; y < h; y++)
131         for (x = 0; x < w; x++)
132             data[y*linesize + x] = data[y*linesize + x] > min_val;
133
134     /* For each pass, if a pixel is itself the same value as the
135        current pass, and its four neighbors are too, then it is
136        incremented. If no pixels are incremented by the end of the
137        pass, then we go again. Edge pixels are counted as always
138        excluded (this should be true anyway for any sane mask, but if
139        it isn't this will ensure that we eventually exit). */
140     while (1) {
141         /* If this doesn't get set by the end of this pass, then we're done. */
142         int has_anything_changed = 0;
143         uint8_t *current_pixel0 = data, *current_pixel;
144         current_pass++;
145
146         for (y = 1; y < h-1; y++) {
147             current_pixel = current_pixel0;
148             for (x = 1; x < w-1; x++) {
149                 /* Apply the in-place erosion transform. It is based
150                    on the following two premises:
151                    1 - Any pixel that fails 1 erosion will fail all
152                        future erosions.
153
154                    2 - Only pixels having survived all erosions up to
155                        the present will be >= to current_pass.
156                    It doesn't matter if it survived the current pass,
157                    failed it, or hasn't been tested yet.  By using >=
158                    instead of ==, we allow the algorithm to work in
159                    place. */
160                 if ( *current_pixel      >= current_pass &&
161                     *(current_pixel + 1) >= current_pass &&
162                     *(current_pixel - 1) >= current_pass &&
163                     *(current_pixel + w) >= current_pass &&
164                     *(current_pixel - w) >= current_pass) {
165                     /* Increment the value since it still has not been
166                      * eroded, as evidenced by the if statement that
167                      * just evaluated to true. */
168                     (*current_pixel)++;
169                     has_anything_changed = 1;
170                 }
171                 current_pixel++;
172             }
173             current_pixel0 += linesize;
174         }
175         if (!has_anything_changed)
176             break;
177     }
178
179     /* Apply the fudge factor, which will increase the size of the
180      * mask a little to reduce jitter at the cost of more blur. */
181     for (y = 1; y < h - 1; y++)
182         for (x = 1; x < w - 1; x++)
183             data[(y * linesize) + x] = apply_mask_fudge_factor(data[(y * linesize) + x]);
184
185     /* As a side-effect, we now know the maximum mask size, which
186      * we'll use to generate our masks. */
187     /* Apply the fudge factor to this number too, since we must ensure
188      * that enough masks are generated. */
189     *max_mask_size = apply_mask_fudge_factor(current_pass + 1);
190 }
191
192 static int query_formats(AVFilterContext *ctx)
193 {
194     enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE };
195     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
196     return 0;
197 }
198
199 static int load_mask(uint8_t **mask, int *w, int *h,
200                      const char *filename, void *log_ctx)
201 {
202     int ret;
203     enum AVPixelFormat pix_fmt;
204     uint8_t *src_data[4], *gray_data[4];
205     int src_linesize[4], gray_linesize[4];
206
207     /* load image from file */
208     if ((ret = ff_load_image(src_data, src_linesize, w, h, &pix_fmt, filename, log_ctx)) < 0)
209         return ret;
210
211     /* convert the image to GRAY8 */
212     if ((ret = ff_scale_image(gray_data, gray_linesize, *w, *h, AV_PIX_FMT_GRAY8,
213                               src_data, src_linesize, *w, *h, pix_fmt,
214                               log_ctx)) < 0)
215         goto end;
216
217     /* copy mask to a newly allocated array */
218     *mask = av_malloc(*w * *h);
219     if (!*mask)
220         ret = AVERROR(ENOMEM);
221     av_image_copy_plane(*mask, *w, gray_data[0], gray_linesize[0], *w, *h);
222
223 end:
224     av_free(src_data[0]);
225     av_free(gray_data[0]);
226     return ret;
227 }
228
229 /**
230  * Generate a scaled down image with half width, height, and intensity.
231  *
232  * This function not only scales down an image, but halves the value
233  * in each pixel too. The purpose of this is to produce a chroma
234  * filter image out of a luma filter image. The pixel values store the
235  * distance to the edge of the logo and halving the dimensions halves
236  * the distance. This function rounds up, because a downwards rounding
237  * error could cause the filter to fail, but an upwards rounding error
238  * will only cause a minor amount of excess blur in the chroma planes.
239  */
240 static void generate_half_size_image(const uint8_t *src_data, int src_linesize,
241                                      uint8_t *dst_data, int dst_linesize,
242                                      int src_w, int src_h,
243                                      int *max_mask_size)
244 {
245     int x, y;
246
247     /* Copy over the image data, using the average of 4 pixels for to
248      * calculate each downsampled pixel. */
249     for (y = 0; y < src_h/2; y++) {
250         for (x = 0; x < src_w/2; x++) {
251             /* Set the pixel if there exists a non-zero value in the
252              * source pixels, else clear it. */
253             dst_data[(y * dst_linesize) + x] =
254                 src_data[((y << 1) * src_linesize) + (x << 1)] ||
255                 src_data[((y << 1) * src_linesize) + (x << 1) + 1] ||
256                 src_data[(((y << 1) + 1) * src_linesize) + (x << 1)] ||
257                 src_data[(((y << 1) + 1) * src_linesize) + (x << 1) + 1];
258             dst_data[(y * dst_linesize) + x] = FFMIN(1, dst_data[(y * dst_linesize) + x]);
259         }
260     }
261
262     convert_mask_to_strength_mask(dst_data, dst_linesize,
263                                   src_w/2, src_h/2, 0, max_mask_size);
264 }
265
266 static av_cold int init(AVFilterContext *ctx, const char *args)
267 {
268     RemovelogoContext *removelogo = ctx->priv;
269     int ***mask;
270     int ret = 0;
271     int a, b, c, w, h;
272     int full_max_mask_size, half_max_mask_size;
273
274     if (!args) {
275         av_log(ctx, AV_LOG_ERROR, "An image file must be specified as argument\n");
276         return AVERROR(EINVAL);
277     }
278
279     /* Load our mask image. */
280     if ((ret = load_mask(&removelogo->full_mask_data, &w, &h, args, ctx)) < 0)
281         return ret;
282     removelogo->mask_w = w;
283     removelogo->mask_h = h;
284
285     convert_mask_to_strength_mask(removelogo->full_mask_data, w, w, h,
286                                   16, &full_max_mask_size);
287
288     /* Create the scaled down mask image for the chroma planes. */
289     if (!(removelogo->half_mask_data = av_mallocz(w/2 * h/2)))
290         return AVERROR(ENOMEM);
291     generate_half_size_image(removelogo->full_mask_data, w,
292                              removelogo->half_mask_data, w/2,
293                              w, h, &half_max_mask_size);
294
295     removelogo->max_mask_size = FFMAX(full_max_mask_size, half_max_mask_size);
296
297     /* Create a circular mask for each size up to max_mask_size. When
298        the filter is applied, the mask size is determined on a pixel
299        by pixel basis, with pixels nearer the edge of the logo getting
300        smaller mask sizes. */
301     mask = (int ***)av_malloc(sizeof(int **) * (removelogo->max_mask_size + 1));
302     if (!mask)
303         return AVERROR(ENOMEM);
304
305     for (a = 0; a <= removelogo->max_mask_size; a++) {
306         mask[a] = (int **)av_malloc(sizeof(int *) * ((a * 2) + 1));
307         if (!mask[a])
308             return AVERROR(ENOMEM);
309         for (b = -a; b <= a; b++) {
310             mask[a][b + a] = (int *)av_malloc(sizeof(int) * ((a * 2) + 1));
311             if (!mask[a][b + a])
312                 return AVERROR(ENOMEM);
313             for (c = -a; c <= a; c++) {
314                 if ((b * b) + (c * c) <= (a * a)) /* Circular 0/1 mask. */
315                     mask[a][b + a][c + a] = 1;
316                 else
317                     mask[a][b + a][c + a] = 0;
318             }
319         }
320     }
321     removelogo->mask = mask;
322
323     /* Calculate our bounding rectangles, which determine in what
324      * region the logo resides for faster processing. */
325     ff_calculate_bounding_box(&removelogo->full_mask_bbox, removelogo->full_mask_data, w, w, h, 0);
326     ff_calculate_bounding_box(&removelogo->half_mask_bbox, removelogo->half_mask_data, w/2, w/2, h/2, 0);
327
328 #define SHOW_LOGO_INFO(mask_type)                                       \
329     av_log(ctx, AV_LOG_VERBOSE, #mask_type " x1:%d x2:%d y1:%d y2:%d max_mask_size:%d\n", \
330            removelogo->mask_type##_mask_bbox.x1, removelogo->mask_type##_mask_bbox.x2, \
331            removelogo->mask_type##_mask_bbox.y1, removelogo->mask_type##_mask_bbox.y2, \
332            mask_type##_max_mask_size);
333     SHOW_LOGO_INFO(full);
334     SHOW_LOGO_INFO(half);
335
336     return 0;
337 }
338
339 static int config_props_input(AVFilterLink *inlink)
340 {
341     AVFilterContext *ctx = inlink->dst;
342     RemovelogoContext *removelogo = ctx->priv;
343
344     if (inlink->w != removelogo->mask_w || inlink->h != removelogo->mask_h) {
345         av_log(ctx, AV_LOG_INFO,
346                "Mask image size %dx%d does not match with the input video size %dx%d\n",
347                removelogo->mask_w, removelogo->mask_h, inlink->w, inlink->h);
348         return AVERROR(EINVAL);
349     }
350
351     return 0;
352 }
353
354 /**
355  * Blur image.
356  *
357  * It takes a pixel that is inside the mask and blurs it. It does so
358  * by finding the average of all the pixels within the mask and
359  * outside of the mask.
360  *
361  * @param mask_data  the mask plane to use for averaging
362  * @param image_data the image plane to blur
363  * @param w width of the image
364  * @param h height of the image
365  * @param x x-coordinate of the pixel to blur
366  * @param y y-coordinate of the pixel to blur
367  */
368 static unsigned int blur_pixel(int ***mask,
369                                const uint8_t *mask_data, int mask_linesize,
370                                uint8_t       *image_data, int image_linesize,
371                                int w, int h, int x, int y)
372 {
373     /* Mask size tells how large a circle to use. The radius is about
374      * (slightly larger than) mask size. */
375     int mask_size;
376     int start_posx, start_posy, end_posx, end_posy;
377     int i, j;
378     unsigned int accumulator = 0, divisor = 0;
379     /* What pixel we are reading out of the circular blur mask. */
380     const uint8_t *image_read_position;
381     /* What pixel we are reading out of the filter image. */
382     const uint8_t *mask_read_position;
383
384     /* Prepare our bounding rectangle and clip it if need be. */
385     mask_size  = mask_data[y * mask_linesize + x];
386     start_posx = FFMAX(0, x - mask_size);
387     start_posy = FFMAX(0, y - mask_size);
388     end_posx   = FFMIN(w - 1, x + mask_size);
389     end_posy   = FFMIN(h - 1, y + mask_size);
390
391     image_read_position = image_data + image_linesize * start_posy + start_posx;
392     mask_read_position  = mask_data  + mask_linesize  * start_posy + start_posx;
393
394     for (j = start_posy; j <= end_posy; j++) {
395         for (i = start_posx; i <= end_posx; i++) {
396             /* Check if this pixel is in the mask or not. Only use the
397              * pixel if it is not. */
398             if (!(*mask_read_position) && mask[mask_size][i - start_posx][j - start_posy]) {
399                 accumulator += *image_read_position;
400                 divisor++;
401             }
402
403             image_read_position++;
404             mask_read_position++;
405         }
406
407         image_read_position += (image_linesize - ((end_posx + 1) - start_posx));
408         mask_read_position  += (mask_linesize - ((end_posx + 1) - start_posx));
409     }
410
411     /* If divisor is 0, it means that not a single pixel is outside of
412        the logo, so we have no data.  Else we need to normalise the
413        data using the divisor. */
414     return divisor == 0 ? 255:
415         (accumulator + (divisor / 2)) / divisor;  /* divide, taking into account average rounding error */
416 }
417
418 /**
419  * Blur image plane using a mask.
420  *
421  * @param source The image to have it's logo removed.
422  * @param destination Where the output image will be stored.
423  * @param source_stride How far apart (in memory) two consecutive lines are.
424  * @param destination Same as source_stride, but for the destination image.
425  * @param width Width of the image. This is the same for source and destination.
426  * @param height Height of the image. This is the same for source and destination.
427  * @param is_image_direct If the image is direct, then source and destination are
428  *        the same and we can save a lot of time by not copying pixels that
429  *        haven't changed.
430  * @param filter The image that stores the distance to the edge of the logo for
431  *        each pixel.
432  * @param logo_start_x smallest x-coordinate that contains at least 1 logo pixel.
433  * @param logo_start_y smallest y-coordinate that contains at least 1 logo pixel.
434  * @param logo_end_x   largest x-coordinate that contains at least 1 logo pixel.
435  * @param logo_end_y   largest y-coordinate that contains at least 1 logo pixel.
436  *
437  * This function processes an entire plane. Pixels outside of the logo are copied
438  * to the output without change, and pixels inside the logo have the de-blurring
439  * function applied.
440  */
441 static void blur_image(int ***mask,
442                        const uint8_t *src_data,  int src_linesize,
443                              uint8_t *dst_data,  int dst_linesize,
444                        const uint8_t *mask_data, int mask_linesize,
445                        int w, int h, int direct,
446                        FFBoundingBox *bbox)
447 {
448     int x, y;
449     uint8_t *dst_line;
450     const uint8_t *src_line;
451
452     if (!direct)
453         av_image_copy_plane(dst_data, dst_linesize, src_data, src_linesize, w, h);
454
455     for (y = bbox->y1; y <= bbox->y2; y++) {
456         src_line = src_data + src_linesize * y;
457         dst_line = dst_data + dst_linesize * y;
458
459         for (x = bbox->x1; x <= bbox->x2; x++) {
460              if (mask_data[y * mask_linesize + x]) {
461                 /* Only process if we are in the mask. */
462                  dst_line[x] = blur_pixel(mask,
463                                           mask_data, mask_linesize,
464                                           dst_data, dst_linesize,
465                                           w, h, x, y);
466             } else {
467                 /* Else just copy the data. */
468                 if (!direct)
469                     dst_line[x] = src_line[x];
470             }
471         }
472     }
473 }
474
475 static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
476 {
477     AVFilterLink *outlink = inlink->dst->outputs[0];
478     AVFilterBufferRef *outpicref;
479
480     outpicref = inpicref;
481
482     outlink->out_buf = outpicref;
483     return ff_start_frame(outlink, avfilter_ref_buffer(outpicref, ~0));
484 }
485
486 static int end_frame(AVFilterLink *inlink)
487 {
488     RemovelogoContext *removelogo = inlink->dst->priv;
489     AVFilterLink *outlink = inlink->dst->outputs[0];
490     AVFilterBufferRef *inpicref  = inlink ->cur_buf;
491     AVFilterBufferRef *outpicref = outlink->out_buf;
492     int direct = inpicref == outpicref;
493
494     blur_image(removelogo->mask,
495                inpicref ->data[0], inpicref ->linesize[0],
496                outpicref->data[0], outpicref->linesize[0],
497                removelogo->full_mask_data, inlink->w,
498                inlink->w, inlink->h, direct, &removelogo->full_mask_bbox);
499     blur_image(removelogo->mask,
500                inpicref ->data[1], inpicref ->linesize[1],
501                outpicref->data[1], outpicref->linesize[1],
502                removelogo->half_mask_data, inlink->w/2,
503                inlink->w/2, inlink->h/2, direct, &removelogo->half_mask_bbox);
504     blur_image(removelogo->mask,
505                inpicref ->data[2], inpicref ->linesize[2],
506                outpicref->data[2], outpicref->linesize[2],
507                removelogo->half_mask_data, inlink->w/2,
508                inlink->w/2, inlink->h/2, direct, &removelogo->half_mask_bbox);
509
510     ff_draw_slice(outlink, 0, inlink->h, 1);
511     return ff_end_frame(outlink);
512 }
513
514 static void uninit(AVFilterContext *ctx)
515 {
516     RemovelogoContext *removelogo = ctx->priv;
517     int a, b;
518
519     av_freep(&removelogo->full_mask_data);
520     av_freep(&removelogo->half_mask_data);
521
522     if (removelogo->mask) {
523         /* Loop through each mask. */
524         for (a = 0; a <= removelogo->max_mask_size; a++) {
525             /* Loop through each scanline in a mask. */
526             for (b = -a; b <= a; b++) {
527                 av_free(removelogo->mask[a][b + a]); /* Free a scanline. */
528             }
529             av_free(removelogo->mask[a]);
530         }
531         /* Free the array of pointers pointing to the masks. */
532         av_freep(&removelogo->mask);
533     }
534 }
535
536 static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { return 0; }
537
538 AVFilter avfilter_vf_removelogo = {
539     .name          = "removelogo",
540     .description   = NULL_IF_CONFIG_SMALL("Remove a TV logo based on a mask image."),
541     .priv_size     = sizeof(RemovelogoContext),
542     .init          = init,
543     .uninit        = uninit,
544     .query_formats = query_formats,
545
546     .inputs = (const AVFilterPad[]) {
547         { .name             = "default",
548           .type             = AVMEDIA_TYPE_VIDEO,
549           .get_video_buffer = ff_null_get_video_buffer,
550           .config_props     = config_props_input,
551           .draw_slice       = null_draw_slice,
552           .start_frame      = start_frame,
553           .end_frame        = end_frame,
554           .min_perms        = AV_PERM_WRITE | AV_PERM_READ },
555         { .name = NULL }
556     },
557     .outputs = (const AVFilterPad[]) {
558         { .name             = "default",
559           .type             = AVMEDIA_TYPE_VIDEO, },
560         { .name = NULL }
561     },
562 };