kusano 7d535a
/* $Id: rgb2ycbcr.c,v 1.14 2011-05-31 17:03:16 bfriesen Exp $ */
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Copyright (c) 1991-1997 Sam Leffler
kusano 7d535a
 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
kusano 7d535a
 *
kusano 7d535a
 * Permission to use, copy, modify, distribute, and sell this software and 
kusano 7d535a
 * its documentation for any purpose is hereby granted without fee, provided
kusano 7d535a
 * that (i) the above copyright notices and this permission notice appear in
kusano 7d535a
 * all copies of the software and related documentation, and (ii) the names of
kusano 7d535a
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
kusano 7d535a
 * publicity relating to the software without the specific, prior written
kusano 7d535a
 * permission of Sam Leffler and Silicon Graphics.
kusano 7d535a
 * 
kusano 7d535a
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
kusano 7d535a
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
kusano 7d535a
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
kusano 7d535a
 * 
kusano 7d535a
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
kusano 7d535a
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
kusano 7d535a
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
kusano 7d535a
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
kusano 7d535a
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
kusano 7d535a
 * OF THIS SOFTWARE.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
#include "tif_config.h"
kusano 7d535a
kusano 7d535a
#include <stdio.h></stdio.h>
kusano 7d535a
#include <string.h></string.h>
kusano 7d535a
#include <stdlib.h></stdlib.h>
kusano 7d535a
kusano 7d535a
#ifdef HAVE_UNISTD_H
kusano 7d535a
# include <unistd.h></unistd.h>
kusano 7d535a
#endif
kusano 7d535a
kusano 7d535a
#ifdef NEED_LIBPORT
kusano 7d535a
# include "libport.h"
kusano 7d535a
#endif
kusano 7d535a
kusano 7d535a
#include "tiffiop.h"
kusano 7d535a
#include "tiffio.h"
kusano 7d535a
kusano 7d535a
#define	streq(a,b)	(strcmp(a,b) == 0)
kusano 7d535a
#define	CopyField(tag, v) \
kusano 7d535a
    if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
kusano 7d535a
kusano 7d535a
#ifndef howmany
kusano 7d535a
#define	howmany(x, y)	(((x)+((y)-1))/(y))
kusano 7d535a
#endif
kusano 7d535a
#define	roundup(x, y)	(howmany(x,y)*((uint32)(y)))
kusano 7d535a
kusano 7d535a
#define	LumaRed		ycbcrCoeffs[0]
kusano 7d535a
#define	LumaGreen	ycbcrCoeffs[1]
kusano 7d535a
#define	LumaBlue	ycbcrCoeffs[2]
kusano 7d535a
kusano 7d535a
uint16	compression = COMPRESSION_PACKBITS;
kusano 7d535a
uint32	rowsperstrip = (uint32) -1;
kusano 7d535a
kusano 7d535a
uint16	horizSubSampling = 2;		/* YCbCr horizontal subsampling */
kusano 7d535a
uint16	vertSubSampling = 2;		/* YCbCr vertical subsampling */
kusano 7d535a
float	ycbcrCoeffs[3] = { .299F, .587F, .114F };
kusano 7d535a
/* default coding range is CCIR Rec 601-1 with no headroom/footroom */
kusano 7d535a
float	refBlackWhite[6] = { 0.F, 255.F, 128.F, 255.F, 128.F, 255.F };
kusano 7d535a
kusano 7d535a
static	int tiffcvt(TIFF* in, TIFF* out);
kusano 7d535a
static	void usage(int code);
kusano 7d535a
static	void setupLumaTables(void);
kusano 7d535a
kusano 7d535a
int
kusano 7d535a
main(int argc, char* argv[])
kusano 7d535a
{
kusano 7d535a
	TIFF *in, *out;
kusano 7d535a
	int c;
kusano 7d535a
	extern int optind;
kusano 7d535a
	extern char *optarg;
kusano 7d535a
kusano 7d535a
	while ((c = getopt(argc, argv, "c:h:r:v:z")) != -1)
kusano 7d535a
		switch (c) {
kusano 7d535a
		case 'c':
kusano 7d535a
			if (streq(optarg, "none"))
kusano 7d535a
			    compression = COMPRESSION_NONE;
kusano 7d535a
			else if (streq(optarg, "packbits"))
kusano 7d535a
			    compression = COMPRESSION_PACKBITS;
kusano 7d535a
			else if (streq(optarg, "lzw"))
kusano 7d535a
			    compression = COMPRESSION_LZW;
kusano 7d535a
			else if (streq(optarg, "jpeg"))
kusano 7d535a
			    compression = COMPRESSION_JPEG;
kusano 7d535a
			else if (streq(optarg, "zip"))
kusano 7d535a
			    compression = COMPRESSION_ADOBE_DEFLATE;
kusano 7d535a
			else
kusano 7d535a
			    usage(-1);
kusano 7d535a
			break;
kusano 7d535a
		case 'h':
kusano 7d535a
			horizSubSampling = atoi(optarg);
kusano 7d535a
			break;
kusano 7d535a
		case 'v':
kusano 7d535a
			vertSubSampling = atoi(optarg);
kusano 7d535a
			break;
kusano 7d535a
		case 'r':
kusano 7d535a
			rowsperstrip = atoi(optarg);
kusano 7d535a
			break;
kusano 7d535a
		case 'z':	/* CCIR Rec 601-1 w/ headroom/footroom */
kusano 7d535a
			refBlackWhite[0] = 16.;
kusano 7d535a
			refBlackWhite[1] = 235.;
kusano 7d535a
			refBlackWhite[2] = 128.;
kusano 7d535a
			refBlackWhite[3] = 240.;
kusano 7d535a
			refBlackWhite[4] = 128.;
kusano 7d535a
			refBlackWhite[5] = 240.;
kusano 7d535a
			break;
kusano 7d535a
		case '?':
kusano 7d535a
			usage(0);
kusano 7d535a
			/*NOTREACHED*/
kusano 7d535a
		}
kusano 7d535a
	if (argc - optind < 2)
kusano 7d535a
		usage(-1);
kusano 7d535a
	out = TIFFOpen(argv[argc-1], "w");
kusano 7d535a
	if (out == NULL)
kusano 7d535a
		return (-2);
kusano 7d535a
	setupLumaTables();
kusano 7d535a
	for (; optind < argc-1; optind++) {
kusano 7d535a
		in = TIFFOpen(argv[optind], "r");
kusano 7d535a
		if (in != NULL) {
kusano 7d535a
			do {
kusano 7d535a
				if (!tiffcvt(in, out) ||
kusano 7d535a
				    !TIFFWriteDirectory(out)) {
kusano 7d535a
					(void) TIFFClose(out);
kusano 7d535a
					return (1);
kusano 7d535a
				}
kusano 7d535a
			} while (TIFFReadDirectory(in));
kusano 7d535a
			(void) TIFFClose(in);
kusano 7d535a
		}
kusano 7d535a
	}
kusano 7d535a
	(void) TIFFClose(out);
kusano 7d535a
	return (0);
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
float	*lumaRed;
kusano 7d535a
float	*lumaGreen;
kusano 7d535a
float	*lumaBlue;
kusano 7d535a
float	D1, D2;
kusano 7d535a
int	Yzero;
kusano 7d535a
kusano 7d535a
static float*
kusano 7d535a
setupLuma(float c)
kusano 7d535a
{
kusano 7d535a
	float *v = (float *)_TIFFmalloc(256 * sizeof (float));
kusano 7d535a
	int i;
kusano 7d535a
	for (i = 0; i < 256; i++)
kusano 7d535a
		v[i] = c * i;
kusano 7d535a
	return (v);
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
static unsigned
kusano 7d535a
V2Code(float f, float RB, float RW, int CR)
kusano 7d535a
{
kusano 7d535a
	unsigned int c = (unsigned int)((((f)*(RW-RB)/CR)+RB)+.5);
kusano 7d535a
	return (c > 255 ? 255 : c);
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
static void
kusano 7d535a
setupLumaTables(void)
kusano 7d535a
{
kusano 7d535a
	lumaRed = setupLuma(LumaRed);
kusano 7d535a
	lumaGreen = setupLuma(LumaGreen);
kusano 7d535a
	lumaBlue = setupLuma(LumaBlue);
kusano 7d535a
	D1 = 1.F/(2.F - 2.F*LumaBlue);
kusano 7d535a
	D2 = 1.F/(2.F - 2.F*LumaRed);
kusano 7d535a
	Yzero = V2Code(0, refBlackWhite[0], refBlackWhite[1], 255);
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
static void
kusano 7d535a
cvtClump(unsigned char* op, uint32* raster, uint32 ch, uint32 cw, uint32 w)
kusano 7d535a
{
kusano 7d535a
	float Y, Cb = 0, Cr = 0;
kusano 7d535a
	uint32 j, k;
kusano 7d535a
	/*
kusano 7d535a
	 * Convert ch-by-cw block of RGB
kusano 7d535a
	 * to YCbCr and sample accordingly.
kusano 7d535a
	 */
kusano 7d535a
	for (k = 0; k < ch; k++) {
kusano 7d535a
		for (j = 0; j < cw; j++) {
kusano 7d535a
			uint32 RGB = (raster - k*w)[j];
kusano 7d535a
			Y = lumaRed[TIFFGetR(RGB)] +
kusano 7d535a
			    lumaGreen[TIFFGetG(RGB)] +
kusano 7d535a
			    lumaBlue[TIFFGetB(RGB)];
kusano 7d535a
			/* accumulate chrominance */
kusano 7d535a
			Cb += (TIFFGetB(RGB) - Y) * D1;
kusano 7d535a
			Cr += (TIFFGetR(RGB) - Y) * D2;
kusano 7d535a
			/* emit luminence */
kusano 7d535a
			*op++ = V2Code(Y,
kusano 7d535a
			    refBlackWhite[0], refBlackWhite[1], 255);
kusano 7d535a
		}
kusano 7d535a
		for (; j < horizSubSampling; j++)
kusano 7d535a
			*op++ = Yzero;
kusano 7d535a
	}
kusano 7d535a
	for (; k < vertSubSampling; k++) {
kusano 7d535a
		for (j = 0; j < horizSubSampling; j++)
kusano 7d535a
			*op++ = Yzero;
kusano 7d535a
	}
kusano 7d535a
	/* emit sampled chrominance values */
kusano 7d535a
	*op++ = V2Code(Cb / (ch*cw), refBlackWhite[2], refBlackWhite[3], 127);
kusano 7d535a
	*op++ = V2Code(Cr / (ch*cw), refBlackWhite[4], refBlackWhite[5], 127);
kusano 7d535a
}
kusano 7d535a
#undef LumaRed
kusano 7d535a
#undef LumaGreen
kusano 7d535a
#undef LumaBlue
kusano 7d535a
#undef V2Code
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Convert a strip of RGB data to YCbCr and
kusano 7d535a
 * sample to generate the output data.
kusano 7d535a
 */
kusano 7d535a
static void
kusano 7d535a
cvtStrip(unsigned char* op, uint32* raster, uint32 nrows, uint32 width)
kusano 7d535a
{
kusano 7d535a
	uint32 x;
kusano 7d535a
	int clumpSize = vertSubSampling * horizSubSampling + 2;
kusano 7d535a
	uint32 *tp;
kusano 7d535a
kusano 7d535a
	for (; nrows >= vertSubSampling; nrows -= vertSubSampling) {
kusano 7d535a
		tp = raster;
kusano 7d535a
		for (x = width; x >= horizSubSampling; x -= horizSubSampling) {
kusano 7d535a
			cvtClump(op, tp,
kusano 7d535a
			    vertSubSampling, horizSubSampling, width);
kusano 7d535a
			op += clumpSize;
kusano 7d535a
			tp += horizSubSampling;
kusano 7d535a
		}
kusano 7d535a
		if (x > 0) {
kusano 7d535a
			cvtClump(op, tp, vertSubSampling, x, width);
kusano 7d535a
			op += clumpSize;
kusano 7d535a
		}
kusano 7d535a
		raster -= vertSubSampling*width;
kusano 7d535a
	}
kusano 7d535a
	if (nrows > 0) {
kusano 7d535a
		tp = raster;
kusano 7d535a
		for (x = width; x >= horizSubSampling; x -= horizSubSampling) {
kusano 7d535a
			cvtClump(op, tp, nrows, horizSubSampling, width);
kusano 7d535a
			op += clumpSize;
kusano 7d535a
			tp += horizSubSampling;
kusano 7d535a
		}
kusano 7d535a
		if (x > 0)
kusano 7d535a
			cvtClump(op, tp, nrows, x, width);
kusano 7d535a
	}
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
static int
kusano 7d535a
cvtRaster(TIFF* tif, uint32* raster, uint32 width, uint32 height)
kusano 7d535a
{
kusano 7d535a
	uint32 y;
kusano 7d535a
	tstrip_t strip = 0;
kusano 7d535a
	tsize_t cc, acc;
kusano 7d535a
	unsigned char* buf;
kusano 7d535a
	uint32 rwidth = roundup(width, horizSubSampling);
kusano 7d535a
	uint32 rheight = roundup(height, vertSubSampling);
kusano 7d535a
	uint32 nrows = (rowsperstrip > rheight ? rheight : rowsperstrip);
kusano 7d535a
        uint32 rnrows = roundup(nrows,vertSubSampling);
kusano 7d535a
kusano 7d535a
	cc = rnrows*rwidth +
kusano 7d535a
	    2*((rnrows*rwidth) / (horizSubSampling*vertSubSampling));
kusano 7d535a
	buf = (unsigned char*)_TIFFmalloc(cc);
kusano 7d535a
	// FIXME unchecked malloc
kusano 7d535a
	for (y = height; (int32) y > 0; y -= nrows) {
kusano 7d535a
		uint32 nr = (y > nrows ? nrows : y);
kusano 7d535a
		cvtStrip(buf, raster + (y-1)*width, nr, width);
kusano 7d535a
		nr = roundup(nr, vertSubSampling);
kusano 7d535a
		acc = nr*rwidth +
kusano 7d535a
			2*((nr*rwidth)/(horizSubSampling*vertSubSampling));
kusano 7d535a
		if (!TIFFWriteEncodedStrip(tif, strip++, buf, acc)) {
kusano 7d535a
			_TIFFfree(buf);
kusano 7d535a
			return (0);
kusano 7d535a
		}
kusano 7d535a
	}
kusano 7d535a
	_TIFFfree(buf);
kusano 7d535a
	return (1);
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
static int
kusano 7d535a
tiffcvt(TIFF* in, TIFF* out)
kusano 7d535a
{
kusano 7d535a
	uint32 width, height;		/* image width & height */
kusano 7d535a
	uint32* raster;			/* retrieve RGBA image */
kusano 7d535a
	uint16 shortv;
kusano 7d535a
	float floatv;
kusano 7d535a
	char *stringv;
kusano 7d535a
	uint32 longv;
kusano 7d535a
	int result;
kusano 7d535a
	size_t pixel_count;
kusano 7d535a
kusano 7d535a
	TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width);
kusano 7d535a
	TIFFGetField(in, TIFFTAG_IMAGELENGTH, &height);
kusano 7d535a
	pixel_count = width * height;
kusano 7d535a
kusano 7d535a
 	/* XXX: Check the integer overflow. */
kusano 7d535a
 	if (!width || !height || pixel_count / width != height) {
kusano 7d535a
 		TIFFError(TIFFFileName(in),
kusano 7d535a
 			  "Malformed input file; "
kusano 7d535a
 			  "can't allocate buffer for raster of %lux%lu size",
kusano 7d535a
 			  (unsigned long)width, (unsigned long)height);
kusano 7d535a
 		return 0;
kusano 7d535a
 	}
kusano 7d535a
 
kusano 7d535a
 	raster = (uint32*)_TIFFCheckMalloc(in, pixel_count, sizeof(uint32),
kusano 7d535a
 					   "raster buffer");
kusano 7d535a
  	if (raster == 0) {
kusano 7d535a
 		TIFFError(TIFFFileName(in),
kusano 7d535a
 			  "Failed to allocate buffer (%lu elements of %lu each)",
kusano 7d535a
 			  (unsigned long)pixel_count,
kusano 7d535a
 			  (unsigned long)sizeof(uint32));
kusano 7d535a
  		return (0);
kusano 7d535a
  	}
kusano 7d535a
kusano 7d535a
	if (!TIFFReadRGBAImage(in, width, height, raster, 0)) {
kusano 7d535a
		_TIFFfree(raster);
kusano 7d535a
		return (0);
kusano 7d535a
	}
kusano 7d535a
kusano 7d535a
	CopyField(TIFFTAG_SUBFILETYPE, longv);
kusano 7d535a
	TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
kusano 7d535a
	TIFFSetField(out, TIFFTAG_IMAGELENGTH, height);
kusano 7d535a
	TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8);
kusano 7d535a
	TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
kusano 7d535a
	TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
kusano 7d535a
	if (compression == COMPRESSION_JPEG)
kusano 7d535a
		TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
kusano 7d535a
	CopyField(TIFFTAG_FILLORDER, shortv);
kusano 7d535a
	TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
kusano 7d535a
	TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3);
kusano 7d535a
	CopyField(TIFFTAG_XRESOLUTION, floatv);
kusano 7d535a
	CopyField(TIFFTAG_YRESOLUTION, floatv);
kusano 7d535a
	CopyField(TIFFTAG_RESOLUTIONUNIT, shortv);
kusano 7d535a
	TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
kusano 7d535a
	{ char buf[2048];
kusano 7d535a
	  char *cp = strrchr(TIFFFileName(in), '/');
kusano 7d535a
	  sprintf(buf, "YCbCr conversion of %s", cp ? cp+1 : TIFFFileName(in));
kusano 7d535a
	  TIFFSetField(out, TIFFTAG_IMAGEDESCRIPTION, buf);
kusano 7d535a
	}
kusano 7d535a
	TIFFSetField(out, TIFFTAG_SOFTWARE, TIFFGetVersion());
kusano 7d535a
	CopyField(TIFFTAG_DOCUMENTNAME, stringv);
kusano 7d535a
kusano 7d535a
	TIFFSetField(out, TIFFTAG_REFERENCEBLACKWHITE, refBlackWhite);
kusano 7d535a
	TIFFSetField(out, TIFFTAG_YCBCRSUBSAMPLING,
kusano 7d535a
	    horizSubSampling, vertSubSampling);
kusano 7d535a
	TIFFSetField(out, TIFFTAG_YCBCRPOSITIONING, YCBCRPOSITION_CENTERED);
kusano 7d535a
	TIFFSetField(out, TIFFTAG_YCBCRCOEFFICIENTS, ycbcrCoeffs);
kusano 7d535a
	rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
kusano 7d535a
	TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
kusano 7d535a
kusano 7d535a
	result = cvtRaster(out, raster, width, height);
kusano 7d535a
        _TIFFfree(raster);
kusano 7d535a
        return result;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
char* stuff[] = {
kusano 7d535a
    "usage: rgb2ycbcr [-c comp] [-r rows] [-h N] [-v N] input... output\n",
kusano 7d535a
    "where comp is one of the following compression algorithms:\n",
kusano 7d535a
    " jpeg\t\tJPEG encoding\n",
kusano 7d535a
    " lzw\t\tLempel-Ziv & Welch encoding\n",
kusano 7d535a
    " zip\t\tdeflate encoding\n",
kusano 7d535a
    " packbits\tPackBits encoding (default)\n",
kusano 7d535a
    " none\t\tno compression\n",
kusano 7d535a
    "and the other options are:\n",
kusano 7d535a
    " -r\trows/strip\n",
kusano 7d535a
    " -h\thorizontal sampling factor (1,2,4)\n",
kusano 7d535a
    " -v\tvertical sampling factor (1,2,4)\n",
kusano 7d535a
    NULL
kusano 7d535a
};
kusano 7d535a
kusano 7d535a
static void
kusano 7d535a
usage(int code)
kusano 7d535a
{
kusano 7d535a
	char buf[BUFSIZ];
kusano 7d535a
	int i;
kusano 7d535a
kusano 7d535a
	setbuf(stderr, buf);
kusano 7d535a
       
kusano 7d535a
 fprintf(stderr, "%s\n\n", TIFFGetVersion());
kusano 7d535a
	for (i = 0; stuff[i] != NULL; i++)
kusano 7d535a
		fprintf(stderr, "%s\n", stuff[i]);
kusano 7d535a
	exit(code);
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
/* vim: set ts=8 sts=8 sw=8 noet: */
kusano 7d535a
/*
kusano 7d535a
 * Local Variables:
kusano 7d535a
 * mode: c
kusano 7d535a
 * c-basic-offset: 8
kusano 7d535a
 * fill-column: 78
kusano 7d535a
 * End:
kusano 7d535a
 */