/*
Copyright (c) 2000-2010, Dirk Krause
All rights reserved.

Redistribution and use in source and binary forms,
with or without modification, are permitted provided
that the following conditions are met:

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.
* Redistributions in binary form must reproduce the above 
  opyright notice, this list of conditions and the following
  disclaimer in the documentation and/or other materials
  provided with the distribution.
* Neither the name of the Dirk Krause nor the names of
  contributors may be used to endorse or promote
  products derived from this software without specific
  prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/



/**	@file	dkbifpng.c	PNG support module for dkbif.
*/



/**	Inside the dkbifpng module.
*/
#define DKBIFPNG_C	1

#include "dkbifi.h"
#include "dkbif.h"




#line 54 "dkbifpng.ctr"




#if DK_HAVE_ZLIB_H	&&	DK_HAVE_PNG_H



/**	Calculate ITM.
	@param	p	Image.
	@param	f	Frame.
*/
static
void
transfer_up DK_P2(dk_bif_t *,p, dk_bif_frame_t *,f)
{
  int ec = 0;
  double dpi_epsilon = DPI_EPSILON;
  f->w = (f->d).png.wi;
  f->h = (f->d).png.he;
  f->ch = (f->d).png.ch;
  f->bpc = (f->d).png.bd;
  if((f->d).png.xppm > 0UL) {
    f->xdpi = 0.0254 * dkma_ul_to_double((f->d).png.xppm);
  }
  if((f->d).png.yppm > 0UL) {
    f->ydpi = 0.0254 * dkma_ul_to_double((f->d).png.yppm);
  }
  /*
    No conversion if the image is at 72 dpi.
    This resolution is PS/EPS/PDF standard, so we avoid
    the conversions.
  */
  dpi_epsilon = 0.0165;
  if(fabs(f->xdpi - 72.0) < dpi_epsilon) {
    if(fabs(f->ydpi - 72.0) < dpi_epsilon) {
      f->xdpi = -1.0; f->ydpi = -1.0;
    }
  }
  
  if((f->d).png.ct == PNG_COLOR_TYPE_PALETTE) {
    f->bpc = 8;
    f->ch = 3;
  }
  f->vmask = dkbif_max_for_bpc(f->bpc);
  f->vmax  = dkma_ul_to_double(f->vmask);
  (f->d).png.vmask = dkbif_max_for_bpc((unsigned short)((f->d).png.bd));
  if((f->d).png.have_kgd) {
    f->mr = dkma_div_double_ok(
      dkma_ul_to_double((unsigned long)((f->d).png.bg.red)),
      f->vmax,
      &ec
    );
    f->mg = dkma_div_double_ok(
      dkma_ul_to_double((unsigned long)((f->d).png.bg.green)),
      f->vmax,
      &ec
    );
    f->mb = dkma_div_double_ok(
      dkma_ul_to_double((unsigned long)((f->d).png.bg.blue)),
      f->vmax,
      &ec
    );
  }
}



/**	Initialize frame structure for PNG image.
	@param	p	Image.
	@param	f	Frame.
*/
static
void
init_png_frame DK_P2(dk_bif_t *,p, dk_bif_frame_t *,f)
{
  f->w = 0UL;
  f->h = 0UL;
  f->ch = 0;
  f->bpc = 0;
  f->vmask = 0;
  f->vmax = 0.0;
  f->xdpi = -1.0;
  f->ydpi = -1.0;
  f->mr = 1.0;
  f->mg = 1.0;
  f->mb = 1.0;
  (f->d).png.wi = 0UL;
  (f->d).png.he = 0UL;
  (f->d).png.vmask = 0;
  (f->d).png.bd = 0;
  (f->d).png.ct = 0;
  (f->d).png.it = 0;
  (f->d).png.zt = 0;
  (f->d).png.ft = 0;
  (f->d).png.ch = 0;
  (f->d).png.bg.red = 255;
  (f->d).png.bg.green = 255;
  (f->d).png.bg.blue = 255;
  (f->d).png.bgp = &((f->d).png.bg);
  (f->d).png.ppm = 0UL;
  (f->d).png.xppm = 0UL;
  (f->d).png.yppm = 0UL;
  (f->d).png.rows = NULL;
  (f->d).png.rowbytes = 0UL;
  (f->d).png.palp = NULL;
  (f->d).png.paln = 0;
  (f->d).png.have_kgd = 0;
}


int
dkbifpng_header DK_P2(dk_bif_t *,p, FILE *,f)
{
  int back = 0;
  png_uint_32 ppm = 0UL, xppm = 0UL, yppm = 0UL;
  int dummy_byte; /* Filter method */
  if((p) && (f)) {
    p->cf = dkbif_frame_new(p, 0UL);
    if(p->cf) {
      p->nof = 1UL;
      init_png_frame(p, p->cf);
      (p->d).png.pp = png_create_read_struct(
        PNG_LIBPNG_VER_STRING, NULL, NULL, NULL
      );
      if((p->d).png.pp) { 
        (p->d).png.pi = png_create_info_struct((p->d).png.pp);
	if((p->d).png.pi) {
#if DK_HAVE_SETJMP_H
          if(setjmp(png_jmpbuf((p->d).png.pp)) == 0) {
#endif
            png_init_io((p->d).png.pp, f);
	    png_read_info((p->d).png.pp, (p->d).png.pi);
	    png_get_IHDR(
	      (p->d).png.pp, (p->d).png.pi,
	      &(((p->cf)->d).png.wi),
	      &(((p->cf)->d).png.he),
	      &(((p->cf)->d).png.bd),
	      &(((p->cf)->d).png.ct),
	      &(((p->cf)->d).png.it),
	      &(((p->cf)->d).png.zt),
	      &(((p->cf)->d).png.ft)
	    );
	    ((p->cf)->d).png.ch = png_get_channels(
	      (p->d).png.pp, (p->d).png.pi
	    );
	    transfer_up(p, p->cf);
	    
	    
	    
	    
	    
	    
	    
	    
	    if(png_get_valid((p->d).png.pp, (p->d).png.pi, PNG_INFO_tRNS)) {
	      png_set_tRNS_to_alpha((p->d).png.pp);
	    }
	    png_read_update_info((p->d).png.pp, (p->d).png.pi);
	    png_get_IHDR(
	      (p->d).png.pp, (p->d).png.pi,
	      &(((p->cf)->d).png.wi),
	      &(((p->cf)->d).png.he),
	      &(((p->cf)->d).png.bd),
	      &(((p->cf)->d).png.ct),
	      &(((p->cf)->d).png.it),
	      &(((p->cf)->d).png.zt),
	      &dummy_byte
	    );
	    ((p->cf)->d).png.ch = png_get_channels(
	      (p->d).png.pp, (p->d).png.pi
	    );
	    ppm = xppm = yppm = 0UL;
	    ppm = png_get_pixels_per_meter((p->d).png.pp, (p->d).png.pi);
	    xppm = png_get_x_pixels_per_meter((p->d).png.pp, (p->d).png.pi);
	    yppm = png_get_y_pixels_per_meter((p->d).png.pp, (p->d).png.pi);
	    if(!xppm) {
	      if(ppm) {
	        xppm = ppm;
	      } else {
	        if(yppm) xppm = yppm;
	      }
	    }
	    if(!yppm) {
	      if(ppm) {
	        yppm = ppm;
	      } else {
	        if(xppm) yppm = xppm;
	      }
	    }
	    ((p->cf)->d).png.xppm = xppm;
	    ((p->cf)->d).png.yppm = yppm;
	    transfer_up(p, p->cf);
	    
	    
	    
	    
	    
	    
	    
	    
	    back = 1;
#if DK_HAVE_SETJMP_H
          } else {
	    back = 0;
	  }
#endif
	} else {
	  /* ERROR: Memory */
	  p->ec = DK_ERR_NOMEM;
	}
      } else {
        /* ERROR: Memory */
	p->ec = DK_ERR_NOMEM;
      }
    } else {
      /* ERROR: Memory */
      p->ec = DK_ERR_NOMEM;
    }
  }
  
  return back;
}



int
dkbifpng_data DK_P2(dk_bif_t *,p, FILE *,f)
{
  int back = 0;
  png_bytep *rowp;
  unsigned long y;
  png_color_16	bg;
  png_color_16p	bgp;
  int ec = 0;
  
  bgp = &bg;
  if(p->cf) {
#if DK_HAVE_SETJMP_H
    if(setjmp(png_jmpbuf((p->d).png.pp)) == 0) {
#endif
      ((p->cf)->d).png.palp = NULL;
      ((p->cf)->d).png.paln = 0;
      ((p->cf)->d).png.rowbytes =
      png_get_rowbytes((p->d).png.pp, (p->d).png.pi);
      
      ((p->cf)->d).png.rows = dk_new(png_bytep,(p->cf)->h);
      if(((p->cf)->d).png.rows) {
        back = 1;
        rowp = ((p->cf)->d).png.rows;
        for(y = 0; y < (p->cf)->h; y++) {
          *rowp = NULL;
	  *rowp = dk_new(png_byte,((p->cf)->d).png.rowbytes);
	  if(!(*rowp)) {
	    back = 0;
	  }
          rowp++;
        }
	if(back) {
	  if(((p->cf)->d).png.ct == PNG_COLOR_TYPE_PALETTE) {
	    png_get_PLTE(
	      (p->d).png.pp, (p->d).png.pi,
	      &(((p->cf)->d).png.palp), &(((p->cf)->d).png.paln)
	    );
	    if(!(((p->cf)->d).png.palp)) {
	      back = 0;
	    }
	    
	    if(!(((p->cf)->d).png.paln)) {
	      back = 0;
	    }
	  }
	}
        if(back) {
          png_read_image((p->d).png.pp, ((p->cf)->d).png.rows);
	  if(png_get_bKGD((p->d).png.pp, (p->d).png.pi, &bgp)) {
	    /* libpng.txt(597): 
	       valid 16-bit red, green and blue values,
	       regardless of color_type
	       NO: LOOKS LIKE 8-bit red, green and blue values!
	    */
	    
	    /*
	    (p->cf)->mr =
	    dkma_ul_to_double((unsigned long)(bgp->red)) / 65535.0;
	    (p->cf)->mg =
	    dkma_ul_to_double((unsigned long)(bgp->green)) / 65535.0;
	    (p->cf)->mb =
	    dkma_ul_to_double((unsigned long)(bgp->blue)) / 65535.0;
	    */
	    (p->cf)->mr = dkma_div_double_ok(
	      dkma_ul_to_double((unsigned long)(bgp->red)),
	      (p->cf)->vmax,
	      &ec
	    );
	    (p->cf)->mg = dkma_div_double_ok(
	      dkma_ul_to_double((unsigned long)(bgp->green)),
	      (p->cf)->vmax,
	      &ec
	    );
	    (p->cf)->mb = dkma_div_double_ok(
	      dkma_ul_to_double((unsigned long)(bgp->blue)),
	      (p->cf)->vmax,
	      &ec
	    );
	    
	  }
        }
      }
#if DK_HAVE_SETJMP_H
    } else {
      back = 0;
    }
#endif

  } 
  return back;
}



/**	Get component.
	@param	p	Image.
	@param	row	Image row.
	@param	i	Byte index.
	@return	The selected value.
*/
static
unsigned short
get_component_at DK_P3(\
  dk_bif_t *,p, png_bytep,row, unsigned long,i\
)
{
  unsigned short back = 0;
  png_byte bh = 0x00, bl = 0x00;
  unsigned short uh = 0, ul = 0;
  unsigned long elpb = 1UL, byteindex = 0UL, innerindex = 0UL;
  unsigned long shiftbits = 0UL;
  
  switch(((p->cf)->d).png.bd) {
    case 16: {			
      bh = row[2UL * i];
      bl = row[2UL * i + 1UL];
    } break;
    case 8: {			
      bl = row[i];
    } break;
    case 4: case 2: case 1: {	
      switch(((p->cf)->d).png.bd) {
        case 4: { elpb = 2UL; } break;
	case 2: { elpb = 4UL; } break;
	default: { elpb = 8UL; } break;
      }
      byteindex = i / elpb;
      innerindex = i % elpb;
      bl = row[byteindex];
      shiftbits = elpb - innerindex - 1;
      switch(((p->cf)->d).png.bd) {
        case 4: { shiftbits = shiftbits * 4UL; } break;
	case 2: { shiftbits = shiftbits * 2UL; } break;
      }
      bl = bl >> shiftbits;
    } break;
  }
  
  uh = (unsigned short)bh; ul = (unsigned short)bl;
  uh = uh << 8; uh = uh & 0xFF00; ul = ul & 0x00FF;
  back = (uh | ul);	
  back = (back & (((p->cf)->d).png.vmask));
  
  return back;
}




unsigned short
dkbifpng_red DK_P3(dk_bif_t *,p, unsigned long,x, unsigned long,y)
{
  unsigned short back = 0;
  png_bytep row = NULL;
  
  if(p->cf) {					
    if( ((p->cf)->d).png.rows ) {		
      row = (((p->cf)->d).png.rows)[y];
      if(row) {					
        switch( ((p->cf)->d).png.ct ) {
          case PNG_COLOR_TYPE_GRAY: {		
	    if( ((p->cf)->d).png.ch == 1 ) {	
	      back = get_component_at(p, row, x);
	    } else {				
	    }
          } break;
          case PNG_COLOR_TYPE_GRAY_ALPHA: {	
	    if( ((p->cf)->d).png.ch == 2 ) {	
	      back = get_component_at(p, row, 2UL*x);
	    } else {				
	    }
          } break;
          case PNG_COLOR_TYPE_PALETTE: {	
	    if( ((p->cf)->d).png.ch == 1 ) {	
	      back = get_component_at(p, row, x);
	      
	      if( ((p->cf)->d).png.palp ) {	
	        if(back < ((p->cf)->d).png.paln) {	
		  back = (((p->cf)->d).png.palp)[back].red;
		  
		} else {			
		}
	      } else {				
	      }
	    } else {				
	    }
          } break;
          case PNG_COLOR_TYPE_RGB: {		
	    if( ((p->cf)->d).png.ch == 3 ) {	
	      back = get_component_at(p, row, 3UL*x);
	    } else {				
	    }
          } break;
          case PNG_COLOR_TYPE_RGB_ALPHA: {	
	    if( ((p->cf)->d).png.ch == 4 ) {	
	      back = get_component_at(p, row, 4UL*x);
	    } else {				
	    }
          } break;
        }
      }
    }
  } 
  return back;
}



unsigned short
dkbifpng_green DK_P3(dk_bif_t *,p, unsigned long,x, unsigned long,y)
{
  unsigned short back = 0;
  png_bytep row = NULL;

  if(p->cf) {
    if( ((p->cf)->d).png.rows ) {
      row = (((p->cf)->d).png.rows)[y];
      if(row) {
        switch( ((p->cf)->d).png.ct ) {
          case PNG_COLOR_TYPE_GRAY: {
	    if( ((p->cf)->d).png.ch == 1 ) {
	      back = get_component_at(p, row, x);
	    }
          } break;
          case PNG_COLOR_TYPE_GRAY_ALPHA: {
	    if( ((p->cf)->d).png.ch == 2 ) {
	      back = get_component_at(p, row, 2UL*x);
	    }
          } break;
          case PNG_COLOR_TYPE_PALETTE: {
	    if( ((p->cf)->d).png.ch == 1 ) {
	      back = get_component_at(p, row, x);
	      if( ((p->cf)->d).png.palp ) {
	        if(back < ((p->cf)->d).png.paln) {
		  back = (((p->cf)->d).png.palp)[back].green;
		}
	      }
	    }
          } break;
          case PNG_COLOR_TYPE_RGB: {
	    if( ((p->cf)->d).png.ch == 3 ) {
	      back = get_component_at(p, row, 3UL*x+1UL);
	    }
          } break;
          case PNG_COLOR_TYPE_RGB_ALPHA: {
	    if( ((p->cf)->d).png.ch == 4 ) {
	      back = get_component_at(p, row, 4UL*x+1UL);
	    }
          } break;
        }
      }
    }
  }
  return back;
}



unsigned short
dkbifpng_blue DK_P3(dk_bif_t *,p, unsigned long,x, unsigned long,y)
{
  unsigned short back = 0;
  png_bytep row = NULL;

  if(p->cf) {
    if( ((p->cf)->d).png.rows ) {
      row = (((p->cf)->d).png.rows)[y];
      if(row) {
        switch( ((p->cf)->d).png.ct ) {
          case PNG_COLOR_TYPE_GRAY: {
	    if( ((p->cf)->d).png.ch == 1 ) {
	      back = get_component_at(p, row, x);
	    }
          } break;
          case PNG_COLOR_TYPE_GRAY_ALPHA: {
	    if( ((p->cf)->d).png.ch == 2 ) {
	      back = get_component_at(p, row, 2UL*x);
	    }
          } break;
          case PNG_COLOR_TYPE_PALETTE: {
	    if( ((p->cf)->d).png.ch == 1 ) {
	      back = get_component_at(p, row, x);
	      if( ((p->cf)->d).png.palp ) {
	        if(back < ((p->cf)->d).png.paln) {
		  back = (((p->cf)->d).png.palp)[back].blue;
		}
	      }
	    }
          } break;
          case PNG_COLOR_TYPE_RGB: {
	    if( ((p->cf)->d).png.ch == 3 ) {
	      back = get_component_at(p, row, 3UL*x+2UL);
	    }
          } break;
          case PNG_COLOR_TYPE_RGB_ALPHA: {
	    if( ((p->cf)->d).png.ch == 4 ) {
	      back = get_component_at(p, row, 4UL*x+2UL);
	    }
          } break;
        }
      }
    }
  }
  return back;
}



unsigned short
dkbifpng_gray DK_P3(dk_bif_t *,p, unsigned long,x, unsigned long,y)
{
  unsigned short back = 0;
  png_bytep row = NULL;
  int ec = 0;
  if(p->cf) {
    if( ((p->cf)->d).png.rows ) {
      row = (((p->cf)->d).png.rows)[y];
      if(row) {
        switch( ((p->cf)->d).png.ct ) {
          case PNG_COLOR_TYPE_GRAY: {
	    if( ((p->cf)->d).png.ch == 1 ) {
	      back = get_component_at(p, row, x);
	    }
          } break;
          case PNG_COLOR_TYPE_GRAY_ALPHA: {
	    if( ((p->cf)->d).png.ch == 2 ) {
	      back = get_component_at(p, row, 2UL*x);
	    }
          } break;
	  default: {	/* convert colors to gray */
	    unsigned short r = 0, g = 0, b = 0;
	    r = dkbifpng_red(p, x, y);
	    g = dkbifpng_green(p, x, y);
	    b = dkbifpng_blue(p, x, y);
	    if(p->fntsc) {
	      back = (unsigned short)(
	        (
	          dkma_add_ulong_ok(
		    dkma_add_ulong_ok(
		      dkma_mul_ulong_ok(54UL,(unsigned long)r,&ec),
		      dkma_mul_ulong_ok(183UL,(unsigned long)g,&ec),
		      &ec
		    ),
		    dkma_mul_ulong_ok(19UL,(unsigned long)b,&ec),
		    &ec
	          ) >> 8
	        ) & 0xFFFF
	      );
	    } else {
	      back = (unsigned short)dkma_double_to_ul_ok(
	        dkma_rint(
	          dkma_add_double_ok(
		    dkma_add_double_ok(
		      dkma_mul_double_ok(
		        0.3,dkma_ul_to_double((unsigned long)r),&ec
		      ),
		      dkma_mul_double_ok(
		        0.59,dkma_ul_to_double((unsigned long)g),&ec
		      ),
		      &ec
		    ),
		    dkma_mul_double_ok(
		      0.11,dkma_ul_to_double((unsigned long)g),&ec
		    ),
		    &ec
		  )
	        ),
	        &ec
	      );
	    }
	    if(ec) { p->ec = DK_ERR_MATH_OOR; }
	  } break;
        }
      }
    }
  }
  return back;
}



unsigned short
dkbifpng_alpha DK_P3(dk_bif_t *,p, unsigned long,x, unsigned long,y)
{
  unsigned short back = 0;
  png_bytep row = NULL;

  if(p->cf) {
    back = (p->cf)->vmask;
    if( ((p->cf)->d).png.rows ) {
      row = (((p->cf)->d).png.rows)[y];
      if(row) {
        switch( ((p->cf)->d).png.ct ) {
          case PNG_COLOR_TYPE_GRAY_ALPHA: {
	    if( ((p->cf)->d).png.ch == 2 ) {
	      back = get_component_at(p, row, 2UL*x+1UL);
	    }
          } break;
          case PNG_COLOR_TYPE_RGB_ALPHA: {
	    if( ((p->cf)->d).png.ch == 4 ) {
	      back = get_component_at(p, row, 4UL*x+3UL);
	    }
          } break;
        }
      }
    }
  }
  return back;
}



void
dkbifpng_frame_release DK_P2(dk_bif_t *,p, dk_bif_frame_t *,f)
{
  png_bytep *rowp;
  unsigned long y;
  if((f->d).png.rows) {
    rowp = (f->d).png.rows;
    for(y = 0; y < f->h; y++) {
      dk_delete(*(rowp++));
    }
    dk_delete((f->d).png.rows);
    (f->d).png.rows = NULL;
    (f->d).png.rowbytes = 0UL;
  }
}



void
dkbifpng_release DK_P1(dk_bif_t *,p)
{
  if((p->d).png.pp) {
    if((p->d).png.pi) {
      png_destroy_info_struct((p->d).png.pp, &((p->d).png.pi));
      (p->d).png.pi = NULL;
    }
    png_destroy_read_struct(&((p->d).png.pp), NULL, NULL);
    (p->d).png.pp = NULL;
  }
}



#endif


