/*
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	dkbifjpg.c	JPEG support module for dkbif.
*/



/**	Inside the dkbifjpg module.
*/
#define	DKBIFJPG_C	1

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




#line 54 "dkbifjpg.ctr"




#if DK_HAVE_JPEGLIB_H



/**	COrrect bits per component setting.
*/
#if BITS_IN_JSAMPLE > 8
#define CORRECT(x) x = ((x >> (BITS_IN_JSAMPLE - 8)) & 0x00FF);
#else
#define CORRECT(x) /* nothing to do */
#endif



unsigned short
dkbifjpg_gray DK_PR((dk_bif_t *p, unsigned long x, unsigned long y));


void
my_error_exit DK_P1(j_common_ptr,cinfo)
{
  dkbif_jpg_error_ptr myerr = (dkbif_jpg_error_ptr)(cinfo->err);
  if(myerr) {
    /* (*cinfo->err->output_message)(cinfo); */
    longjmp(myerr->setjmp_buffer, 1);
  }
}



/**	Initialize frame for JPEG contents.
	@param	p	Image.
	@param	f	Frame.
	@return	1 on success, 0 on error.
*/
static
int
init_jpeg_frame DK_P2(dk_bif_t *,p, dk_bif_frame_t *,f)
{
  int back = 1;
  
  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).jpg.rowbuffer = NULL;
  
  return back;
}


int
dkbifjpg_header DK_P2(dk_bif_t *,p, FILE *,f)
{
  int back = 0;
  int me = 0;
  double dpi_epsilon = DPI_EPSILON;
  
  if((p) && (f)) {
    p->cf = dkbif_frame_new(p, 0UL);
    if(p->cf) {
      p->nof = 1UL;
      if(init_jpeg_frame(p, p->cf)) {
        /* analyze fast by inspecting the file */
	/* (p->d).jpg.jpgana.is_printing = 0; */
	(p->d).jpg.jpgana.inputfile = f;
	(p->d).jpg.jpgana.os = NULL;
	(p->d).jpg.jpgana.a = NULL;
        dkbif_jfif_analyze(&((p->d).jpg.jpgana));
	/* second analysis using jpeg library */
	rewind(f);
        (p->d).jpg.state = 0;
	((p->cf)->d).jpg.rowbuffer = NULL;
        (p->d).jpg.cinfo.err = jpeg_std_error(&((p->d).jpg.emgr.pub));
        (p->d).jpg.emgr.pub.error_exit = my_error_exit;
#if DK_HAVE_SETJMP_H
        if(setjmp((p->d).jpg.emgr.setjmp_buffer)) {
          /* recover from error condition */
          switch((p->d).jpg.state) {
            /* fall-through is intended here */
            case 3: {
            }
            case 2: {
            }
            case 1: {
	      
              jpeg_destroy_decompress(&((p->d).jpg.cinfo));
            }
          }
	  (p->d).jpg.state = 254;
        } else {
#endif
          jpeg_create_decompress(&((p->d).jpg.cinfo));
          (p->d).jpg.state = 1;		/* decompress structure initialized */
          jpeg_stdio_src(&((p->d).jpg.cinfo), f);
          (p->d).jpg.state = 2;		/* input source defined */
          (void)jpeg_read_header(&((p->d).jpg.cinfo), TRUE);
          (p->d).jpg.state = 3;
	  (void)jpeg_start_decompress(&((p->d).jpg.cinfo));
	  (p->d).jpg.state = 4;
	  /* (p->cf)->n = 0UL; */
	  (p->cf)->w = (unsigned long)((p->d).jpg.cinfo.output_width);
	  
	  (p->cf)->h = (unsigned long)((p->d).jpg.cinfo.output_height);
	  
	  (p->cf)->ch = (unsigned long)((p->d).jpg.cinfo.output_components);
	  
	  (p->cf)->bpc = 8;
	  
	  (p->cf)->vmask = dkbif_max_for_bpc((p->cf)->bpc);
	  (p->cf)->vmax = dkma_ul_to_double((unsigned long)((p->cf)->vmax));
          back = 1;
#if DK_HAVE_SETJMP_H
        }
#endif
        if((p->d).jpg.jpgana.is_jfif < 2) {
	  if((p->d).jpg.jpgana.dpi_setting) {
	    (p->cf)->xdpi = dkma_ul_to_double(
	      (unsigned long)((p->d).jpg.jpgana.xres)
	    );
	    (p->cf)->ydpi = dkma_ul_to_double(
	      (unsigned long)((p->d).jpg.jpgana.yres)
	    );
	    if((p->d).jpg.jpgana.dpi_setting == 2) {
	      (p->cf)->xdpi = dkma_mul_double_ok(2.54, (p->cf)->xdpi, &me);
	      (p->cf)->ydpi = dkma_mul_double_ok(2.54, (p->cf)->ydpi, &me);
	      dpi_epsilon = 1.67;
	    }
	    if(fabs((p->cf)->xdpi - 72.0) < dpi_epsilon) {
	        if(fabs((p->cf)->ydpi - 72.0) < dpi_epsilon) {
		  (p->cf)->xdpi = (p->cf)->ydpi = -1.0;
		}
	    }
	  }
	}
      } else {
        /* ERROR: Failed to initialize frame */
	p->ec = DK_ERR_NOMEM;
      }
    } else {
      /* ERROR: Memory */
      p->ec = DK_ERR_NOMEM;
    }
  } else {
    /* ERROR: Invalid pointers */
  }
  
  return back;
}



/**	Abbreviation for use with sizeof operator.
*/
typedef JSAMPLE *LINEPOINTER;



/**	Release buffers.
	@param	f	Frame.
	@param	b	Row buffers to release.
*/
static
void
release_buffer DK_P2(dk_bif_frame_t *,f, JSAMPLE **,b)
{
  JSAMPLE **jspp;
  unsigned long i;
  
  jspp = b;
  for(i = 0UL; i < f->h; i++) {
    if(*jspp) {
      dk_delete(*jspp); *jspp = NULL;
    }
    jspp++;
  }
  dk_delete(b);
  
}



/**	Allocate memory for buffers.
	@param	p	Image.
	@return	Pointer to rows array on success, NULL on error.
*/
static
JSAMPLE **
allocate_buffer DK_P1(dk_bif_t *,p)
{
  JSAMPLE **back = NULL, **jspp;
  size_t ls;
  int ok;
  unsigned long i;
  ls = (p->d).jpg.cinfo.output_width
       * (p->d).jpg.cinfo.output_components
       * sizeof(JSAMPLE);
  back = dk_new(LINEPOINTER,(p->cf)->h);
  if(back) {
    jspp = back;
    for(i = 0UL; i < (p->cf)->h; i++) {
      *(jspp++) = NULL;
    }
    jspp = back; ok = 1;
    for(i = 0UL; i < (p->cf)->h; i++) {
      *jspp = dk_new(JSAMPLE,ls);
      if(!(*jspp)) {
        ok = 0;
      }
      jspp++;
    }
    if(!ok) {
      release_buffer(p->cf, back); back = NULL;
    }
  }
  return back;
}




int
dkbifjpg_data DK_P2(dk_bif_t *,p, FILE *,f)
{
  int back = 0;
  JSAMPLE **jspp;
  unsigned long i;
  
  if((p) && (f)) {	
    if(!(p->cf)) {
      dksto_it_reset(p->fi);
      p->cf = dksto_it_next(p->fi);
    }
    if(p->cf) {		
      ((p->cf)->d).jpg.rowbuffer = allocate_buffer(p);
      if(((p->cf)->d).jpg.rowbuffer) {	
        if((p->d).jpg.state == 4) {
          if(setjmp((p->d).jpg.emgr.setjmp_buffer)) {
	    
	    /* recover from error condition */
	    switch((p->d).jpg.state) {
	      /* fall-through is intended here */
	      case 4: {
	        
	        jpeg_abort((struct jpeg_common_struct *)(&((p->d).jpg.cinfo)));
	      }
	      case 3: {
	      }
	      case 2: {
	      } 
	      case 1: case 5: {
	        
	        jpeg_destroy_decompress(&((p->d).jpg.cinfo));
	      }
	    }
	    (p->d).jpg.state = 254;
	  } else {			
	    
	    jspp = ((p->cf)->d).jpg.rowbuffer;
	    for(i = 0UL; i < (p->cf)->h; i++) {
	      
	      (void)jpeg_read_scanlines(&((p->d).jpg.cinfo), jspp, 1);
	      jspp++;
	    }
	    jpeg_finish_decompress(&((p->d).jpg.cinfo));
	    (p->d).jpg.state = 5;
	    
	    back = 1;
	  }
	}
      } else {				
        /* ERROR: Memory */
	p->ec = DK_ERR_NOMEM;
      }
    }
  }
  
  return back;
}



unsigned short
dkbifjpg_red DK_P3(dk_bif_t *,p, unsigned long,x, unsigned long,y)
{
  unsigned short back = 255;
  JSAMPLE i;
  if(p) {
  if(p->cf) {
  if(x < (p->cf)->w) {
  if(y < (p->cf)->h) {
  if(((p->cf)->d).jpg.rowbuffer) {
  if((p->d).jpg.cinfo.out_color_space == JCS_GRAYSCALE) {
    back = dkbifjpg_gray(p, x, y);
  } else {
    if((p->d).jpg.cinfo.quantize_colors) {
      i = ((((p->cf)->d).jpg.rowbuffer)[y])[x];
      i = (((p->d).jpg.cinfo.colormap)[0])[i];
    } else {
      i = ((((p->cf)->d).jpg.rowbuffer)[y])[3UL * x];
    }
    CORRECT(i)
    back = i;
  }
  }
  }
  }
  }
  }
  return back;
}



unsigned short
dkbifjpg_green DK_P3(dk_bif_t *,p, unsigned long,x, unsigned long,y)
{
  unsigned short back = 255;
  JSAMPLE i;
  if(p) {
  if(p->cf) {
  if(x < (p->cf)->w) {
  if(y < (p->cf)->h) {
  if(((p->cf)->d).jpg.rowbuffer) {
  if((p->d).jpg.cinfo.out_color_space == JCS_GRAYSCALE) {
    back = dkbifjpg_gray(p, x, y);
  } else {
    if((p->d).jpg.cinfo.quantize_colors) {
      i = ((((p->cf)->d).jpg.rowbuffer)[y])[x];
      i = (((p->d).jpg.cinfo.colormap)[1])[i];
    } else {
      i = ((((p->cf)->d).jpg.rowbuffer)[y])[3UL * x + 1UL];
    }
    CORRECT(i)
    back = i;
  }
  }
  }
  }
  }
  }
  return back;
}



unsigned short
dkbifjpg_blue DK_P3(dk_bif_t *,p, unsigned long,x, unsigned long,y)
{
  unsigned short back = 255;
  JSAMPLE i;
  if(p) {
  if(p->cf) {
  if(x < (p->cf)->w) {
  if(y < (p->cf)->h) {
  if(((p->cf)->d).jpg.rowbuffer) {
  if((p->d).jpg.cinfo.out_color_space == JCS_GRAYSCALE) {
    back = dkbifjpg_gray(p, x, y);
  } else {
    if((p->d).jpg.cinfo.quantize_colors) {
      i = ((((p->cf)->d).jpg.rowbuffer)[y])[x];
      i = (((p->d).jpg.cinfo.colormap)[2])[i];
    } else {
      i = ((((p->cf)->d).jpg.rowbuffer)[y])[3UL * x + 2UL];
    }
    CORRECT(i)
    back = i;
  }
  }
  }
  }
  }
  }
  return back;
}



unsigned short
dkbifjpg_gray DK_P3(dk_bif_t *,p, unsigned long,x, unsigned long,y)
{
  unsigned short back = 255;
  JSAMPLE i;
  int ec = 0;
  if(p) {
  if(p->cf) {
  if(x < (p->cf)->w) {
  if(y < (p->cf)->h) {
  if(((p->cf)->d).jpg.rowbuffer) {
  if((p->d).jpg.cinfo.out_color_space == JCS_GRAYSCALE) {
    i = ((((p->cf)->d).jpg.rowbuffer)[y])[x];
    if((p->d).jpg.cinfo.quantize_colors) {
      i = (((p->d).jpg.cinfo.colormap)[0])[i];
    }
    CORRECT(i)
    back = i;
  } else {
    /* get r,g,b and use formula */
    unsigned short r, g, b;
    r = dkbifjpg_red(p, x, y);
    g = dkbifjpg_green(p, x, y);
    b = dkbifjpg_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; }
  }
  }
  }
  }
  }
  }
  return back;
}



unsigned short
dkbifjpg_alpha DK_P3(dk_bif_t *,p, unsigned long,x, unsigned long,y)
{
  unsigned short back = 255;
  return back;
}



void
dkbifjpg_frame_release DK_P2(dk_bif_t *,p, dk_bif_frame_t *,f)
{
  
  if((p) && (f)) {
    if((f->d).jpg.rowbuffer) {
      
      release_buffer(f, (f->d).jpg.rowbuffer);
      (f->d).jpg.rowbuffer = NULL;
    }
  }
  
}



void
dkbifjpg_release DK_P1(dk_bif_t *,p)
{
  
  if(p) {
    if(setjmp((p->d).jpg.emgr.setjmp_buffer)) {
      
    } else {
      switch((p->d).jpg.state) {
        case 4: {
	  
	  jpeg_abort((struct jpeg_common_struct *)(&((p->d).jpg.cinfo)));
	}
        case 3: {
	}
	case 2: {
	}
        case 5: case 1: {
	  
	  jpeg_destroy_decompress(&((p->d).jpg.cinfo));
	}
      }
      (p->d).jpg.state = 255;
    }
  }
  
}



#endif



