]> 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 "bbox.h"
75 #include "lavfutils.h"
76 #include "lswsutils.h"
77
78 typedef struct {
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. */
81     int ***mask;
82     int max_mask_size;
83     int mask_w, mask_h;
84
85     uint8_t      *full_mask_data;
86     FFBoundingBox full_mask_bbox;
87     uint8_t      *half_mask_data;
88     FFBoundingBox half_mask_bbox;
89 } RemovelogoContext;
90
91 /**
92  * Choose a slightly larger mask size to improve performance.
93  *
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.
100  */
101 #define apply_mask_fudge_factor(x) (((x) >> 2) + x)
102
103 /**
104  * Pre-process an image to give distance information.
105  *
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.
113  *
114  * @param mask image which will be converted from a greyscale image
115  * into a distance image.
116  */
117 static void convert_mask_to_strength_mask(uint8_t *data, int linesize,
118                                           int w, int h, int min_val,
119                                           int *max_mask_size)
120 {
121     int x, y;
122
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;
126
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;
131
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). */
138     while (1) {
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;
142         current_pass++;
143
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
150                        future erosions.
151
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
157                    place. */
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. */
166                     (*current_pixel)++;
167                     has_anything_changed = 1;
168                 }
169                 current_pixel++;
170             }
171             current_pixel0 += linesize;
172         }
173         if (!has_anything_changed)
174             break;
175     }
176
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]);
182
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);
188 }
189
190 static int query_formats(AVFilterContext *ctx)
191 {
192     enum PixelFormat pix_fmts[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
193     avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
194     return 0;
195 }
196
197 static int load_mask(uint8_t **mask, int *w, int *h,
198                      const char *filename, void *log_ctx)
199 {
200     int ret;
201     enum PixelFormat pix_fmt;
202     uint8_t *src_data[4], *gray_data[4];
203     int src_linesize[4], gray_linesize[4];
204
205     /* load image from file */
206     if ((ret = ff_load_image(src_data, src_linesize, w, h, &pix_fmt, filename, log_ctx)) < 0)
207         return ret;
208
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,
212                               log_ctx)) < 0)
213         goto end;
214
215     /* copy mask to a newly allocated array */
216     *mask = av_malloc(*w * *h);
217     if (!*mask)
218         ret = AVERROR(ENOMEM);
219     av_image_copy_plane(*mask, *w, gray_data[0], gray_linesize[0], *w, *h);
220
221 end:
222     av_free(src_data[0]);
223     av_free(gray_data[0]);
224     return ret;
225 }
226
227 /**
228  * Generate a scaled down image with half width, height, and intensity.
229  *
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.
237  */
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,
241                                      int *max_mask_size)
242 {
243     int x, y;
244
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]);
257         }
258     }
259
260     convert_mask_to_strength_mask(dst_data, dst_linesize,
261                                   src_w/2, src_h/2, 0, max_mask_size);
262 }
263
264 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
265 {
266     RemovelogoContext *removelogo = ctx->priv;
267     int ***mask;
268     int ret = 0;
269     int a, b, c, w, h;
270     int full_max_mask_size, half_max_mask_size;
271
272     if (!args) {
273         av_log(ctx, AV_LOG_ERROR, "An image file must be specified as argument\n");
274         return AVERROR(EINVAL);
275     }
276
277     /* Load our mask image. */
278     if ((ret = load_mask(&removelogo->full_mask_data, &w, &h, args, ctx)) < 0)
279         return ret;
280     removelogo->mask_w = w;
281     removelogo->mask_h = h;
282
283     convert_mask_to_strength_mask(removelogo->full_mask_data, w, w, h,
284                                   16, &full_max_mask_size);
285
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);
292
293     removelogo->max_mask_size = FFMAX(full_max_mask_size, half_max_mask_size);
294
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));
300     if (!mask)
301         return AVERROR(ENOMEM);
302
303     for (a = 0; a <= removelogo->max_mask_size; a++) {
304         mask[a] = (int **)av_malloc(sizeof(int *) * ((a * 2) + 1));
305         if (!mask[a])
306             return AVERROR(ENOMEM);
307         for (b = -a; b <= a; b++) {
308             mask[a][b + a] = (int *)av_malloc(sizeof(int) * ((a * 2) + 1));
309             if (!mask[a][b + a])
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;
314                 else
315                     mask[a][b + a][c + a] = 0;
316             }
317         }
318     }
319     removelogo->mask = mask;
320
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);
325
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);
333
334     return 0;
335 }
336
337 static int config_props_input(AVFilterLink *inlink)
338 {
339     AVFilterContext *ctx = inlink->dst;
340     RemovelogoContext *removelogo = ctx->priv;
341
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);
347     }
348
349     return 0;
350 }
351
352 /**
353  * Blur image.
354  *
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.
358  *
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
365  */
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)
370 {
371     /* Mask size tells how large a circle to use. The radius is about
372      * (slightly larger than) mask size. */
373     int mask_size;
374     int start_posx, start_posy, end_posx, end_posy;
375     int i, j;
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;
381
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);
388
389     image_read_position = image_data + image_linesize * start_posy + start_posx;
390     mask_read_position  = mask_data  + mask_linesize  * start_posy + start_posx;
391
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;
398                 divisor++;
399             }
400
401             image_read_position++;
402             mask_read_position++;
403         }
404
405         image_read_position += (image_linesize - ((end_posx + 1) - start_posx));
406         mask_read_position  += (mask_linesize - ((end_posx + 1) - start_posx));
407     }
408
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 */
414 }
415
416 /**
417  * Blur image plane using a mask.
418  *
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
427  *        haven't changed.
428  * @param filter The image that stores the distance to the edge of the logo for
429  *        each pixel.
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.
434  *
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
437  * function applied.
438  */
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,
444                        FFBoundingBox *bbox)
445 {
446     int x, y;
447     uint8_t *dst_line;
448     const uint8_t *src_line;
449
450     if (!direct)
451         av_image_copy_plane(dst_data, dst_linesize, src_data, src_linesize, w, h);
452
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;
456
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,
463                                           w, h, x, y);
464             } else {
465                 /* Else just copy the data. */
466                 if (!direct)
467                     dst_line[x] = src_line[x];
468             }
469         }
470     }
471 }
472
473 static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
474 {
475     AVFilterLink *outlink = inlink->dst->outputs[0];
476     AVFilterBufferRef *outpicref;
477
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;
484     } else
485         outpicref = inpicref;
486
487     outlink->out_buf = outpicref;
488     avfilter_start_frame(outlink, avfilter_ref_buffer(outpicref, ~0));
489 }
490
491 static void end_frame(AVFilterLink *inlink)
492 {
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;
498
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);
514
515     avfilter_draw_slice(outlink, 0, inlink->h, 1);
516     avfilter_end_frame(outlink);
517     avfilter_unref_buffer(inpicref);
518     if (!direct)
519         avfilter_unref_buffer(outpicref);
520 }
521
522 static void uninit(AVFilterContext *ctx)
523 {
524     RemovelogoContext *removelogo = ctx->priv;
525     int a, b;
526
527     av_freep(&removelogo->full_mask_data);
528     av_freep(&removelogo->half_mask_data);
529
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. */
536             }
537             av_free(removelogo->mask[a]);
538         }
539         /* Free the array of pointers pointing to the masks. */
540         av_freep(&removelogo->mask);
541     }
542 }
543
544 static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
545
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),
550     .init          = init,
551     .uninit        = uninit,
552     .query_formats = query_formats,
553
554     .inputs = (const AVFilterPad[]) {
555         { .name             = "default",
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 },
564         { .name = NULL }
565     },
566     .outputs = (const AVFilterPad[]) {
567         { .name             = "default",
568           .type             = AVMEDIA_TYPE_VIDEO, },
569         { .name = NULL }
570     },
571 };