/* Copyright (C) 1995 Aladdin Enterprises.  All rights reserved.
  
  This file is part of Aladdin Ghostscript.
  
  Aladdin Ghostscript is distributed with NO WARRANTY OF ANY KIND.  No author
  or distributor accepts any responsibility for the consequences of using it,
  or for whether it serves any particular purpose or works at all, unless he
  or she says so in writing.  Refer to the Aladdin Ghostscript Free Public
  License (the "License") for full details.
  
  Every copy of Aladdin Ghostscript must include a copy of the License,
  normally in a plain ASCII text file named PUBLIC.  The License grants you
  the right to copy, modify and redistribute Aladdin Ghostscript, but only
  under certain conditions described in the License.  Among other things, the
  License requires that the copyright notice and this notice be preserved on
  all copies.
*/

/* gsimage0.c */
/* Generic image enumeration and cleanup */
#include "gx.h"
#include "memory_.h"
#include "gserrors.h"
#include "gxdevice.h"
#include "gxfixed.h"
#include "gzstate.h"
#include "gzpath.h"			/* for gxcpath.h */
#include "gxcpath.h"
#include "gximage.h"

/* Process the next piece of an image */
int
gs_image_next(register gs_image_enum *penum, const byte *dbytes, uint dsize,
  uint *pused)
{	uint rsize = penum->bytes_per_row;
	uint pos = penum->byte_in_row;
	int width = penum->width;
	int nplanes = penum->num_planes;
	uint dleft = dsize;
	uint dpos = 0;
	uint rows = 0;
	gs_state *pgs = penum->pgs;
	gx_device *save_dev = 0;
	fixed adjust;
	int code;

	/* Accumulate separated colors, if needed */

	if ( penum->plane_index != 0 )
	  if ( dsize != penum->planes[0].size )
	    return_error(gs_error_undefinedresult);
	penum->planes[penum->plane_index].data = dbytes;
	penum->planes[penum->plane_index].size = dsize;
	if ( ++(penum->plane_index) != nplanes )
		return 0;
	penum->plane_index = 0;
	adjust = penum->adjust;

	/* We've accumulated an entire set of planes. */
	/* Install the clipping device if needed. */

	if ( !penum->never_clip )
	   {	gx_device_clip *cdev = penum->clip_dev;
		save_dev = gs_currentdevice_inline(pgs);
		cdev->target = save_dev;
		gx_set_device_only(pgs, (gx_device *)cdev);
	   }
	if ( penum->rop_dev )
	  {	gx_device_rop_texture *rtdev = penum->rop_dev;
		gx_device *dev = gs_currentdevice_inline(pgs);
		if ( save_dev == 0 )
		  save_dev = dev;
		((gx_device_forward *)rtdev)->target = dev;
		gx_set_device_only(pgs, (gx_device *)rtdev);
	  }

	/* Now render complete rows. */

	while ( dleft )
	   {	/* Fill up a row, then display it. */
		uint bcount = min(dleft, rsize - pos);
		int px;
		for ( px = 0; px < nplanes; px++ )
		  (*penum->unpack)(penum, &penum->map[px],
				   penum->buffer + (px << penum->log2_xbytes),
				   penum->planes[px].data + dpos, bcount, pos);
		pos += bcount;
		dpos += bcount;
		dleft -= bcount;
		if ( pos == rsize )	/* filled an entire row */
		  {
#ifdef DEBUG
			if ( gs_debug_c('B') )
			  { int i, n = width * penum->spp;
			    dputs("[B]row:");
			    for ( i = 0; i < n; i++ )
			      dprintf1(" %02x", penum->buffer[i]);
			    dputs("\n");
			  }
#endif
			penum->xcur = dda_current(penum->next_x);
			dda_next(penum->next_x);
			penum->ycur = dda_current(penum->next_y);
			dda_next(penum->next_y);
			++rows;		/* count rows for error backout */
			if ( !penum->interpolate )
			  switch ( penum->posture )
			  {
			  case image_portrait:
			    {	/* Precompute integer y and height, */
				/* and check for clipping. */
				fixed yc = penum->ycur,
				  yn = dda_current(penum->next_y);

				if ( yn < yc )
				  { fixed temp = yn; yn = yc; yc = temp; }
				yc -= adjust;
				if ( yc >= penum->clip_box.q.y ) goto mt;
				yn += adjust;
				if ( yn <= penum->clip_box.p.y ) goto mt;
				penum->yci = fixed2int_var_rounded(yc);
				penum->hci =
				  fixed2int_var_rounded(yn) - penum->yci;
				if ( penum->hci == 0 ) goto mt;
			    }	break;
			  case image_landscape:
			    {	/* Check for no pixel centers in x. */
				fixed xc = penum->xcur,
				  xn = dda_current(penum->next_x);

				xc -= adjust;
				if ( xn < xc )
				  { fixed temp = xn; xn = xc; xc = temp; }
				if ( xc >= penum->clip_box.q.x ) goto mt;
				xn += adjust;
				if ( xn <= penum->clip_box.p.x ) goto mt;
				penum->xci = fixed2int_var_rounded(xc);
				penum->wci =
				  fixed2int_var_rounded(xn) - penum->xci;
				if ( penum->wci == 0 ) goto mt;
			    }	break;
			  case image_skewed:
			    ;
			  }
			code = (*penum->render)(penum, penum->buffer,
						width * penum->spp, 1);
			if ( code < 0 )
			  goto err;
mt:			if ( ++(penum->y) == penum->height )
			  goto end;
			pos = 0;
		   }
	   }
	penum->byte_in_row = pos;
	code = 0;
	goto out;
end:	/* End of data.  Render any left-over buffered data. */
	switch ( penum->posture )
	  {
	  case image_portrait:
	    {	fixed yc = dda_current(penum->next_y);
		penum->yci = fixed2int_rounded(yc - adjust);
		penum->hci = fixed2int_rounded(yc + adjust) - penum->yci;
	    }	break;
	  case image_landscape:
	    {	fixed xc = dda_current(penum->next_x);
		penum->xci = fixed2int_rounded(xc - adjust);
		penum->wci = fixed2int_rounded(xc + adjust) - penum->xci;
	    }	break;
	  case image_skewed:		/* pacify compilers */
	    ;
	  }
	code = (*penum->render)(penum, NULL, width * penum->spp, 0);
	if ( code < 0 )
	  { penum->y--;
	    goto err;
	  }
	code = 1;
	goto out;
err:	/* Error or interrupt, restore original state. */
	penum->plane_index = penum->spread - 1;
	penum->y -= rows - 1;
	while ( rows-- )
	  { dda_previous(penum->next_x);
	    dda_previous(penum->next_y);
	  }
	/* Note that caller must call gs_image_cleanup */
	/* for both error and normal termination. */
out:	if ( save_dev != 0 )
		gx_set_device_only(pgs, save_dev);
	if ( code >= 0 )
		*pused = dpos;
	return code;
}

/* Clean up by releasing the buffers. */
void
gs_image_cleanup(register gs_image_enum *penum)
{	gs_memory_t *mem = penum->pgs->memory;
	stream_IScale_state *scaler = penum->scaler;

	gs_free_object(mem, penum->rop_dev, "image RasterOp");
	penum->rop_dev = 0;
	gs_free_object(mem, penum->clip_dev, "image clipper");
	penum->clip_dev = 0;
	if ( scaler != 0 )
	  { (*s_IScale_template.release)((stream_state *)scaler);
	    gs_free_object(mem, scaler, "image scaler state");
	    penum->scaler = 0;
	  }
	gs_free_object(mem, penum->line, "image line");
	penum->line = 0;
	gs_free_object(mem, penum->buffer, "image buffer");
	penum->buffer = 0;
}

/* ------ Unpacking procedures ------ */

void
image_unpack_copy(const gs_image_enum *penum, const sample_map *pmap,
  byte *bptr, const byte *data, uint dsize, uint inpos)
{	register byte *bufp = bptr + inpos;
	if ( data != bufp )
	  memcpy(bufp, data, dsize);
}

void
image_unpack_1(const gs_image_enum *penum, const sample_map *pmap,
  byte *bptr, register const byte *data, uint dsize, uint inpos)
{	register bits32 *bufp = (bits32 *)(bptr + (inpos << 3));
	int left = dsize;
	register const bits32 *map = &pmap->table.lookup4x1to32[0];
	register uint b;
	if ( left & 1 )
	   {	b = data[0];
		bufp[0] = map[b >> 4];
		bufp[1] = map[b & 0xf];
		data++, bufp += 2;
	   }
	left >>= 1;
	while ( left-- )
	   {	b = data[0];
		bufp[0] = map[b >> 4];
		bufp[1] = map[b & 0xf];
		b = data[1];
		bufp[2] = map[b >> 4];
		bufp[3] = map[b & 0xf];
		data += 2, bufp += 4;
	   }
}

void
image_unpack_2(const gs_image_enum *penum, const sample_map *pmap,
  byte *bptr, register const byte *data, uint dsize, uint inpos)
{	register bits16 *bufp = (bits16 *)(bptr + (inpos << 2));
	int left = dsize;
	register const bits16 *map = &pmap->table.lookup2x2to16[0];
	while ( left-- )
	   {	register unsigned b = *data++;
		*bufp++ = map[b >> 4];
		*bufp++ = map[b & 0xf];
	   }
}

void
image_unpack_4(const gs_image_enum *penum, const sample_map *pmap,
  byte *bptr, register const byte *data, uint dsize, uint inpos)
{	register int spread = penum->spread;
	register byte *bufp = bptr + (inpos << 1) * spread;
	int left = dsize;
	register const byte *map = &pmap->table.lookup8[0];
	while ( left-- )
	   {	register unsigned b = *data++;
		*bufp = map[b >> 4]; bufp += spread;
		*bufp = map[b & 0xf]; bufp += spread;
	   }
}

void
image_unpack_8(const gs_image_enum *penum, const sample_map *pmap,
  byte *bptr, const byte *data, uint dsize, uint inpos)
{	register byte *bufp = bptr + inpos;
	if ( pmap->table.lookup8[0] != 0 || pmap->table.lookup8[255] != 255 )
	  {	register uint left = dsize;
		register const byte *map = &pmap->table.lookup8[0];
		while ( left-- )
		  *bufp++ = map[*data++];
	  }
	else if ( data != bufp )
	  memcpy(bufp, data, dsize);
}
