convert.c 65.6 KB
Newer Older
1
/*
2 3 4 5 6 7 8
 * The copyright in this software is being made available under the 2-clauses 
 * BSD License, included below. This software may be subject to other third 
 * party and contributor rights, including patent rights, and no such rights
 * are granted under this license.
 *
 * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
 * Copyright (c) 2002-2014, Professor Benoit Macq
9 10
 * Copyright (c) 2001-2003, David Janssens
 * Copyright (c) 2002-2003, Yannick Verschueren
11 12
 * Copyright (c) 2003-2007, Francois-Olivier Devaux 
 * Copyright (c) 2003-2014, Antonin Descampe
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
 * Copyright (c) 2005, Herve Drolon, FreeImage Team
 * Copyright (c) 2006-2007, Parvatha Elangovan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
38
#include "opj_apps_config.h"
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "openjpeg.h"
#include "convert.h"

/*
 * Get logarithm of an integer and round downwards.
 *
 * log2(a)
 */
static int int_floorlog2(int a) {
54 55 56 57 58
    int l;
    for (l = 0; a > 1; l++) {
        a >>= 1;
    }
    return l;
59 60
}

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
/* Component precision scaling */
void clip_component(opj_image_comp_t* component, OPJ_UINT32 precision)
{
	OPJ_SIZE_T i;
	OPJ_SIZE_T len;
	OPJ_UINT32 umax = (OPJ_UINT32)((OPJ_INT32)-1);
	
	len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
	if (precision < 32) {
		umax = (1U << precision) - 1U;
	}
	
	if (component->sgnd) {
		OPJ_INT32* l_data = component->data;
		OPJ_INT32 max = (OPJ_INT32)(umax / 2U);
		OPJ_INT32 min = -max - 1;
		for (i = 0; i < len; ++i) {
			if (l_data[i] > max) {
				l_data[i] = max;
			} else if (l_data[i] < min) {
				l_data[i] = min;
			}
		}
	} else {
		OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
		for (i = 0; i < len; ++i) {
			if (l_data[i] > umax) {
				l_data[i] = umax;
			}
		}
	}
	component->prec = precision;
}

/* Component precision scaling */
static void scale_component_up(opj_image_comp_t* component, OPJ_UINT32 precision)
{
	OPJ_SIZE_T i, len;
	
	len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
	if (component->sgnd) {
		OPJ_INT64  newMax = (OPJ_INT64)(1U << (precision - 1));
		OPJ_INT64  oldMax = (OPJ_INT64)(1U << (component->prec - 1));
		OPJ_INT32* l_data = component->data;
		for (i = 0; i < len; ++i) {
			l_data[i] = (OPJ_INT32)(((OPJ_INT64)l_data[i] * newMax) / oldMax);
		}
	} else {
		OPJ_UINT64  newMax = (OPJ_UINT64)((1U << precision) - 1U);
		OPJ_UINT64  oldMax = (OPJ_UINT64)((1U << component->prec) - 1U);
		OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
		for (i = 0; i < len; ++i) {
			l_data[i] = (OPJ_UINT32)(((OPJ_UINT64)l_data[i] * newMax) / oldMax);
		}
	}
	component->prec = precision;
	component->bpp = precision;
}
void scale_component(opj_image_comp_t* component, OPJ_UINT32 precision)
{
	int shift;
	OPJ_SIZE_T i, len;
	
	if (component->prec == precision) {
		return;
	}
	if (component->prec < precision) {
		scale_component_up(component, precision);
		return;
	}
	shift = (int)(component->prec - precision);
	len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
	if (component->sgnd) {
		OPJ_INT32* l_data = component->data;
		for (i = 0; i < len; ++i) {
			l_data[i] >>= shift;
		}
	} else {
		OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
		for (i = 0; i < len; ++i) {
			l_data[i] >>= shift;
		}
	}
	component->bpp = precision;
	component->prec = precision;
}


/* planar / interleaved conversions */
/* used by PNG/TIFF */
static void convert_32s_C1P1(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst, OPJ_SIZE_T length)
{
	memcpy(pDst[0], pSrc, length * sizeof(OPJ_INT32));
}
static void convert_32s_C2P2(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst, OPJ_SIZE_T length)
{
	OPJ_SIZE_T i;
	OPJ_INT32* pDst0 = pDst[0];
	OPJ_INT32* pDst1 = pDst[1];
	
	for (i = 0; i < length; i++) {
		pDst0[i] = pSrc[2*i+0];
		pDst1[i] = pSrc[2*i+1];
	}
}
static void convert_32s_C3P3(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst, OPJ_SIZE_T length)
{
	OPJ_SIZE_T i;
	OPJ_INT32* pDst0 = pDst[0];
	OPJ_INT32* pDst1 = pDst[1];
	OPJ_INT32* pDst2 = pDst[2];
	
	for (i = 0; i < length; i++) {
		pDst0[i] = pSrc[3*i+0];
		pDst1[i] = pSrc[3*i+1];
		pDst2[i] = pSrc[3*i+2];
	}
}
static void convert_32s_C4P4(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst, OPJ_SIZE_T length)
{
	OPJ_SIZE_T i;
	OPJ_INT32* pDst0 = pDst[0];
	OPJ_INT32* pDst1 = pDst[1];
	OPJ_INT32* pDst2 = pDst[2];
	OPJ_INT32* pDst3 = pDst[3];
	
	for (i = 0; i < length; i++) {
		pDst0[i] = pSrc[4*i+0];
		pDst1[i] = pSrc[4*i+1];
		pDst2[i] = pSrc[4*i+2];
		pDst3[i] = pSrc[4*i+3];
	}
}
const convert_32s_CXPX convert_32s_CXPX_LUT[5] = {
	NULL,
	convert_32s_C1P1,
	convert_32s_C2P2,
	convert_32s_C3P3,
	convert_32s_C4P4
};

static void convert_32s_P1C1(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length, OPJ_INT32 adjust)
{
	OPJ_SIZE_T i;
	const OPJ_INT32* pSrc0 = pSrc[0];
	
	for (i = 0; i < length; i++) {
		pDst[i] = pSrc0[i] + adjust;
	}
}
static void convert_32s_P2C2(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length, OPJ_INT32 adjust)
{
	OPJ_SIZE_T i;
	const OPJ_INT32* pSrc0 = pSrc[0];
	const OPJ_INT32* pSrc1 = pSrc[1];
	
	for (i = 0; i < length; i++) {
		pDst[2*i+0] = pSrc0[i] + adjust;
		pDst[2*i+1] = pSrc1[i] + adjust;
	}
}
static void convert_32s_P3C3(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length, OPJ_INT32 adjust)
{
	OPJ_SIZE_T i;
	const OPJ_INT32* pSrc0 = pSrc[0];
	const OPJ_INT32* pSrc1 = pSrc[1];
	const OPJ_INT32* pSrc2 = pSrc[2];
	
	for (i = 0; i < length; i++) {
		pDst[3*i+0] = pSrc0[i] + adjust;
		pDst[3*i+1] = pSrc1[i] + adjust;
		pDst[3*i+2] = pSrc2[i] + adjust;
	}
}
static void convert_32s_P4C4(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length, OPJ_INT32 adjust)
{
	OPJ_SIZE_T i;
	const OPJ_INT32* pSrc0 = pSrc[0];
	const OPJ_INT32* pSrc1 = pSrc[1];
	const OPJ_INT32* pSrc2 = pSrc[2];
	const OPJ_INT32* pSrc3 = pSrc[3];
	
	for (i = 0; i < length; i++) {
		pDst[4*i+0] = pSrc0[i] + adjust;
		pDst[4*i+1] = pSrc1[i] + adjust;
		pDst[4*i+2] = pSrc2[i] + adjust;
		pDst[4*i+3] = pSrc3[i] + adjust;
	}
}
const convert_32s_PXCX convert_32s_PXCX_LUT[5] = {
	NULL,
	convert_32s_P1C1,
	convert_32s_P2C2,
	convert_32s_P3C3,
	convert_32s_P4C4
};

/* bit depth conversions */
/* used by PNG/TIFF up to 8bpp */
static void convert_1u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length)
{
	OPJ_SIZE_T i;
	for (i = 0; i < (length & ~(OPJ_SIZE_T)7U); i+=8U) {
		OPJ_UINT32 val = *pSrc++;
		pDst[i+0] = (OPJ_INT32)( val >> 7);
		pDst[i+1] = (OPJ_INT32)((val >> 6) & 0x1U);
		pDst[i+2] = (OPJ_INT32)((val >> 5) & 0x1U);
		pDst[i+3] = (OPJ_INT32)((val >> 4) & 0x1U);
		pDst[i+4] = (OPJ_INT32)((val >> 3) & 0x1U);
		pDst[i+5] = (OPJ_INT32)((val >> 2) & 0x1U);
		pDst[i+6] = (OPJ_INT32)((val >> 1) & 0x1U);
		pDst[i+7] = (OPJ_INT32)(val & 0x1U);
	}
	if (length & 7U) {
		OPJ_UINT32 val = *pSrc++;
		length = length & 7U;
		pDst[i+0] = (OPJ_INT32)(val >> 7);
		
		if (length > 1U) {
			pDst[i+1] = (OPJ_INT32)((val >> 6) & 0x1U);
			if (length > 2U) {
				pDst[i+2] = (OPJ_INT32)((val >> 5) & 0x1U);
				if (length > 3U) {
					pDst[i+3] = (OPJ_INT32)((val >> 4) & 0x1U);
					if (length > 4U) {
						pDst[i+4] = (OPJ_INT32)((val >> 3) & 0x1U);
						if (length > 5U) {
							pDst[i+5] = (OPJ_INT32)((val >> 2) & 0x1U);
							if (length > 6U) {
								pDst[i+6] = (OPJ_INT32)((val >> 1) & 0x1U);
							}
						}
					}
				}
			}
		}
	}
}
static void convert_2u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length)
{
	OPJ_SIZE_T i;
	for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i+=4U) {
		OPJ_UINT32 val = *pSrc++;
		pDst[i+0] = (OPJ_INT32)( val >> 6);
		pDst[i+1] = (OPJ_INT32)((val >> 4) & 0x3U);
		pDst[i+2] = (OPJ_INT32)((val >> 2) & 0x3U);
		pDst[i+3] = (OPJ_INT32)(val & 0x3U);
	}
	if (length & 3U) {
		OPJ_UINT32 val = *pSrc++;
		length = length & 3U;
		pDst[i+0] =  (OPJ_INT32)(val >> 6);
		
		if (length > 1U) {
			pDst[i+1] = (OPJ_INT32)((val >> 4) & 0x3U);
			if (length > 2U) {
				pDst[i+2] = (OPJ_INT32)((val >> 2) & 0x3U);
				
			}
		}
	}
}
static void convert_4u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length)
{
	OPJ_SIZE_T i;
	for (i = 0; i < (length & ~(OPJ_SIZE_T)1U); i+=2U) {
		OPJ_UINT32 val = *pSrc++;
		pDst[i+0] = (OPJ_INT32)(val >> 4);
		pDst[i+1] = (OPJ_INT32)(val & 0xFU);
	}
	if (length & 1U) {
		OPJ_UINT8 val = *pSrc++;
		pDst[i+0] = (OPJ_INT32)(val >> 4);
	}
}
static void convert_6u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length)
{
	OPJ_SIZE_T i;
	for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i+=4U) {
		OPJ_UINT32 val0 = *pSrc++;
		OPJ_UINT32 val1 = *pSrc++;
		OPJ_UINT32 val2 = *pSrc++;
		pDst[i+0] = (OPJ_INT32)(val0 >> 2);
		pDst[i+1] = (OPJ_INT32)(((val0 & 0x3U) << 4) | (val1 >> 4));
		pDst[i+2] = (OPJ_INT32)(((val1 & 0xFU) << 2) | (val2 >> 6));
		pDst[i+3] = (OPJ_INT32)(val2 & 0x3FU);
		
	}
	if (length & 3U) {
		OPJ_UINT32 val0 = *pSrc++;
		length = length & 3U;
		pDst[i+0] = (OPJ_INT32)(val0 >> 2);
		
		if (length > 1U) {
			OPJ_UINT32 val1 = *pSrc++;
			pDst[i+1] = (OPJ_INT32)(((val0 & 0x3U) << 4) | (val1 >> 4));
			if (length > 2U) {
				OPJ_UINT32 val2 = *pSrc++;
				pDst[i+2] = (OPJ_INT32)(((val1 & 0xFU) << 2) | (val2 >> 6));
			}
		}
	}
}
static void convert_8u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length)
{
	OPJ_SIZE_T i;
	for (i = 0; i < length; i++) {
		pDst[i] = pSrc[i];
	}
}
const convert_XXx32s_C1R convert_XXu32s_C1R_LUT[9] = {
	NULL,
	convert_1u32s_C1R,
	convert_2u32s_C1R,
	NULL,
	convert_4u32s_C1R,
	NULL,
	convert_6u32s_C1R,
	NULL,
	convert_8u32s_C1R
};


static void convert_32s1u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length)
{
	OPJ_SIZE_T i;
	for (i = 0; i < (length & ~(OPJ_SIZE_T)7U); i+=8U) {
		OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
		OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i+1];
		OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i+2];
		OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i+3];
		OPJ_UINT32 src4 = (OPJ_UINT32)pSrc[i+4];
		OPJ_UINT32 src5 = (OPJ_UINT32)pSrc[i+5];
		OPJ_UINT32 src6 = (OPJ_UINT32)pSrc[i+6];
		OPJ_UINT32 src7 = (OPJ_UINT32)pSrc[i+7];
		
		*pDst++ = (OPJ_BYTE)((src0 << 7) | (src1 << 6) | (src2 << 5) | (src3 << 4) | (src4 << 3) | (src5 << 2) | (src6 << 1) | src7);
	}
	
	if (length & 7U) {
		OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
		OPJ_UINT32 src1 = 0U;
		OPJ_UINT32 src2 = 0U;
		OPJ_UINT32 src3 = 0U;
		OPJ_UINT32 src4 = 0U;
		OPJ_UINT32 src5 = 0U;
		OPJ_UINT32 src6 = 0U;
		length = length & 7U;
		
		if (length > 1U) {
			src1 = (OPJ_UINT32)pSrc[i+1];
			if (length > 2U) {
				src2 = (OPJ_UINT32)pSrc[i+2];
				if (length > 3U) {
					src3 = (OPJ_UINT32)pSrc[i+3];
					if (length > 4U) {
						src4 = (OPJ_UINT32)pSrc[i+4];
						if (length > 5U) {
							src5 = (OPJ_UINT32)pSrc[i+5];
							if (length > 6U) {
								src6 = (OPJ_UINT32)pSrc[i+6];
							}
						}
					}
				}
			}
		}
		*pDst++ = (OPJ_BYTE)((src0 << 7) | (src1 << 6) | (src2 << 5) | (src3 << 4) | (src4 << 3) | (src5 << 2) | (src6 << 1));
	}
}

static void convert_32s2u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length)
{
	OPJ_SIZE_T i;
	for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i+=4U) {
		OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
		OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i+1];
		OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i+2];
		OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i+3];
		
		*pDst++ = (OPJ_BYTE)((src0 << 6) | (src1 << 4) | (src2 << 2) | src3);
	}
	
	if (length & 3U) {
		OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
		OPJ_UINT32 src1 = 0U;
		OPJ_UINT32 src2 = 0U;
		length = length & 3U;
		
		if (length > 1U) {
			src1 = (OPJ_UINT32)pSrc[i+1];
			if (length > 2U) {
				src2 = (OPJ_UINT32)pSrc[i+2];
			}
		}
		*pDst++ = (OPJ_BYTE)((src0 << 6) | (src1 << 4) | (src2 << 2));
	}
}

static void convert_32s4u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length)
{
	OPJ_SIZE_T i;
	for (i = 0; i < (length & ~(OPJ_SIZE_T)1U); i+=2U) {
		OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
		OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i+1];
		
		*pDst++ = (OPJ_BYTE)((src0 << 4) | src1);
	}
	
	if (length & 1U) {
		OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
		*pDst++ = (OPJ_BYTE)((src0 << 4));
	}
}

static void convert_32s6u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length)
{
	OPJ_SIZE_T i;
	for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i+=4U) {
		OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
		OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i+1];
		OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i+2];
		OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i+3];
		
		*pDst++ = (OPJ_BYTE)((src0 << 2) | (src1 >> 4));
		*pDst++ = (OPJ_BYTE)(((src1 & 0xFU) << 4) | (src2 >> 2));
		*pDst++ = (OPJ_BYTE)(((src2 & 0x3U) << 6) | src3);
	}
	
	if (length & 3U) {
		OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
		OPJ_UINT32 src1 = 0U;
		OPJ_UINT32 src2 = 0U;
		length = length & 3U;
		
		if (length > 1U) {
			src1 = (OPJ_UINT32)pSrc[i+1];
			if (length > 2U) {
				src2 = (OPJ_UINT32)pSrc[i+2];
			}
		}
		*pDst++ = (OPJ_BYTE)((src0 << 2) | (src1 >> 4));
		if (length > 1U) {
			*pDst++ = (OPJ_BYTE)(((src1 & 0xFU) << 4) | (src2 >> 2));
			if (length > 2U) {
				*pDst++ = (OPJ_BYTE)(((src2 & 0x3U) << 6));
			}
		}
	}
}
static void convert_32s8u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length)
{
	OPJ_SIZE_T i;
	for (i = 0; i < length; ++i) {
		pDst[i] = (OPJ_BYTE)pSrc[i];
	}
}
const convert_32sXXx_C1R convert_32sXXu_C1R_LUT[9] = {
	NULL,
	convert_32s1u_C1R,
	convert_32s2u_C1R,
	NULL,
	convert_32s4u_C1R,
	NULL,
	convert_32s6u_C1R,
	NULL,
	convert_32s8u_C1R
};

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
/* -->> -->> -->> -->>

  TGA IMAGE FORMAT

 <<-- <<-- <<-- <<-- */

#ifdef INFORMATION_ONLY
/* TGA header definition. */
struct tga_header
{                           
    unsigned char   id_length;              /* Image id field length    */
    unsigned char   colour_map_type;        /* Colour map type          */
    unsigned char   image_type;             /* Image type               */
    /*
    ** Colour map specification
    */
    unsigned short  colour_map_index;       /* First entry index        */
    unsigned short  colour_map_length;      /* Colour map length        */
    unsigned char   colour_map_entry_size;  /* Colour map entry size    */
    /*
    ** Image specification
    */
    unsigned short  x_origin;               /* x origin of image        */
    unsigned short  y_origin;               /* u origin of image        */
    unsigned short  image_width;            /* Image width              */
    unsigned short  image_height;           /* Image height             */
    unsigned char   pixel_depth;            /* Pixel depth              */
    unsigned char   image_desc;             /* Image descriptor         */
};
#endif /* INFORMATION_ONLY */

561 562
static unsigned short get_ushort(const unsigned char *data) {
    unsigned short val = *(const unsigned short *)data;
563
#ifdef OPJ_BIG_ENDIAN
564
    val = ((val & 0xffU) << 8) | (val >> 8);
565
#endif
566
    return val;
567 568 569 570 571
}

#define TGA_HEADER_SIZE 18

static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel, 
572
                          unsigned int *width, unsigned int *height, int *flip_image)
573
{
574
    int palette_size;
575
    unsigned char tga[TGA_HEADER_SIZE];
576 577 578 579 580 581 582 583 584 585 586 587 588
    unsigned char id_len, /*cmap_type,*/ image_type;
    unsigned char pixel_depth, image_desc;
    unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
    unsigned short /*x_origin, y_origin,*/ image_w, image_h;

    if (!bits_per_pixel || !width || !height || !flip_image)
        return 0;

    if ( fread(tga, TGA_HEADER_SIZE, 1, fp) != 1 )
    {
        fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
        return 0 ;
    }
589 590 591 592 593 594
    id_len = tga[0];
    /*cmap_type = tga[1];*/
    image_type = tga[2];
    /*cmap_index = get_ushort(&tga[3]);*/
    cmap_len = get_ushort(&tga[5]);
    cmap_entry_size = tga[7];
595 596 597


#if 0
598 599
    x_origin = get_ushort(&tga[8]);
    y_origin = get_ushort(&tga[10]);
600
#endif
601 602 603 604
    image_w = get_ushort(&tga[12]);
    image_h = get_ushort(&tga[14]);
    pixel_depth = tga[16];
    image_desc  = tga[17];
605 606 607 608 609 610 611 612 613

    *bits_per_pixel = (unsigned int)pixel_depth;
    *width  = (unsigned int)image_w;
    *height = (unsigned int)image_h;

    /* Ignore tga identifier, if present ... */
    if (id_len)
    {
        unsigned char *id = (unsigned char *) malloc(id_len);
614 615 616 617
		if(id == 0){
			fprintf(stderr, "tga_readheader: memory out\n");
			return 0;
		}
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
        if ( !fread(id, id_len, 1, fp) )
        {
            fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
            free(id);
            return 0 ;
        }
        free(id);
    }

    /* Test for compressed formats ... not yet supported ...
    // Note :-  9 - RLE encoded palettized.
    //	  	   10 - RLE encoded RGB. */
    if (image_type > 8)
    {
        fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
        return 0 ;
    }

    *flip_image = !(image_desc & 32);

    /* Palettized formats are not yet supported, skip over the palette, if present ... */
    palette_size = cmap_len * (cmap_entry_size/8);

    if (palette_size>0)
    {
        fprintf(stderr, "File contains a palette - not yet supported.");
        fseek(fp, palette_size, SEEK_CUR);
    }
    return 1;
647 648
}

649
#ifdef OPJ_BIG_ENDIAN
650

651
static INLINE OPJ_UINT16 swap16(OPJ_UINT16 x)
652
{
653
    return (OPJ_UINT16)(((x & 0x00ffU) <<  8) | ((x & 0xff00U) >>  8));
654 655 656 657 658
}

#endif

static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height, 
659
                           OPJ_BOOL flip_image)
660
{
661
    OPJ_UINT16 image_w, image_h, us0;
662 663
    unsigned char uc0, image_type;
    unsigned char pixel_depth, image_desc;
664

665 666
    if (!bits_per_pixel || !width || !height)
        return 0;
667

668
    pixel_depth = 0;
669

670 671 672 673 674 675 676
    if ( bits_per_pixel < 256 )
        pixel_depth = (unsigned char)bits_per_pixel;
    else{
        fprintf(stderr,"ERROR: Wrong bits per pixel inside tga_header");
        return 0;
    }
    uc0 = 0;
677

678 679
    if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* id_length */
    if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_type */
680

681 682
    image_type = 2; /* Uncompressed. */
    if(fwrite(&image_type, 1, 1, fp) != 1) goto fails;
683

684 685 686 687
    us0 = 0;
    if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_index */
    if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_length */
    if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_entry_size */
688

689 690
    if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* x_origin */
    if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* y_origin */
691

692 693
    image_w = (unsigned short)width;
    image_h = (unsigned short) height;
694

695 696 697
#ifndef OPJ_BIG_ENDIAN
    if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
    if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
698
#else
699 700 701 702
    image_w = swap16(image_w);
    image_h = swap16(image_h);
    if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
    if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
703 704
#endif

705
    if(fwrite(&pixel_depth, 1, 1, fp) != 1) goto fails;
706

707
    image_desc = 8; /* 8 bits per component. */
708

709 710 711
    if (flip_image)
        image_desc |= 32;
    if(fwrite(&image_desc, 1, 1, fp) != 1) goto fails;
712

713
    return 1;
714 715

fails:
716 717
    fputs("\nwrite_tgaheader: write ERROR\n", stderr);
    return 0;
718 719 720
}

opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
    FILE *f;
    opj_image_t *image;
    unsigned int image_width, image_height, pixel_bit_depth;
    unsigned int x, y;
    int flip_image=0;
    opj_image_cmptparm_t cmptparm[4];	/* maximum 4 components */
    int numcomps;
    OPJ_COLOR_SPACE color_space;
    OPJ_BOOL mono ;
    OPJ_BOOL save_alpha;
    int subsampling_dx, subsampling_dy;
    int i;

    f = fopen(filename, "rb");
    if (!f) {
        fprintf(stderr, "Failed to open %s for reading !!\n", filename);
        return 0;
    }
739

740 741
    if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image)) {
        fclose(f);
742
        return NULL;
743
    }
744

745
    /* We currently only support 24 & 32 bit tga's ... */
746 747
    if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) {
        fclose(f);
748
        return NULL;
749
    }
750

751 752
    /* initialize image components */
    memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
753

754 755
    mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16);  /* Mono with & without alpha. */
    save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
756

757 758 759 760 761 762 763 764 765 766 767
    if (mono) {
        color_space = OPJ_CLRSPC_GRAY;
        numcomps = save_alpha ? 2 : 1;
    }
    else {
        numcomps = save_alpha ? 4 : 3;
        color_space = OPJ_CLRSPC_SRGB;
    }

    subsampling_dx = parameters->subsampling_dx;
    subsampling_dy = parameters->subsampling_dy;
768

769 770 771 772 773 774 775 776 777
    for (i = 0; i < numcomps; i++) {
        cmptparm[i].prec = 8;
        cmptparm[i].bpp = 8;
        cmptparm[i].sgnd = 0;
        cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
        cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
        cmptparm[i].w = image_width;
        cmptparm[i].h = image_height;
    }
778

779 780
    /* create the image */
    image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
781

782 783
    if (!image) {
        fclose(f);
784
        return NULL;
785 786
    }

787

788 789 790 791 792
    /* set image offset and reference grid */
    image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
    image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
    image->x1 =	!image->x0 ? (OPJ_UINT32)(image_width - 1)  * (OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1)  * (OPJ_UINT32)subsampling_dx + 1;
    image->y1 =	!image->y0 ? (OPJ_UINT32)(image_height - 1) * (OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) * (OPJ_UINT32)subsampling_dy + 1;
793

794 795 796 797
    /* set image data */
    for (y=0; y < image_height; y++)
    {
        int index;
798

799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
        if (flip_image)
            index = (int)((image_height-y-1)*image_width);
        else
            index = (int)(y*image_width);

        if (numcomps==3)
        {
            for (x=0;x<image_width;x++)
            {
                unsigned char r,g,b;

                if( !fread(&b, 1, 1, f) )
                {
                    fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
                    opj_image_destroy(image);
814
                    fclose(f);
815 816 817 818 819 820
                    return NULL;
                }
                if ( !fread(&g, 1, 1, f) )
                {
                    fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
                    opj_image_destroy(image);
821
                    fclose(f);
822 823 824 825 826 827
                    return NULL;
                }
                if ( !fread(&r, 1, 1, f) )
                {
                    fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
                    opj_image_destroy(image);
828
                    fclose(f);
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
                    return NULL;
                }

                image->comps[0].data[index]=r;
                image->comps[1].data[index]=g;
                image->comps[2].data[index]=b;
                index++;
            }
        }
        else if (numcomps==4)
        {
            for (x=0;x<image_width;x++)
            {
                unsigned char r,g,b,a;
                if ( !fread(&b, 1, 1, f) )
                {
                    fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
                    opj_image_destroy(image);
847
                    fclose(f);
848 849 850 851 852 853
                    return NULL;
                }
                if ( !fread(&g, 1, 1, f) )
                {
                    fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
                    opj_image_destroy(image);
854
                    fclose(f);
855 856 857 858 859 860
                    return NULL;
                }
                if ( !fread(&r, 1, 1, f) )
                {
                    fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
                    opj_image_destroy(image);
861
                    fclose(f);
862 863 864 865 866 867
                    return NULL;
                }
                if ( !fread(&a, 1, 1, f) )
                {
                    fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
                    opj_image_destroy(image);
868
                    fclose(f);
869 870 871 872 873 874 875 876 877 878 879 880 881 882
                    return NULL;
                }

                image->comps[0].data[index]=r;
                image->comps[1].data[index]=g;
                image->comps[2].data[index]=b;
                image->comps[3].data[index]=a;
                index++;
            }
        }
        else {
            fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
        }
    }
883
    fclose(f);
884 885
    return image;
}
886

887 888 889 890 891 892 893 894 895 896 897 898
int imagetotga(opj_image_t * image, const char *outfile) {
    int width, height, bpp, x, y;
    OPJ_BOOL write_alpha;
    unsigned int i;
    int adjustR, adjustG, adjustB, fails;
    unsigned int alpha_channel;
    float r,g,b,a;
    unsigned char value;
    float scale;
    FILE *fdest;
    size_t res;
    fails = 1;
899

900 901 902
    fdest = fopen(outfile, "wb");
    if (!fdest) {
        fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
903
        return 1;
904
    }
905

906 907 908 909
    for (i = 0; i < image->numcomps-1; i++)	{
        if ((image->comps[0].dx != image->comps[i+1].dx)
                ||(image->comps[0].dy != image->comps[i+1].dy)
                ||(image->comps[0].prec != image->comps[i+1].prec))	{
910
            fclose(fdest);
911 912
            fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
            return 1;
913
        }
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
    }

    width  = (int)image->comps[0].w;
    height = (int)image->comps[0].h;

    /* Mono with alpha, or RGB with alpha. */
    write_alpha = (image->numcomps==2) || (image->numcomps==4);

    /* Write TGA header  */
    bpp = write_alpha ? 32 : 24;

    if (!tga_writeheader(fdest, bpp, width , height, OPJ_TRUE))
		goto fin;

    alpha_channel = image->numcomps-1;

    scale = 255.0f / (float)((1<<image->comps[0].prec)-1);

    adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
    adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
    adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);

	for (y=0; y < height; y++) 
   {
	unsigned int index= (unsigned int)(y*width);

	for (x=0; x < width; x++, index++)	
  {
	r = (float)(image->comps[0].data[index] + adjustR);

	if (image->numcomps > 2) 
 {
	g = (float)(image->comps[1].data[index] + adjustG);
	b = (float)(image->comps[2].data[index] + adjustB);
 }
	else  
 {/* Greyscale ... */
	g = r;
	b = r;
 }

/* TGA format writes BGR ... */
	if(b > 255.) b = 255.; else if(b < 0.) b = 0.;
	value = (unsigned char)(b*scale);
	res = fwrite(&value,1,1,fdest);

	if( res < 1 ) 
 {
 	fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
	goto fin;
 }
	if(g > 255.) g = 255.; else if(g < 0.) g = 0.;
	value = (unsigned char)(g*scale);
	res = fwrite(&value,1,1,fdest);

	if( res < 1 ) 
 {
	fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
	goto fin;
 }
	if(r > 255.) r = 255.; else if(r < 0.) r = 0.;
	value = (unsigned char)(r*scale);
	res = fwrite(&value,1,1,fdest);
977

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
	if( res < 1 ) 
 {
	fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
	goto fin;
 }

	if (write_alpha) 
 {
	a = (float)(image->comps[alpha_channel].data[index]);
	if(a > 255.) a = 255.; else if(a < 0.) a = 0.;
	value = (unsigned char)(a*scale);
	res = fwrite(&value,1,1,fdest);

		if( res < 1 ) 
	   {
		fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
		goto fin;
	   }
 }
  }
   }
	fails = 0;
fin:
	fclose(fdest);

	return fails;
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
}

/* -->> -->> -->> -->>

PGX IMAGE FORMAT

<<-- <<-- <<-- <<-- */


static unsigned char readuchar(FILE * f)
{
1015 1016 1017 1018 1019 1020 1021
    unsigned char c1;
    if ( !fread(&c1, 1, 1, f) )
    {
        fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
        return 0;
    }
    return c1;
1022 1023 1024 1025
}

static unsigned short readushort(FILE * f, int bigendian)
{
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    unsigned char c1, c2;
    if ( !fread(&c1, 1, 1, f) )
    {
        fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
        return 0;
    }
    if ( !fread(&c2, 1, 1, f) )
    {
        fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
        return 0;
    }
    if (bigendian)
        return (unsigned short)((c1 << 8) + c2);
    else
        return (unsigned short)((c2 << 8) + c1);
1041 1042 1043 1044
}

static unsigned int readuint(FILE * f, int bigendian)
{
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
    unsigned char c1, c2, c3, c4;
    if ( !fread(&c1, 1, 1, f) )
    {
        fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
        return 0;
    }
    if ( !fread(&c2, 1, 1, f) )
    {
        fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
        return 0;
    }
    if ( !fread(&c3, 1, 1, f) )
    {
        fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
        return 0;
    }
    if ( !fread(&c4, 1, 1, f) )
    {
        fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
        return 0;
    }
    if (bigendian)
        return (unsigned int)(c1 << 24) + (unsigned int)(c2 << 16) + (unsigned int)(c3 << 8) + c4;
    else
        return (unsigned int)(c4 << 24) + (unsigned int)(c3 << 16) + (unsigned int)(c2 << 8) + c1;
1070 1071 1072
}

opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
1073 1074 1075 1076 1077 1078 1079
    FILE *f = NULL;
    int w, h, prec;
    int i, numcomps, max;
    OPJ_COLOR_SPACE color_space;
    opj_image_cmptparm_t cmptparm;	/* maximum of 1 component  */
    opj_image_t * image = NULL;
    int adjustS, ushift, dshift, force8;
1080

1081 1082
    char endian1,endian2,sign;
    char signtmp[32];
1083

1084 1085 1086
    char temp[32];
    int bigendian;
    opj_image_comp_t *comp = NULL;
1087

1088 1089
    numcomps = 1;
    color_space = OPJ_CLRSPC_GRAY;
1090

1091
    memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
1092

1093
    max = 0;
1094

1095 1096 1097 1098 1099
    f = fopen(filename, "rb");
    if (!f) {
        fprintf(stderr, "Failed to open %s for reading !\n", filename);
        return NULL;
    }
1100

1101 1102
    fseek(f, 0, SEEK_SET);
    if( fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h) != 9){
1103
        fclose(f);
1104 1105 1106
        fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n");
        return NULL;
    }
1107

1108 1109 1110 1111 1112 1113
    i=0;
    sign='+';
    while (signtmp[i]!='\0') {
        if (signtmp[i]=='-') sign='-';
        i++;
    }
1114

1115 1116 1117 1118 1119 1120
    fgetc(f);
    if (endian1=='M' && endian2=='L') {
        bigendian = 1;
    } else if (endian2=='M' && endian1=='L') {
        bigendian = 0;
    } else {
1121
        fclose(f);
1122 1123 1124
        fprintf(stderr, "Bad pgx header, please check input file\n");
        return NULL;
    }
1125

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
    /* initialize image component */

    cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
    cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
    cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + 1;
    cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + 1;

    if (sign == '-') {
        cmptparm.sgnd = 1;
    } else {
        cmptparm.sgnd = 0;
    }
    if(prec < 8)
    {
        force8 = 1;
        ushift = 8 - prec; dshift = prec - ushift;
        if(cmptparm.sgnd) adjustS = (1<<(prec - 1)); else adjustS = 0;
        cmptparm.sgnd = 0;
        prec = 8;
    }
    else ushift = dshift = force8 = adjustS = 0;

    cmptparm.prec = (OPJ_UINT32)prec;
    cmptparm.bpp = (OPJ_UINT32)prec;
    cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
    cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;

    /* create the image */
    image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
    if(!image) {
        fclose(f);
        return NULL;
    }
    /* set image offset and reference grid */
    image->x0 = cmptparm.x0;
    image->y0 = cmptparm.x0;
    image->x1 = cmptparm.w;
    image->y1 = cmptparm.h;

    /* set image data */

    comp = &image->comps[0];

    for (i = 0; i < w * h; i++) {
        int v;
        if(force8)
        {
            v = readuchar(f) + adjustS;
            v = (v<<ushift) + (v>>dshift);
            comp->data[i] = (unsigned char)v;

            if(v > max) max = v;

            continue;
        }
        if (comp->prec == 8) {
            if (!comp->sgnd) {
                v = readuchar(f);
            } else {
                v = (char) readuchar(f);
            }
        } else if (comp->prec <= 16) {
            if (!comp->sgnd) {
                v = readushort(f, bigendian);
            } else {
                v = (short) readushort(f, bigendian);
            }
        } else {
            if (!comp->sgnd) {
                v = (int)readuint(f, bigendian);
            } else {
                v = (int) readuint(f, bigendian);
            }
        }
        if (v > max)
            max = v;
        comp->data[i] = v;
    }
    fclose(f);
    comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;

    return image;
}

#define CLAMP(x,a,b) x < a ? a : (x > b ? b : x)

static INLINE int clamp( const int value, const int prec, const int sgnd )
{
  if( sgnd )
    {
    if (prec <= 8)       return CLAMP(value,-128,127);
    else if (prec <= 16) return CLAMP(value,-32768,32767);
    else                 return CLAMP(value,-2147483647-1,2147483647);
    }
  else
    {
    if (prec <= 8)       return CLAMP(value,0,255);
    else if (prec <= 16) return CLAMP(value,0,65535);
    else                 return value; /*CLAMP(value,0,4294967295);*/
    }
}

int imagetopgx(opj_image_t * image, const char *outfile) 
{
  int w, h;
  int i, j, fails = 1;
  unsigned int compno;
  FILE *fdest = NULL;

  for (compno = 0; compno < image->numcomps; compno++) 
1236
	{
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    opj_image_comp_t *comp = &image->comps[compno];
    char bname[256]; /* buffer for name */
    char *name = bname; /* pointer */
    int nbytes = 0;
    size_t res;
    const size_t olen = strlen(outfile);
    const size_t dotpos = olen - 4;
    const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */

    if( outfile[dotpos] != '.' ) 
1247
		{
1248 1249 1250
      /* `pgx` was recognized but there is no dot at expected position */
      fprintf(stderr, "ERROR -> Impossible happen." );
      goto fin;
1251
		}
1252
    if( total > 256 ) 
1253
		{
1254
      name = (char*)malloc(total+1);
1255 1256 1257 1258 1259
			if (name == NULL) {
				fprintf(stderr, "imagetopgx: memory out\n");
				goto fin;
			}
		}
1260
    strncpy(name, outfile, dotpos);
1261
    sprintf(name+dotpos, "_%u.pgx", compno);
1262
    fdest = fopen(name, "wb");
1263 1264
    /* don't need name anymore */
			
1265
    if (!fdest) 
1266 1267
		{
				
1268
      fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
1269
			if( total > 256 ) free(name);
1270
      goto fin;
1271
		}
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286

    w = (int)image->comps[compno].w;
    h = (int)image->comps[compno].h;

    fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
      w, h);

    if (comp->prec <= 8) 
      nbytes = 1;
    else if (comp->prec <= 16)
      nbytes = 2;
    else
      nbytes = 4;

    for (i = 0; i < w * h; i++) 
1287
		{
1288 1289 1290 1291 1292
      /* FIXME: clamp func is being called within a loop */
      const int val = clamp(image->comps[compno].data[i],
        (int)comp->prec, (int)comp->sgnd);

      for (j = nbytes - 1; j >= 0; j--) 
1293
			{
1294 1295 1296 1297 1298
        int v = (int)(val >> (j * 8));
        unsigned char byte = (unsigned char)v;
        res = fwrite(&byte, 1, 1, fdest);

        if( res < 1 ) 
1299
				{
1300
          fprintf(stderr, "failed to write 1 byte for %s\n", name);
1301
					if( total > 256 ) free(name);
1302
          goto fin;
1303 1304 1305 1306
				}
			}
		}
		if( total > 256 ) free(name);
1307
    fclose(fdest); fdest = NULL;
1308
	}
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
  fails = 0;
fin:
  if(fdest) fclose(fdest);

  return fails;
}

/* -->> -->> -->> -->>

PNM IMAGE FORMAT

<<-- <<-- <<-- <<-- */

struct pnm_header
{
    int width, height, maxval, depth, format;
    char rgb, rgba, gray, graya, bw;
1326 1327 1328 1329 1330
    char ok;
};

static char *skip_white(char *s)
{
1331
    if (s != NULL)
1332
    {
1333 1334 1335 1336 1337 1338
        while(*s)
        {
            if(*s == '\n' || *s == '\r') return NULL;
            if(isspace(*s)) { ++s; continue; }
            return s;
        }
1339
    }
1340 1341 1342 1343 1344 1345 1346 1347
    return NULL;
}

static char *skip_int(char *start, int *out_n)
{
    char *s;
    char c;

1348
    *out_n = 0;
1349 1350 1351 1352 1353 1354

    s = skip_white(start);
    if(s == NULL) return NULL;
    start = s;

    while(*s)
1355 1356 1357 1358
    {
        if( !isdigit(*s)) break;
        ++s;
    }
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
    c = *s; *s = 0; *out_n = atoi(start); *s = c;
    return s;
}

static char *skip_idf(char *start, char out_idf[256])
{
    char *s;
    char c;

    s = skip_white(start);
    if(s == NULL) return NULL;
    start = s;

    while(*s)
1373 1374 1375 1376
    {
        if(isalpha(*s) || *s == '_') { ++s; continue; }
        break;
    }
1377 1378 1379 1380 1381 1382
    c = *s; *s = 0; strncpy(out_idf, start, 255); *s = c;
    return s;
}

static void read_pnm_header(FILE *reader, struct pnm_header *ph)
{
1383
    int format, end, ttype;
1384 1385 1386 1387 1388
    char idf[256], type[256];
    char line[256];

    if (fgets(line, 250, reader) == NULL)
    {
1389 1390
        fprintf(stderr,"\nWARNING: fgets return a NULL value");
        return;
1391 1392 1393
    }

    if(line[0] != 'P')
1394 1395 1396
    {
        fprintf(stderr,"read_pnm_header:PNM:magic P missing\n"); return;
    }
1397 1398
    format = atoi(line + 1);
    if(format < 1 || format > 7)
1399 1400 1401 1402
    {
        fprintf(stderr,"read_pnm_header:magic format %d invalid\n", format);
        return;
    }
1403
    ph->format = format;
1404
    ttype = end = 0;
1405 1406

    while(fgets(line, 250, reader))
1407
    {
1408
        char *s;
1409
        int allow_null = 0;
1410

1411
        if(*line == '#') continue;
1412

1413
        s = line;
1414

1415 1416 1417
        if(format == 7)
        {
            s = skip_idf(s, idf);
1418

1419
            if(s == NULL || *s == 0) return;
1420

1421 1422 1423 1424 1425 1426 1427 1428
            if(strcmp(idf, "ENDHDR") == 0)
            {
                end = 1; break;
            }
            if(strcmp(idf, "WIDTH") == 0)
            {
                s = skip_int(s, &ph->width);
                if(s == NULL || *s == 0) return;
1429

1430 1431 1432 1433 1434 1435
                continue;
            }
            if(strcmp(idf, "HEIGHT") == 0)
            {
                s = skip_int(s, &ph->height);
                if(s == NULL || *s == 0) return;
1436

1437 1438 1439 1440 1441 1442
                continue;
            }
            if(strcmp(idf, "DEPTH") == 0)
            {
                s = skip_int(s, &ph->depth);
                if(s == NULL || *s == 0) return;
1443

1444 1445 1446 1447 1448 1449
                continue;
            }
            if(strcmp(idf, "MAXVAL") == 0)
            {
                s = skip_int(s, &ph->maxval);
                if(s == NULL || *s == 0) return;
1450

1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
                continue;
            }
            if(strcmp(idf, "TUPLTYPE") == 0)
            {
                s = skip_idf(s, type);
                if(s == NULL || *s == 0) return;

                if(strcmp(type, "BLACKANDWHITE") == 0)
                {
                    ph->bw = 1; ttype = 1; continue;
                }
                if(strcmp(type, "GRAYSCALE") == 0)
                {
                    ph->gray = 1; ttype = 1; continue;
                }
                if(strcmp(type, "GRAYSCALE_ALPHA") == 0)
                {
                    ph->graya = 1; ttype = 1; continue;
                }
                if(strcmp(type, "RGB") == 0)
                {
                    ph->rgb = 1; ttype = 1; continue;
                }
                if(strcmp(type, "RGB_ALPHA") == 0)
                {
                    ph->rgba = 1; ttype = 1; continue;
                }
                fprintf(stderr,"read_pnm_header:unknown P7 TUPLTYPE %s\n",type);
                return;
            }
            fprintf(stderr,"read_pnm_header:unknown P7 idf %s\n",idf);
            return;
        } /* if(format == 7) */
1484

1485 1486
        /* Here format is in range [1,6] */
        if (ph->width == 0) {
1487
            s = skip_int(s, &ph->width);
1488 1489 1490 1491
            if ((s == NULL) || (*s == 0) || (ph->width < 1)) return;
            allow_null = 1;
        }
        if (ph->height == 0) {
1492
            s = skip_int(s, &ph->height);
1493 1494 1495 1496
            if ((s == NULL) && allow_null) continue;
            if ((s == NULL) || (*s == 0) || (ph->height < 1)) return;
            if(format == 1 || format == 4) {
                break;
1497
            }
1498
            allow_null = 1;
1499
        }
1500 1501 1502 1503
        /* here, format is in P2, P3, P5, P6 */
        s = skip_int(s, &ph->maxval);
        if ((s == NULL) && allow_null) continue;
        if ((s == NULL) || (*s == 0)) return;
1504 1505
        break;
    }/* while(fgets( ) */
1506
    if(format == 2 || format == 3 || format > 4)
1507 1508 1509
    {
        if(ph->maxval < 1 || ph->maxval > 65535) return;
    }
1510 1511 1512
    if(ph->width < 1 || ph->height < 1) return;

    if(format == 7)
1513 1514 1515 1516 1517 1518
    {
        if(!end)
        {
            fprintf(stderr,"read_pnm_header:P7 without ENDHDR\n"); return;
        }
        if(ph->depth < 1 || ph->depth > 4) return;
1519

1520
        if (ttype)
1521 1522
            ph->ok = 1;
    }
1523
    else
1524
    {
1525 1526
        ph->ok = 1;
        if(format == 1 || format == 4)
1527 1528 1529 1530
        {
            ph->maxval = 255;
        }
    }
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
}

static int has_prec(int val)
{
    if(val < 2) return 1;
    if(val < 4) return 2;
    if(val < 8) return 3;
    if(val < 16) return 4;
    if(val < 32) return 5;
    if(val < 64) return 6;
    if(val < 128) return 7;
    if(val < 256) return 8;
    if(val < 512) return 9;
    if(val < 1024) return 10;
    if(val < 2048) return 11;
    if(val < 4096) return 12;
    if(val < 8192) return 13;
    if(val < 16384) return 14;
    if(val < 32768) return 15;
    return 16;
}

opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
    int subsampling_dx = parameters->subsampling_dx;
    int subsampling_dy = parameters->subsampling_dy;

    FILE *fp = NULL;
    int i, compno, numcomps, w, h, prec, format;
    OPJ_COLOR_SPACE color_space;
    opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
    opj_image_t * image = NULL;
    struct pnm_header header_info;

    if((fp = fopen(filename, "rb")) == NULL)
    {
        fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n",filename);
        return NULL;
    }
    memset(&header_info, 0, sizeof(struct pnm_header));
1570

1571
    read_pnm_header(fp, &header_info);
1572

1573
    if(!header_info.ok) { fclose(fp); return NULL; }
1574

1575
    format = header_info.format;
1576 1577

    switch(format)
1578
    {
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
    case 1: /* ascii bitmap */
    case 4: /* raw bitmap */
        numcomps = 1;
        break;

    case 2: /* ascii greymap */
    case 5: /* raw greymap */
        numcomps = 1;
        break;

    case 3: /* ascii pixmap */
    case 6: /* raw pixmap */
        numcomps = 3;
        break;

    case 7: /* arbitrary map */
        numcomps = header_info.depth;
1596
        break;
1597 1598

    default: fclose(fp); return NULL;
1599
    }
1600
    if(numcomps < 3)
1601
        color_space = OPJ_CLRSPC_GRAY;/* GRAY, GRAYA */
1602
    else
1603
        color_space = OPJ_CLRSPC_SRGB;/* RGB, RGBA */
1604 1605 1606

    prec = has_prec(header_info.maxval);

1607
    if(prec < 8) prec = 8;
1608 1609 1610 1611 1612 1613

    w = header_info.width;
    h = header_info.height;
    subsampling_dx = parameters->subsampling_dx;
    subsampling_dy = parameters->subsampling_dy;

1614
    memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
1615 1616

    for(i = 0; i < numcomps; i++)
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
    {
        cmptparm[i].prec = (OPJ_UINT32)prec;
        cmptparm[i].bpp = (OPJ_UINT32)prec;
        cmptparm[i].sgnd = 0;
        cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
        cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
        cmptparm[i].w = (OPJ_UINT32)w;
        cmptparm[i].h = (OPJ_UINT32)h;
    }
    image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
1627 1628 1629

    if(!image) { fclose(fp); return NULL; }

1630 1631 1632 1633 1634
    /* set image offset and reference grid */
    image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
    image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
    image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx + 1);
    image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy + 1);
1635 1636

    if((format == 2) || (format == 3)) /* ascii pixmap */
1637 1638
    {
        unsigned int index;
1639

1640 1641 1642 1643 1644 1645 1646
        for (i = 0; i < w * h; i++)
        {
            for(compno = 0; compno < numcomps; compno++)
            {
                index = 0;
                if (fscanf(fp, "%u", &index) != 1)
                    fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1647

1648 1649 1650 1651
                image->comps[compno].data[i] = (OPJ_INT32)(index * 255)/header_info.maxval;
            }
        }
    }
1652
    else
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
        if((format == 5)
                || (format == 6)
                ||((format == 7)
                   && (   header_info.gray || header_info.graya
                          || header_info.rgb || header_info.rgba)))/* binary pixmap */
        {
            unsigned char c0, c1, one;

            one = (prec < 9);

            for (i = 0; i < w * h; i++)
            {
                for(compno = 0; compno < numcomps; compno++)
                {
                if ( !fread(&c0, 1, 1, fp) )
                  {
                  fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
                  opj_image_destroy(image);
1671
                  fclose(fp);
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
                  return NULL;
                  }
                    if(one)
                    {
                        image->comps[compno].data[i] = c0;
                    }
                    else
                    {
                        if ( !fread(&c1, 1, 1, fp) )
                            fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
                        /* netpbm: */
                        image->comps[compno].data[i] = ((c0<<8) | c1);
                    }
                }
            }
        }
1688
        else
1689 1690 1691 1692 1693
            if(format == 1) /* ascii bitmap */
            {
                for (i = 0; i < w * h; i++)
                {
                    unsigned int index;
1694

1695 1696
                    if ( fscanf(fp, "%u", &index) != 1)
                        fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1697

1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
                    image->comps[0].data[i] = (index?0:255);
                }
            }
            else
                if(format == 4)
                {
                    int x, y, bit;
                    unsigned char uc;

                    i = 0;
                    for(y = 0; y < h; ++y)
                    {
                        bit = -1; uc = 0;

                        for(x = 0; x < w; ++x)
                        {
                            if(bit == -1)
                            {
                                bit = 7;
                                uc = (unsigned char)getc(fp);
                            }
                            image->comps[0].data[i] = (((uc>>bit) & 1)?0:255);
                            --bit; ++i;
                        }
                    }
                }
                else
                    if((format == 7 && header_info.bw)) /*MONO*/
                    {
                        unsigned char uc;

                        for(i = 0; i < w * h; ++i)
                        {
                            if ( !fread(&uc, 1, 1, fp) )
                                fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
                            image->comps[0].data[i] = (uc & 1)?0:255;
                        }
                    }
1736 1737 1738 1739 1740
    fclose(fp);

    return image;
}/* pnmtoimage() */

1741
int imagetopnm(opj_image_t * image, const char *outfile, int force_split)
1742
{
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
    int *red, *green, *blue, *alpha;
    int wr, hr, max;
    int i;
    unsigned int compno, ncomp;
    int adjustR, adjustG, adjustB, adjustA;
    int fails, two, want_gray, has_alpha, triple;
    int prec, v;
    FILE *fdest = NULL;
    const char *tmp = outfile;
    char *destname;

1754
    alpha = NULL;
1755 1756 1757 1758 1759 1760 1761

    if((prec = (int)image->comps[0].prec) > 16)
    {
        fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
                "\n\t: refused.\n",__FILE__,__LINE__,prec);
        return 1;
    }
1762
    two = has_alpha = 0; fails = 1;
1763 1764 1765 1766 1767 1768 1769 1770
    ncomp = image->numcomps;

    while (*tmp) ++tmp; tmp -= 2;
    want_gray = (*tmp == 'g' || *tmp == 'G');
    ncomp = image->numcomps;

    if(want_gray) ncomp = 1;

1771 1772
    if ((force_split == 0) &&
				(ncomp == 2 /* GRAYA */
1773 1774 1775 1776 1777 1778 1779
            || (ncomp > 2 /* RGB, RGBA */
                && image->comps[0].dx == image->comps[1].dx
                && image->comps[1].dx == image->comps[2].dx
                && image->comps[0].dy == image->comps[1].dy
                && image->comps[1].dy == image->comps[2].dy
                && image->comps[0].prec == image->comps[1].prec
                && image->comps[1].prec == image->comps[2].prec
1780 1781
                )))
		{
1782
        fdest = fopen(outfile, "wb");
1783

1784 1785 1786 1787 1788 1789 1790 1791 1792
        if (!fdest)
        {
            fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
            return fails;
        }
        two = (prec > 8);
        triple = (ncomp > 2);
        wr = (int)image->comps[0].w; hr = (int)image->comps[0].h;
        max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);