/*
// 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.                    |
// |________________________________________________________________________|
*/

#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 get_red(image, x, y) ((double) (image->red[((y) * image->width) + (x)]))
#define get_green(image, x, y) ((double) (image->green[((y) * image->width) + (x)]))
#define get_blue(image, x, y) ((double) (image->blue[((y) * image->width) + (x)]))
#define get_alpha(image, x, y) ((double) (image->alpha[((y) * image->width) + (x)]))
#define get_char_red(image, x, y) ((unsigned char) (image->red[((y) * image->width) + (x)]))
#define GAUSSIAN_SIZE 9
#define GAUSSIAN_MASK_SIZE ((GAUSSIAN_SIZE * 2) + 1)
#define GAUSSIAN_DECAY_RATE 1 /* Decay rate for mask size 1. Rate is the (n * n)th root for masks of size n. */
#define hypot(x, y) (sqrt(((x) * (x)) + ((y) * (y))))

#define get_red_rgb(mpi, x, y, bpp) ((double) *(mpi->planes[0] + (mpi->stride[0] * y) + (bpp * x)))
#define get_green_rgb(mpi, x, y, bpp) ((double) *(mpi->planes[0] + (mpi->stride[0] * y) + (bpp * x) + 1))
#define get_blue_rgb(mpi, x, y, bpp) ((double) *(mpi->planes[0] + (mpi->stride[0] * y) + (bpp * x) + 2))
#define get_blue_bgr(mpi, x, y, bpp) ((double) *(mpi->planes[0] + (mpi->stride[0] * y) + (bpp * x)))
#define get_green_bgr(mpi, x, y, bpp) ((double) *(mpi->planes[0] + (mpi->stride[0] * y) + (bpp * x) + 1))
#define get_red_bgr(mpi, x, y, bpp) ((double) *(mpi->planes[0] + (mpi->stride[0] * y) + (bpp * x) + 2))

#define get_y_yv12(mpi, x, y) ((double) *(mpi->planes[0] + (mpi->stride[0] * (y)) + (x)))
#define get_u_yv12(mpi, x, y) ((double) *(mpi->planes[1] + (mpi->stride[1] * ((y) / 2)) + ((x) / 2)))
#define get_v_yv12(mpi, x, y) ((double) *(mpi->planes[2] + (mpi->stride[2] * ((y) / 2)) + ((x) / 2)))

double gaussian_mask[GAUSSIAN_SIZE + 1][GAUSSIAN_MASK_SIZE][GAUSSIAN_MASK_SIZE];

void initialize_gaussian_mask()
{
  int i;
  int n;
  double x;
  int power;
  double decay_rate = GAUSSIAN_DECAY_RATE;
  /* Generate unnormalized gaussian mask. Because we will always exclude some pixels, it will have to be normalized every time anyway, so why lose precision? */
  gaussian_mask[0][GAUSSIAN_SIZE][GAUSSIAN_SIZE] = 1; /* Because of division by zero issues, just hard code the zero mask (which does absolutely zero blurring). This mask shouldn't be used, but it's here for elegance and a bit of safety. */
  for (power = 1; power <= GAUSSIAN_SIZE; power++)
  {
    for (i = 0; i <= power; i++)
    {
      for (n = 0; n <= i; n++)
      {
        x = pow(pow(GAUSSIAN_DECAY_RATE, 1.0 / (power * power)), hypot((double) i, (double) n) * hypot((double) i, (double) n));
        gaussian_mask[power][GAUSSIAN_SIZE + i][GAUSSIAN_SIZE + n] = x;
        gaussian_mask[power][GAUSSIAN_SIZE + i][GAUSSIAN_SIZE - n] = x;
        gaussian_mask[power][GAUSSIAN_SIZE - i][GAUSSIAN_SIZE + n] = x;
        gaussian_mask[power][GAUSSIAN_SIZE - i][GAUSSIAN_SIZE - n] = x;
        gaussian_mask[power][GAUSSIAN_SIZE + n][GAUSSIAN_SIZE + i] = x;
        gaussian_mask[power][GAUSSIAN_SIZE - n][GAUSSIAN_SIZE + i] = x;
        gaussian_mask[power][GAUSSIAN_SIZE + n][GAUSSIAN_SIZE - i] = x;
        gaussian_mask[power][GAUSSIAN_SIZE - n][GAUSSIAN_SIZE - i] = x;
      }
    }
  }

  return;
}

void rgb_to_yuv(double in_red, double in_green, double in_blue, double * out_y, double * out_u, double * out_v)
{
  *out_y = (0.299 * in_red) + (0.587 * in_green) + (0.114 * in_blue);
  *out_u = (0.565 * (in_blue - *out_y));
  *out_v = (0.713 * (in_red - *out_y));

  return;
}

void yuv_to_rgb(double in_y, double in_u, double in_v, unsigned char * out_red, unsigned char * out_green, unsigned char * out_blue)
{
  double temp_red, temp_green, temp_blue;

  temp_red = in_y + (1.403 * in_v) + .5;
  temp_green = in_y - ((0.344 * in_u) + (0.714 * in_v));
  temp_blue = in_y + (1.770 * in_u);

  *out_red = (unsigned char) min(max(temp_red + 0.5, 0), 255.4);
  *out_green = (unsigned char) min(max(temp_green + 0.5, 0), 255.4);
  *out_blue = (unsigned char) min(max(temp_blue + 0.5, 0), 255.4);

  return;
}

void error(const char * message)
{
  mp_msg(MSGT_VFILTER,MSGL_ERR, message);
  exit(1);
}

typedef struct
{
  unsigned short int width;
  unsigned short int height;

  unsigned char * red;
  unsigned char * green;
  unsigned char * blue;
  unsigned char * alpha;

} tga_structure;

tga_structure * filter;

/* 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. This is wasteful of memory, but I don't like rewriting my structures. */
void convert_mask_to_strength_mask(tga_structure * mask)
{
  int x, y;
  int has_anything_changed = 1;
  int current_pass;
  char * current_pixel = mask->red;
  /* First pass, set all non-zero values to 1. */
  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 of 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 < mask->height - 1; y++)
    {
      for (x = 1; x < mask->width - 1; x++)
      {
        if (mask->red[(y * mask->width) + x] >= current_pass && /* By using >= instead of ==, we allow the algorithm to work in place. */
            mask->red[(y * mask->width) + (x + 1)] >= current_pass &&
            mask->red[(y * mask->width) + (x - 1)] >= current_pass &&
            mask->red[((y + 1) * mask->width) + x] >= current_pass &&
            mask->red[((y - 1) * mask->width) + x] >= current_pass)
         {
           mask->red[(y * mask->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;
         }
      }
    }
  }
}

void get_gaussian_color_rgb(double * red_out, double * green_out, double * blue_out, const tga_structure * logo_mask, const mp_image_t * image, const int x, const int y, int bpp)
{
  int gaussian_power; /* Gaussian power tells how powerful a gaussian blur must be applied based on how deep in the logo we are. */
  if (gaussian_power = get_char_red(logo_mask, x, y))
  { /* This pixel does indeed need to get its value from its neighbors using a masked gaussian blur. */
    int start_posx, start_posy, end_posx, end_posy;
    int i, j;
    double red = 0, green = 0, blue = 0, divisor = 0;
//    printf("Power = %d\n", gaussian_power);
    /* Prepare our bounding rectangle and clip it if need be. */
    start_posx = max(0, x - gaussian_power);
    start_posy = max(0, y - gaussian_power);
    end_posx = min(image->width - 1, x + gaussian_power);
    end_posy = min(image->height - 1, y + gaussian_power);

    for (i = start_posx; i <= end_posx; i++)
    {
      for (j = start_posy; j <= end_posy; j++)
      {
        if (!get_char_red(logo_mask, i, j)) /* Check to see if this pixel is in the logo or not. Only use the pixel if it is not. */
        {
          double mask_value = gaussian_mask[gaussian_power][GAUSSIAN_SIZE + (i - x)][GAUSSIAN_SIZE + (j - y)];

          red += mask_value * get_red_rgb(image, i, j, bpp);
          green += mask_value * get_green_rgb(image, i, j, bpp);
          blue += mask_value * get_blue_rgb(image, i, j, bpp);
          divisor += mask_value;
        }
      }
    }

    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. */
      *red_out = 255; /* Hot pink? Nothing more catching than this. */
      *green_out = 0;
      *blue_out = 255;
    }
    else /* Else we need to normalise the data using the divisor. */
    {
      *red_out = red /divisor;
      *green_out = green / divisor;
      *blue_out = blue / divisor;
    }
  }
  else /* This pixel is not supposed to be masked, so we just copy the current pixel data without changing it. */
  {

    *red_out = get_red_rgb(image, x, y, bpp);
    *green_out = get_red_rgb(image, x, y, bpp);
    *blue_out = get_red_rgb(image, x, y, bpp);
  }

  return;
}

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

  if (new_tga == NULL)
  {
    fprintf(stderr, "Unable to allocate memory in load_tga().\n");
    exit(1);
  }

  FILE * input;
  if((input = fopen(file_name, "rb")) == NULL)
  {
    mp_msg(MSGT_VFILTER,MSGL_ERR,"Unable to open targa file %s.\n", file_name);
  }

  if (fgetc(input) != 0)
    error("Identsize field in targa file must be 0.\n");
  if (fgetc(input) != 0)
    error("Indexed targa files not supported.\n");
  if (fgetc(input) != 2)
    error("Only RGB targa files are supported.\n");
  if (fgetc(input) || fgetc(input) || fgetc(input) || fgetc(input) || fgetc(input))
    error("Palletes not supported in targa files.\n");
  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);
  if (fgetc(input) != 32)
    error("Only 32 bbp images supported.\n");
  flags = fgetc(input);

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

  if (new_tga->red == NULL || new_tga->green == NULL || new_tga->blue == NULL || new_tga->alpha == NULL)
  {
    fprintf (stderr, "Unable to malloc memory in load_tga().\n");
    exit(1);
  }

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

  return new_tga;
}

static unsigned int bgr_list[]=
{
  IMGFMT_YV12,
  IMGFMT_RGB32,
  IMGFMT_BGR32,

//    IMGFMT_BGR24,
//    IMGFMT_RGB24,
    0
};

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;
}

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

struct vf_priv_s {
    unsigned int fmt;
};

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->fmt)
	vf->priv->fmt=find_best(vf);
    if(!vf->priv->fmt){
	// no matching fmt, so force one...
	if(outfmt==IMGFMT_RGB8) vf->priv->fmt=IMGFMT_RGB32;
	else if(outfmt==IMGFMT_BGR8) vf->priv->fmt=IMGFMT_BGR32;
	else return 0;
    }
    return vf_next_config(vf,width,height,d_width,d_height,flags,vf->priv->fmt);
}

static int bittab[8]={128,64,32,16,8,4,2,1};

static void convert(mp_image_t *mpi, mp_image_t *dmpi, int bpp){
    int y;
    int x;
/*
    for (y = 0; y < mpi->h; y++)
    {
      unsigned char * src = (unsigned char *) mpi->planes[0]+mpi->stride[0]*y;
      unsigned char * dst = (unsigned char *) dmpi->planes[0]+dmpi->stride[0]*y;

      for (x = 0; x < (mpi->w * 4); x += 4)
      {
        dst[x] = src[x + 2];
        dst[x + 1] = src[x + 1];
        dst[x + 2] = src[x];
        dst[x + 3] = 0x70;
      }
    }
*/
//    copy_src_to_tga(input, mpi, format, bpp);

    /* Used for BGR and RGB modes. */
    unsigned char * dst;
    unsigned char * src;

    /* Used for YV12 mode. */
    unsigned char * dst_y;
    unsigned char * dst_u;
    unsigned char * dst_v;
    unsigned char * src_y;
    unsigned char * src_u;
    unsigned char * src_v;

    int in_bpp = 4;

    for (y = 0; y < mpi->h; y++)
    {
      if ((mpi->imgfmt & IMGFMT_RGB_MASK) == IMGFMT_RGB || (mpi->imgfmt & IMGFMT_BGR_MASK) == IMGFMT_BGR)
      {
        src = (unsigned char *) mpi->planes[0]+mpi->stride[0]*y;
        in_bpp = 4;
      }
      else if (mpi->imgfmt == IMGFMT_YV12)
      {
        src_y = (unsigned char *) dmpi->planes[0]+mpi->stride[0]*y;
        src_u = (unsigned char *) dmpi->planes[1]+mpi->stride[1]*(y / 2);
        src_v = (unsigned char *) dmpi->planes[2]+mpi->stride[2]*(y / 2);
      }
      if ((dmpi->imgfmt & IMGFMT_RGB_MASK) == IMGFMT_RGB || (dmpi->imgfmt & IMGFMT_BGR_MASK) == IMGFMT_BGR)
        dst = (unsigned char *) dmpi->planes[0]+dmpi->stride[0]*y;
      else if (dmpi->imgfmt == IMGFMT_YV12)
      {
        dst_y = (unsigned char *) dmpi->planes[0]+dmpi->stride[0]*y;
        dst_u = (unsigned char *) dmpi->planes[1]+dmpi->stride[1]*(y / 2);
        dst_v = (unsigned char *) dmpi->planes[2]+dmpi->stride[2]*(y / 2);
      }

      for (x = 0; x < mpi->w; x++)
      {
        double input_red;
        double input_green;
        double input_blue;
        double output_red;
        double output_green;
        double output_blue;

        /* Load our input values. */
        if ((mpi->imgfmt & IMGFMT_RGB_MASK) == IMGFMT_RGB)
        {
          input_red = get_red_rgb(mpi, x, y, in_bpp);
          input_green = get_green_rgb(mpi, x, y, in_bpp);
          input_blue = get_blue_rgb(mpi, x, y, in_bpp);
        }
        else if ((mpi->imgfmt & IMGFMT_BGR_MASK) == IMGFMT_BGR)
        {
          input_red = get_red_bgr(mpi, x, y, in_bpp);
          input_green = get_green_bgr(mpi, x, y, in_bpp);
          input_blue = get_blue_bgr(mpi, x, y, in_bpp);
        }

        if (filter->red[(y * filter->width) + x]) /* Only process if we are in the logo. */
        {
          if ((mpi->imgfmt & IMGFMT_RGB_MASK) == IMGFMT_RGB)
            get_gaussian_color_rgb(&output_red, &output_green, &output_blue, filter, mpi, x, y, in_bpp);
          else if ((mpi->imgfmt & IMGFMT_BGR_MASK) == IMGFMT_BGR)
            get_gaussian_color_rgb(&output_blue, &output_green, &output_red, filter, mpi, x, y, in_bpp);
        }
        else /* Else just copy the data. */
        {
//            ((uint32_t *)dst)[x] = ((uint32_t *)src)[x];
          output_red = input_red;
          output_green = input_green;
          output_blue = input_blue;
        }

        /* Save the results in the specified output format. */
        if (dmpi->imgfmt == IMGFMT_YV12)
        { /* This does a maximum quality colorspace conversion, at the cost of a lot of CPU cycles. */
          /* It includes blending the 4 U and 4 V pixels together and compensating for truncation induced drift. */
          double temp_y, temp_u, temp_v;
          rgb_to_yuv(output_red, output_green, output_blue, &temp_y, &temp_u, &temp_v);

          dst_y[x] = (unsigned char) (min(max((temp_y + 0.5), 0), 255.4));
          if (x % 2 == 0 && y % 2 == 0)
          {
            dst_u[x / 2] = (unsigned char) ((((temp_u + 130) / 4)));
            dst_v[x / 2] = (unsigned char) ((((temp_v + 130) / 4)));
          }
          else
          {
            dst_u[x / 2] += (unsigned char) ((((temp_u + 130) / 4)));
            dst_v[x / 2] += (unsigned char) ((((temp_v + 130) / 4)));
          }
        }
        else if ((dmpi->imgfmt & IMGFMT_RGB_MASK) == IMGFMT_RGB)
        {
          dst[x * bpp] = output_red + 0.5;
          dst[(x * bpp) + 1] = output_green + 0.5;
          dst[(x * bpp) + 2] = output_blue + 0.5;
        }
        else if ((dmpi->imgfmt & IMGFMT_BGR_MASK) == IMGFMT_BGR)
        {
          dst[x * bpp] = output_blue + 0.5;
          dst[(x * bpp) + 1] = output_green + 0.5;
          dst[(x * bpp) + 2] = output_red + 0.5;
        }
      }
    }
/*
    for(y=0;y<mpi->h;y++){
	unsigned char* src=mpi->planes[0]+mpi->stride[0]*y;
	switch(bpp){
	case 1: {
	    unsigned char* dst=dmpi->planes[0]+dmpi->stride[0]*y;
	    int x;
	    for(x=0;x<mpi->w;x++)
		dst[x]=(src[x>>3]&bittab[x&7]) ? value1 : value0;
	    break; }
	case 2: {
	    uint16_t* dst=(uint16_t*)(dmpi->planes[0]+dmpi->stride[0]*y);
	    int x;
	    for(x=0;x<mpi->w;x++)
		dst[x]=(src[x>>3]&bittab[x&7]) ? value1 : value0;
	    break; }
	case 4: {
	    uint32_t* dst=(uint32_t*)(dmpi->planes[0]+dmpi->stride[0]*y);
	    int x;
	    for(x=0;x<mpi->w;x++)
		dst[x]=(src[x>>3]&bittab[x&7]) ? value1 : value0;
	    break; }
	}
    }
*/
}

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->fmt,
	MP_IMGTYPE_TEMP, MP_IMGFLAG_ACCEPT_STRIDE,
	mpi->w, mpi->h);

    switch(dmpi->imgfmt){
    case IMGFMT_RGB32:
    case IMGFMT_BGR32:
	convert(mpi,dmpi,4);
	break;
    case IMGFMT_YV12:
        convert(mpi,dmpi,1);
        break;
    default:
	mp_msg(MSGT_VFILTER,MSGL_ERR,"Unhandled format: 0x%X\n",dmpi->imgfmt);
	return 0;
    }

    return vf_next_put_image(vf,dmpi);
}

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

static int query_format(struct vf_instance_s* vf, unsigned int fmt){
    int best;
    if(fmt!=IMGFMT_RGB32 && fmt!=IMGFMT_BGR32) return 0;
    best=find_best(vf);
    if(!best) return 0; // no match
    return vf->next->query_format(vf->next,best);
}

static int open(vf_instance_t *vf, char* args){
    filter = load_tga("/home/yartrebo/programming/remove_logo/output.tga");
    convert_mask_to_strength_mask(filter);

    initialize_gaussian_mask();

    vf->config=config;
    vf->put_image=put_image;
    vf->query_format=query_format;
    vf->priv=malloc(sizeof(struct vf_priv_s));
    memset(vf->priv, 0, sizeof(struct vf_priv_s));
    return 1;
}

vf_info_t vf_info_remove_logo = {
    "remove_logo -> RGB 32bpp only",
    "remove_logo",
    "Robert",
    "testing",
    open,
    NULL
};

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