/*
// Copyright 2005 Robert Edele.

// e-mail: yartrebo@earthlink.net

// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version.

// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Public License for more
// details.

// You should have reveived a copy of the GNU General Public License
// along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
// 02111-1307 USA

// __________________________________________________________________________
// | Robert Edele                                           Fri. 4-Feb-2005 |
// | This program loads a .tga file from the trainer program and applies    |
// | the inverse transform needed to remove the tv logo.                    |
// |________________________________________________________________________|
*/

/*
    Hello and welcome. This code implements a filter to remove annoying TV
logos and other annoying images placed onto a video stream. It works by filling
in the pixels that comprise the logo with neighboring pixels. The transform is
very loosely based on a gaussian blur, but it is different enough to merit its
own paragraph later on. It is a major improvement on the old delogo filter as
it both uses a better blurring algorithm and uses a bitmap to use an arbitrary
and generally much tighter fitting shape than a rectangle.

    The filter requires 1 argument and has no optional arguments. It requires
a filter bitmap, which must be in TGA format (24 or 32 bpp, no compression). A
sample invocation would be -vf remove_logo=/home/username/logo_bitmaps/xyz.tga.
Only the red layer of the image is used. Pixels with a zero red component are
not part of the logo, and non-zero pixels are part of the logo. If you use
white (255, 255, 255) for the logo and black (0, 0, 0) for the rest, you will
be safe. For making the filter bitmap, I recommend taking a screen capture of
a black frame with the logo visible, and then using The GIMP's threshold
filter followed by the erode filter once or twice. If needed, little splotches
can be fixed manually. Remember that if logo pixels are not covered, the
filter quality will be much reduced. Marking too many pixels are part of the
logo doesn't hurt as much, but it will increase the amount of blurring needed
to cover over the image, and will loose more information than is needed.

    The logo removal algorithm has two key points. The first is that it
distinguishes between pixels in the logo and those not in the logo by using the
passed-in bitmap. Pixels not in the logo are copied over directly without being
modified and they also serve as source pixels for the logo fill-in. Pixels
inside the logo have the mask applied.

    At init-time the bitmap is reprocessed internally, and the distance to the
nearest edge of the logo (Manhattan distance), along with a little extra to
remove rough edges, is stored in each pixel. This is done using an in-place
erosion algorithm, and incrementing each pixel that survives any given erosion.
Once every pixel is eroded, the maximum value is recorded, and a set of masks
from size 0 to this size are generaged. The masks are circular binary masks,
with each pixel within a radius N (where N is the size of the mask) is a 1, and
all other pixels are a 0. Although a gaussian mask would be more mathematically
accurate, a binary mask works better in practice because we generally do not
use the central pixels in the mask (because they are in the logo region), and
thus a gaussian mask will cause too little blur and thus a very unstable image.

    The mask is applied in a special way. Namely, only pixels in the mask that
line up to pixels outside the logo are used. The dynamic mask size means that
the mask is just big enough so that the edges touch pixels outside the logo, so
the blurring is kept to a minimum and at least the first boundary condition
(that the image function itself is continuous), even if the second boundary
condition (that the derivative of the image function is continuous) is not met.
A masking algorithm that does preserve the second boundary coundition
(perhaps something based on a highly-modified bi-cubic algorithm) should offer
even better results on paper, but the noise in a typical TV signal should make
anything based on derivatives hopelessly noisy.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>

#include "../config.h"
#include "../mp_msg.h"

#include "img_format.h"
#include "mp_image.h"
#include "vf.h"

#include "../postproc/rgb2rgb.h"

//===========================================================================//

#define max(x,y) ((x)>(y)?(x):(y))
#define min(x,y) ((x)>(y)?(y):(x))

#define test_filter(image, x, y) ((unsigned char) (image->red[((y) * image->width) + (x)])) /* Tests to see if the pixel is in or not in the tv logo. */

#define get_part_of_pixel_yv12(mpi, x, y, plane) ((float) *(mpi->planes[(plane)] + (mpi->stride[(plane)] * (y)) + (x))) /* Returns on of the pieces (luminance [plane == 0], blue chrominance [plane == 1], or red chrominance [plane == 2]) of a YV12 pixel. The coordinates are local to the plane, so divide x and y by 2 for the chroma planes. */

#define apply_mask_fudge_factor(x) (((x) >> 2) + x) /* This function maps the absolute minimum mask size needed to the mask size we'll actually use. f(x) = x (the smallest that will work) will produce the sharpest results, but will be quite jittery. f(x) = 1.25x (what I'm using) is a good tradeoff in my opinion. This will calculate only at init-time, so you can put a long expression here without effecting performance. */

/* This struct does a far from complete implementation of the TGA image format. Only the red channel is kept, as we have no need for the others.*/
typedef struct
{
  unsigned short int width;
  unsigned short int height;

  unsigned char * red;

} tga_structure;

/* This struct stores our filter data. */
typedef struct
{
  unsigned int fmt; /* Not exactly sure of the use for this. It came with the example filter I used as a basis for this, and it looks like a lot of stuff will break if I remove it. */
  int max_mask_size; /* The largest possible mask size that will be needed with the given filter and corresponding half_size_filter. The half_size_filter can have a larger requirment in some rare (but not degenerate) cases. */
  int * * * mask; /* Stores our collection of masks. The first * is for an array of masks, the second for the y axis, and the third for the x axis. */
  tga_structure * filter; /* Stores the full-size filter image. This is used to tell what pixels are in the logo or not in the luma plane. */
  tga_structure * half_size_filter; /* Stores a 50% width and 50% height filter image. This is used to tell what pixels are in the logo or not in the chroma planes. */
} vf_priv_s;

/* Simple little function to display an error message in an MPlayer friendly way. */
void error(const char * message)
{
  mp_msg(MSGT_VFILTER,MSGL_ERR, message);
}

/* Mallocs memory, and checks to make sure it was successfully allocated. Because of how MPlayer works, it cannot safely halt execution, but at least the user will get an error message before the segfault happens. */
void * safe_malloc(int size)
{
  void * answer = malloc(size);
  if (answer == NULL)
    error("Unable to allocate memory in vf_remove_logo.c\n");

  return answer;
}

/* We call this function when our filter is done. It will free the memory allocated to the masks and leave the variables in a safe state. */
void destroy_masks(vf_instance_t * vf)
{
  int a, b;

  /* Load values from the vf->priv struct for faster dereferencing. */
  int * * * mask = ((vf_priv_s *)vf->priv)->mask;
  int max_mask_size = ((vf_priv_s *)vf->priv)->max_mask_size;

  if (mask == NULL)
    return; /* Nothing allocated, so return before we segfault. */

  /* Free all allocated memory. */
  for (a = 0; a <= max_mask_size; a++) /* Loop through each mask. */
  {
    for (b = -a; b <= a; b++) /* Loop through each scanline in a mask. */
    {
      free(mask[a][b + a]); /* Free a scanline. */
    }
    free(mask[a]); /* Free a mask. */
  }
  free(mask); /* Free the array of pointers pointing to the masks. */

  /* Set the pointer to NULL, so that any duplicate calls to this function will not cause a crash. */
  ((vf_priv_s *)vf->priv)->mask = NULL;

  return;
}

/* Create our masks and give them their values. The values will not change during program execution once this function is done. */
void initialize_masks(vf_instance_t * vf)
{
  int a, b, c;

  /* Load values from the vf->priv struct for faster dereferencing. */
  int * * * mask = ((vf_priv_s *)vf->priv)->mask;
  int max_mask_size = ((vf_priv_s *)vf->priv)->max_mask_size; /* This tells us how many masks we'll need to generate. */

  /* Create a circular mask for each size up to max_mask_size. When the filter is applied, the mask size is determined on a pixel by pixel basis, with pixels nearer the edge of the logo getting smaller mask sizes. */
  mask = (int * * *) safe_malloc(sizeof(int * *) * (max_mask_size + 1));
  for (a = 0; a <= max_mask_size; a++)
  {
    mask[a] = (int * *) safe_malloc(sizeof(int *) * ((a * 2) + 1));
    for (b = -a; b <= a; b++)
    {
      mask[a][b + a] = (int *) safe_malloc(sizeof(int) * ((a * 2) + 1));
      for (c = -a; c <= a; c++)
      {
        if ((b * b) + (c * c) <= (a * a)) /* Circular 0/1 mask. */
          mask[a][b + a][c + a] = 1;
        else
          mask[a][b + a][c + a] = 0; 
      }
    }
  }

  /* Store values back to vf->priv so they aren't lost after the function returns. */
  ((vf_priv_s *)vf->priv)->mask = mask;

  return;
}

/* This marks pixels that are 1 away from the edge with a 1, 2 as a 2, and so forth. Uses the manhatten distance (ie., abs(dekta_x) + abs(delta_y)). This will overestimate the distance, but that is safe, and is far easier to implement than a proper pythagorean distance since I'm using a modified erosion algorithm. */
/* For masking, only the red channel is used, so that is why the others are ignored. In fact, the other channels have been removed from the tga_structure struct, so as not to waste memory. */
void convert_mask_to_strength_mask(vf_instance_t * vf, tga_structure * mask)
{
  int x, y; /* Used by our for loops to go through every single in the picture one at a time. */
  int has_anything_changed = 1; /* Used by the main while() loop to know if anything changed on the last erosion. */
  int current_pass = 0; /* How many times we've gone through the loop. Used in the in-place erosion algorithm and to get us max_mask_size later on. */
  int max_mask_size; /* This will record how large a mask the pixel that is the furthest from the edge of the logo (and thus the neediest) is. */
  char * current_pixel = mask->red; /* This is

  /* First pass, set all non-zero values to 1. After this loop finishes, the data should be considered numeric data for the filter, not color data. */
  for (x = 0; x < mask->height * mask->width; x++, current_pixel++)
    if(*current_pixel) *current_pixel = 1;

  /* Second pass and future passes. For each pass, if a pixel is itself the same value as the current pass, and its four neighbors are too, then it is incremented. If no pixels are incremented by the end of the pass, then we go again. Edge pixels are counted as always excluded (this should be true anyway for any sane mask, but if it isn't this will ensure that we eventually exit). */
  while (has_anything_changed)
  {
    current_pass++;
    current_pixel = mask->red;

    has_anything_changed = 0; /* If this doesn't get set by the end of this pass, then we're done. */

    for (y = 1; y < mask->height - 1; y++)
    {
      for (x = 1; x < mask->width - 1; x++)
      {
        /* Apply the in-place erosion transform. It is based on the following two premisees: 1 - Any pixel that fails 1 erosion will fail all future erosions. 2 - Only pixels having survived all erosions up to the present will be >= to current_pass. It doesn't matter if it survived the current pass, failed it, or hasn't been tested yet. */
        if (*current_pixel >= current_pass && /* By using >= instead of ==, we allow the algorithm to work in place. */
            *(current_pixel + 1) >= current_pass &&
            *(current_pixel - 1) >= current_pass &&
            *(current_pixel + mask->width) >= current_pass &&
            *(current_pixel - mask->width) >= current_pass)
         {
           (*current_pixel)++; /* Increment the value since it still has not been eroded, as evidenced by the if statement that just evaluated to true. */
           has_anything_changed = 1;
         }
        current_pixel++;
      }
    }
  }

  /* Apply the fudge factor, which will increase the size of the mask a little to reduce jitter at the cost of more blur. */
  for (y = 1; y < mask->height - 1; y++)
  {
   for (x = 1; x < mask->width - 1; x++)
    {
      mask->red[(y * mask->width) + x] = apply_mask_fudge_factor(mask->red[(y * mask->width) + x]);
    }
  }

  max_mask_size = current_pass + 1; /* As a side-effect, we now know the maximum mask size, which we'll use to generate our masks. */
  max_mask_size = apply_mask_fudge_factor(max_mask_size); /* Apply the fudge factor to this number too, since we must ensure that enough masks are generated. */
  ((vf_priv_s *)vf->priv)->max_mask_size = max_mask_size; /* Commit the newly calculated max_mask_size to the vf->priv struct. */

  return;
}

void get_blur(vf_instance_t * vf, float * value_out, const tga_structure * logo_mask, const mp_image_t * image, const int x, const int y, int plane)
{
  int mask_size; /* Gaussian power tells how large a circle to use. */
  int * * * mask;

  /* Get values from vf->priv for faster dereferencing. */
  mask = ((vf_priv_s *)vf->priv)->mask;

  if (mask_size = test_filter(logo_mask, x, y))
  { /* This pixel does indeed need to get its value from its neighbors. */
    int start_posx, start_posy, end_posx, end_posy;
    int i, j;
    float accumulator = 0, divisor = 0;
//    printf("Power = %d\n", mask_size);
    /* Prepare our bounding rectangle and clip it if need be. */
    start_posx = max(0, x - mask_size);
    start_posy = max(0, y - mask_size);
    end_posx = min(image->width - 1, x + mask_size);
    end_posy = min(image->height - 1, y + mask_size);

    for (i = start_posx; i <= end_posx; i++)
    {
      for (j = start_posy; j <= end_posy; j++)
      {
        if (!test_filter(logo_mask, i, j) && mask[mask_size][i - start_posx][j - start_posy]) /* Check to see if this pixel is in the logo or not. Only use the pixel if it is not. */
        {
          accumulator += get_part_of_pixel_yv12(image, i, j, plane);
          divisor++;
        }
      }
    }

    if (divisor == 0) /* This means that not a single pixel is outside of the logo, so we have no data. */
    { /* We should put some eye catching value here, to indicate the flaw to the user. */
      *value_out = 255; /* Hot pink. Nothing more catching than this. */
    }
    else /* Else we need to normalise the data using the divisor. */
    {
      *value_out = accumulator / divisor;
    }
  }
  else /* This pixel is not supposed to be masked, so we just copy the current pixel data without changing it. */
  {

    *value_out = get_part_of_pixel_yv12(image, x, y, plane);
  }

  return;
}

void destroy_tga(tga_structure * to_be_destroyed)
{
  if (to_be_destroyed == NULL)
    return; /* Don't do anything if a NULL pointer was passed it. */

  /* Internally allocated memory. */
  if (to_be_destroyed->red != NULL)
  {
    free(to_be_destroyed->red);
    to_be_destroyed->red = NULL;
  }

  /* Free the actual struct instance. This is done here and not by the calling function. */
  free(to_be_destroyed);
}

tga_structure * load_tga(const char * file_name)
{
  unsigned char flags;
  int x, y;
  int bpp;
  tga_structure * new_tga = (tga_structure *) malloc (sizeof(tga_structure));

  if (new_tga == NULL)
  {
    error("Unable to allocate memory in vf_remove_logo::load_tga().\n");
    return NULL;
  }

  FILE * input;
  if((input = fopen(file_name, "rb")) == NULL)
  {
    error("Unable to open targa file in vf_remove_logo::load_tga().\n");
    return NULL;
  }

  if (fgetc(input) != 0)
  {
    error("Identsize field in targa file must be 0.\n");
    return NULL;
  }
  if (fgetc(input) != 0)
  {
    error("Indexed targa files not supported.\n");
    return NULL;
  }
  if (fgetc(input) != 2)
  {
    error("Only RGB targa files are supported.\n");
    return NULL;
  }
  if (fgetc(input) || fgetc(input) || fgetc(input) || fgetc(input) || fgetc(input))
  {
    error("Palletes not supported in targa files.\n");
    return NULL;
  }
  if (fgetc(input) || fgetc(input) || fgetc(input) || fgetc(input))
  {
    error("Origin must be at (0, 0)\n");
  }
  new_tga->width = fgetc(input) | (fgetc(input) << 8);
  new_tga->height = fgetc(input) | (fgetc(input) << 8);
  bpp = fgetc(input); /* Bits per pixel. Only 24 and 32 are supported. */
  if (bpp != 24 && bpp != 32)
  {
    error("Only 24 and 32 bbp images supported.\n");
  }
  flags = fgetc(input);

  new_tga->red = (unsigned char *) malloc (sizeof(unsigned char) * new_tga->width * new_tga->height);

  if (new_tga->red == NULL)
  {
    error("unable to malloc memory in vf_remove_logo::load_tga().\n");
    return NULL;
  }

  /* Load the pixels. */
  if (flags & 0x20)
  {
    for (y = 0; y < new_tga->height; y++)
    {
      for (x = 0; x < new_tga->width; x++)
      {
        fgetc(input);
        fgetc(input);
        new_tga->red[(y * new_tga->width) + x] = fgetc(input);
        if (bpp == 32) fgetc(input);
      }
    }
  }
  else
  {
    for (y = new_tga->height - 1; y >= 0; y--)
    {
      for (x = 0; x < new_tga->width; x++)
      {
        fgetc(input);
        fgetc(input);
        new_tga->red[(y * new_tga->width) + x] = fgetc(input);
        if (bpp == 32) fgetc(input);
      }
    }
  }

  return new_tga;
}

tga_structure * generate_half_size_image(vf_instance_t * vf, tga_structure * input_image)
{
  int x, y;
  tga_structure * new_tga = (tga_structure *) malloc (sizeof(tga_structure));

  if (new_tga == NULL)
  {
    error("Unable to allocate memory in vf_remove_logo::load_tga().\n");
    return NULL;
  }

  new_tga->width = input_image->width;
  new_tga->height = input_image->height;
  new_tga->red = (unsigned char *) malloc (sizeof(unsigned char) * new_tga->width * new_tga->height);

  /* Copy over the image data, using the average of 4 pixels for to calculate each downsampled pixel. */
  for (y = 0; y < new_tga->height; y++)
    for (x = 0; x < new_tga->width; x++)
    {
      /* Set the pixel if there exists a non-zero value in the source pixels, else clear it. */
      new_tga->red[(y * new_tga->width) + x] = input_image->red[((y << 1) * input_image->width) + (x << 1)] ||
                                               input_image->red[((y << 1) * input_image->width) + (x << 1) + 1] ||
                                               input_image->red[(((y << 1) + 1) * input_image->width) + (x << 1)] ||
                                               input_image->red[(((y << 1) + 1) * input_image->width) + (x << 1) + 1];
      new_tga->red[(y * new_tga->width) + x] = min(1, new_tga->red[(y * new_tga->width) + x]);
    }

  /* Now we need to recalculate the numbers for the smaller size. Just using the old_value / 2 can cause subtle and fairly rare, but very nasty, bugs. */

  int has_anything_changed = 1;
  int current_pass;
  int max_mask_size;
  char * current_pixel = new_tga->red;
  /* First pass, set all non-zero values to 1. */
  for (x = 0; x < new_tga->height * new_tga->width; x++, current_pixel++)
    if(*current_pixel) *current_pixel = 1;

  /* Second pass and future passes. For each pass, if a pixel is itself the same value as the current pass, and its four neighbors are too, then it is incremented. If no pixels are incremented by the end of the pass, then we go again. Edge pixels are counted as always excluded (this should be true anyway for any sane mask, but if it isn't this will ensure that we eventually exit). */
  current_pass = 0;
  while (has_anything_changed)
  {
    current_pass++;

    has_anything_changed = 0; /* If this doesn't get set by the end of this pass, then we're done. */

    for (y = 1; y < new_tga->height - 1; y++)
    {
      for (x = 1; x < new_tga->width - 1; x++)
      {
        if (new_tga->red[(y * new_tga->width) + x] >= current_pass && /* By using >= instead of ==, we allow the algorithm to work in place. */
            new_tga->red[(y * new_tga->width) + (x + 1)] >= current_pass &&
            new_tga->red[(y * new_tga->width) + (x - 1)] >= current_pass &&
            new_tga->red[((y + 1) * new_tga->width) + x] >= current_pass &&
            new_tga->red[((y - 1) * new_tga->width) + x] >= current_pass)
         {
           new_tga->red[(y * new_tga->width) + x]++; /* Increment the value since it still has not been eroded, as evidenced by the if statement that just evaluated to true. */
           has_anything_changed = 1;
         }
      }
    }
  }

  for (y = 1; y < new_tga->height - 1; y++)
  {
   for (x = 1; x < new_tga->width - 1; x++)
    {
      new_tga->red[(y * new_tga->width) + x] = apply_mask_fudge_factor(new_tga->red[(y * new_tga->width) + x]);
    }
  }

  max_mask_size = current_pass + 1; /* As a side-effect, we now know the maximum mask size, which we'll use to generate our masks. */
  max_mask_size = apply_mask_fudge_factor(max_mask_size);
  /* Commit the newly calculated max_mask_size to the vf->priv struct. */
  ((vf_priv_s *)vf->priv)->max_mask_size = max(max_mask_size, ((vf_priv_s *)vf->priv)->max_mask_size);

  return new_tga;
}

/* This struct is from the example filter I used. As can be seen, our filter only supports a single format - YV12. */
static unsigned int bgr_list[]=
{
  IMGFMT_YV12,
  0
};

/* Likewise, this function is from the example filter I used. Not exactly sure how it works, but it works. */
static unsigned int find_best(struct vf_instance_s* vf){
    unsigned int best=0;
    int ret;
    unsigned int * p=bgr_list;
    while(*p){
	ret=vf->next->query_format(vf->next,*p);
	mp_msg(MSGT_VFILTER,MSGL_V,"[%s] query(%s) -> %d\n",vf->info->name,vo_format_name(*p),ret&3);
	if(ret&VFCAP_CSP_SUPPORTED_BY_HW){ best=*p; break;} // no conversion -> bingo!
	if(ret&VFCAP_CSP_SUPPORTED && !best) best=*p; // best with conversion
	++p;
    }
    return best;
}

//===========================================================================//

/* Once again, this function is only slightly modified from the example filter's version. Not exactly sure how it works either. */
static int config(struct vf_instance_s* vf,
        int width, int height, int d_width, int d_height,
	unsigned int flags, unsigned int outfmt){
    if (!((vf_priv_s *)vf->priv)->fmt)
	((vf_priv_s *)vf->priv)->fmt=find_best(vf);
    if(!((vf_priv_s *)vf->priv)->fmt){
	// no matching fmt, so force one...
	if(outfmt==IMGFMT_RGB8) ((vf_priv_s *)vf->priv)->fmt=IMGFMT_RGB32;
	else if(outfmt==IMGFMT_BGR8) ((vf_priv_s *)vf->priv)->fmt=IMGFMT_BGR32;
	else return 0;
    }
    return vf_next_config(vf,width,height,d_width,d_height,flags,((vf_priv_s *)vf->priv)->fmt);
}

static void convert_yv12(vf_instance_t * vf, mp_image_t * mpi, mp_image_t * dmpi)
{
  int y;
  int x;

  /* These pointers point to where we are getting our pixel data (inside mpi) and where we are storing it (inside dmpi). */
  unsigned char * source_luminance;
  unsigned char * source_blue_chrominance;
  unsigned char * source_red_chrominance;
  unsigned char * destination_luminance;
  unsigned char * destination_blue_chrominance;
  unsigned char * destination_red_chrominance;

  /* These struct pointers point to our filter images, which tells us which pixels are part of the logo and which are not. */
  tga_structure * filter;
  tga_structure * half_size_filter;

  /* Retrieve data from vf->priv for faster access. */
  filter = ((vf_priv_s *)vf->priv)->filter;
  half_size_filter = ((vf_priv_s *)vf->priv)->half_size_filter;

  /* Let's take care of the luminance plane. The two chroinance planes will be handled in a different loop because they are of a different size (half the size to be precise). */
  for (y = 0; y < mpi->h; y++)
  {
    source_luminance = (unsigned char *) mpi->planes[0]+mpi->stride[0]*y;
    destination_luminance = (unsigned char *) dmpi->planes[0]+dmpi->stride[0]*y;

    for (x = 0; x < mpi->w; x++)
    {
      float output_luminance;

      if (filter->red[(y * filter->width) + x]) /* Only process if we are in the logo. */
      {
        get_blur(vf, &output_luminance, filter, mpi, x, y, 0);
        destination_luminance[x] = (unsigned char) (output_luminance + 0.5);
      }
      else /* Else just copy the data. */
        destination_luminance[x] = source_luminance[x];
    }
  }

  /* Now let's take care of the two chrominance planes. */
  for (y = 0; y < (mpi->h >> 1); y++)
  {
    source_blue_chrominance = (unsigned char *) mpi->planes[1]+mpi->stride[1]*y;
    source_red_chrominance = (unsigned char *) mpi->planes[2]+mpi->stride[2]*y;

    destination_blue_chrominance = (unsigned char *) dmpi->planes[1]+dmpi->stride[1]*y;
    destination_red_chrominance = (unsigned char *) dmpi->planes[2]+dmpi->stride[2]*y;

    for (x = 0; x < (mpi->w >> 1); x++)
    {
      float output_blue_chrominance;
      float output_red_chrominance;

      if (half_size_filter->red[(y * half_size_filter->width) + x]) /* Only process if we are in the logo. */
      {
        get_blur(vf, &output_blue_chrominance, half_size_filter, mpi, x, y, 1);
        get_blur(vf, &output_red_chrominance, half_size_filter, mpi, x, y, 2);

        destination_blue_chrominance[x] = (unsigned char) (output_blue_chrominance + 0.5);
        destination_red_chrominance[x] = (unsigned char) (output_red_chrominance + 0.5);
      }
      else /* Else just copy the data. */
      {
        destination_blue_chrominance[x] = source_blue_chrominance[x];
        destination_red_chrominance[x] = source_red_chrominance[x];
      }
    }
  }
}

/* Not sure how this works, because it's from filter I used as an example. */
static int put_image(struct vf_instance_s* vf, mp_image_t *mpi){
    mp_image_t *dmpi;
    
    // hope we'll get DR buffer:
//    dmpi=vf_get_image(vf->next,vf->priv->fmt,
    dmpi=vf_get_image(vf->next,((vf_priv_s *)vf->priv)->fmt,
	MP_IMGTYPE_TEMP, MP_IMGFLAG_ACCEPT_STRIDE,
	mpi->w, mpi->h);

    switch(dmpi->imgfmt){
    case IMGFMT_YV12:
        convert_yv12(vf, mpi, dmpi);
        break;

    default:
	mp_msg(MSGT_VFILTER,MSGL_ERR,"Unhandled format: 0x%X\n",dmpi->imgfmt);
	return 0;
    }

    return vf_next_put_image(vf,dmpi);
}

//===========================================================================//

/* Once again, not sure how this works because it's from another filter. */
static int query_format(struct vf_instance_s * vf, unsigned int fmt){
    int best;
    best=find_best(vf);
    if(!best) return 0; // no match
    return vf->next->query_format(vf->next,best);
}

/* Initialize our filter. */
static int open(vf_instance_t * vf, char* args){
    vf->priv = safe_malloc(sizeof(vf_priv_s));

    /* Load our filter image. */
    if (args) ((vf_priv_s *)vf->priv)->filter = load_tga(args);
    if (((vf_priv_s *)vf->priv)->filter == NULL)
      return 0;

    /* Create the scaled down filter image for the chroma planes. */
    convert_mask_to_strength_mask(vf, ((vf_priv_s *)vf->priv)->filter);
    ((vf_priv_s *)vf->priv)->half_size_filter = generate_half_size_image(vf, ((vf_priv_s *)vf->priv)->filter);

    /* Now that we know how many masks we need (the info is in vf), we can generate the masks. */
    initialize_masks(vf);

    vf->config=config;
    vf->put_image=put_image;
    vf->query_format=query_format;
    return 1;
}

/* Free memory now that our filter is exiting. */
void uninit(vf_instance_t * vf)
{
  /* Destroy our masks and images. */
  destroy_tga(((vf_priv_s *)vf->priv)->filter);
  destroy_tga(((vf_priv_s *)vf->priv)->half_size_filter);
  destroy_masks(vf);

  /* Destroy our private structure that had been used to store those masks and images. */
  free(vf->priv);

  return;
}

vf_info_t vf_info_remove_logo = {
    "Removes a tv logo based on a mask image.",
    "remove-logo",
    "Robert Edele",
    "",
    open,
    NULL
};

//===========================================================================//
