Alien-FreeImage

 view release on metacpan or  search on metacpan

MANIFEST  view on Meta::CPAN

src/Source/FreeImageToolkit/CopyPaste.cpp
src/Source/FreeImageToolkit/Display.cpp
src/Source/FreeImageToolkit/Filters.h
src/Source/FreeImageToolkit/Flip.cpp
src/Source/FreeImageToolkit/JPEGTransform.cpp
src/Source/FreeImageToolkit/MultigridPoissonSolver.cpp
src/Source/FreeImageToolkit/Rescale.cpp
src/Source/FreeImageToolkit/Resize.cpp
src/Source/FreeImageToolkit/Resize.h
src/Source/LibJPEG/ansi2knr.c
src/Source/LibJPEG/cderror.h
src/Source/LibJPEG/cdjpeg.c
src/Source/LibJPEG/cdjpeg.h
src/Source/LibJPEG/change.log
src/Source/LibJPEG/cjpeg.c
src/Source/LibJPEG/ckconfig.c
src/Source/LibJPEG/coderules.txt
src/Source/LibJPEG/djpeg.c
src/Source/LibJPEG/example.c
src/Source/LibJPEG/filelist.txt
src/Source/LibJPEG/install.txt

MANIFEST  view on Meta::CPAN

src/Source/LibJPEG/jddctmgr.c
src/Source/LibJPEG/jdhuff.c
src/Source/LibJPEG/jdinput.c
src/Source/LibJPEG/jdmainct.c
src/Source/LibJPEG/jdmarker.c
src/Source/LibJPEG/jdmaster.c
src/Source/LibJPEG/jdmerge.c
src/Source/LibJPEG/jdpostct.c
src/Source/LibJPEG/jdsample.c
src/Source/LibJPEG/jdtrans.c
src/Source/LibJPEG/jerror.c
src/Source/LibJPEG/jerror.h
src/Source/LibJPEG/jfdctflt.c
src/Source/LibJPEG/jfdctfst.c
src/Source/LibJPEG/jfdctint.c
src/Source/LibJPEG/jidctflt.c
src/Source/LibJPEG/jidctfst.c
src/Source/LibJPEG/jidctint.c
src/Source/LibJPEG/jinclude.h
src/Source/LibJPEG/jmemansi.c
src/Source/LibJPEG/jmemdos.c
src/Source/LibJPEG/jmemdosa.asm

MANIFEST  view on Meta::CPAN

src/Source/LibPNG/LibPNG.2013.vcxproj
src/Source/LibPNG/LibPNG.2013.vcxproj.filters
src/Source/LibPNG/libpng.3
src/Source/LibPNG/libpngpf.3
src/Source/LibPNG/LICENSE
src/Source/LibPNG/png.5
src/Source/LibPNG/png.c
src/Source/LibPNG/png.h
src/Source/LibPNG/pngconf.h
src/Source/LibPNG/pngdebug.h
src/Source/LibPNG/pngerror.c
src/Source/LibPNG/pngget.c
src/Source/LibPNG/pnginfo.h
src/Source/LibPNG/pnglibconf.h
src/Source/LibPNG/pngmem.c
src/Source/LibPNG/pngpread.c
src/Source/LibPNG/pngpriv.h
src/Source/LibPNG/pngread.c
src/Source/LibPNG/pngrio.c
src/Source/LibPNG/pngrtran.c
src/Source/LibPNG/pngrutil.c

MANIFEST  view on Meta::CPAN

src/Source/LibTIFF4/tif_config.h-vms
src/Source/LibTIFF4/tif_config.h.in
src/Source/LibTIFF4/tif_config.vc.h
src/Source/LibTIFF4/tif_config.wince.h
src/Source/LibTIFF4/tif_dir.c
src/Source/LibTIFF4/tif_dir.h
src/Source/LibTIFF4/tif_dirinfo.c
src/Source/LibTIFF4/tif_dirread.c
src/Source/LibTIFF4/tif_dirwrite.c
src/Source/LibTIFF4/tif_dumpmode.c
src/Source/LibTIFF4/tif_error.c
src/Source/LibTIFF4/tif_extension.c
src/Source/LibTIFF4/tif_fax3.c
src/Source/LibTIFF4/tif_fax3.h
src/Source/LibTIFF4/tif_fax3sm.c
src/Source/LibTIFF4/tif_flush.c
src/Source/LibTIFF4/tif_getimage.c
src/Source/LibTIFF4/tif_jbig.c
src/Source/LibTIFF4/tif_jpeg.c
src/Source/LibTIFF4/tif_jpeg_12.c
src/Source/LibTIFF4/tif_luv.c

src/Makefile.srcs  view on Meta::CPAN

VER_MAJOR = 3
VER_MINOR = 17.0
SRCS = ./Source/FreeImage/BitmapAccess.cpp ./Source/FreeImage/ColorLookup.cpp ./Source/FreeImage/FreeImage.cpp ./Source/FreeImage/FreeImageC.c ./Source/FreeImage/FreeImageIO.cpp ./Source/FreeImage/GetType.cpp ./Source/FreeImage/MemoryIO.cpp ./Source/...
INCLS = ./Examples/OpenGL/TextureManager/TextureManager.h ./Examples/Plugin/PluginCradle.h ./Examples/Generic/FIIO_Mem.h ./Source/MapIntrospector.h ./Source/FreeImage - Copie.h ./Source/CacheFile.h ./Source/LibTIFF/tiffconf.vc.h ./Source/LibTIFF/tif_...

INCLUDE = -I. -ISource -ISource/Metadata -ISource/FreeImageToolkit -ISource/LibJPEG -ISource/LibPNG -ISource/LibTIFF4 -ISource/ZLib -ISource/LibOpenJPEG -ISource/OpenEXR -ISource/OpenEXR/Half -ISource/OpenEXR/Iex -ISource/OpenEXR/IlmImf -ISource/Open...

src/Source/FreeImage.h  view on Meta::CPAN

FI_ENUM(FREE_IMAGE_QUANTIZE) {
    FIQ_WUQUANT = 0,		//! Xiaolin Wu color quantization algorithm
    FIQ_NNQUANT = 1,		//! NeuQuant neural-net quantization algorithm by Anthony Dekker
	FIQ_LFPQUANT = 2		//! Lossless Fast Pseudo-Quantization Algorithm by Carsten Klein
};

/** Dithering algorithms.
Constants used in FreeImage_Dither.
*/
FI_ENUM(FREE_IMAGE_DITHER) {
    FID_FS			= 0,	//! Floyd & Steinberg error diffusion
	FID_BAYER4x4	= 1,	//! Bayer ordered dispersed dot dithering (order 2 dithering matrix)
	FID_BAYER8x8	= 2,	//! Bayer ordered dispersed dot dithering (order 3 dithering matrix)
	FID_CLUSTER6x6	= 3,	//! Ordered clustered dot dithering (order 3 - 6x6 matrix)
	FID_CLUSTER8x8	= 4,	//! Ordered clustered dot dithering (order 4 - 8x8 matrix)
	FID_CLUSTER16x16= 5,	//! Ordered clustered dot dithering (order 8 - 16x16 matrix)
	FID_BAYER16x16	= 6		//! Bayer ordered dispersed dot dithering (order 4 dithering matrix)
};

/** Lossless JPEG transformations
Constants used in FreeImage_JPEGTransform

src/Source/FreeImage/Halftoning.cpp  view on Meta::CPAN

//
// Use at your own risk!
// ==========================================================

#include "FreeImage.h"
#include "Utilities.h"

static const int WHITE = 255;
static const int BLACK = 0;

// Floyd & Steinberg error diffusion dithering
// This algorithm use the following filter
//          *   7
//      3   5   1     (1/16)
static FIBITMAP* FloydSteinberg(FIBITMAP *dib) {

#define RAND(RN) (((seed = 1103515245 * seed + 12345) >> 12) % (RN))
#define INITERR(X, Y) (((int) X) - (((int) Y) ? WHITE : BLACK) + ((WHITE/2)-((int)X)) / 2)

	int seed = 0;
	int x, y, p, pixel, threshold, error;
	int width, height, pitch;
	BYTE *bits, *new_bits;
	FIBITMAP *new_dib = NULL;

	// allocate a 8-bit DIB
	width = FreeImage_GetWidth(dib);
	height = FreeImage_GetHeight(dib);
	pitch = FreeImage_GetPitch(dib);
	new_dib = FreeImage_Allocate(width, height, 8);
	if(NULL == new_dib) return NULL;

	// allocate space for error arrays
	int *lerr = (int*)malloc (width * sizeof(int));
	int *cerr = (int*)malloc (width * sizeof(int));
	memset(lerr, 0, width * sizeof(int));
	memset(cerr, 0, width * sizeof(int));

	// left border
	error = 0;
	for(y = 0; y < height; y++) {
		bits = FreeImage_GetScanLine(dib, y);
		new_bits = FreeImage_GetScanLine(new_dib, y);

		threshold = (WHITE / 2 + RAND(129) - 64);
		pixel = bits[0] + error;
		p = (pixel > threshold) ? WHITE : BLACK;
		error = pixel - p;
		new_bits[0] = (BYTE)p;
	}
	// right border
	error = 0;
	for(y = 0; y < height; y++) {
		bits = FreeImage_GetScanLine(dib, y);
		new_bits = FreeImage_GetScanLine(new_dib, y);

		threshold = (WHITE / 2 + RAND(129) - 64);
		pixel = bits[width-1] + error;
		p = (pixel > threshold) ? WHITE : BLACK;
		error = pixel - p;
		new_bits[width-1] = (BYTE)p;
	}
	// top border
	bits = FreeImage_GetBits(dib);
	new_bits = FreeImage_GetBits(new_dib);
	error = 0;
	for(x = 0; x < width; x++) {
		threshold = (WHITE / 2 + RAND(129) - 64);
		pixel = bits[x] + error;
		p = (pixel > threshold) ? WHITE : BLACK;
		error = pixel - p;
		new_bits[x] = (BYTE)p;
		lerr[x] = INITERR(bits[x], p);
	}

	// interior bits
	for(y = 1; y < height; y++) {
		// scan left to right
		bits = FreeImage_GetScanLine(dib, y);
		new_bits = FreeImage_GetScanLine(new_dib, y);

	    cerr[0] = INITERR(bits[0], new_bits[0]);
		for(x = 1; x < width - 1; x++) {
			error = (lerr[x-1] + 5 * lerr[x] + 3 * lerr[x+1] + 7 * cerr[x-1]) / 16;
			pixel = bits[x] + error;
			if(pixel > (WHITE / 2)) {		
				new_bits[x] = WHITE;
				cerr[x] = pixel - WHITE; 
			} else {
				new_bits[x] = BLACK;
				cerr[x] = pixel - BLACK; 
			}
		}
		// set errors for ends of the row
		cerr[0] = INITERR (bits[0], new_bits[0]);
		cerr[width - 1] = INITERR (bits[width - 1], new_bits[width - 1]);

		// swap error buffers
		int *terr = lerr; lerr = cerr; cerr = terr;
	}

	free(lerr);
	free(cerr);

	return new_dib;
}

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

src/Source/FreeImage/MemoryIO.cpp  view on Meta::CPAN

// =====================================================================
// Reading or Writing in Memory stream
// =====================================================================

/**
Reads data from a memory stream
@param buffer Storage location for data
@param size Item size in bytes
@param count Maximum number of items to be read
@param stream Pointer to FIMEMORY structure
@return Returns the number of full items actually read, which may be less than count if an error occurs
*/
unsigned DLL_CALLCONV 
FreeImage_ReadMemory(void *buffer, unsigned size, unsigned count, FIMEMORY *stream) {
	FreeImageIO io;
	SetMemoryIO(&io);

	if (stream != NULL) {
		return io.read_proc(buffer, size, count, stream);
	}

	return 0;
}

/**
Writes data to a memory stream.
@param buffer Pointer to data to be written
@param size Item size in bytes
@param count Maximum number of items to be written
@param stream Pointer to FIMEMORY structure
@return Returns the number of full items actually written, which may be less than count if an error occurs
*/
unsigned DLL_CALLCONV 
FreeImage_WriteMemory(const void *buffer, unsigned size, unsigned count, FIMEMORY *stream) {
	if (stream != NULL) {
		FreeImageIO io;
		SetMemoryIO(&io);

		FIMEMORYHEADER *mem_header = (FIMEMORYHEADER*)(((FIMEMORY*)stream)->data);

		if(mem_header->delete_me == TRUE) {

src/Source/FreeImage/MultiPage.cpp  view on Meta::CPAN

				if (!read_only) {
					std::string cache_name;
					ReplaceExtension(cache_name, filename, "ficache");

					std::auto_ptr<CacheFile> cache_file (new CacheFile(cache_name, keep_cache_in_memory));

					if (cache_file->open()) {
						// we can use release() as std::bad_alloc won't be thrown from here on
						header->m_cachefile = cache_file.release();
					} else {
						// an error occured ...
						fclose(handle);
						return NULL;
					}
				}
				// return the multibitmap
				// std::bad_alloc won't be thrown from here on
				header.release(); // now owned by bitmap
				io.release();	  // now owned by bitmap
				return bitmap.release(); // now owned by caller
			}
		}
	} catch (std::bad_alloc &) {
		/** @todo report error */
	}
	if (handle)
		fclose(handle);
	return NULL;
}

FIMULTIBITMAP * DLL_CALLCONV
FreeImage_OpenMultiBitmapFromHandle(FREE_IMAGE_FORMAT fif, FreeImageIO *io, fi_handle handle, int flags) {
	try {
		BOOL read_only = FALSE;	// modifications (if any) will be stored into the memory cache

src/Source/FreeImage/MultiPage.cpp  view on Meta::CPAN

							header->m_cachefile = cache_file.release();
						}
					}
					tmp_io.release();
					header.release();
					return bitmap.release();
				}
			}
		}
	} catch (std::bad_alloc &) {
		/** @todo report error */
	}
	return NULL;
}

BOOL DLL_CALLCONV
FreeImage_SaveMultiBitmapToHandle(FREE_IMAGE_FORMAT fif, FIMULTIBITMAP *bitmap, FreeImageIO *io, fi_handle handle, int flags) {
	if(!bitmap || !bitmap->data || !io || !handle) {
		return FALSE;
	}

src/Source/FreeImage/MultiPage.cpp  view on Meta::CPAN

					std::string spool_name;

					ReplaceExtension(spool_name, header->m_filename, "fispool");

					// open the spool file and the source file
        
					FILE *f = fopen(spool_name.c_str(), "w+b");
				
					// saves changes
					if (f == NULL) {
						FreeImage_OutputMessageProc(header->fif, "Failed to open %s, %s", spool_name.c_str(), strerror(errno));
						success = FALSE;
					} else {
						success = FreeImage_SaveMultiBitmapToHandle(header->fif, bitmap, header->io, (fi_handle)f, flags);

						// close the files

						if (fclose(f) != 0) {
							success = FALSE;
							FreeImage_OutputMessageProc(header->fif, "Failed to close %s, %s", spool_name.c_str(), strerror(errno));
						}
					}
					if (header->handle) {
						fclose((FILE *)header->handle);
					}
				
					// applies changes to the destination file

					if (success) {
						remove(header->m_filename);

src/Source/FreeImage/NNQuantizer.cpp  view on Meta::CPAN


	// image size as viewed by the scan algorithm
	lengthcount = img_width * img_height * 3;

	// number of samples used for the learning phase
	samplepixels = lengthcount / (3 * sampling_factor);

	// decrease learning rate after delta pixel presentations
	delta = samplepixels / ncycles;
	if(delta == 0) {
		// avoid a 'divide by zero' error with very small images
		delta = 1;
	}

	// initialize learning parameters
	alphadec = 30 + ((sampling_factor - 1) / 3);
	alpha = initalpha;
	radius = initradius;
	
	rad = radius >> radiusbiasshift;
	if (rad <= 1) rad = 0;

src/Source/FreeImage/NNQuantizer.cpp  view on Meta::CPAN



	// 2) Get DIB parameters

	dib_ptr = dib;
	
	img_width  = FreeImage_GetWidth(dib);	// DIB width
	img_height = FreeImage_GetHeight(dib);	// DIB height
	img_line   = FreeImage_GetLine(dib);	// DIB line length in bytes (should be equal to 3 x W)

	// For small images, adjust the sampling factor to avoid a 'divide by zero' error later 
	// (see delta in learn() routine)
	int adjust = (img_width * img_height) / ncycles;
	if(sampling >= adjust)
		sampling = 1;


	// 3) Initialize the network and apply the learning algorithm

	if( netsize > ReserveSize ) {
		netsize -= ReserveSize;

src/Source/FreeImage/PluginG3.cpp  view on Meta::CPAN

#define G3_DEFAULT_WIDTH	1728

#define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3)

// ==========================================================
//   libtiff interface 
// ==========================================================

static tmsize_t 
_g3ReadProc(thandle_t handle, void *buf, tmsize_t size) {
	// returns an error when reading the TIFF header
	return 0;
}

static tmsize_t
_g3WriteProc(thandle_t handle, void *buf, tmsize_t size) {
	// returns ok when writing the TIFF header
	return size;
}

static toff_t

src/Source/FreeImage/PluginG3.cpp  view on Meta::CPAN

			throw FI_MSG_ERROR_MEMORY;
		}

		tifin->tif_rawdatasize = G3GetFileSize(io, handle);
		tifin->tif_rawdata = (tidata_t) _TIFFmalloc(tifin->tif_rawdatasize);
		if (tifin->tif_rawdata == NULL) {
			throw FI_MSG_ERROR_MEMORY;
		}
			
		if(!G3ReadFile(io, handle, tifin->tif_rawdata, tifin->tif_rawdatasize)) {
			throw "Read error at scanline 0";
		}
		tifin->tif_rawcp = tifin->tif_rawdata;
		tifin->tif_rawcc = tifin->tif_rawdatasize;

		(*tifin->tif_setupdecode)(tifin);
		(*tifin->tif_predecode)(tifin, (uint16) 0);
		tifin->tif_row = 0;
		badfaxlines = 0;
		badfaxrun = 0;

src/Source/FreeImage/PluginHDR.cpp  view on Meta::CPAN

	float exposure;				// a value of 1.0 in an image corresponds to <exposure> watts/steradian/m^2. defaults to 1.0
} rgbeHeaderInfo;

#ifdef _WIN32
#pragma pack(pop)
#else
#pragma pack()
#endif

typedef enum {
	rgbe_read_error,
	rgbe_write_error,
	rgbe_format_error,
	rgbe_memory_error
} rgbe_error_code;

// ----------------------------------------------------------
// Prototypes
// ----------------------------------------------------------

static BOOL rgbe_Error(rgbe_error_code error_code, const char *msg);
static BOOL rgbe_GetLine(FreeImageIO *io, fi_handle handle, char *buffer, int length);
static inline void rgbe_FloatToRGBE(BYTE rgbe[4], FIRGBF *rgbf);
static inline void rgbe_RGBEToFloat(FIRGBF *rgbf, BYTE rgbe[4]);
static BOOL rgbe_ReadHeader(FreeImageIO *io, fi_handle handle, unsigned *width, unsigned *height, rgbeHeaderInfo *header_info);
static BOOL rgbe_WriteHeader(FreeImageIO *io, fi_handle handle, unsigned width, unsigned height, rgbeHeaderInfo *info);
static BOOL rgbe_ReadPixels(FreeImageIO *io, fi_handle handle, FIRGBF *data, unsigned numpixels);
static BOOL rgbe_WritePixels(FreeImageIO *io, fi_handle handle, FIRGBF *data, unsigned numpixels);
static BOOL rgbe_ReadPixels_RLE(FreeImageIO *io, fi_handle handle, FIRGBF *data, int scanline_width, unsigned num_scanlines);
static BOOL rgbe_WriteBytes_RLE(FreeImageIO *io, fi_handle handle, BYTE *data, int numbytes);
static BOOL rgbe_WritePixels_RLE(FreeImageIO *io, fi_handle handle, FIRGBF *data, unsigned scanline_width, unsigned num_scanlines);
static BOOL rgbe_ReadMetadata(FIBITMAP *dib, rgbeHeaderInfo *header_info);
static BOOL rgbe_WriteMetadata(FIBITMAP *dib, rgbeHeaderInfo *header_info);

// ----------------------------------------------------------

/**
Default error routine.  change this to change error handling 
*/
static BOOL  
rgbe_Error(rgbe_error_code error_code, const char *msg) {
	switch (error_code) {
		case rgbe_read_error:
			FreeImage_OutputMessageProc(s_format_id, "RGBE read error");
			break;
		case rgbe_write_error:
			FreeImage_OutputMessageProc(s_format_id, "RGBE write error");
			break;
		case rgbe_format_error:
			FreeImage_OutputMessageProc(s_format_id, "RGBE bad file format: %s\n", msg);
			break;
		default:
		case rgbe_memory_error:
			FreeImage_OutputMessageProc(s_format_id, "RGBE error: %s\n",msg);
	}

	return FALSE;
}

/**
Get a line from a ASCII io stream
*/
static BOOL 
rgbe_GetLine(FreeImageIO *io, fi_handle handle, char *buffer, int length) {

src/Source/FreeImage/PluginHDR.cpp  view on Meta::CPAN

	BOOL bFormatFound = FALSE;
	BOOL bHeaderFound = FALSE;

	header_info->valid = 0;
	header_info->programtype[0] = 0;
	header_info->gamma = 1.0;
	header_info->exposure = 1.0;

	// get the first line
	if(!rgbe_GetLine(io, handle, buf, HDR_MAXLINE))
		return rgbe_Error(rgbe_read_error, NULL);

	// check the signature

	if ((buf[0] != '#')||(buf[1] != '?')) {
		// if you don't want to require the magic token then comment the next line
		return rgbe_Error(rgbe_format_error,"bad initial token");
	}
	else {
		header_info->valid |= RGBE_VALID_PROGRAMTYPE;
		for(i = 0; i < sizeof(header_info->programtype) - 1; i++) {
			if((buf[i+2] == 0) || isspace(buf[i+2]))
				break;
			header_info->programtype[i] = buf[i+2];
		}
		header_info->programtype[i] = 0;
	}

	for(;;) {
		// get next line
		if(!rgbe_GetLine(io, handle, buf, HDR_MAXLINE))
			return rgbe_Error(rgbe_read_error, NULL);

		if((buf[0] == 0) || (buf[0] == '\n')) {
			// end of header so break out of loop
			bHeaderFound = TRUE;
			break;
		}
		else if(strcmp(buf,"FORMAT=32-bit_rle_rgbe\n") == 0) {
			bFormatFound = TRUE;
		}
		else if(sscanf(buf, "GAMMA=%g", &tempf) == 1) {

src/Source/FreeImage/PluginHDR.cpp  view on Meta::CPAN

		else if(sscanf(buf,"EXPOSURE=%g",&tempf) == 1) {
			header_info->exposure = tempf;
			header_info->valid |= RGBE_VALID_EXPOSURE;
		}
		else if((buf[0] == '#') && (buf[1] == 0x20)) {
			header_info->valid |= RGBE_VALID_COMMENT;
			strcpy(header_info->comment, buf);
		}
	}
	if(!bHeaderFound || !bFormatFound) {
		return rgbe_Error(rgbe_format_error, "invalid header");
	}

	// get next line
	if(!rgbe_GetLine(io, handle, buf, HDR_MAXLINE))
		return rgbe_Error(rgbe_read_error, NULL);

	// get the image width & height
	if(sscanf(buf,"-Y %d +X %d", height, width) < 2) {
		if(sscanf(buf,"+X %d +Y %d", height, width) < 2) {
			return rgbe_Error(rgbe_format_error, "missing image size specifier");
		}
	}

	return TRUE;
}

/**
 default minimal header. modify if you want more information in header 
*/
static BOOL 

src/Source/FreeImage/PluginHDR.cpp  view on Meta::CPAN

	char buffer[HDR_MAXLINE];

	const char *programtype = "RADIANCE";

	if(info && (info->valid & RGBE_VALID_PROGRAMTYPE)) {
		programtype = info->programtype;
	}
	// The #? is to identify file type, the programtype is optional
	sprintf(buffer, "#?%s\n", programtype);
	if(io->write_proc(buffer, 1, (unsigned int)strlen(buffer), handle) < 1)
		return rgbe_Error(rgbe_write_error, NULL);
	sprintf(buffer, "%s\n", info->comment);
	if(io->write_proc(buffer, 1, (unsigned int)strlen(buffer), handle) < 1)
		return rgbe_Error(rgbe_write_error, NULL);
	sprintf(buffer, "FORMAT=32-bit_rle_rgbe\n");
	if(io->write_proc(buffer, 1, (unsigned int)strlen(buffer), handle) < 1)
		return rgbe_Error(rgbe_write_error, NULL);
	if(info && (info->valid & RGBE_VALID_GAMMA)) {
		sprintf(buffer, "GAMMA=%g\n", info->gamma);
		if(io->write_proc(buffer, 1, (unsigned int)strlen(buffer), handle) < 1)
			return rgbe_Error(rgbe_write_error, NULL);
	}
	if(info && (info->valid & RGBE_VALID_EXPOSURE)) {
		sprintf(buffer,"EXPOSURE=%g\n", info->exposure);
		if(io->write_proc(buffer, 1, (unsigned int)strlen(buffer), handle) < 1)
			return rgbe_Error(rgbe_write_error, NULL);
	}
	sprintf(buffer, "\n-Y %d +X %d\n", height, width);
	if(io->write_proc(buffer, 1, (unsigned int)strlen(buffer), handle) < 1)
		return rgbe_Error(rgbe_write_error, NULL);

	return TRUE;
}

static BOOL 
rgbe_ReadMetadata(FIBITMAP *dib, rgbeHeaderInfo *header_info) {
	return TRUE;
}
static BOOL 
rgbe_WriteMetadata(FIBITMAP *dib, rgbeHeaderInfo *header_info) {

src/Source/FreeImage/PluginHDR.cpp  view on Meta::CPAN


/** 
Simple read routine. Will not correctly handle run length encoding 
*/
static BOOL 
rgbe_ReadPixels(FreeImageIO *io, fi_handle handle, FIRGBF *data, unsigned numpixels) {
  BYTE rgbe[4];

  for(unsigned x = 0; x < numpixels; x++) {
	if(io->read_proc(rgbe, 1, sizeof(rgbe), handle) < 1) {
		return rgbe_Error(rgbe_read_error, NULL);
	}
	rgbe_RGBEToFloat(&data[x], rgbe);
  }

  return TRUE;
}

/**
 Simple write routine that does not use run length encoding. 
 These routines can be made faster by allocating a larger buffer and
 fread-ing and fwrite-ing the data in larger chunks.
*/
static BOOL 
rgbe_WritePixels(FreeImageIO *io, fi_handle handle, FIRGBF *data, unsigned numpixels) {
  BYTE rgbe[4];

  for(unsigned x = 0; x < numpixels; x++) {
	  rgbe_FloatToRGBE(rgbe, &data[x]);
	  if(io->write_proc(rgbe, sizeof(rgbe), 1, handle) < 1)
		  return rgbe_Error(rgbe_write_error, NULL);
  }

  return TRUE;
}

static BOOL 
rgbe_ReadPixels_RLE(FreeImageIO *io, fi_handle handle, FIRGBF *data, int scanline_width, unsigned num_scanlines) {
	BYTE rgbe[4], *scanline_buffer, *ptr, *ptr_end;
	int i, count;
	BYTE buf[2];
	
	if ((scanline_width < 8)||(scanline_width > 0x7fff)) {
		// run length encoding is not allowed so read flat
		return rgbe_ReadPixels(io, handle, data, scanline_width * num_scanlines);
	}
	scanline_buffer = NULL;
	// read in each successive scanline 
	while(num_scanlines > 0) {
		if(io->read_proc(rgbe, 1, sizeof(rgbe), handle) < 1) {
			free(scanline_buffer);
			return rgbe_Error(rgbe_read_error,NULL);
		}
		if((rgbe[0] != 2) || (rgbe[1] != 2) || (rgbe[2] & 0x80)) {
			// this file is not run length encoded
			rgbe_RGBEToFloat(data, rgbe);
			data ++;
			free(scanline_buffer);
			return rgbe_ReadPixels(io, handle, data, scanline_width * num_scanlines - 1);
		}
		if((((int)rgbe[2]) << 8 | rgbe[3]) != scanline_width) {
			free(scanline_buffer);
			return rgbe_Error(rgbe_format_error,"wrong scanline width");
		}
		if(scanline_buffer == NULL) {
			scanline_buffer = (BYTE*)malloc(sizeof(BYTE) * 4 * scanline_width);
			if(scanline_buffer == NULL) {
				return rgbe_Error(rgbe_memory_error, "unable to allocate buffer space");
			}
		}
		
		ptr = &scanline_buffer[0];
		// read each of the four channels for the scanline into the buffer
		for(i = 0; i < 4; i++) {
			ptr_end = &scanline_buffer[(i+1)*scanline_width];
			while(ptr < ptr_end) {
				if(io->read_proc(buf, 1, 2 * sizeof(BYTE), handle) < 1) {
					free(scanline_buffer);
					return rgbe_Error(rgbe_read_error, NULL);
				}
				if(buf[0] > 128) {
					// a run of the same value
					count = buf[0] - 128;
					if((count == 0) || (count > ptr_end - ptr)) {
						free(scanline_buffer);
						return rgbe_Error(rgbe_format_error, "bad scanline data");
					}
					while(count-- > 0)
						*ptr++ = buf[1];
				}
				else {
					// a non-run
					count = buf[0];
					if((count == 0) || (count > ptr_end - ptr)) {
						free(scanline_buffer);
						return rgbe_Error(rgbe_format_error, "bad scanline data");
					}
					*ptr++ = buf[1];
					if(--count > 0) {
						if(io->read_proc(ptr, 1, sizeof(BYTE) * count, handle) < 1) {
							free(scanline_buffer);
							return rgbe_Error(rgbe_read_error, NULL);
						}
						ptr += count;
					}
				}
			}
		}
		// now convert data from buffer into floats
		for(i = 0; i < scanline_width; i++) {
			rgbe[0] = scanline_buffer[i];
			rgbe[1] = scanline_buffer[i+scanline_width];

src/Source/FreeImage/PluginHDR.cpp  view on Meta::CPAN

			run_count = 1;
			while((beg_run + run_count < numbytes) && (run_count < 127) && (data[beg_run] == data[beg_run + run_count])) {
				run_count++;
			}
		}
		// if data before next big run is a short run then write it as such 
		if ((old_run_count > 1)&&(old_run_count == beg_run - cur)) {
			buf[0] = (BYTE)(128 + old_run_count);   // write short run
			buf[1] = data[cur];
			if(io->write_proc(buf, 2 * sizeof(BYTE), 1, handle) < 1)
				return rgbe_Error(rgbe_write_error, NULL);
			cur = beg_run;
		}
		// write out bytes until we reach the start of the next run 
		while(cur < beg_run) {
			nonrun_count = beg_run - cur;
			if (nonrun_count > 128) 
				nonrun_count = 128;
			buf[0] = (BYTE)nonrun_count;
			if(io->write_proc(buf, sizeof(buf[0]), 1, handle) < 1)
				return rgbe_Error(rgbe_write_error,NULL);
			if(io->write_proc(&data[cur], sizeof(data[0]) * nonrun_count, 1, handle) < 1)
				return rgbe_Error(rgbe_write_error,NULL);
			cur += nonrun_count;
		}
		// write out next run if one was found 
		if (run_count >= MINRUNLENGTH) {
			buf[0] = (BYTE)(128 + run_count);
			buf[1] = data[beg_run];
			if(io->write_proc(buf, sizeof(buf[0]) * 2, 1, handle) < 1)
				return rgbe_Error(rgbe_write_error,NULL);
			cur += run_count;
		}
	}
	
	return TRUE;
}

static BOOL 
rgbe_WritePixels_RLE(FreeImageIO *io, fi_handle handle, FIRGBF *data, unsigned scanline_width, unsigned num_scanlines) {
	BYTE rgbe[4];

src/Source/FreeImage/PluginHDR.cpp  view on Meta::CPAN

		// no buffer space so write flat 
		return rgbe_WritePixels(io, handle, data, scanline_width * num_scanlines);
	}
	while(num_scanlines-- > 0) {
		rgbe[0] = (BYTE)2;
		rgbe[1] = (BYTE)2;
		rgbe[2] = (BYTE)(scanline_width >> 8);
		rgbe[3] = (BYTE)(scanline_width & 0xFF);
		if(io->write_proc(rgbe, sizeof(rgbe), 1, handle) < 1) {
			free(buffer);
			return rgbe_Error(rgbe_write_error, NULL);
		}
		for(unsigned x = 0; x < scanline_width; x++) {
			rgbe_FloatToRGBE(rgbe, data);
			buffer[x] = rgbe[0];
			buffer[x+scanline_width] = rgbe[1];
			buffer[x+2*scanline_width] = rgbe[2];
			buffer[x+3*scanline_width] = rgbe[3];
			data ++;
		}
		// write out each of the four channels separately run length encoded

src/Source/FreeImage/PluginJ2K.cpp  view on Meta::CPAN


static int s_format_id;

// ==========================================================
// Internal functions
// ==========================================================

/**
OpenJPEG Error callback 
*/
static void j2k_error_callback(const char *msg, void *client_data) {
	FreeImage_OutputMessageProc(s_format_id, "Error: %s", msg);
}
/**
OpenJPEG Warning callback 
*/
static void j2k_warning_callback(const char *msg, void *client_data) {
	FreeImage_OutputMessageProc(s_format_id, "Warning: %s", msg);
}

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

src/Source/FreeImage/PluginJ2K.cpp  view on Meta::CPAN

		try {
			// decode the JPEG-2000 codestream

			// get a decoder handle
			d_codec = opj_create_decompress(OPJ_CODEC_J2K);
			
			// configure the event callbacks
			// catch events using our callbacks (no local context needed here)
			opj_set_info_handler(d_codec, NULL, NULL);
			opj_set_warning_handler(d_codec, j2k_warning_callback, NULL);
			opj_set_error_handler(d_codec, j2k_error_callback, NULL);

			// setup the decoder decoding parameters using user parameters
			if( !opj_setup_decoder(d_codec, &parameters) ) {
				throw "Failed to setup the decoder\n";
			}
			
			// read the main header of the codestream and if necessary the JP2 boxes
			if( !opj_read_header(d_stream, d_codec, &image)) {
				throw "Failed to read the header\n";
			}

src/Source/FreeImage/PluginJ2K.cpp  view on Meta::CPAN


			// encode the destination image

			// get a J2K compressor handle
			c_codec = opj_create_compress(OPJ_CODEC_J2K);

			// configure the event callbacks
			// catch events using our callbacks (no local context needed here)
			opj_set_info_handler(c_codec, NULL, NULL);
			opj_set_warning_handler(c_codec, j2k_warning_callback, NULL);
			opj_set_error_handler(c_codec, j2k_error_callback, NULL);

			// setup the encoder parameters using the current image and using user parameters
			opj_setup_encoder(c_codec, &parameters, image);

			// encode the image
			bSuccess = opj_start_compress(c_codec, image, c_stream);
			if(bSuccess) {
				bSuccess = bSuccess && opj_encode(c_codec, c_stream);
				if(bSuccess) {
					bSuccess = bSuccess && opj_end_compress(c_codec, c_stream);

src/Source/FreeImage/PluginJP2.cpp  view on Meta::CPAN


static int s_format_id;

// ==========================================================
// Internal functions
// ==========================================================

/**
OpenJPEG Error callback 
*/
static void jp2_error_callback(const char *msg, void *client_data) {
	FreeImage_OutputMessageProc(s_format_id, "Error: %s", msg);
}
/**
OpenJPEG Warning callback 
*/
static void jp2_warning_callback(const char *msg, void *client_data) {
	FreeImage_OutputMessageProc(s_format_id, "Warning: %s", msg);
}

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

src/Source/FreeImage/PluginJP2.cpp  view on Meta::CPAN

		try {
			// decode the JPEG-2000 file

			// get a decoder handle
			d_codec = opj_create_decompress(OPJ_CODEC_JP2);
			
			// configure the event callbacks
			// catch events using our callbacks (no local context needed here)
			opj_set_info_handler(d_codec, NULL, NULL);
			opj_set_warning_handler(d_codec, jp2_warning_callback, NULL);
			opj_set_error_handler(d_codec, jp2_error_callback, NULL);

			// setup the decoder decoding parameters using user parameters
			if( !opj_setup_decoder(d_codec, &parameters) ) {
				throw "Failed to setup the decoder\n";
			}
			
			// read the main header of the codestream and if necessary the JP2 boxes
			if( !opj_read_header(d_stream, d_codec, &image)) {
				throw "Failed to read the header\n";
			}

src/Source/FreeImage/PluginJP2.cpp  view on Meta::CPAN


			// encode the destination image

			// get a JP2 compressor handle
			c_codec = opj_create_compress(OPJ_CODEC_JP2);

			// configure the event callbacks
			// catch events using our callbacks (no local context needed here)
			opj_set_info_handler(c_codec, NULL, NULL);
			opj_set_warning_handler(c_codec, jp2_warning_callback, NULL);
			opj_set_error_handler(c_codec, jp2_error_callback, NULL);

			// setup the encoder parameters using the current image and using user parameters
			opj_setup_encoder(c_codec, &parameters, image);

			// encode the image
			bSuccess = opj_start_compress(c_codec, image, c_stream);
			if(bSuccess) {
				bSuccess = bSuccess && opj_encode(c_codec, c_stream);
				if(bSuccess) {
					bSuccess = bSuccess && opj_end_compress(c_codec, c_stream);

src/Source/FreeImage/PluginJPEG.cpp  view on Meta::CPAN

#pragma warning (disable : 4786) // identifier was truncated to 'number' characters
#endif

extern "C" {
#define XMD_H
#undef FAR
#include <setjmp.h>

#include "../LibJPEG/jinclude.h"
#include "../LibJPEG/jpeglib.h"
#include "../LibJPEG/jerror.h"
}

#include "FreeImage.h"
#include "Utilities.h"

#include "../Metadata/FreeImageTag.h"


// ==========================================================
// Plugin Interface

src/Source/FreeImage/PluginJPEG.cpp  view on Meta::CPAN

#define JFXX_TYPE_JPEG 	0x10	// JFIF extension marker: JPEG-compressed thumbnail image
#define JFXX_TYPE_8bit 	0x11	// JFIF extension marker: palette thumbnail image
#define JFXX_TYPE_24bit	0x13	// JFIF extension marker: RGB thumbnail image

// ----------------------------------------------------------
//   Typedef declarations
// ----------------------------------------------------------

typedef struct tagErrorManager {
	/// "public" fields
	struct jpeg_error_mgr pub;
	/// for return to caller
	jmp_buf setjmp_buffer;
} ErrorManager;

typedef struct tagSourceManager {
	/// public fields
	struct jpeg_source_mgr pub;
	/// source stream
	fi_handle infile;
	FreeImageIO *m_io;

src/Source/FreeImage/PluginJPEG.cpp  view on Meta::CPAN

	struct jpeg_destination_mgr pub;
	/// destination stream
	fi_handle outfile;
	FreeImageIO *m_io;
	/// start of buffer
	JOCTET * buffer;
} DestinationManager;

typedef SourceManager*		freeimage_src_ptr;
typedef DestinationManager* freeimage_dst_ptr;
typedef ErrorManager*		freeimage_error_ptr;

// ----------------------------------------------------------
//   Error handling
// ----------------------------------------------------------

/** Fatal errors (print message and exit) */
static inline void
JPEG_EXIT(j_common_ptr cinfo, int code) {
	freeimage_error_ptr error_ptr = (freeimage_error_ptr)cinfo->err;
	error_ptr->pub.msg_code = code;
	error_ptr->pub.error_exit(cinfo);
}

/** Nonfatal errors (we can keep going, but the data is probably corrupt) */
static inline void
JPEG_WARNING(j_common_ptr cinfo, int code) {
	freeimage_error_ptr error_ptr = (freeimage_error_ptr)cinfo->err;
	error_ptr->pub.msg_code = code;
	error_ptr->pub.emit_message(cinfo, -1);
}

/**
	Receives control for a fatal error.  Information sufficient to
	generate the error message has been stored in cinfo->err; call
	output_message to display it.  Control must NOT return to the caller;
	generally this routine will exit() or longjmp() somewhere.
*/
METHODDEF(void)
jpeg_error_exit (j_common_ptr cinfo) {
	freeimage_error_ptr error_ptr = (freeimage_error_ptr)cinfo->err;

	// always display the message
	error_ptr->pub.output_message(cinfo);

	// allow JPEG with unknown markers
	if(error_ptr->pub.msg_code != JERR_UNKNOWN_MARKER) {
	
		// let the memory manager delete any temp files before we die
		jpeg_destroy(cinfo);
		
		// return control to the setjmp point
		longjmp(error_ptr->setjmp_buffer, 1);		
	}
}

/**
	Actual output of any JPEG message.  Note that this method does not know
	how to generate a message, only where to send it.
*/
METHODDEF(void)
jpeg_output_message (j_common_ptr cinfo) {
	char buffer[JMSG_LENGTH_MAX];
	freeimage_error_ptr error_ptr = (freeimage_error_ptr)cinfo->err;

	// create the message
	error_ptr->pub.format_message(cinfo, buffer);
	// send it to user's message proc
	FreeImage_OutputMessageProc(s_format_id, buffer);
}

// ----------------------------------------------------------
//   Destination manager
// ----------------------------------------------------------

/**
	Initialize destination.  This is called by jpeg_start_compress()

src/Source/FreeImage/PluginJPEG.cpp  view on Meta::CPAN

	suspension is desired.
*/
METHODDEF(boolean)
fill_input_buffer (j_decompress_ptr cinfo) {
	freeimage_src_ptr src = (freeimage_src_ptr) cinfo->src;

	size_t nbytes = src->m_io->read_proc(src->buffer, 1, INPUT_BUF_SIZE, src->infile);

	if (nbytes <= 0) {
		if (src->start_of_file)	{
			// treat empty input file as fatal error

			// let the memory manager delete any temp files before we die
			jpeg_destroy((j_common_ptr)cinfo);

			JPEG_EXIT((j_common_ptr)cinfo, JERR_INPUT_EMPTY);
		}

		JPEG_WARNING((j_common_ptr)cinfo, JWRN_JPEG_EOF);

		/* Insert a fake EOI marker */

src/Source/FreeImage/PluginJPEG.cpp  view on Meta::CPAN

		src->pub.bytes_in_buffer -= (size_t) num_bytes;
	}
}

/**
	Terminate source --- called by jpeg_finish_decompress
	after all data has been read.  Often a no-op.

	NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
	application must deal with any cleanup that should happen even
	for error exit.
*/
METHODDEF(void)
term_source (j_decompress_ptr cinfo) {
  // no work necessary here
}

// ----------------------------------------------------------
//   Source manager & Destination manager setup
// ----------------------------------------------------------

src/Source/FreeImage/PluginJPEG.cpp  view on Meta::CPAN

  returned data, and *icc_data_len is set to its length.
  
  IMPORTANT: the data at **icc_data_ptr has been allocated with malloc()
  and must be freed by the caller with free() when the caller no longer
  needs it.  (Alternatively, we could write this routine to use the
  IJG library's memory allocator, so that the data would be freed implicitly
  at jpeg_finish_decompress() time.  But it seems likely that many apps
  will prefer to have the data stick around after decompression finishes.)
  
  NOTE: if the file contains invalid ICC APP2 markers, we just silently
  return FALSE.  You might want to issue an error message instead.
*/
static BOOL 
jpeg_read_icc_profile(j_decompress_ptr cinfo, JOCTET **icc_data_ptr, unsigned *icc_data_len) {
	jpeg_saved_marker_ptr marker;
	int num_markers = 0;
	int seq_no;
	JOCTET *icc_data;
	unsigned total_length;

	const int MAX_SEQ_NO = 255;			// sufficient since marker numbers are bytes

src/Source/FreeImage/PluginJPEG.cpp  view on Meta::CPAN

static FIBITMAP * DLL_CALLCONV
Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
	if (handle) {
		FIBITMAP *dib = NULL;

		BOOL header_only = (flags & FIF_LOAD_NOPIXELS) == FIF_LOAD_NOPIXELS;

		// set up the jpeglib structures

		struct jpeg_decompress_struct cinfo;
		ErrorManager fi_error_mgr;

		try {

			// step 1: allocate and initialize JPEG decompression object

			// we set up the normal JPEG error routines, then override error_exit & output_message
			cinfo.err = jpeg_std_error(&fi_error_mgr.pub);
			fi_error_mgr.pub.error_exit     = jpeg_error_exit;
			fi_error_mgr.pub.output_message = jpeg_output_message;
			
			// establish the setjmp return context for jpeg_error_exit to use
			if (setjmp(fi_error_mgr.setjmp_buffer)) {
				// If we get here, the JPEG code has signaled an error.
				// We need to clean up the JPEG object, close the input file, and return.
				jpeg_destroy_decompress(&cinfo);
				throw (const char*)NULL;
			}

			jpeg_create_decompress(&cinfo);

			// step 2a: specify data source (eg, a handle)

			jpeg_freeimage_src(&cinfo, handle, io);

src/Source/FreeImage/PluginJPEG.cpp  view on Meta::CPAN


			if(bpp == 8) {
				// allow grey, reverse grey and palette 
				if ((color_type != FIC_MINISBLACK) && (color_type != FIC_MINISWHITE) && (color_type != FIC_PALETTE)) {
					throw sError;
				}
			}


			struct jpeg_compress_struct cinfo;
			ErrorManager fi_error_mgr;

			// Step 1: allocate and initialize JPEG compression object

			// we set up the normal JPEG error routines, then override error_exit & output_message
			cinfo.err = jpeg_std_error(&fi_error_mgr.pub);
			fi_error_mgr.pub.error_exit     = jpeg_error_exit;
			fi_error_mgr.pub.output_message = jpeg_output_message;
			
			// establish the setjmp return context for jpeg_error_exit to use
			if (setjmp(fi_error_mgr.setjmp_buffer)) {
				// If we get here, the JPEG code has signaled an error.
				// We need to clean up the JPEG object, close the input file, and return.
				jpeg_destroy_compress(&cinfo);
				throw (const char*)NULL;
			}

			// Now we can initialize the JPEG compression object

			jpeg_create_compress(&cinfo);

			// Step 2: specify data destination (eg, a file)

src/Source/FreeImage/PluginJXR.cpp  view on Meta::CPAN

		return WMP_errSuccess;
	}
	return WMP_errOutOfMemory;
}

// ==========================================================
// JPEG XR Error handling
// ==========================================================

static const char* 
JXR_ErrorMessage(const int error) {
	switch(error) {
		case WMP_errNotYetImplemented:
		case WMP_errAbstractMethod:
			return "Not yet implemented";
		case WMP_errOutOfMemory:
			return "Out of memory";
		case WMP_errFileIO:
			return "File I/O error";
		case WMP_errBufferOverflow:
			return "Buffer overflow";
		case WMP_errInvalidParameter:
			return "Invalid parameter";
		case WMP_errInvalidArgument:
			return "Invalid argument";
		case WMP_errUnsupportedFormat:
			return "Unsupported format";
		case WMP_errIncorrectCodecVersion:
			return "Incorrect codec version";

src/Source/FreeImage/PluginJXR.cpp  view on Meta::CPAN

		case WMP_errNotInitialized:
		default:
			return "Invalid instruction - please contact the FreeImage team";
	}
}

// ==========================================================
// Helper functions & macro
// ==========================================================

#define JXR_CHECK(error_code) \
	if(error_code < 0) { \
		const char *error_message = JXR_ErrorMessage(error_code); \
		throw error_message; \
	}

// --------------------------------------------------------------------------

/**
Input conversions natively understood by FreeImage
@see GetNativePixelFormat
*/
typedef struct tagJXRInputConversion {
	BITDEPTH_BITS bdBitDepth;

src/Source/FreeImage/PluginJXR.cpp  view on Meta::CPAN

@param guid_format (returned value) Output pixel format
@param image_type (returned value) Image type
@param bpp (returned value) Image bit depth
@param red_mask (returned value) RGB mask
@param green_mask (returned value) RGB mask
@param blue_mask (returned value) RGB mask
@return Returns TRUE if successful, returns FALSE otherwise
*/
static ERR
GetInputPixelFormat(PKImageDecode *pDecoder, PKPixelFormatGUID *guid_format, FREE_IMAGE_TYPE *image_type, unsigned *bpp, unsigned *red_mask, unsigned *green_mask, unsigned *blue_mask) {
	ERR error_code = 0;		// error code as returned by the interface
	PKPixelInfo pixelInfo;	// image specifications

	try {		
		// get input file pixel format ...
		PKPixelFormatGUID pguidSourcePF;
		error_code = pDecoder->GetPixelFormat(pDecoder, &pguidSourcePF);
		JXR_CHECK(error_code);
		pixelInfo.pGUIDPixFmt = &pguidSourcePF;
		// ... check for a supported format and get the format specifications
		error_code = PixelFormatLookup(&pixelInfo, LOOKUP_FORWARD);
		JXR_CHECK(error_code);

		// search for an equivalent native FreeImage format
		error_code = GetNativePixelFormat(&pixelInfo, guid_format, image_type, bpp, red_mask, green_mask, blue_mask);

		if(error_code != WMP_errSuccess) {
			// try to find a suitable conversion function ...
			const PKPixelFormatGUID *ppguidTargetPF = NULL;	// target pixel format
			unsigned iIndex = 0;	// first available conversion function
			do {
				error_code = PKFormatConverter_EnumConversions(&pguidSourcePF, iIndex, &ppguidTargetPF);
				if(error_code == WMP_errSuccess) {
					// found a conversion function, is the converted format a native FreeImage format ?
					pixelInfo.pGUIDPixFmt = ppguidTargetPF;
					error_code = PixelFormatLookup(&pixelInfo, LOOKUP_FORWARD);
					JXR_CHECK(error_code);
					error_code = GetNativePixelFormat(&pixelInfo, guid_format, image_type, bpp, red_mask, green_mask, blue_mask);
					if(error_code == WMP_errSuccess) {
						break;
					}
				}
				// try next conversion function
				iIndex++;
			} while(error_code != WMP_errIndexNotFound);

		}

		return (error_code == WMP_errSuccess) ? WMP_errSuccess : WMP_errUnsupportedFormat;

	} catch(...) {
		return error_code;
	}
}

// --------------------------------------------------------------------------

/**
Scan input dib format and return the equivalent PKPixelFormatGUID format for saving
@param dib Image to be saved
@param guid_format (returned value) GUID format
@param bHasAlpha (returned value) TRUE if an alpha layer is present

src/Source/FreeImage/PluginJXR.cpp  view on Meta::CPAN

	ReadPropVariant(WMP_tagHostComputer, pDescMetadata->pvarHostComputer, dib);
	return WMP_errSuccess;
}

/**
Read ICC, XMP, Exif, Exif-GPS, IPTC, descriptive (i.e. Exif-TIFF) metadata
@see ReadProfile, ReadDescriptiveMetadata
*/
static ERR
ReadMetadata(PKImageDecode *pID, FIBITMAP *dib) {
	ERR error_code = 0;		// error code as returned by the interface
	size_t currentPos = 0;	// current stream position
	
	WMPStream *pStream = pID->pStream;
	WmpDEMisc *wmiDEMisc = &pID->WMP.wmiDEMisc;
	BYTE *pbProfile = NULL;

	try {
		// save current position
		error_code = pStream->GetPos(pStream, &currentPos);
		JXR_CHECK(error_code);

		// ICC profile
		if(0 != wmiDEMisc->uColorProfileByteCount) {
			unsigned cbByteCount = wmiDEMisc->uColorProfileByteCount;
			unsigned uOffset = wmiDEMisc->uColorProfileOffset;
			error_code = ReadProfile(pStream, cbByteCount, uOffset, &pbProfile);
			JXR_CHECK(error_code);
			FreeImage_CreateICCProfile(dib, pbProfile, cbByteCount);
		}

		// XMP metadata
		if(0 != wmiDEMisc->uXMPMetadataByteCount) {
			unsigned cbByteCount = wmiDEMisc->uXMPMetadataByteCount;
			unsigned uOffset = wmiDEMisc->uXMPMetadataOffset;
			error_code = ReadProfile(pStream, cbByteCount, uOffset, &pbProfile);
			JXR_CHECK(error_code);
			// store the tag as XMP
			FITAG *tag = FreeImage_CreateTag();
			if(tag) {
				FreeImage_SetTagLength(tag, cbByteCount);
				FreeImage_SetTagCount(tag, cbByteCount);
				FreeImage_SetTagType(tag, FIDT_ASCII);
				FreeImage_SetTagValue(tag, pbProfile);
				FreeImage_SetTagKey(tag, g_TagLib_XMPFieldName);
				FreeImage_SetMetadata(FIMD_XMP, dib, FreeImage_GetTagKey(tag), tag);
				FreeImage_DeleteTag(tag);
			}
		}

		// IPTC metadata
		if(0 != wmiDEMisc->uIPTCNAAMetadataByteCount) {
			unsigned cbByteCount = wmiDEMisc->uIPTCNAAMetadataByteCount;
			unsigned uOffset = wmiDEMisc->uIPTCNAAMetadataOffset;
			error_code = ReadProfile(pStream, cbByteCount, uOffset, &pbProfile);
			JXR_CHECK(error_code);
			// decode the IPTC profile
			read_iptc_profile(dib, pbProfile, cbByteCount);
		}

		// Exif metadata
		if(0 != wmiDEMisc->uEXIFMetadataByteCount) {
			unsigned cbByteCount = wmiDEMisc->uEXIFMetadataByteCount;
			unsigned uOffset = wmiDEMisc->uEXIFMetadataOffset;
			error_code = ReadProfile(pStream, cbByteCount, uOffset, &pbProfile);
			JXR_CHECK(error_code);
			// decode the Exif profile
			jpegxr_read_exif_profile(dib, pbProfile, cbByteCount, uOffset);
		}

		// Exif-GPS metadata
		if(0 != wmiDEMisc->uGPSInfoMetadataByteCount) {
			unsigned cbByteCount = wmiDEMisc->uGPSInfoMetadataByteCount;
			unsigned uOffset = wmiDEMisc->uGPSInfoMetadataOffset;
			error_code = ReadProfile(pStream, cbByteCount, uOffset, &pbProfile);
			JXR_CHECK(error_code);
			// decode the Exif-GPS profile
			jpegxr_read_exif_gps_profile(dib, pbProfile, cbByteCount, uOffset);
		}

		// free profile buffer
		free(pbProfile);
		// restore initial position
		error_code = pID->pStream->SetPos(pID->pStream, currentPos);
		JXR_CHECK(error_code);

		// as a LAST STEP, read descriptive metadata
		// these metadata overwrite possible identical Exif-TIFF metadata 
		// that could have been read inside the Exif IFD
		
		return ReadDescriptiveMetadata(pID, dib);

	} catch(...) {
		// free profile buffer
		free(pbProfile);
		if(currentPos) {
			// restore initial position
			pStream->SetPos(pStream, currentPos);
		}
		return error_code;
	}
}

// ==========================================================
// Metadata saving
// ==========================================================

/**
Convert a FITAG (coming from FIMD_EXIF_MAIN) to a DPKPROPVARIANT.
No allocation is needed here, the function just copy pointers when needed. 

src/Source/FreeImage/PluginJXR.cpp  view on Meta::CPAN

	
	return TRUE;
}

/**
Write EXIF_MAIN metadata to JPEG-XR descriptive metadata
@see WritePropVariant
*/
static ERR
WriteDescriptiveMetadata(PKImageEncode *pIE, FIBITMAP *dib) {
	ERR error_code = 0;		// error code as returned by the interface
	DESCRIPTIVEMETADATA DescMetadata;

	// fill the DESCRIPTIVEMETADATA structure (use pointers to arrays when needed)
	WritePropVariant(dib, WMP_tagImageDescription, DescMetadata.pvarImageDescription);
	WritePropVariant(dib, WMP_tagCameraMake, DescMetadata.pvarCameraMake);
	WritePropVariant(dib, WMP_tagCameraModel, DescMetadata.pvarCameraModel);
	WritePropVariant(dib, WMP_tagSoftware, DescMetadata.pvarSoftware);
	WritePropVariant(dib, WMP_tagDateTime, DescMetadata.pvarDateTime);
	WritePropVariant(dib, WMP_tagArtist, DescMetadata.pvarArtist);
	WritePropVariant(dib, WMP_tagCopyright, DescMetadata.pvarCopyright);
	WritePropVariant(dib, WMP_tagRatingStars, DescMetadata.pvarRatingStars);
	WritePropVariant(dib, WMP_tagRatingValue, DescMetadata.pvarRatingValue);
	WritePropVariant(dib, WMP_tagCaption, DescMetadata.pvarCaption);
	WritePropVariant(dib, WMP_tagDocumentName, DescMetadata.pvarDocumentName);
	WritePropVariant(dib, WMP_tagPageName, DescMetadata.pvarPageName);
	WritePropVariant(dib, WMP_tagPageNumber, DescMetadata.pvarPageNumber);
	WritePropVariant(dib, WMP_tagHostComputer, DescMetadata.pvarHostComputer);

	// copy the structure to the encoder
	error_code = pIE->SetDescriptiveMetadata(pIE, &DescMetadata);

	// no need to free anything here
	return error_code;
}

/**
Write ICC, XMP, Exif, Exif-GPS, IPTC, descriptive (i.e. Exif-TIFF) metadata
*/
static ERR
WriteMetadata(PKImageEncode *pIE, FIBITMAP *dib) {
	ERR error_code = 0;		// error code as returned by the interface
	BYTE *profile = NULL;
	unsigned profile_size = 0;
	
	try {
		// write ICC profile
		{
			FIICCPROFILE *iccProfile = FreeImage_GetICCProfile(dib);
			if(iccProfile->data) {
				error_code = pIE->SetColorContext(pIE, (U8*)iccProfile->data, iccProfile->size);
				JXR_CHECK(error_code);
			}
		}
		
		// write descriptive metadata
		if(FreeImage_GetMetadataCount(FIMD_EXIF_MAIN, dib)) {
			error_code = WriteDescriptiveMetadata(pIE, dib);
			JXR_CHECK(error_code);
		}

		// write IPTC metadata
		if(FreeImage_GetMetadataCount(FIMD_IPTC, dib)) {
			// create a binary profile
			if(write_iptc_profile(dib, &profile, &profile_size)) {
				// write the profile
				error_code = PKImageEncode_SetIPTCNAAMetadata_WMP(pIE, profile, profile_size);
				JXR_CHECK(error_code);
				// release profile
				free(profile);
				profile = NULL;
			}
		}

		// write XMP metadata
		{
			FITAG *tag_xmp = NULL;
			if(FreeImage_GetMetadata(FIMD_XMP, dib, g_TagLib_XMPFieldName, &tag_xmp)) {
				error_code = PKImageEncode_SetXMPMetadata_WMP(pIE, (BYTE*)FreeImage_GetTagValue(tag_xmp), FreeImage_GetTagLength(tag_xmp));
				JXR_CHECK(error_code);
			}
		}

		// write Exif metadata
		{
			if(tiff_get_ifd_profile(dib, FIMD_EXIF_EXIF, &profile, &profile_size)) {
				error_code = PKImageEncode_SetEXIFMetadata_WMP(pIE, profile, profile_size);
				JXR_CHECK(error_code);
				// release profile
				free(profile);
				profile = NULL;
			}
		}

		// write Exif GPS metadata
		{
			if(tiff_get_ifd_profile(dib, FIMD_EXIF_GPS, &profile, &profile_size)) {
				error_code = PKImageEncode_SetGPSInfoMetadata_WMP(pIE, profile, profile_size);
				JXR_CHECK(error_code);
				// release profile
				free(profile);
				profile = NULL;
			}
		}

		return WMP_errSuccess;

	} catch(...) {
		free(profile);
		return error_code;
	}
}



// ==========================================================
// Quantization tables (Y, U, V, YHP, UHP, VHP), 
// optimized for PSNR
// ==========================================================

src/Source/FreeImage/PluginJXR.cpp  view on Meta::CPAN

@param pDecoder Decoder handle
@param out_guid_format Target guid format
@param dib Output dib
@param width Image width
@param height Image height
@return Returns 0 if successful, returns ERR otherwise
*/
static ERR
CopyPixels(PKImageDecode *pDecoder, PKPixelFormatGUID out_guid_format, FIBITMAP *dib, int width, int height) {
	PKFormatConverter *pConverter = NULL;	// pixel format converter
	ERR error_code = 0;	// error code as returned by the interface
	BYTE *pb = NULL;	// local buffer used for pixel format conversion
	
	// image dimensions
	const PKRect rect = {0, 0, width, height};

	try {
		// get input file pixel format ...
		PKPixelFormatGUID in_guid_format;
		error_code = pDecoder->GetPixelFormat(pDecoder, &in_guid_format);
		JXR_CHECK(error_code);
		
		// is a format conversion needed ?

		if(IsEqualGUID(out_guid_format, in_guid_format)) {
			// no conversion, load bytes "as is" ...

			// get a pointer to dst pixel data
			BYTE *dib_bits = FreeImage_GetBits(dib);

			// get dst pitch (count of BYTE for stride)
			const unsigned cbStride = FreeImage_GetPitch(dib);			

			// decode and copy bits to dst array
			error_code = pDecoder->Copy(pDecoder, &rect, dib_bits, cbStride);
			JXR_CHECK(error_code);		
		}
		else {
			// we need to use the conversion API ...
			
			// allocate the pixel format converter
			error_code = PKCodecFactory_CreateFormatConverter(&pConverter);
			JXR_CHECK(error_code);
			
			// set the conversion function
			error_code = pConverter->Initialize(pConverter, pDecoder, NULL, out_guid_format);
			JXR_CHECK(error_code);
			
			// get the maximum stride
			unsigned cbStride = 0;
			{
				PKPixelInfo pPIFrom;
				PKPixelInfo pPITo;
				
				pPIFrom.pGUIDPixFmt = &in_guid_format;
				error_code = PixelFormatLookup(&pPIFrom, LOOKUP_FORWARD);
				JXR_CHECK(error_code);

				pPITo.pGUIDPixFmt = &out_guid_format;
				error_code = PixelFormatLookup(&pPITo, LOOKUP_FORWARD);
				JXR_CHECK(error_code);

				unsigned cbStrideFrom = ((pPIFrom.cbitUnit + 7) >> 3) * width;
				unsigned cbStrideTo = ((pPITo.cbitUnit + 7) >> 3) * width;
				cbStride = MAX(cbStrideFrom, cbStrideTo);
			}

			// allocate a local decoder / encoder buffer
			error_code = PKAllocAligned((void **) &pb, cbStride * height, 128);
			JXR_CHECK(error_code);

			// copy / convert pixels
			error_code = pConverter->Copy(pConverter, &rect, pb, cbStride);
			JXR_CHECK(error_code);

			// now copy pixels into the dib
			const size_t line_size = FreeImage_GetLine(dib);
			for(int y = 0; y < height; y++) {
				BYTE *src_bits = (BYTE*)(pb + y * cbStride);
				BYTE *dst_bits = (BYTE*)FreeImage_GetScanLine(dib, y);
				memcpy(dst_bits, src_bits, line_size);
			}
			
			// free the local buffer

src/Source/FreeImage/PluginJXR.cpp  view on Meta::CPAN

#endif
		
		return WMP_errSuccess;

	} catch(...) {
		// free the local buffer
		PKFreeAligned((void **) &pb);
		// free the pixel format converter
		PKFormatConverter_Release(&pConverter);

		return error_code;
	}
}

// --------------------------------------------------------------------------

static FIBITMAP * DLL_CALLCONV
Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
	PKImageDecode *pDecoder = NULL;	// decoder interface
	ERR error_code = 0;				// error code as returned by the interface
	PKPixelFormatGUID guid_format;	// loaded pixel format (== input file pixel format if no conversion needed)
	
	FREE_IMAGE_TYPE image_type = FIT_UNKNOWN;	// input image type
	unsigned bpp = 0;							// input image bit depth
	FIBITMAP *dib = NULL;
	
	// get the I/O stream wrapper
	WMPStream *pDecodeStream = (WMPStream*)data;

	if(!handle || !pDecodeStream) {
		return NULL;
	}

	BOOL header_only = (flags & FIF_LOAD_NOPIXELS) == FIF_LOAD_NOPIXELS;

	try {
		int width, height;	// image dimensions (in pixels)

		// create a JXR decoder interface and initialize function pointers with *_WMP functions
		error_code = PKImageDecode_Create_WMP(&pDecoder);
		JXR_CHECK(error_code);

		// attach the stream to the decoder ...
		// ... then read the image container and the metadata
		error_code = pDecoder->Initialize(pDecoder, pDecodeStream);
		JXR_CHECK(error_code);

		// set decoder parameters
		SetDecoderParameters(pDecoder, flags);

		// get dst image format specifications
		unsigned red_mask = 0, green_mask = 0, blue_mask = 0;
		error_code = GetInputPixelFormat(pDecoder, &guid_format, &image_type, &bpp, &red_mask, &green_mask, &blue_mask);
		JXR_CHECK(error_code);

		// get image dimensions
		pDecoder->GetSize(pDecoder, &width, &height);

		// allocate dst image
		{			
			dib = FreeImage_AllocateHeaderT(header_only, image_type, width, height, bpp, red_mask, green_mask, blue_mask);
			if(!dib) {
				throw FI_MSG_ERROR_DIB_MEMORY;
			}

src/Source/FreeImage/PluginJXR.cpp  view on Meta::CPAN

		// get image resolution
		{
			float resX, resY;	// image resolution (in dots per inch)
			// convert from English units, i.e. dots per inch to universal units, i.e. dots per meter
			pDecoder->GetResolution(pDecoder, &resX, &resY);
			FreeImage_SetDotsPerMeterX(dib, (unsigned)(resX / 0.0254F + 0.5F));
			FreeImage_SetDotsPerMeterY(dib, (unsigned)(resY / 0.0254F + 0.5F));
		}

		// get metadata & ICC profile
		error_code = ReadMetadata(pDecoder, dib);
		JXR_CHECK(error_code);

		if(header_only) {
			// header only mode ...
			
			// free the decoder
			pDecoder->Release(&pDecoder);
			assert(pDecoder == NULL);

			return dib;
		}
		
		// copy pixels into the dib, perform pixel conversion if needed
		error_code = CopyPixels(pDecoder, guid_format, dib, width, height);
		JXR_CHECK(error_code);

		// free the decoder
		pDecoder->Release(&pDecoder);
		assert(pDecoder == NULL);

		return dib;

	} catch (const char *message) {
		// unload the dib
		FreeImage_Unload(dib);

src/Source/FreeImage/PluginJXR.cpp  view on Meta::CPAN

// --------------------------------------------------------------------------

static BOOL DLL_CALLCONV
Save(FreeImageIO *io, FIBITMAP *dib, fi_handle handle, int page, int flags, void *data) {
	BOOL bIsFlipped = FALSE;		// FreeImage DIB are upside-down relative to usual graphic conventions
	PKPixelFormatGUID guid_format;	// image format
	PKPixelInfo pixelInfo;			// image specifications
	BOOL bHasAlpha = FALSE;			// is alpha layer present ?

	PKImageEncode *pEncoder = NULL;		// encoder interface
	ERR error_code = 0;					// error code as returned by the interface

	// get the I/O stream wrapper
	WMPStream *pEncodeStream = (WMPStream*)data;

	if(!dib || !handle || !pEncodeStream) {
		return FALSE;
	}

	try {
		// get image dimensions
		unsigned width = FreeImage_GetWidth(dib);
		unsigned height = FreeImage_GetHeight(dib);

		// check JPEG-XR limits
		if((width < MB_WIDTH_PIXEL) || (height < MB_HEIGHT_PIXEL)) {
			FreeImage_OutputMessageProc(s_format_id, "Unsupported image size: width x height = %d x %d", width, height);
			throw (const char*)NULL;
		}

		// get output pixel format
		error_code = GetOutputPixelFormat(dib, &guid_format, &bHasAlpha);
		JXR_CHECK(error_code);
		pixelInfo.pGUIDPixFmt = &guid_format;
		error_code = PixelFormatLookup(&pixelInfo, LOOKUP_FORWARD);
		JXR_CHECK(error_code);

		// create a JXR encoder interface and initialize function pointers with *_WMP functions
		error_code = PKImageEncode_Create_WMP(&pEncoder);
		JXR_CHECK(error_code);

		// attach the stream to the encoder and set all encoder parameters to zero ...
		error_code = pEncoder->Initialize(pEncoder, pEncodeStream, &pEncoder->WMP.wmiSCP, sizeof(CWMIStrCodecParam));
		JXR_CHECK(error_code);

		// ... then configure the encoder
		SetEncoderParameters(&pEncoder->WMP.wmiSCP, &pixelInfo, flags, bHasAlpha);

		// set pixel format
		pEncoder->SetPixelFormat(pEncoder, guid_format);

		// set image size
		pEncoder->SetSize(pEncoder, width, height);
		

src/Source/FreeImage/PluginJXR.cpp  view on Meta::CPAN

		// dib coordinates are upside-down relative to usual conventions
		bIsFlipped = FreeImage_FlipVertical(dib);

		// get a pointer to dst pixel data
		BYTE *dib_bits = FreeImage_GetBits(dib);

		// get dst pitch (count of BYTE for stride)
		const unsigned cbStride = FreeImage_GetPitch(dib);

		// write metadata + pixels on output
		error_code = pEncoder->WritePixels(pEncoder, height, dib_bits, cbStride);
		JXR_CHECK(error_code);

		// recover dib coordinates
		FreeImage_FlipVertical(dib);

		// free the encoder
		pEncoder->Release(&pEncoder);
		assert(pEncoder == NULL);
		
		return TRUE;

src/Source/FreeImage/PluginPCX.cpp  view on Meta::CPAN

		unsigned width = header.window[2] - header.window[0] + 1;
		unsigned height = header.window[3] - header.window[1] + 1;
		unsigned bitcount = header.bpp * header.planes;

		if (bitcount == 24) {
			dib = FreeImage_AllocateHeader(header_only, width, height, bitcount, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK);
		} else {
			dib = FreeImage_AllocateHeader(header_only, width, height, bitcount);			
		}

		// if the dib couldn't be allocated, throw an error

		if (!dib) {
			throw FI_MSG_ERROR_DIB_MEMORY;
		}

		// metrics handling code

		FreeImage_SetDotsPerMeterX(dib, (unsigned) (((float)header.hdpi) / 0.0254000 + 0.5));
		FreeImage_SetDotsPerMeterY(dib, (unsigned) (((float)header.vdpi) / 0.0254000 + 0.5));

src/Source/FreeImage/PluginPFM.cpp  view on Meta::CPAN

		io->read_proc(&id_two, 1, 1, handle);

		if(id_one == 'P') {
			if(id_two == 'F') {
				image_type = FIT_RGBF;
			} else if(id_two == 'f') {
				image_type = FIT_FLOAT;
			}
		}
		if(image_type == FIT_UNKNOWN) {
			// signature error
			throw FI_MSG_ERROR_MAGIC_NUMBER;
		}

		// Read the header information: width, height and the scale value
		unsigned width  = (unsigned) pfm_get_int(io, handle);
		unsigned height = (unsigned) pfm_get_int(io, handle);
		float scalefactor = 1;

		BOOL bResult = pfm_get_line(io, handle, line_buffer, PFM_MAXLINE);
		if(bResult) {
			bResult = (sscanf(line_buffer, "%f", &scalefactor) == 1) ? TRUE : FALSE;
		}
		if(!bResult) {
			throw "Read error: invalid PFM header";
		}

		// Create a new DIB
		dib = FreeImage_AllocateHeaderT(header_only, image_type, width, height);
		if (dib == NULL) {
			throw FI_MSG_ERROR_DIB_MEMORY;
		}

		if(header_only) {
			// header only mode

src/Source/FreeImage/PluginPFM.cpp  view on Meta::CPAN

			const unsigned lineWidth = 3 * width;
			lineBuffer = (float*)malloc(lineWidth * sizeof(float));
			if(!lineBuffer) {
				throw FI_MSG_ERROR_MEMORY;
			}

			for (unsigned y = 0; y < height; y++) {	
				FIRGBF *bits = (FIRGBF*)FreeImage_GetScanLine(dib, height - 1 - y);

				if(io->read_proc(lineBuffer, sizeof(float), lineWidth, handle) != lineWidth) {
					throw "Read error";
				}
				float *channel = lineBuffer;
				if(scalefactor > 0) {
					// MSB
					for (unsigned x = 0; x < width; x++) {
						REVERSEBYTES(channel++, &bits[x].red);
						REVERSEBYTES(channel++, &bits[x].green);
						REVERSEBYTES(channel++, &bits[x].blue);
					}
				} else {

src/Source/FreeImage/PluginPFM.cpp  view on Meta::CPAN

			const unsigned lineWidth = width;
			lineBuffer = (float*)malloc(lineWidth * sizeof(float));
			if(!lineBuffer) {
				throw FI_MSG_ERROR_MEMORY;
			}

			for (unsigned y = 0; y < height; y++) {	
				float *bits = (float*)FreeImage_GetScanLine(dib, height - 1 - y);

				if(io->read_proc(lineBuffer, sizeof(float), lineWidth, handle) != lineWidth) {
					throw "Read error";
				}
				float *channel = lineBuffer;
				if(scalefactor > 0) {
					// MSB - File is Big endian
					for (unsigned x = 0; x < width; x++) {
						REVERSEBYTES(channel++, &bits[x]);
					}
				} else {
					// LSB - File is Little Endian
					for (unsigned x = 0; x < width; x++) {

src/Source/FreeImage/PluginPNG.cpp  view on Meta::CPAN


// ==========================================================
// libpng interface
// ==========================================================

static void
_ReadProc(png_structp png_ptr, unsigned char *data, png_size_t size) {
    pfi_ioStructure pfio = (pfi_ioStructure)png_get_io_ptr(png_ptr);
	unsigned n = pfio->s_io->read_proc(data, (unsigned int)size, 1, pfio->s_handle);
	if(size && (n == 0)) {
		throw "Read error: invalid or corrupted PNG file";
	}
}

static void
_WriteProc(png_structp png_ptr, unsigned char *data, png_size_t size) {
    pfi_ioStructure pfio = (pfi_ioStructure)png_get_io_ptr(png_ptr);
    pfio->s_io->write_proc(data, (unsigned int)size, 1, pfio->s_handle);
}

static void
_FlushProc(png_structp png_ptr) {
	(png_structp)png_ptr;
	// empty flush implementation
}

static void
error_handler(png_structp png_ptr, const char *error) {
	(png_structp)png_ptr;
	throw error;
}

// in FreeImage warnings disabled

static void
warning_handler(png_structp png_ptr, const char *warning) {
	(png_structp)png_ptr;
	(char*)warning;
}

src/Source/FreeImage/PluginPNG.cpp  view on Meta::CPAN

			BYTE png_check[PNG_BYTES_TO_CHECK];

			io->read_proc(png_check, PNG_BYTES_TO_CHECK, 1, handle);

			if (png_sig_cmp(png_check, (png_size_t)0, PNG_BYTES_TO_CHECK) != 0) {
				return NULL;	// Bad signature
			}
			
			// create the chunk manage structure

			png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, error_handler, warning_handler);

			if (!png_ptr) {
				return NULL;			
			}

			// create the info structure

		    info_ptr = png_create_info_struct(png_ptr);

			if (!info_ptr) {

src/Source/FreeImage/PluginPNG.cpp  view on Meta::CPAN


			row_pointers = (png_bytepp)malloc(height * sizeof(png_bytep));

			if (!row_pointers) {
				png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
				FreeImage_Unload(dib);
				return NULL;
			}

			// read in the bitmap bits via the pointer table
			// allow loading of PNG with minor errors (such as images with several IDAT chunks)

			for (png_uint_32 k = 0; k < height; k++) {
				row_pointers[height - 1 - k] = FreeImage_GetScanLine(dib, k);
			}

			png_set_benign_errors(png_ptr, 1);
			png_read_image(png_ptr, row_pointers);

			// check if the bitmap contains transparency, if so enable it in the header

			if (FreeImage_GetBPP(dib) == 32) {
				if (FreeImage_GetColorType(dib) == FIC_RGBALPHA) {
					FreeImage_SetTransparent(dib, TRUE);
				} else {
					FreeImage_SetTransparent(dib, FALSE);
				}

src/Source/FreeImage/PluginPNG.cpp  view on Meta::CPAN

	int	interlace_type;

	fi_ioStructure fio;
    fio.s_handle = handle;
	fio.s_io = io;

	if ((dib) && (handle)) {
		try {
			// create the chunk manage structure

			png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, error_handler, warning_handler);

			if (!png_ptr)  {
				return FALSE;
			}

			// allocate/initialize the image information data.

			info_ptr = png_create_info_struct(png_ptr);

			if (!info_ptr)  {
				png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
				return FALSE;
			}

			// Set error handling.  REQUIRED if you aren't supplying your own
			// error handling functions in the png_create_write_struct() call.

			if (setjmp(png_jmpbuf(png_ptr)))  {
				// if we get here, we had a problem reading the file

				png_destroy_write_struct(&png_ptr, &info_ptr);

				return FALSE;
			}

			// init the IO

src/Source/FreeImage/PluginPNM.cpp  view on Meta::CPAN

		FREE_IMAGE_TYPE image_type = FIT_BITMAP;	// standard image: 1-, 8-, 24-bit

		// Read the first two bytes of the file to determine the file format
		// "P1" = ascii bitmap, "P2" = ascii greymap, "P3" = ascii pixmap,
		// "P4" = raw bitmap, "P5" = raw greymap, "P6" = raw pixmap

		io->read_proc(&id_one, 1, 1, handle);
		io->read_proc(&id_two, 1, 1, handle);

		if ((id_one != 'P') || (id_two < '1') || (id_two > '6')) {			
			// signature error
			throw FI_MSG_ERROR_MAGIC_NUMBER;
		}

		// Read the header information: width, height and the 'max' value if any

		int width  = GetInt(io, handle);
		int height = GetInt(io, handle);
		int maxval = 1;

		if((id_two == '2') || (id_two == '5') || (id_two == '3') || (id_two == '6')) {

src/Source/FreeImage/PluginRAW.cpp  view on Meta::CPAN

	libraw_processed_image_t *thumb_image = NULL;
	
	try {
		// unpack data
		if(RawProcessor->unpack_thumb() != LIBRAW_SUCCESS) {
			// run silently "LibRaw : failed to run unpack_thumb"
			return NULL;
		}

		// retrieve thumb image
		int error_code = 0;
		thumb_image = RawProcessor->dcraw_make_mem_thumb(&error_code);
		if(thumb_image) {
			if(thumb_image->type != LIBRAW_IMAGE_BITMAP) {
				// attach the binary data to a memory stream
				FIMEMORY *hmem = FreeImage_OpenMemory((BYTE*)thumb_image->data, (DWORD)thumb_image->data_size);
				// get the file type
				FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem, 0);
				if(fif == FIF_JPEG) {
					// rotate according to Exif orientation
					flags |= JPEG_EXIFROTATE;
				}

src/Source/FreeImage/PluginTIFF.cpp  view on Meta::CPAN

_TIFFmemcpy(void* d, const void* s, tmsize_t c) {
	memcpy(d, s, (size_t) c);
}

int
_TIFFmemcmp(const void* p1, const void* p2, tmsize_t c) {
	return (memcmp(p1, p2, (size_t) c));
}

// ----------------------------------------------------------
//   in FreeImage warnings and errors are disabled
// ----------------------------------------------------------

static void
msdosWarningHandler(const char* module, const char* fmt, va_list ap) {
}

TIFFErrorHandler _TIFFwarningHandler = msdosWarningHandler;

static void
msdosErrorHandler(const char* module, const char* fmt, va_list ap) {

src/Source/FreeImage/PluginTIFF.cpp  view on Meta::CPAN

	// use this for diagnostic only (do not use otherwise, even in DEBUG mode)
	/*
	if (module != NULL) {
		char msg[1024];
		vsprintf(msg, fmt, ap);
		FreeImage_OutputMessageProc(s_format_id, "%s: %s", module, msg);
	}
	*/
}

TIFFErrorHandler _TIFFerrorHandler = msdosErrorHandler;

// ----------------------------------------------------------

#define CVT(x)      (((x) * 255L) / ((1L<<16)-1))
#define	SCALE(x)	(((x)*((1L<<16)-1))/255)

// ==========================================================
// Internal functions
// ==========================================================

src/Source/FreeImage/PluginTIFF.cpp  view on Meta::CPAN


			// create a new DIB (take care of different samples-per-pixel in case 
			// of converted CMYK image (RGB conversion is on sample per pixel less)

			if (photometric == PHOTOMETRIC_SEPARATED && samplesperpixel == 4) {
				samplesperpixel = 3;
			}

			dib = CreateImageType(header_only, image_type, width, height, bitspersample, samplesperpixel);
			if (dib == NULL) {
				// free the raster pointer and output an error if allocation failed
				if(raster) {
					_TIFFfree(raster);
				}
				throw FI_MSG_ERROR_DIB_MEMORY;
			}
			
			// fill in the resolution (english or universal)

			ReadResolution(tif, dib);

src/Source/FreeImage/PluginTIFF.cpp  view on Meta::CPAN

				memset(buf, 0, TIFFStripSize(tif) * sizeof(BYTE));
				
				BOOL bThrowMessage = FALSE;
				
				if(planar_config == PLANARCONFIG_CONTIG) {

					for (uint32 y = 0; y < height; y += rowsperstrip) {
						int32 strips = (y + rowsperstrip > height ? height - y : rowsperstrip);

						if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, y, 0), buf, strips * src_line) == -1) {
							// ignore errors as they can be frequent and not really valid errors, especially with fax images
							bThrowMessage = TRUE;							
							/*
							free(buf);
							throw FI_MSG_ERROR_PARSING;
							*/
						} 
						if(src_line == dst_line) {
							// channel count match
							for (int l = 0; l < strips; l++) {							
								memcpy(bits, buf + l * src_line, src_line);

src/Source/FreeImage/PluginTIFF.cpp  view on Meta::CPAN

					// - loop for strip blocks -
					
					for (uint32 y = 0; y < height; y += rowsperstrip) {
						const int32 strips = (y + rowsperstrip > height ? height - y : rowsperstrip);
						
						// - loop for channels (planes) -
						
						for(uint16 sample = 0; sample < samplesperpixel; sample++) {
							
							if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, y, sample), buf, strips * src_line) == -1) {
								// ignore errors as they can be frequent and not really valid errors, especially with fax images
								bThrowMessage = TRUE;	
							} 
									
							if(sample >= chCount) {
								// TODO Write to Extra Channel
								break; 
							}
							
							const unsigned channelOffset = sample * Bpc;			
							

src/Source/FreeImage/PluginTIFF.cpp  view on Meta::CPAN

							
						// done with a strip block, incr to the next
						dib_strip -= strips * dst_pitch;
							
					} // height

				}
				free(buf);
				
				if(bThrowMessage) {
					FreeImage_OutputMessageProc(s_format_id, "Warning: parsing error. Image may be incomplete or contain invalid data !");
				}
				
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
				SwapRedBlue32(dib);
#endif

			} // !header only
			
		} else if(loadMethod == LoadAsTiled) {
			// ---------------------------------------------------------------------------------

src/Source/FreeImage/PluginWebP.cpp  view on Meta::CPAN

}

static FIBITMAP * DLL_CALLCONV
Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
	WebPMux *mux = NULL;
	WebPMuxFrameInfo webp_frame = { 0 };	// raw image
	WebPData color_profile;	// ICC raw data
	WebPData xmp_metadata;	// XMP raw data
	WebPData exif_metadata;	// EXIF raw data
	FIBITMAP *dib = NULL;
	WebPMuxError error_status;

	if(!handle) {
		return NULL;
	}

	try {
		// get the MUX object
		mux = (WebPMux*)data;
		if(!mux) {
			throw (1);
		}
		
		// gets the feature flags from the mux object
		uint32_t webp_flags = 0;
		error_status = WebPMuxGetFeatures(mux, &webp_flags);
		if(error_status != WEBP_MUX_OK) {
			throw (1);
		}

		// get image data
		error_status = WebPMuxGetFrame(mux, 1, &webp_frame);

		if(error_status == WEBP_MUX_OK) {
			// decode the data (can be limited to the header if flags uses FIF_LOAD_NOPIXELS)
			dib = DecodeImage(&webp_frame.bitstream, flags);
			if(!dib) {
				throw (1);
			}
			
			// get ICC profile
			if(webp_flags & ICCP_FLAG) {
				error_status = WebPMuxGetChunk(mux, "ICCP", &color_profile);
				if(error_status == WEBP_MUX_OK) {
					FreeImage_CreateICCProfile(dib, (void*)color_profile.bytes, (long)color_profile.size);
				}
			}

			// get XMP metadata
			if(webp_flags & XMP_FLAG) {
				error_status = WebPMuxGetChunk(mux, "XMP ", &xmp_metadata);
				if(error_status == WEBP_MUX_OK) {
					// create a tag
					FITAG *tag = FreeImage_CreateTag();
					if(tag) {
						FreeImage_SetTagKey(tag, g_TagLib_XMPFieldName);
						FreeImage_SetTagLength(tag, (DWORD)xmp_metadata.size);
						FreeImage_SetTagCount(tag, (DWORD)xmp_metadata.size);
						FreeImage_SetTagType(tag, FIDT_ASCII);
						FreeImage_SetTagValue(tag, xmp_metadata.bytes);
						
						// store the tag
						FreeImage_SetMetadata(FIMD_XMP, dib, FreeImage_GetTagKey(tag), tag);

						// destroy the tag
						FreeImage_DeleteTag(tag);
					}
				}
			}

			// get Exif metadata
			if(webp_flags & EXIF_FLAG) {
				error_status = WebPMuxGetChunk(mux, "EXIF", &exif_metadata);
				if(error_status == WEBP_MUX_OK) {
					// read the Exif raw data as a blob
					jpeg_read_exif_profile_raw(dib, exif_metadata.bytes, (unsigned)exif_metadata.size);
					// read and decode the Exif data
					jpeg_read_exif_profile(dib, exif_metadata.bytes, (unsigned)exif_metadata.size);
				}
			}
		}

		WebPDataClear(&webp_frame.bitstream);

src/Source/FreeImage/PluginWebP.cpp  view on Meta::CPAN


	return FALSE;
}

static BOOL DLL_CALLCONV
Save(FreeImageIO *io, FIBITMAP *dib, fi_handle handle, int page, int flags, void *data) {
	WebPMux *mux = NULL;
	FIMEMORY *hmem = NULL;
	WebPData webp_image;
	WebPData output_data = { 0 };
	WebPMuxError error_status;

	int copy_data = 1;	// 1 : copy data into the mux, 0 : keep a link to local data

	if(!dib || !handle || !data) {
		return FALSE;
	}

	try {

		// get the MUX object

src/Source/FreeImage/PluginWebP.cpp  view on Meta::CPAN

		hmem = FreeImage_OpenMemory();
		if(!hmem || !EncodeImage(hmem, dib, flags)) {
			throw (1);
		}
		// store the blob into the mux
		BYTE *data = NULL;
		DWORD data_size = 0;
		FreeImage_AcquireMemory(hmem, &data, &data_size);
		webp_image.bytes = data;
		webp_image.size = data_size;
		error_status = WebPMuxSetImage(mux, &webp_image, copy_data);
		// no longer needed since copy_data == 1
		FreeImage_CloseMemory(hmem);
		hmem = NULL;
		if(error_status != WEBP_MUX_OK) {
			throw (1);
		}

		// --- set metadata ---
		
		// set ICC color profile
		{
			FIICCPROFILE *iccProfile = FreeImage_GetICCProfile(dib);
			if (iccProfile->size && iccProfile->data) {
				WebPData icc_profile;
				icc_profile.bytes = (uint8_t*)iccProfile->data;
				icc_profile.size = (size_t)iccProfile->size;
				error_status = WebPMuxSetChunk(mux, "ICCP", &icc_profile, copy_data);
				if(error_status != WEBP_MUX_OK) {
					throw (1);
				}
			}
		}

		// set XMP metadata
		{
			FITAG *tag = NULL;
			if(FreeImage_GetMetadata(FIMD_XMP, dib, g_TagLib_XMPFieldName, &tag)) {
				WebPData xmp_profile;
				xmp_profile.bytes = (uint8_t*)FreeImage_GetTagValue(tag);
				xmp_profile.size = (size_t)FreeImage_GetTagLength(tag);
				error_status = WebPMuxSetChunk(mux, "XMP ", &xmp_profile, copy_data);
				if(error_status != WEBP_MUX_OK) {
					throw (1);
				}
			}
		}

		// set Exif metadata
		{
			FITAG *tag = NULL;
			if(FreeImage_GetMetadata(FIMD_EXIF_RAW, dib, g_TagLib_ExifRawFieldName, &tag)) {
				WebPData exif_profile;
				exif_profile.bytes = (uint8_t*)FreeImage_GetTagValue(tag);
				exif_profile.size = (size_t)FreeImage_GetTagLength(tag);
				error_status = WebPMuxSetChunk(mux, "EXIF", &exif_profile, copy_data);
				if(error_status != WEBP_MUX_OK) {
					throw (1);
				}
			}
		}
		
		// get data from mux in WebP RIFF format
		error_status = WebPMuxAssemble(mux, &output_data);
		if(error_status != WEBP_MUX_OK) {
			FreeImage_OutputMessageProc(s_format_id, "Failed to create webp output file");
			throw (1);
		}

		// write the file to the output stream
		if(io->write_proc((void*)output_data.bytes, 1, (unsigned)output_data.size, handle) != output_data.size) {
			FreeImage_OutputMessageProc(s_format_id, "Failed to write webp output file");
			throw (1);
		}

src/Source/FreeImage/PluginXBM.cpp  view on Meta::CPAN


#include "FreeImage.h"
#include "Utilities.h"

// ==========================================================
// Internal functions
// ==========================================================

#define MAX_LINE	512

static const char *ERR_XBM_SYNTAX	= "Syntax error";
static const char *ERR_XBM_LINE		= "Line too long";
static const char *ERR_XBM_DECL		= "Unable to find a line in the file containing the start of C array declaration (\"static char\" or whatever)";
static const char *ERR_XBM_EOFREAD	= "EOF / read error";
static const char *ERR_XBM_WIDTH	= "Invalid width";
static const char *ERR_XBM_HEIGHT	= "Invalid height";
static const char *ERR_XBM_MEMORY	= "Out of memory";

/**
Get a string from a stream. 
Read the string from the current stream to the first newline character. 
The result stored in str is appended with a null character.
@param str Storage location for data 
@param n Maximum number of characters to read 
@param io Pointer to the FreeImageIO structure
@param handle Handle to the stream
@return Returns str. NULL is returned to indicate an error or an end-of-file condition.
*/
static char* 
readLine(char *str, int n, FreeImageIO *io, fi_handle handle) {
	char c;
	int count, i = 0;
	do {
		count = io->read_proc(&c, 1, 1, handle);
		str[i++] = c;
	} while((c != '\n') && (i < n));
	if(count <= 0)

src/Source/FreeImage/PluginXBM.cpp  view on Meta::CPAN

	return c;
}

/**
Read an XBM file into a buffer
@param io Pointer to the FreeImageIO structure
@param handle Handle to the stream
@param widthP (return value) Pointer to the bitmap width
@param heightP (return value) Pointer to the bitmap height
@param dataP (return value) Pointer to the bitmap buffer
@return Returns NULL if OK, returns an error message otherwise
*/
static const char* 
readXBMFile(FreeImageIO *io, fi_handle handle, int *widthP, int *heightP, char **dataP) {
	char line[MAX_LINE], name_and_type[MAX_LINE];
	char* ptr;
	char* t;
	int version = 0;
	int raster_length, v;
	int bytes, bytes_per_line, padding;
	int c1, c2, value1, value2;

src/Source/FreeImage/PluginXBM.cpp  view on Meta::CPAN


static FIBITMAP * DLL_CALLCONV
Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
	char *buffer = NULL;
	int width, height;
	FIBITMAP *dib = NULL;

	try {

		// load the bitmap data
		const char* error = readXBMFile(io, handle, &width, &height, &buffer);
		// Microsoft doesn't implement throw between functions :(
		if(error) throw (char*)error;


		// allocate a new dib
		dib = FreeImage_Allocate(width, height, 1);
		if(!dib) throw (char*)ERR_XBM_MEMORY;

		// write the palette data
		RGBQUAD *pal = FreeImage_GetPalette(dib);
		pal[0].rgbRed = pal[0].rgbGreen = pal[0].rgbBlue = 0;
		pal[1].rgbRed = pal[1].rgbGreen = pal[1].rgbBlue = 255;

src/Source/FreeImage/ZLibInterface.cpp  view on Meta::CPAN

// SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
// PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// Use at your own risk!
// ==========================================================

#include "../ZLib/zlib.h"
#include "FreeImage.h"
#include "Utilities.h"
#include "../ZLib/zutil.h"	/* must be the last header because of error C3163 in VS2008 (_vsnprintf defined in stdio.h) */

/**
Compresses a source buffer into a target buffer, using the ZLib library. 
Upon entry, target_size is the total size of the destination buffer, 
which must be at least 0.1% larger than source_size plus 12 bytes. 

@param target Destination buffer
@param target_size Size of the destination buffer, in bytes
@param source Source buffer
@param source_size Size of the source buffer, in bytes
@return Returns the actual size of the compressed buffer, returns 0 if an error occured
@see FreeImage_ZLibUncompress
*/
DWORD DLL_CALLCONV 
FreeImage_ZLibCompress(BYTE *target, DWORD target_size, BYTE *source, DWORD source_size) {
	uLongf dest_len = (uLongf)target_size;

	int zerr = compress(target, &dest_len, source, source_size);
	switch(zerr) {
		case Z_MEM_ERROR:	// not enough memory
		case Z_BUF_ERROR:	// not enough room in the output buffer
			FreeImage_OutputMessageProc(FIF_UNKNOWN, "Zlib error : %s", zError(zerr));
			return 0;
		case Z_OK:
			return dest_len;
	}

	return 0;
}

/**
Decompresses a source buffer into a target buffer, using the ZLib library. 
Upon entry, target_size is the total size of the destination buffer, 
which must be large enough to hold the entire uncompressed data. 
The size of the uncompressed data must have been saved previously by the compressor 
and transmitted to the decompressor by some mechanism outside the scope of this 
compression library.

@param target Destination buffer
@param target_size Size of the destination buffer, in bytes
@param source Source buffer
@param source_size Size of the source buffer, in bytes
@return Returns the actual size of the uncompressed buffer, returns 0 if an error occured
@see FreeImage_ZLibCompress
*/
DWORD DLL_CALLCONV 
FreeImage_ZLibUncompress(BYTE *target, DWORD target_size, BYTE *source, DWORD source_size) {
	uLongf dest_len = (uLongf)target_size;

	int zerr = uncompress(target, &dest_len, source, source_size);
	switch(zerr) {
		case Z_MEM_ERROR:	// not enough memory
		case Z_BUF_ERROR:	// not enough room in the output buffer
		case Z_DATA_ERROR:	// input data was corrupted
			FreeImage_OutputMessageProc(FIF_UNKNOWN, "Zlib error : %s", zError(zerr));
			return 0;
		case Z_OK:
			return dest_len;
	}

	return 0;
}

/**
Compresses a source buffer into a target buffer, using the ZLib library. 
On success, the target buffer contains a GZIP compatible layout.
Upon entry, target_size is the total size of the destination buffer, 
which must be at least 0.1% larger than source_size plus 24 bytes. 

@param target Destination buffer
@param target_size Size of the destination buffer, in bytes
@param source Source buffer
@param source_size Size of the source buffer, in bytes
@return Returns the actual size of the compressed buffer, returns 0 if an error occured
@see FreeImage_ZLibCompress
*/
DWORD DLL_CALLCONV 
FreeImage_ZLibGZip(BYTE *target, DWORD target_size, BYTE *source, DWORD source_size) {
	uLongf dest_len = (uLongf)target_size - 12;
	DWORD crc = crc32(0L, NULL, 0);

    // set up header (stolen from zlib/gzio.c)
    sprintf((char *)target, "%c%c%c%c%c%c%c%c", 0x1f, 0x8b,
         Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/);
    int zerr = compress2(target + 8, &dest_len, source, source_size, Z_BEST_COMPRESSION);
	switch(zerr) {
		case Z_MEM_ERROR:	// not enough memory
		case Z_BUF_ERROR:	// not enough room in the output buffer
			FreeImage_OutputMessageProc(FIF_UNKNOWN, "Zlib error : %s", zError(zerr));
			return 0;
        case Z_OK: {
            // patch header, setup crc and length (stolen from mod_trace_output)
            BYTE *p = target + 8; *p++ = 2; *p = OS_CODE; // xflags, os_code
 	        crc = crc32(crc, source, source_size);
	        memcpy(target + 4 + dest_len, &crc, 4);
	        memcpy(target + 8 + dest_len, &source_size, 4);
            return dest_len + 12;
        }
	}

src/Source/FreeImage/ZLibInterface.cpp  view on Meta::CPAN

Upon entry, target_size is the total size of the destination buffer, 
which must be large enough to hold the entire uncompressed data. 
The size of the uncompressed data must have been saved previously by the compressor 
and transmitted to the decompressor by some mechanism outside the scope of this 
compression library.

@param target Destination buffer
@param target_size Size of the destination buffer, in bytes
@param source Source buffer
@param source_size Size of the source buffer, in bytes
@return Returns the actual size of the uncompressed buffer, returns 0 if an error occured
@see FreeImage_ZLibGZip
*/

static int get_byte(z_stream *stream) {
    if (stream->avail_in <= 0) return EOF;
    stream->avail_in--;
    return *(stream->next_in)++;
}

static int checkheader(z_stream *stream) {

src/Source/FreeImage/ZLibInterface.cpp  view on Meta::CPAN

            if ((zerr = checkheader(&stream)) == Z_OK) {
                zerr = inflate (&stream, Z_NO_FLUSH);
                dest_len = target_size - stream.avail_out;

                if (zerr == Z_OK || zerr == Z_STREAM_END)
                    inflateEnd(&stream);
            } 
        }
    }
    if (zerr != Z_OK && zerr != Z_STREAM_END) {
        FreeImage_OutputMessageProc(FIF_UNKNOWN, "Zlib error : %s", zError(zerr));
        return 0;
    }
    return dest_len;
}

/**
Update a running crc from source and return the updated crc, using the ZLib library.
If source is NULL, this function returns the required initial value for the crc.

@param crc Running crc value

src/Source/FreeImageToolkit/BSplineRotate.cpp  view on Meta::CPAN

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Coefficients routines

/**
 ConvertToInterpolationCoefficients

 @param c Input samples --> output coefficients
 @param DataLength Number of samples or coefficients
 @param z Poles
 @param NbPoles Number of poles
 @param Tolerance Admissible relative error
*/
static void 
ConvertToInterpolationCoefficients(double *c, long DataLength, double *z, long NbPoles,	double Tolerance) {
	double	Lambda = 1;
	long	n, k;

	// special case required by mirror boundaries
	if(DataLength == 1L) {
		return;
	}

src/Source/FreeImageToolkit/BSplineRotate.cpp  view on Meta::CPAN

		}
	}
} 

/**
 InitialCausalCoefficient

 @param c Coefficients
 @param DataLength Number of coefficients
 @param z Actual pole
 @param Tolerance Admissible relative error
 @return
*/
static double 
InitialCausalCoefficient(double	*c, long DataLength, double	z, double Tolerance) {
	double	Sum, zn, z2n, iz;
	long	n, Horizon;

	// this initialization corresponds to mirror boundaries 
	Horizon = DataLength;
	if(Tolerance > 0) {

src/Source/FreeImageToolkit/JPEGTransform.cpp  view on Meta::CPAN

// Use at your own risk!
// ==========================================================

extern "C" {
#define XMD_H
#undef FAR
#include <setjmp.h>

#include "../LibJPEG/jinclude.h"
#include "../LibJPEG/jpeglib.h"
#include "../LibJPEG/jerror.h"
#include "../LibJPEG/transupp.h"
}

#include "FreeImage.h"
#include "Utilities.h"
#include "FreeImageIO.h"

// ----------------------------------------------------------
//   Source manager & Destination manager setup
//   (see PluginJPEG.cpp)

src/Source/FreeImageToolkit/JPEGTransform.cpp  view on Meta::CPAN


void jpeg_freeimage_src(j_decompress_ptr cinfo, fi_handle infile, FreeImageIO *io);
void jpeg_freeimage_dst(j_compress_ptr cinfo, fi_handle outfile, FreeImageIO *io);

// ----------------------------------------------------------
//   Error handling
//   (see also PluginJPEG.cpp)
// ----------------------------------------------------------

/**
	Receives control for a fatal error.  Information sufficient to
	generate the error message has been stored in cinfo->err; call
	output_message to display it.  Control must NOT return to the caller;
	generally this routine will exit() or longjmp() somewhere.
*/
METHODDEF(void)
ls_jpeg_error_exit (j_common_ptr cinfo) {
	// always display the message
	(*cinfo->err->output_message)(cinfo);

	// allow JPEG with a premature end of file
	if((cinfo)->err->msg_parm.i[0] != 13) {

		// let the memory manager delete any temp files before we die
		jpeg_destroy(cinfo);

		throw FIF_JPEG;

src/Source/FreeImageToolkit/JPEGTransform.cpp  view on Meta::CPAN

JPEGTransformFromHandle(FreeImageIO* src_io, fi_handle src_handle, FreeImageIO* dst_io, fi_handle dst_handle, FREE_IMAGE_JPEG_OPERATION operation, int* left, int* top, int* right, int* bottom, BOOL perfect) {
	const BOOL onlyReturnCropRect = (dst_io == NULL) || (dst_handle == NULL);
	const long stream_start = onlyReturnCropRect ? 0 : dst_io->tell_proc(dst_handle);
	BOOL swappedDim = FALSE;
	BOOL trimH = FALSE;
	BOOL trimV = FALSE;

	// Set up the jpeglib structures
	jpeg_decompress_struct srcinfo;
	jpeg_compress_struct dstinfo;
	jpeg_error_mgr jsrcerr, jdsterr;
	jvirt_barray_ptr *src_coef_arrays = NULL;
	jvirt_barray_ptr *dst_coef_arrays = NULL;
	// Support for copying optional markers from source to destination file
	JCOPY_OPTION copyoption;
	// Image transformation options
	jpeg_transform_info transfoptions;

	// Initialize structures
	memset(&srcinfo, 0, sizeof(srcinfo));
	memset(&jsrcerr, 0, sizeof(jsrcerr));

src/Source/FreeImageToolkit/JPEGTransform.cpp  view on Meta::CPAN

			transfoptions.transform = JXFORM_NONE;
			break;
	}
	// (perfect == TRUE) ==> fail if there is non-transformable edge blocks
	transfoptions.perfect = (perfect == TRUE) ? TRUE : FALSE;
	// Drop non-transformable edge blocks: trim off any partial edge MCUs that the transform can't handle.
	transfoptions.trim = TRUE;

	try {

		// Initialize the JPEG decompression object with default error handling
		srcinfo.err = jpeg_std_error(&jsrcerr);
		srcinfo.err->error_exit = ls_jpeg_error_exit;
		srcinfo.err->output_message = ls_jpeg_output_message;
		jpeg_create_decompress(&srcinfo);

		// Initialize the JPEG compression object with default error handling
		dstinfo.err = jpeg_std_error(&jdsterr);
		dstinfo.err->error_exit = ls_jpeg_error_exit;
		dstinfo.err->output_message = ls_jpeg_output_message;
		jpeg_create_compress(&dstinfo);

		// Specify data source for decompression
		jpeg_freeimage_src(&srcinfo, src_handle, src_io);

		// Enable saving of extra markers that we want to copy
		jcopy_markers_setup(&srcinfo, copyoption);

		// Read the file header

src/Source/LibJPEG/LibJPEG.2005.vcproj  view on Meta::CPAN

			</File>
			<File
				RelativePath="jdsample.c"
				>
			</File>
			<File
				RelativePath="jdtrans.c"
				>
			</File>
			<File
				RelativePath="jerror.c"
				>
			</File>
			<File
				RelativePath="jfdctflt.c"
				>
			</File>
			<File
				RelativePath="jfdctfst.c"
				>
			</File>

src/Source/LibJPEG/LibJPEG.2005.vcproj  view on Meta::CPAN

			>
			<File
				RelativePath="jconfig.h"
				>
			</File>
			<File
				RelativePath="jdct.h"
				>
			</File>
			<File
				RelativePath="jerror.h"
				>
			</File>
			<File
				RelativePath="jinclude.h"
				>
			</File>
			<File
				RelativePath="jmemsys.h"
				>
			</File>

src/Source/LibJPEG/LibJPEG.2008.vcproj  view on Meta::CPAN

			</File>
			<File
				RelativePath="jdsample.c"
				>
			</File>
			<File
				RelativePath="jdtrans.c"
				>
			</File>
			<File
				RelativePath="jerror.c"
				>
			</File>
			<File
				RelativePath="jfdctflt.c"
				>
			</File>
			<File
				RelativePath="jfdctfst.c"
				>
			</File>

src/Source/LibJPEG/LibJPEG.2008.vcproj  view on Meta::CPAN

			>
			<File
				RelativePath="jconfig.h"
				>
			</File>
			<File
				RelativePath="jdct.h"
				>
			</File>
			<File
				RelativePath="jerror.h"
				>
			</File>
			<File
				RelativePath="jinclude.h"
				>
			</File>
			<File
				RelativePath="jmemsys.h"
				>
			</File>

src/Source/LibJPEG/LibJPEG.2013.vcxproj  view on Meta::CPAN

    <ClCompile Include="jddctmgr.c" />
    <ClCompile Include="jdhuff.c" />
    <ClCompile Include="jdinput.c" />
    <ClCompile Include="jdmainct.c" />
    <ClCompile Include="jdmarker.c" />
    <ClCompile Include="jdmaster.c" />
    <ClCompile Include="jdmerge.c" />
    <ClCompile Include="jdpostct.c" />
    <ClCompile Include="jdsample.c" />
    <ClCompile Include="jdtrans.c" />
    <ClCompile Include="jerror.c" />
    <ClCompile Include="jfdctflt.c" />
    <ClCompile Include="jfdctfst.c" />
    <ClCompile Include="jfdctint.c" />
    <ClCompile Include="jidctflt.c" />
    <ClCompile Include="jidctfst.c" />
    <ClCompile Include="jidctint.c" />
    <ClCompile Include="jmemmgr.c" />
    <ClCompile Include="jmemnobs.c" />
    <ClCompile Include="jquant1.c" />
    <ClCompile Include="jquant2.c" />
    <ClCompile Include="jutils.c" />
    <ClCompile Include="transupp.c" />
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="jconfig.h" />
    <ClInclude Include="jdct.h" />
    <ClInclude Include="jerror.h" />
    <ClInclude Include="jinclude.h" />
    <ClInclude Include="jmemsys.h" />
    <ClInclude Include="jmorecfg.h" />
    <ClInclude Include="jpegint.h" />
    <ClInclude Include="jpeglib.h" />
    <ClInclude Include="jversion.h" />
    <ClInclude Include="transupp.h" />
  </ItemGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">

src/Source/LibJPEG/LibJPEG.2013.vcxproj.filters  view on Meta::CPAN

    </ClCompile>
    <ClCompile Include="jdpostct.c">
      <Filter>Source Files</Filter>
    </ClCompile>
    <ClCompile Include="jdsample.c">
      <Filter>Source Files</Filter>
    </ClCompile>
    <ClCompile Include="jdtrans.c">
      <Filter>Source Files</Filter>
    </ClCompile>
    <ClCompile Include="jerror.c">
      <Filter>Source Files</Filter>
    </ClCompile>
    <ClCompile Include="jfdctflt.c">
      <Filter>Source Files</Filter>
    </ClCompile>
    <ClCompile Include="jfdctfst.c">
      <Filter>Source Files</Filter>
    </ClCompile>
    <ClCompile Include="jfdctint.c">
      <Filter>Source Files</Filter>

src/Source/LibJPEG/LibJPEG.2013.vcxproj.filters  view on Meta::CPAN

      <Filter>Source Files</Filter>
    </ClCompile>
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="jconfig.h">
      <Filter>Header Files</Filter>
    </ClInclude>
    <ClInclude Include="jdct.h">
      <Filter>Header Files</Filter>
    </ClInclude>
    <ClInclude Include="jerror.h">
      <Filter>Header Files</Filter>
    </ClInclude>
    <ClInclude Include="jinclude.h">
      <Filter>Header Files</Filter>
    </ClInclude>
    <ClInclude Include="jmemsys.h">
      <Filter>Header Files</Filter>
    </ClInclude>
    <ClInclude Include="jmorecfg.h">
      <Filter>Header Files</Filter>

src/Source/LibJPEG/ansi2knr.c  view on Meta::CPAN

program under the GPL.
*/

/*
 * Usage:
	ansi2knr [--filename FILENAME] [INPUT_FILE [OUTPUT_FILE]]
 * --filename provides the file name for the #line directive in the output,
 * overriding input_file (if present).
 * If no input_file is supplied, input is read from stdin.
 * If no output_file is supplied, output goes to stdout.
 * There are no error messages.
 *
 * ansi2knr recognizes function definitions by seeing a non-keyword
 * identifier at the left margin, followed by a left parenthesis, with a
 * right parenthesis as the last character on the line, and with a left
 * brace as the first token on the following line (ignoring possible
 * intervening comments and/or preprocessor directives), except that a line
 * consisting of only
 *	identifier1(identifier2)
 * will not be considered a function definition unless identifier2 is
 * the word "void", and a line consisting of

src/Source/LibJPEG/ansi2knr.c  view on Meta::CPAN

		wherever comments are allowed
	lpd 1999-04-12 added minor fixes from Pavel Roskin
		<pavel_roskin@geocities.com> for clean compilation with
		gcc -W -Wall
	lpd 1999-03-22 added hack to recognize lines consisting of
		identifier1(identifier2, xxx) as *not* being procedures
	lpd 1999-02-03 made indentation of preprocessor commands consistent
	lpd 1999-01-28 fixed two bugs: a '/' in an argument list caused an
		endless loop; quoted strings within an argument list
		confused the parser
	lpd 1999-01-24 added a check for write errors on the output,
		suggested by Jim Meyering <meyering@ascend.com>
	lpd 1998-11-09 added further hack to recognize identifier(void)
		as being a procedure
	lpd 1998-10-23 added hack to recognize lines consisting of
		identifier1(identifier2) as *not* being procedures
	lpd 1997-12-08 made input_file optional; only closes input and/or
		output file if not stdin or stdout respectively; prints
		usage message on stderr rather than stdout; adds
		--filename switch (changes suggested by
		<ceder@lysator.liu.se>)

src/Source/LibJPEG/ansi2knr.c  view on Meta::CPAN

		program under the GPL
	lpd 1994-12-18 added conditionals for systems where ctype macros
		don't handle 8-bit characters properly, suggested by
		Francois Pinard <pinard@iro.umontreal.ca>;
		removed --varargs switch (this is now the default)
	lpd 1994-10-10 removed CONFIG_BROKETS conditional
	lpd 1994-07-16 added some conditionals to help GNU `configure',
		suggested by Francois Pinard <pinard@iro.umontreal.ca>;
		properly erase prototype args in function parameters,
		contributed by Jim Avera <jima@netcom.com>;
		correct error in writeblanks (it shouldn't erase EOLs)
	lpd 1989-xx-xx original version
 */

/* Most of the conditionals here are to make ansi2knr work with */
/* or without the GNU configure machinery. */

#if HAVE_CONFIG_H
# include <config.h>
#endif

src/Source/LibJPEG/ansi2knr.c  view on Meta::CPAN

	  "Usage: ansi2knr [--filename FILENAME] [INPUT_FILE [OUTPUT_FILE]]\n";
	/*
	 * In previous versions, ansi2knr recognized a --varargs switch.
	 * If this switch was supplied, ansi2knr would attempt to convert
	 * a ... argument to va_alist and va_dcl; if this switch was not
	 * supplied, ansi2knr would simply drop any such arguments.
	 * Now, ansi2knr always does this conversion, and we only
	 * check for this switch for backward compatibility.
	 */
	int convert_varargs = 1;
	int output_error;

	while ( argc > 1 && argv[1][0] == '-' ) {
	  if ( !strcmp(argv[1], "--varargs") ) {
	    convert_varargs = 1;
	    argc--;
	    argv++;
	    continue;
	  }
	  if ( !strcmp(argv[1], "--filename") && argc > 2 ) {
	    filename = argv[2];

src/Source/LibJPEG/ansi2knr.c  view on Meta::CPAN

		default:		/* not a function */
wl:			fputs(buf, out);
			break;
		   }
		line = buf;
	   }
	if ( line != buf )
	  fputs(buf, out);
	free(buf);
	if ( output_name ) {
	  output_error = ferror(out);
	  output_error |= fclose(out);
	} else {		/* out == stdout */
	  fflush(out);
	  output_error = ferror(out);
	}
	if ( output_error ) {
	  fprintf(stderr, "%s: error writing to %s\n", program_name,
		  (output_name ? output_name : "stdout"));
	  exit(1);
	}
	if ( in != stdin )
	  fclose(in);
	return 0;
}

/*
 * Skip forward or backward over one or more preprocessor directives.

src/Source/LibJPEG/cderror.h  view on Meta::CPAN

/*
 * cderror.h
 *
 * Copyright (C) 1994-1997, Thomas G. Lane.
 * Modified 2009 by Guido Vollbeding.
 * This file is part of the Independent JPEG Group's software.
 * For conditions of distribution and use, see the accompanying README file.
 *
 * This file defines the error and message codes for the cjpeg/djpeg
 * applications.  These strings are not needed as part of the JPEG library
 * proper.
 * Edit this file to add new codes, or to translate the message strings to
 * some other language.
 */

/*
 * To define the enum list of message codes, include this file without
 * defining macro JMESSAGE.  To create a message string table, include it
 * again with a suitable JMESSAGE definition (see jerror.c for an example).
 */
#ifndef JMESSAGE
#ifndef CDERROR_H
#define CDERROR_H
/* First time through, define the enum list */
#define JMAKE_ENUM_LIST
#else
/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
#define JMESSAGE(code,string)
#endif /* CDERROR_H */

src/Source/LibJPEG/cderror.h  view on Meta::CPAN

JMESSAGE(JERR_PPM_COLORSPACE, "PPM output must be grayscale or RGB")
JMESSAGE(JERR_PPM_NONNUMERIC, "Nonnumeric data in PPM file")
JMESSAGE(JERR_PPM_NOT, "Not a PPM/PGM file")
JMESSAGE(JTRC_PGM, "%ux%u PGM image")
JMESSAGE(JTRC_PGM_TEXT, "%ux%u text PGM image")
JMESSAGE(JTRC_PPM, "%ux%u PPM image")
JMESSAGE(JTRC_PPM_TEXT, "%ux%u text PPM image")
#endif /* PPM_SUPPORTED */

#ifdef RLE_SUPPORTED
JMESSAGE(JERR_RLE_BADERROR, "Bogus error code from RLE library")
JMESSAGE(JERR_RLE_COLORSPACE, "RLE output must be grayscale or RGB")
JMESSAGE(JERR_RLE_DIMENSIONS, "Image dimensions (%ux%u) too large for RLE")
JMESSAGE(JERR_RLE_EMPTY, "Empty RLE file")
JMESSAGE(JERR_RLE_EOF, "Premature EOF in RLE header")
JMESSAGE(JERR_RLE_MEM, "Insufficient memory for RLE header")
JMESSAGE(JERR_RLE_NOT, "Not an RLE file")
JMESSAGE(JERR_RLE_TOOMANYCHANNELS, "Cannot handle %d output channels for RLE")
JMESSAGE(JERR_RLE_UNSUPPORTED, "Cannot handle this RLE setup")
JMESSAGE(JTRC_RLE, "%ux%u full-color RLE file")
JMESSAGE(JTRC_RLE_FULLMAP, "%ux%u full-color RLE file with map of length %d")



( run in 0.410 second using v1.01-cache-2.11-cpan-65fba6d93b7 )