roentgen b75cab
/* $Id: bmp2tiff.c,v 1.23 2010-03-10 18:56:49 bfriesen Exp $
roentgen b75cab
 *
roentgen b75cab
 * Project:  libtiff tools
roentgen b75cab
 * Purpose:  Convert Windows BMP files in TIFF.
roentgen b75cab
 * Author:   Andrey Kiselev, dron@ak4719.spb.edu
roentgen b75cab
 *
roentgen b75cab
 ******************************************************************************
roentgen b75cab
 * Copyright (c) 2004, Andrey Kiselev <dron@ak4719.spb.edu></dron@ak4719.spb.edu>
roentgen b75cab
 *
roentgen b75cab
 * Permission to use, copy, modify, distribute, and sell this software and 
roentgen b75cab
 * its documentation for any purpose is hereby granted without fee, provided
roentgen b75cab
 * that (i) the above copyright notices and this permission notice appear in
roentgen b75cab
 * all copies of the software and related documentation, and (ii) the names of
roentgen b75cab
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
roentgen b75cab
 * publicity relating to the software without the specific, prior written
roentgen b75cab
 * permission of Sam Leffler and Silicon Graphics.
roentgen b75cab
 * 
roentgen b75cab
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
roentgen b75cab
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
roentgen b75cab
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
roentgen b75cab
 * 
roentgen b75cab
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
roentgen b75cab
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
roentgen b75cab
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
roentgen b75cab
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
roentgen b75cab
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
roentgen b75cab
 * OF THIS SOFTWARE.
roentgen b75cab
 */
roentgen b75cab
roentgen b75cab
#include "tif_config.h"
roentgen b75cab
roentgen b75cab
#include <stdio.h></stdio.h>
roentgen b75cab
#include <stdlib.h></stdlib.h>
roentgen b75cab
#include <string.h></string.h>
roentgen b75cab
#include <ctype.h></ctype.h>
roentgen b75cab
#include <sys types.h=""></sys>
roentgen b75cab
#include <sys stat.h=""></sys>
roentgen b75cab
roentgen b75cab
#ifdef HAVE_UNISTD_H
roentgen b75cab
# include <unistd.h></unistd.h>
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
#if HAVE_FCNTL_H
roentgen b75cab
# include <fcntl.h></fcntl.h>
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
#if HAVE_SYS_TYPES_H
roentgen b75cab
# include <sys types.h=""></sys>
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
#if HAVE_IO_H
roentgen b75cab
# include <io.h></io.h>
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
#ifdef NEED_LIBPORT
roentgen b75cab
# include "libport.h"
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
#include "tiffio.h"
roentgen b75cab
roentgen b75cab
#ifndef O_BINARY
roentgen b75cab
# define O_BINARY 0
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
enum BMPType
roentgen b75cab
{
roentgen b75cab
    BMPT_WIN4,      /* BMP used in Windows 3.0/NT 3.51/95 */
roentgen b75cab
    BMPT_WIN5,      /* BMP used in Windows NT 4.0/98/Me/2000/XP */
roentgen b75cab
    BMPT_OS21,      /* BMP used in OS/2 PM 1.x */
roentgen b75cab
    BMPT_OS22       /* BMP used in OS/2 PM 2.x */
roentgen b75cab
};
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Bitmap file consists of a BMPFileHeader structure followed by a
roentgen b75cab
 * BMPInfoHeader structure. An array of BMPColorEntry structures (also called
roentgen b75cab
 * a colour table) follows the bitmap information header structure. The colour
roentgen b75cab
 * table is followed by a second array of indexes into the colour table (the
roentgen b75cab
 * actual bitmap data). Data may be comressed, for 4-bpp and 8-bpp used RLE
roentgen b75cab
 * compression.
roentgen b75cab
 *
roentgen b75cab
 * +---------------------+
roentgen b75cab
 * | BMPFileHeader       |
roentgen b75cab
 * +---------------------+
roentgen b75cab
 * | BMPInfoHeader       |
roentgen b75cab
 * +---------------------+
roentgen b75cab
 * | BMPColorEntry array |
roentgen b75cab
 * +---------------------+
roentgen b75cab
 * | Colour-index array  |
roentgen b75cab
 * +---------------------+
roentgen b75cab
 *
roentgen b75cab
 * All numbers stored in Intel order with least significant byte first.
roentgen b75cab
 */
roentgen b75cab
roentgen b75cab
enum BMPComprMethod
roentgen b75cab
{
roentgen b75cab
    BMPC_RGB = 0L,          /* Uncompressed */
roentgen b75cab
    BMPC_RLE8 = 1L,         /* RLE for 8 bpp images */
roentgen b75cab
    BMPC_RLE4 = 2L,         /* RLE for 4 bpp images */
roentgen b75cab
    BMPC_BITFIELDS = 3L,    /* Bitmap is not compressed and the colour table
roentgen b75cab
			     * consists of three DWORD color masks that specify
roentgen b75cab
			     * the red, green, and blue components of each
roentgen b75cab
			     * pixel. This is valid when used with
roentgen b75cab
			     * 16- and 32-bpp bitmaps. */
roentgen b75cab
    BMPC_JPEG = 4L,         /* Indicates that the image is a JPEG image. */
roentgen b75cab
    BMPC_PNG = 5L           /* Indicates that the image is a PNG image. */
roentgen b75cab
};
roentgen b75cab
roentgen b75cab
enum BMPLCSType                 /* Type of logical color space. */
roentgen b75cab
{
roentgen b75cab
    BMPLT_CALIBRATED_RGB = 0,	/* This value indicates that endpoints and
roentgen b75cab
				 * gamma values are given in the appropriate
roentgen b75cab
				 * fields. */
roentgen b75cab
    BMPLT_DEVICE_RGB = 1,
roentgen b75cab
    BMPLT_DEVICE_CMYK = 2
roentgen b75cab
};
roentgen b75cab
roentgen b75cab
typedef struct
roentgen b75cab
{
roentgen b75cab
    int32   iCIEX;
roentgen b75cab
    int32   iCIEY;
roentgen b75cab
    int32   iCIEZ;
roentgen b75cab
} BMPCIEXYZ;
roentgen b75cab
roentgen b75cab
typedef struct                  /* This structure contains the x, y, and z */
roentgen b75cab
{				/* coordinates of the three colors that */
roentgen b75cab
				/* correspond */
roentgen b75cab
    BMPCIEXYZ   iCIERed;        /* to the red, green, and blue endpoints for */
roentgen b75cab
    BMPCIEXYZ   iCIEGreen;      /* a specified logical color space. */
roentgen b75cab
    BMPCIEXYZ	iCIEBlue;
roentgen b75cab
} BMPCIEXYZTriple;
roentgen b75cab
roentgen b75cab
typedef struct
roentgen b75cab
{
roentgen b75cab
    char	bType[2];       /* Signature "BM" */
roentgen b75cab
    uint32	iSize;          /* Size in bytes of the bitmap file. Should
roentgen b75cab
				 * always be ignored while reading because
roentgen b75cab
				 * of error in Windows 3.0 SDK's description
roentgen b75cab
				 * of this field */
roentgen b75cab
    uint16	iReserved1;     /* Reserved, set as 0 */
roentgen b75cab
    uint16	iReserved2;     /* Reserved, set as 0 */
roentgen b75cab
    uint32	iOffBits;       /* Offset of the image from file start in bytes */
roentgen b75cab
} BMPFileHeader;
roentgen b75cab
roentgen b75cab
/* File header size in bytes: */
roentgen b75cab
const int       BFH_SIZE = 14;
roentgen b75cab
roentgen b75cab
typedef struct
roentgen b75cab
{
roentgen b75cab
    uint32	iSize;          /* Size of BMPInfoHeader structure in bytes.
roentgen b75cab
				 * Should be used to determine start of the
roentgen b75cab
				 * colour table */
roentgen b75cab
    int32	iWidth;         /* Image width */
roentgen b75cab
    int32	iHeight;        /* Image height. If positive, image has bottom
roentgen b75cab
				 * left origin, if negative --- top left. */
roentgen b75cab
    int16	iPlanes;        /* Number of image planes (must be set to 1) */
roentgen b75cab
    int16	iBitCount;      /* Number of bits per pixel (1, 4, 8, 16, 24
roentgen b75cab
				 * or 32). If 0 then the number of bits per
roentgen b75cab
				 * pixel is specified or is implied by the
roentgen b75cab
				 * JPEG or PNG format. */
roentgen b75cab
    uint32	iCompression;	/* Compression method */
roentgen b75cab
    uint32	iSizeImage;     /* Size of uncomressed image in bytes. May
roentgen b75cab
				 * be 0 for BMPC_RGB bitmaps. If iCompression
roentgen b75cab
				 * is BI_JPEG or BI_PNG, iSizeImage indicates
roentgen b75cab
				 * the size of the JPEG or PNG image buffer. */
roentgen b75cab
    int32	iXPelsPerMeter; /* X resolution, pixels per meter (0 if not used) */
roentgen b75cab
    int32	iYPelsPerMeter; /* Y resolution, pixels per meter (0 if not used) */
roentgen b75cab
    uint32	iClrUsed;       /* Size of colour table. If 0, iBitCount should
roentgen b75cab
				 * be used to calculate this value
roentgen b75cab
				 * (1<
roentgen b75cab
				 * unsigned for proper shifting. */
roentgen b75cab
    int32	iClrImportant;  /* Number of important colours. If 0, all
roentgen b75cab
				 * colours are required */
roentgen b75cab
roentgen b75cab
    /*
roentgen b75cab
     * Fields above should be used for bitmaps, compatible with Windows NT 3.51
roentgen b75cab
     * and earlier. Windows 98/Me, Windows 2000/XP introduces additional fields:
roentgen b75cab
     */
roentgen b75cab
roentgen b75cab
    int32	iRedMask;       /* Colour mask that specifies the red component
roentgen b75cab
				 * of each pixel, valid only if iCompression
roentgen b75cab
				 * is set to BI_BITFIELDS. */
roentgen b75cab
    int32	iGreenMask;     /* The same for green component */
roentgen b75cab
    int32	iBlueMask;      /* The same for blue component */
roentgen b75cab
    int32	iAlphaMask;     /* Colour mask that specifies the alpha
roentgen b75cab
				 * component of each pixel. */
roentgen b75cab
    uint32	iCSType;        /* Colour space of the DIB. */
roentgen b75cab
    BMPCIEXYZTriple sEndpoints; /* This member is ignored unless the iCSType
roentgen b75cab
				 * member specifies BMPLT_CALIBRATED_RGB. */
roentgen b75cab
    int32	iGammaRed;      /* Toned response curve for red. This member
roentgen b75cab
				 * is ignored unless color values are
roentgen b75cab
				 * calibrated RGB values and iCSType is set to
roentgen b75cab
				 * BMPLT_CALIBRATED_RGB. Specified
roentgen b75cab
				 * in 16^16 format. */
roentgen b75cab
    int32	iGammaGreen;    /* Toned response curve for green. */
roentgen b75cab
    int32	iGammaBlue;     /* Toned response curve for blue. */
roentgen b75cab
} BMPInfoHeader;
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Info header size in bytes:
roentgen b75cab
 */
roentgen b75cab
const unsigned int  BIH_WIN4SIZE = 40; /* for BMPT_WIN4 */
roentgen b75cab
const unsigned int  BIH_WIN5SIZE = 57; /* for BMPT_WIN5 */
roentgen b75cab
const unsigned int  BIH_OS21SIZE = 12; /* for BMPT_OS21 */
roentgen b75cab
const unsigned int  BIH_OS22SIZE = 64; /* for BMPT_OS22 */
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * We will use plain byte array instead of this structure, but declaration
roentgen b75cab
 * provided for reference
roentgen b75cab
 */
roentgen b75cab
typedef struct
roentgen b75cab
{
roentgen b75cab
    char       bBlue;
roentgen b75cab
    char       bGreen;
roentgen b75cab
    char       bRed;
roentgen b75cab
    char       bReserved;      /* Must be 0 */
roentgen b75cab
} BMPColorEntry;
roentgen b75cab
roentgen b75cab
static	uint16 compression = (uint16) -1;
roentgen b75cab
static	int jpegcolormode = JPEGCOLORMODE_RGB;
roentgen b75cab
static	int quality = 75;		/* JPEG quality */
roentgen b75cab
static	uint16 predictor = 0;
roentgen b75cab
roentgen b75cab
static void usage(void);
roentgen b75cab
static int processCompressOptions(char*);
roentgen b75cab
static void rearrangePixels(char *, uint32, uint32);
roentgen b75cab
roentgen b75cab
int
roentgen b75cab
main(int argc, char* argv[])
roentgen b75cab
{
roentgen b75cab
	uint32	width, length;
roentgen b75cab
	uint16	nbands = 1;		/* number of bands in input image */
roentgen b75cab
        uint16	depth = 8;		/* bits per pixel in input image */
roentgen b75cab
	uint32	rowsperstrip = (uint32) -1;
roentgen b75cab
        uint16	photometric = PHOTOMETRIC_MINISBLACK;
roentgen b75cab
	int	fd = 0;
roentgen b75cab
	struct stat instat;
roentgen b75cab
	char	*outfilename = NULL, *infilename = NULL;
roentgen b75cab
	TIFF	*out = NULL;
roentgen b75cab
roentgen b75cab
	BMPFileHeader file_hdr;
roentgen b75cab
        BMPInfoHeader info_hdr;
roentgen b75cab
        int     bmp_type;
roentgen b75cab
        uint32  clr_tbl_size, n_clr_elems = 3;
roentgen b75cab
        unsigned char *clr_tbl;
roentgen b75cab
	unsigned short *red_tbl = NULL, *green_tbl = NULL, *blue_tbl = NULL;
roentgen b75cab
	uint32	row, clr;
roentgen b75cab
roentgen b75cab
	int	c;
roentgen b75cab
	extern int optind;
roentgen b75cab
	extern char* optarg;
roentgen b75cab
roentgen b75cab
	while ((c = getopt(argc, argv, "c:r:o:h")) != -1) {
roentgen b75cab
		switch (c) {
roentgen b75cab
		case 'c':		/* compression scheme */
roentgen b75cab
			if (!processCompressOptions(optarg))
roentgen b75cab
				usage();
roentgen b75cab
			break;
roentgen b75cab
		case 'r':		/* rows/strip */
roentgen b75cab
			rowsperstrip = atoi(optarg);
roentgen b75cab
			break;
roentgen b75cab
		case 'o':
roentgen b75cab
			outfilename = optarg;
roentgen b75cab
			break;
roentgen b75cab
		case 'h':
roentgen b75cab
			usage();
roentgen b75cab
		default:
roentgen b75cab
			break;
roentgen b75cab
		}
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
	if (argc - optind < 2)
roentgen b75cab
		usage();
roentgen b75cab
roentgen b75cab
	if (outfilename == NULL)
roentgen b75cab
		outfilename = argv[argc-1];
roentgen b75cab
	out = TIFFOpen(outfilename, "w");
roentgen b75cab
	if (out == NULL) {
roentgen b75cab
		TIFFError(infilename, "Cannot open file %s for output",
roentgen b75cab
			  outfilename);
roentgen b75cab
		goto bad3;
roentgen b75cab
	}
roentgen b75cab
	
roentgen b75cab
roentgen b75cab
	while (optind < argc-1) {
roentgen b75cab
		infilename = argv[optind];
roentgen b75cab
		optind++;
roentgen b75cab
	    
roentgen b75cab
		fd = open(infilename, O_RDONLY|O_BINARY, 0);
roentgen b75cab
		if (fd < 0) {
roentgen b75cab
			TIFFError(infilename, "Cannot open input file");
roentgen b75cab
			return -1;
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
		read(fd, file_hdr.bType, 2);
roentgen b75cab
		if(file_hdr.bType[0] != 'B' || file_hdr.bType[1] != 'M') {
roentgen b75cab
			TIFFError(infilename, "File is not BMP");
roentgen b75cab
			goto bad;
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
/* -------------------------------------------------------------------- */
roentgen b75cab
/*      Read the BMPFileHeader. We need iOffBits value only             */
roentgen b75cab
/* -------------------------------------------------------------------- */
roentgen b75cab
		lseek(fd, 10, SEEK_SET);
roentgen b75cab
		read(fd, &file_hdr.iOffBits, 4);
roentgen b75cab
#ifdef WORDS_BIGENDIAN
roentgen b75cab
		TIFFSwabLong(&file_hdr.iOffBits);
roentgen b75cab
#endif
roentgen b75cab
		fstat(fd, &instat);
roentgen b75cab
		file_hdr.iSize = instat.st_size;
roentgen b75cab
roentgen b75cab
/* -------------------------------------------------------------------- */
roentgen b75cab
/*      Read the BMPInfoHeader.                                         */
roentgen b75cab
/* -------------------------------------------------------------------- */
roentgen b75cab
roentgen b75cab
		lseek(fd, BFH_SIZE, SEEK_SET);
roentgen b75cab
		read(fd, &info_hdr.iSize, 4);
roentgen b75cab
#ifdef WORDS_BIGENDIAN
roentgen b75cab
		TIFFSwabLong(&info_hdr.iSize);
roentgen b75cab
#endif
roentgen b75cab
roentgen b75cab
		if (info_hdr.iSize == BIH_WIN4SIZE)
roentgen b75cab
			bmp_type = BMPT_WIN4;
roentgen b75cab
		else if (info_hdr.iSize == BIH_OS21SIZE)
roentgen b75cab
			bmp_type = BMPT_OS21;
roentgen b75cab
		else if (info_hdr.iSize == BIH_OS22SIZE
roentgen b75cab
			 || info_hdr.iSize == 16)
roentgen b75cab
			bmp_type = BMPT_OS22;
roentgen b75cab
		else
roentgen b75cab
			bmp_type = BMPT_WIN5;
roentgen b75cab
roentgen b75cab
		if (bmp_type == BMPT_WIN4
roentgen b75cab
		    || bmp_type == BMPT_WIN5
roentgen b75cab
		    || bmp_type == BMPT_OS22) {
roentgen b75cab
			read(fd, &info_hdr.iWidth, 4);
roentgen b75cab
			read(fd, &info_hdr.iHeight, 4);
roentgen b75cab
			read(fd, &info_hdr.iPlanes, 2);
roentgen b75cab
			read(fd, &info_hdr.iBitCount, 2);
roentgen b75cab
			read(fd, &info_hdr.iCompression, 4);
roentgen b75cab
			read(fd, &info_hdr.iSizeImage, 4);
roentgen b75cab
			read(fd, &info_hdr.iXPelsPerMeter, 4);
roentgen b75cab
			read(fd, &info_hdr.iYPelsPerMeter, 4);
roentgen b75cab
			read(fd, &info_hdr.iClrUsed, 4);
roentgen b75cab
			read(fd, &info_hdr.iClrImportant, 4);
roentgen b75cab
#ifdef WORDS_BIGENDIAN
roentgen b75cab
			TIFFSwabLong((uint32*) &info_hdr.iWidth);
roentgen b75cab
			TIFFSwabLong((uint32*) &info_hdr.iHeight);
roentgen b75cab
			TIFFSwabShort((uint16*) &info_hdr.iPlanes);
roentgen b75cab
			TIFFSwabShort((uint16*) &info_hdr.iBitCount);
roentgen b75cab
			TIFFSwabLong((uint32*) &info_hdr.iCompression);
roentgen b75cab
			TIFFSwabLong((uint32*) &info_hdr.iSizeImage);
roentgen b75cab
			TIFFSwabLong((uint32*) &info_hdr.iXPelsPerMeter);
roentgen b75cab
			TIFFSwabLong((uint32*) &info_hdr.iYPelsPerMeter);
roentgen b75cab
			TIFFSwabLong((uint32*) &info_hdr.iClrUsed);
roentgen b75cab
			TIFFSwabLong((uint32*) &info_hdr.iClrImportant);
roentgen b75cab
#endif
roentgen b75cab
			n_clr_elems = 4;
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
		if (bmp_type == BMPT_OS22) {
roentgen b75cab
			/* 
roentgen b75cab
			 * FIXME: different info in different documents
roentgen b75cab
			 * regarding this!
roentgen b75cab
			 */
roentgen b75cab
			 n_clr_elems = 3;
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
		if (bmp_type == BMPT_OS21) {
roentgen b75cab
			int16  iShort;
roentgen b75cab
roentgen b75cab
			read(fd, &iShort, 2);
roentgen b75cab
#ifdef WORDS_BIGENDIAN
roentgen b75cab
			TIFFSwabShort((uint16*) &iShort);
roentgen b75cab
#endif
roentgen b75cab
			info_hdr.iWidth = iShort;
roentgen b75cab
			read(fd, &iShort, 2);
roentgen b75cab
#ifdef WORDS_BIGENDIAN
roentgen b75cab
			TIFFSwabShort((uint16*) &iShort);
roentgen b75cab
#endif
roentgen b75cab
			info_hdr.iHeight = iShort;
roentgen b75cab
			read(fd, &iShort, 2);
roentgen b75cab
#ifdef WORDS_BIGENDIAN
roentgen b75cab
			TIFFSwabShort((uint16*) &iShort);
roentgen b75cab
#endif
roentgen b75cab
			info_hdr.iPlanes = iShort;
roentgen b75cab
			read(fd, &iShort, 2);
roentgen b75cab
#ifdef WORDS_BIGENDIAN
roentgen b75cab
			TIFFSwabShort((uint16*) &iShort);
roentgen b75cab
#endif
roentgen b75cab
			info_hdr.iBitCount = iShort;
roentgen b75cab
			info_hdr.iCompression = BMPC_RGB;
roentgen b75cab
			n_clr_elems = 3;
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
		if (info_hdr.iBitCount != 1  && info_hdr.iBitCount != 4  &&
roentgen b75cab
		    info_hdr.iBitCount != 8  && info_hdr.iBitCount != 16 &&
roentgen b75cab
		    info_hdr.iBitCount != 24 && info_hdr.iBitCount != 32) {
roentgen b75cab
		    TIFFError(infilename,
roentgen b75cab
			      "Cannot process BMP file with bit count %d",
roentgen b75cab
			      info_hdr.iBitCount);
roentgen b75cab
		    close(fd);
roentgen b75cab
		    return 0;
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
		width = info_hdr.iWidth;
roentgen b75cab
		length = (info_hdr.iHeight > 0) ? info_hdr.iHeight : -info_hdr.iHeight;
roentgen b75cab
roentgen b75cab
		switch (info_hdr.iBitCount)
roentgen b75cab
		{
roentgen b75cab
			case 1:
roentgen b75cab
			case 4:
roentgen b75cab
			case 8:
roentgen b75cab
				nbands = 1;
roentgen b75cab
				depth = info_hdr.iBitCount;
roentgen b75cab
				photometric = PHOTOMETRIC_PALETTE;
roentgen b75cab
				/* Allocate memory for colour table and read it. */
roentgen b75cab
				if (info_hdr.iClrUsed)
roentgen b75cab
				    clr_tbl_size =
roentgen b75cab
					    ((uint32)(1<
roentgen b75cab
					    ? (uint32) (1 << depth)
roentgen b75cab
					    : info_hdr.iClrUsed;
roentgen b75cab
				else
roentgen b75cab
				    clr_tbl_size = 1 << depth;
roentgen b75cab
				clr_tbl = (unsigned char *)
roentgen b75cab
					_TIFFmalloc(n_clr_elems * clr_tbl_size);
roentgen b75cab
				if (!clr_tbl) {
roentgen b75cab
					TIFFError(infilename,
roentgen b75cab
					"Can't allocate space for color table");
roentgen b75cab
					goto bad;
roentgen b75cab
				}
roentgen b75cab
roentgen b75cab
				lseek(fd, BFH_SIZE + info_hdr.iSize, SEEK_SET);
roentgen b75cab
				read(fd, clr_tbl, n_clr_elems * clr_tbl_size);
roentgen b75cab
roentgen b75cab
				red_tbl = (unsigned short*)
roentgen b75cab
					_TIFFmalloc(((tmsize_t)1)<
roentgen b75cab
				if (!red_tbl) {
roentgen b75cab
					TIFFError(infilename,
roentgen b75cab
				"Can't allocate space for red component table");
roentgen b75cab
					_TIFFfree(clr_tbl);
roentgen b75cab
					goto bad1;
roentgen b75cab
				}
roentgen b75cab
				green_tbl = (unsigned short*)
roentgen b75cab
					_TIFFmalloc(((tmsize_t)1)<
roentgen b75cab
				if (!green_tbl) {
roentgen b75cab
					TIFFError(infilename,
roentgen b75cab
				"Can't allocate space for green component table");
roentgen b75cab
					_TIFFfree(clr_tbl);
roentgen b75cab
					goto bad2;
roentgen b75cab
				}
roentgen b75cab
				blue_tbl = (unsigned short*)
roentgen b75cab
					_TIFFmalloc(((tmsize_t)1)<
roentgen b75cab
				if (!blue_tbl) {
roentgen b75cab
					TIFFError(infilename,
roentgen b75cab
				"Can't allocate space for blue component table");
roentgen b75cab
					_TIFFfree(clr_tbl);
roentgen b75cab
					goto bad3;
roentgen b75cab
				}
roentgen b75cab
roentgen b75cab
				for(clr = 0; clr < clr_tbl_size; clr++) {
roentgen b75cab
				    red_tbl[clr] = 257*clr_tbl[clr*n_clr_elems+2];
roentgen b75cab
				    green_tbl[clr] = 257*clr_tbl[clr*n_clr_elems+1];
roentgen b75cab
				    blue_tbl[clr] = 257*clr_tbl[clr*n_clr_elems];
roentgen b75cab
				}
roentgen b75cab
roentgen b75cab
				_TIFFfree(clr_tbl);
roentgen b75cab
				break;
roentgen b75cab
			case 16:
roentgen b75cab
			case 24:
roentgen b75cab
				nbands = 3;
roentgen b75cab
				depth = info_hdr.iBitCount / nbands;
roentgen b75cab
				photometric = PHOTOMETRIC_RGB;
roentgen b75cab
				break;
roentgen b75cab
			case 32:
roentgen b75cab
				nbands = 3;
roentgen b75cab
				depth = 8;
roentgen b75cab
				photometric = PHOTOMETRIC_RGB;
roentgen b75cab
				break;
roentgen b75cab
			default:
roentgen b75cab
				break;
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
/* -------------------------------------------------------------------- */
roentgen b75cab
/*  Create output file.                                                 */
roentgen b75cab
/* -------------------------------------------------------------------- */
roentgen b75cab
roentgen b75cab
		TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
roentgen b75cab
		TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
roentgen b75cab
		TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
roentgen b75cab
		TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nbands);
roentgen b75cab
		TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, depth);
roentgen b75cab
		TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
roentgen b75cab
		TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
roentgen b75cab
		TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
roentgen b75cab
			     TIFFDefaultStripSize(out, rowsperstrip));
roentgen b75cab
		
roentgen b75cab
		if (red_tbl && green_tbl && blue_tbl) {
roentgen b75cab
			TIFFSetField(out, TIFFTAG_COLORMAP,
roentgen b75cab
				     red_tbl, green_tbl, blue_tbl);
roentgen b75cab
		}
roentgen b75cab
		
roentgen b75cab
		if (compression == (uint16) -1)
roentgen b75cab
			compression = COMPRESSION_PACKBITS;
roentgen b75cab
		TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
roentgen b75cab
		switch (compression) {
roentgen b75cab
		case COMPRESSION_JPEG:
roentgen b75cab
			if (photometric == PHOTOMETRIC_RGB
roentgen b75cab
			    && jpegcolormode == JPEGCOLORMODE_RGB)
roentgen b75cab
				photometric = PHOTOMETRIC_YCBCR;
roentgen b75cab
			TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
roentgen b75cab
			TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
roentgen b75cab
			break;
roentgen b75cab
		case COMPRESSION_LZW:
roentgen b75cab
		case COMPRESSION_DEFLATE:
roentgen b75cab
			if (predictor != 0)
roentgen b75cab
				TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
roentgen b75cab
			break;
roentgen b75cab
		}
roentgen b75cab
roentgen b75cab
/* -------------------------------------------------------------------- */
roentgen b75cab
/*  Read uncompressed image data.                                       */
roentgen b75cab
/* -------------------------------------------------------------------- */
roentgen b75cab
roentgen b75cab
		if (info_hdr.iCompression == BMPC_RGB) {
roentgen b75cab
			uint32 offset, size;
roentgen b75cab
			char *scanbuf;
roentgen b75cab
roentgen b75cab
			/* XXX: Avoid integer overflow. We can calculate size
roentgen b75cab
			 * in one step using
roentgen b75cab
			 *
roentgen b75cab
			 *  size = ((width * info_hdr.iBitCount + 31) & ~31) / 8
roentgen b75cab
			 *
roentgen b75cab
			 * formulae, but we should check for overflow
roentgen b75cab
			 * conditions during calculation.
roentgen b75cab
			 */
roentgen b75cab
			size = width * info_hdr.iBitCount + 31;
roentgen b75cab
			if (!width || !info_hdr.iBitCount
roentgen b75cab
			    || (size - 31) / info_hdr.iBitCount != width ) {
roentgen b75cab
				TIFFError(infilename,
roentgen b75cab
					  "Wrong image parameters; can't "
roentgen b75cab
					  "allocate space for scanline buffer");
roentgen b75cab
				goto bad3;
roentgen b75cab
			}
roentgen b75cab
			size = (size & ~31) / 8;
roentgen b75cab
roentgen b75cab
			scanbuf = (char *) _TIFFmalloc(size);
roentgen b75cab
			if (!scanbuf) {
roentgen b75cab
				TIFFError(infilename,
roentgen b75cab
				"Can't allocate space for scanline buffer");
roentgen b75cab
				goto bad3;
roentgen b75cab
			}
roentgen b75cab
roentgen b75cab
			for (row = 0; row < length; row++) {
roentgen b75cab
				if (info_hdr.iHeight > 0)
roentgen b75cab
					offset = file_hdr.iOffBits+(length-row-1)*size;
roentgen b75cab
				else
roentgen b75cab
					offset = file_hdr.iOffBits + row * size;
roentgen b75cab
				if (lseek(fd, offset, SEEK_SET) == (off_t)-1) {
roentgen b75cab
					TIFFError(infilename,
roentgen b75cab
						  "scanline %lu: Seek error",
roentgen b75cab
						  (unsigned long) row);
roentgen b75cab
					break;
roentgen b75cab
				}
roentgen b75cab
roentgen b75cab
				if (read(fd, scanbuf, size) < 0) {
roentgen b75cab
					TIFFError(infilename,
roentgen b75cab
						  "scanline %lu: Read error",
roentgen b75cab
						  (unsigned long) row);
roentgen b75cab
					break;
roentgen b75cab
				}
roentgen b75cab
roentgen b75cab
				rearrangePixels(scanbuf, width, info_hdr.iBitCount);
roentgen b75cab
roentgen b75cab
				if (TIFFWriteScanline(out, scanbuf, row, 0)<0) {
roentgen b75cab
					TIFFError(infilename,
roentgen b75cab
						  "scanline %lu: Write error",
roentgen b75cab
						  (unsigned long) row);
roentgen b75cab
					break;
roentgen b75cab
				}
roentgen b75cab
			}
roentgen b75cab
roentgen b75cab
			_TIFFfree(scanbuf);
roentgen b75cab
roentgen b75cab
/* -------------------------------------------------------------------- */
roentgen b75cab
/*  Read compressed image data.                                         */
roentgen b75cab
/* -------------------------------------------------------------------- */
roentgen b75cab
roentgen b75cab
		} else if ( info_hdr.iCompression == BMPC_RLE8
roentgen b75cab
			    || info_hdr.iCompression == BMPC_RLE4 ) {
roentgen b75cab
			uint32		i, j, k, runlength;
roentgen b75cab
			uint32		compr_size, uncompr_size;
roentgen b75cab
			unsigned char   *comprbuf;
roentgen b75cab
			unsigned char   *uncomprbuf;
roentgen b75cab
roentgen b75cab
			compr_size = file_hdr.iSize - file_hdr.iOffBits;
roentgen b75cab
			uncompr_size = width * length;
roentgen b75cab
			comprbuf = (unsigned char *) _TIFFmalloc( compr_size );
roentgen b75cab
			if (!comprbuf) {
roentgen b75cab
				TIFFError(infilename,
roentgen b75cab
			"Can't allocate space for compressed scanline buffer");
roentgen b75cab
				goto bad3;
roentgen b75cab
			}
roentgen b75cab
			uncomprbuf = (unsigned char *)_TIFFmalloc(uncompr_size);
roentgen b75cab
			if (!uncomprbuf) {
roentgen b75cab
				TIFFError(infilename,
roentgen b75cab
			"Can't allocate space for uncompressed scanline buffer");
roentgen b75cab
				goto bad3;
roentgen b75cab
			}
roentgen b75cab
roentgen b75cab
			lseek(fd, file_hdr.iOffBits, SEEK_SET);
roentgen b75cab
			read(fd, comprbuf, compr_size);
roentgen b75cab
			i = 0;
roentgen b75cab
			j = 0;
roentgen b75cab
			if (info_hdr.iBitCount == 8) {		/* RLE8 */
roentgen b75cab
			    while(j < uncompr_size && i < compr_size) {
roentgen b75cab
				if ( comprbuf[i] ) {
roentgen b75cab
				    runlength = comprbuf[i++];
roentgen b75cab
				    while( runlength > 0
roentgen b75cab
					   && j < uncompr_size
roentgen b75cab
					   && i < compr_size ) {
roentgen b75cab
					uncomprbuf[j++] = comprbuf[i];
roentgen b75cab
					runlength--;
roentgen b75cab
				    }
roentgen b75cab
				    i++;
roentgen b75cab
				} else {
roentgen b75cab
				    i++;
roentgen b75cab
				    if (comprbuf[i] == 0) /* Next scanline */
roentgen b75cab
					i++;
roentgen b75cab
				    else if (comprbuf[i] == 1) /* End of image */
roentgen b75cab
					break;
roentgen b75cab
				    else if (comprbuf[i] == 2) { /* Move to... */
roentgen b75cab
					i++;
roentgen b75cab
					if (i < compr_size - 1) {
roentgen b75cab
					    j+=comprbuf[i]+comprbuf[i+1]*width;
roentgen b75cab
					    i += 2;
roentgen b75cab
					}
roentgen b75cab
					else
roentgen b75cab
					    break;
roentgen b75cab
				    } else {            /* Absolute mode */
roentgen b75cab
					runlength = comprbuf[i++];
roentgen b75cab
					for (k = 0; k < runlength && j < uncompr_size && i < compr_size; k++)
roentgen b75cab
					    uncomprbuf[j++] = comprbuf[i++];
roentgen b75cab
					if ( k & 0x01 )
roentgen b75cab
					    i++;
roentgen b75cab
				    }
roentgen b75cab
				}
roentgen b75cab
			    }
roentgen b75cab
			}
roentgen b75cab
			else {				    /* RLE4 */
roentgen b75cab
			    while( j < uncompr_size && i < compr_size ) {
roentgen b75cab
				if ( comprbuf[i] ) {
roentgen b75cab
				    runlength = comprbuf[i++];
roentgen b75cab
				    while( runlength > 0 && j < uncompr_size && i < compr_size ) {
roentgen b75cab
					if ( runlength & 0x01 )
roentgen b75cab
					    uncomprbuf[j++] = (comprbuf[i] & 0xF0) >> 4;
roentgen b75cab
					else
roentgen b75cab
					    uncomprbuf[j++] = comprbuf[i] & 0x0F;
roentgen b75cab
					runlength--;
roentgen b75cab
				    }
roentgen b75cab
				    i++;
roentgen b75cab
				} else {
roentgen b75cab
				    i++;
roentgen b75cab
				    if (comprbuf[i] == 0) /* Next scanline */
roentgen b75cab
					i++;
roentgen b75cab
				    else if (comprbuf[i] == 1) /* End of image */
roentgen b75cab
					break;
roentgen b75cab
				    else if (comprbuf[i] == 2) { /* Move to... */
roentgen b75cab
					i++;
roentgen b75cab
					if (i < compr_size - 1) {
roentgen b75cab
					    j+=comprbuf[i]+comprbuf[i+1]*width;
roentgen b75cab
					    i += 2;
roentgen b75cab
					}
roentgen b75cab
					else
roentgen b75cab
					    break;
roentgen b75cab
				    } else {            /* Absolute mode */
roentgen b75cab
					runlength = comprbuf[i++];
roentgen b75cab
					for (k = 0; k < runlength && j < uncompr_size && i < compr_size; k++) {
roentgen b75cab
					    if (k & 0x01)
roentgen b75cab
						uncomprbuf[j++] = comprbuf[i++] & 0x0F;
roentgen b75cab
					    else
roentgen b75cab
						uncomprbuf[j++] = (comprbuf[i] & 0xF0) >> 4;
roentgen b75cab
					}
roentgen b75cab
					if (k & 0x01)
roentgen b75cab
					    i++;
roentgen b75cab
				    }
roentgen b75cab
				}
roentgen b75cab
			    }
roentgen b75cab
			}
roentgen b75cab
roentgen b75cab
			_TIFFfree(comprbuf);
roentgen b75cab
roentgen b75cab
			for (row = 0; row < length; row++) {
roentgen b75cab
				if (TIFFWriteScanline(out,
roentgen b75cab
					uncomprbuf + (length - row - 1) * width,
roentgen b75cab
					row, 0) < 0) {
roentgen b75cab
					TIFFError(infilename,
roentgen b75cab
						"scanline %lu: Write error.\n",
roentgen b75cab
						  (unsigned long) row);
roentgen b75cab
				}
roentgen b75cab
			}
roentgen b75cab
roentgen b75cab
			_TIFFfree(uncomprbuf);
roentgen b75cab
		}
roentgen b75cab
		TIFFWriteDirectory(out);
roentgen b75cab
		if (blue_tbl) {
roentgen b75cab
		  _TIFFfree(blue_tbl);
roentgen b75cab
		  blue_tbl=NULL;
roentgen b75cab
		}
roentgen b75cab
		if (green_tbl) {
roentgen b75cab
		  _TIFFfree(green_tbl);
roentgen b75cab
		  green_tbl=NULL;
roentgen b75cab
		}
roentgen b75cab
		if (red_tbl) {
roentgen b75cab
		  _TIFFfree(red_tbl);
roentgen b75cab
		  red_tbl=NULL;
roentgen b75cab
		}
roentgen b75cab
	}
roentgen b75cab
roentgen b75cab
bad3:
roentgen b75cab
	if (blue_tbl)
roentgen b75cab
		_TIFFfree(blue_tbl);
roentgen b75cab
bad2:
roentgen b75cab
	if (green_tbl)
roentgen b75cab
		_TIFFfree(green_tbl);
roentgen b75cab
bad1:
roentgen b75cab
	if (red_tbl)
roentgen b75cab
		_TIFFfree(red_tbl);
roentgen b75cab
bad:
roentgen b75cab
        close(fd);
roentgen b75cab
roentgen b75cab
	if (out)
roentgen b75cab
		TIFFClose(out);
roentgen b75cab
        return 0;
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
/*
roentgen b75cab
 * Image data in BMP file stored in BGR (or ABGR) format. We should rearrange
roentgen b75cab
 * pixels to RGB (RGBA) format.
roentgen b75cab
 */
roentgen b75cab
static void
roentgen b75cab
rearrangePixels(char *buf, uint32 width, uint32 bit_count)
roentgen b75cab
{
roentgen b75cab
	char tmp;
roentgen b75cab
	uint32 i;
roentgen b75cab
roentgen b75cab
        switch(bit_count) {
roentgen b75cab
		case 16:    /* FIXME: need a sample file */
roentgen b75cab
                        break;
roentgen b75cab
                case 24:
roentgen b75cab
			for (i = 0; i < width; i++, buf += 3) {
roentgen b75cab
				tmp = *buf;
roentgen b75cab
				*buf = *(buf + 2);
roentgen b75cab
				*(buf + 2) = tmp;
roentgen b75cab
			}
roentgen b75cab
                        break;
roentgen b75cab
                case 32:
roentgen b75cab
			{
roentgen b75cab
				char	*buf1 = buf;
roentgen b75cab
roentgen b75cab
				for (i = 0; i < width; i++, buf += 4) {
roentgen b75cab
					tmp = *buf;
roentgen b75cab
					*buf1++ = *(buf + 2);
roentgen b75cab
					*buf1++ = *(buf + 1);
roentgen b75cab
					*buf1++ = tmp;
roentgen b75cab
				}
roentgen b75cab
			}
roentgen b75cab
                        break;
roentgen b75cab
                default:
roentgen b75cab
                        break;
roentgen b75cab
        }
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static int
roentgen b75cab
processCompressOptions(char* opt)
roentgen b75cab
{
roentgen b75cab
	if (strcmp(opt, "none") == 0)
roentgen b75cab
		compression = COMPRESSION_NONE;
roentgen b75cab
	else if (strcmp(opt, "packbits") == 0)
roentgen b75cab
		compression = COMPRESSION_PACKBITS;
roentgen b75cab
	else if (strncmp(opt, "jpeg", 4) == 0) {
roentgen b75cab
		char* cp = strchr(opt, ':');
roentgen b75cab
roentgen b75cab
                compression = COMPRESSION_JPEG;
roentgen b75cab
                while( cp )
roentgen b75cab
                {
roentgen b75cab
                    if (isdigit((int)cp[1]))
roentgen b75cab
			quality = atoi(cp+1);
roentgen b75cab
                    else if (cp[1] == 'r' )
roentgen b75cab
			jpegcolormode = JPEGCOLORMODE_RAW;
roentgen b75cab
                    else
roentgen b75cab
                        usage();
roentgen b75cab
roentgen b75cab
                    cp = strchr(cp+1,':');
roentgen b75cab
                }
roentgen b75cab
	} else if (strncmp(opt, "lzw", 3) == 0) {
roentgen b75cab
		char* cp = strchr(opt, ':');
roentgen b75cab
		if (cp)
roentgen b75cab
			predictor = atoi(cp+1);
roentgen b75cab
		compression = COMPRESSION_LZW;
roentgen b75cab
	} else if (strncmp(opt, "zip", 3) == 0) {
roentgen b75cab
		char* cp = strchr(opt, ':');
roentgen b75cab
		if (cp)
roentgen b75cab
			predictor = atoi(cp+1);
roentgen b75cab
		compression = COMPRESSION_DEFLATE;
roentgen b75cab
	} else
roentgen b75cab
		return (0);
roentgen b75cab
	return (1);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
static char* stuff[] = {
roentgen b75cab
"bmp2tiff --- convert Windows BMP files to TIFF",
roentgen b75cab
"usage: bmp2tiff [options] input.bmp [input2.bmp ...] output.tif",
roentgen b75cab
"where options are:",
roentgen b75cab
" -r #		make each strip have no more than # rows",
roentgen b75cab
"",
roentgen b75cab
" -c lzw[:opts]	compress output with Lempel-Ziv & Welch encoding",
roentgen b75cab
" -c zip[:opts]	compress output with deflate encoding",
roentgen b75cab
" -c jpeg[:opts]compress output with JPEG encoding",
roentgen b75cab
" -c packbits	compress output with packbits encoding",
roentgen b75cab
" -c none	use no compression algorithm on output",
roentgen b75cab
"",
roentgen b75cab
"JPEG options:",
roentgen b75cab
" #		set compression quality level (0-100, default 75)",
roentgen b75cab
" r		output color image as RGB rather than YCbCr",
roentgen b75cab
"For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality",
roentgen b75cab
"",
roentgen b75cab
"LZW and deflate options:",
roentgen b75cab
" #		set predictor value",
roentgen b75cab
"For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
roentgen b75cab
" -o out.tif	write output to out.tif",
roentgen b75cab
" -h		this help message",
roentgen b75cab
NULL
roentgen b75cab
};
roentgen b75cab
roentgen b75cab
static void
roentgen b75cab
usage(void)
roentgen b75cab
{
roentgen b75cab
	char buf[BUFSIZ];
roentgen b75cab
	int i;
roentgen b75cab
roentgen b75cab
	setbuf(stderr, buf);
roentgen b75cab
        fprintf(stderr, "%s\n\n", TIFFGetVersion());
roentgen b75cab
	for (i = 0; stuff[i] != NULL; i++)
roentgen b75cab
		fprintf(stderr, "%s\n", stuff[i]);
roentgen b75cab
	exit(-1);
roentgen b75cab
}
roentgen b75cab
roentgen b75cab
/* vim: set ts=8 sts=8 sw=8 noet: */
roentgen b75cab
/*
roentgen b75cab
 * Local Variables:
roentgen b75cab
 * mode: c
roentgen b75cab
 * c-basic-offset: 8
roentgen b75cab
 * fill-column: 78
roentgen b75cab
 * End:
roentgen b75cab
 */