73ec9f6e68a823b370da954cc5bcc7a1ee3d5110
[openjpeg.git] / src / bin / jp2 / convert.c
1 /*
2  * The copyright in this software is being made available under the 2-clauses 
3  * BSD License, included below. This software may be subject to other third 
4  * party and contributor rights, including patent rights, and no such rights
5  * are granted under this license.
6  *
7  * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
8  * Copyright (c) 2002-2014, Professor Benoit Macq
9  * Copyright (c) 2001-2003, David Janssens
10  * Copyright (c) 2002-2003, Yannick Verschueren
11  * Copyright (c) 2003-2007, Francois-Olivier Devaux 
12  * Copyright (c) 2003-2014, Antonin Descampe
13  * Copyright (c) 2005, Herve Drolon, FreeImage Team
14  * Copyright (c) 2006-2007, Parvatha Elangovan
15  * All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
27  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
30  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 #include "opj_apps_config.h"
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <ctype.h>
44
45 #include "openjpeg.h"
46 #include "convert.h"
47
48 /*
49  * Get logarithm of an integer and round downwards.
50  *
51  * log2(a)
52  */
53 static int int_floorlog2(int a) {
54     int l;
55     for (l = 0; a > 1; l++) {
56         a >>= 1;
57     }
58     return l;
59 }
60
61 /* Component precision scaling */
62 void clip_component(opj_image_comp_t* component, OPJ_UINT32 precision)
63 {
64         OPJ_SIZE_T i;
65         OPJ_SIZE_T len;
66         OPJ_UINT32 umax = (OPJ_UINT32)((OPJ_INT32)-1);
67         
68         len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
69         if (precision < 32) {
70                 umax = (1U << precision) - 1U;
71         }
72         
73         if (component->sgnd) {
74                 OPJ_INT32* l_data = component->data;
75                 OPJ_INT32 max = (OPJ_INT32)(umax / 2U);
76                 OPJ_INT32 min = -max - 1;
77                 for (i = 0; i < len; ++i) {
78                         if (l_data[i] > max) {
79                                 l_data[i] = max;
80                         } else if (l_data[i] < min) {
81                                 l_data[i] = min;
82                         }
83                 }
84         } else {
85                 OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
86                 for (i = 0; i < len; ++i) {
87                         if (l_data[i] > umax) {
88                                 l_data[i] = umax;
89                         }
90                 }
91         }
92         component->prec = precision;
93 }
94
95 /* Component precision scaling */
96 static void scale_component_up(opj_image_comp_t* component, OPJ_UINT32 precision)
97 {
98         OPJ_SIZE_T i, len;
99         
100         len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
101         if (component->sgnd) {
102                 OPJ_INT64  newMax = (OPJ_INT64)(1U << (precision - 1));
103                 OPJ_INT64  oldMax = (OPJ_INT64)(1U << (component->prec - 1));
104                 OPJ_INT32* l_data = component->data;
105                 for (i = 0; i < len; ++i) {
106                         l_data[i] = (OPJ_INT32)(((OPJ_INT64)l_data[i] * newMax) / oldMax);
107                 }
108         } else {
109                 OPJ_UINT64  newMax = (OPJ_UINT64)((1U << precision) - 1U);
110                 OPJ_UINT64  oldMax = (OPJ_UINT64)((1U << component->prec) - 1U);
111                 OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
112                 for (i = 0; i < len; ++i) {
113                         l_data[i] = (OPJ_UINT32)(((OPJ_UINT64)l_data[i] * newMax) / oldMax);
114                 }
115         }
116         component->prec = precision;
117         component->bpp = precision;
118 }
119 void scale_component(opj_image_comp_t* component, OPJ_UINT32 precision)
120 {
121         int shift;
122         OPJ_SIZE_T i, len;
123         
124         if (component->prec == precision) {
125                 return;
126         }
127         if (component->prec < precision) {
128                 scale_component_up(component, precision);
129                 return;
130         }
131         shift = (int)(component->prec - precision);
132         len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
133         if (component->sgnd) {
134                 OPJ_INT32* l_data = component->data;
135                 for (i = 0; i < len; ++i) {
136                         l_data[i] >>= shift;
137                 }
138         } else {
139                 OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
140                 for (i = 0; i < len; ++i) {
141                         l_data[i] >>= shift;
142                 }
143         }
144         component->bpp = precision;
145         component->prec = precision;
146 }
147
148
149 /* planar / interleaved conversions */
150 /* used by PNG/TIFF */
151 static void convert_32s_C1P1(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst, OPJ_SIZE_T length)
152 {
153         memcpy(pDst[0], pSrc, length * sizeof(OPJ_INT32));
154 }
155 static void convert_32s_C2P2(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst, OPJ_SIZE_T length)
156 {
157         OPJ_SIZE_T i;
158         OPJ_INT32* pDst0 = pDst[0];
159         OPJ_INT32* pDst1 = pDst[1];
160         
161         for (i = 0; i < length; i++) {
162                 pDst0[i] = pSrc[2*i+0];
163                 pDst1[i] = pSrc[2*i+1];
164         }
165 }
166 static void convert_32s_C3P3(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst, OPJ_SIZE_T length)
167 {
168         OPJ_SIZE_T i;
169         OPJ_INT32* pDst0 = pDst[0];
170         OPJ_INT32* pDst1 = pDst[1];
171         OPJ_INT32* pDst2 = pDst[2];
172         
173         for (i = 0; i < length; i++) {
174                 pDst0[i] = pSrc[3*i+0];
175                 pDst1[i] = pSrc[3*i+1];
176                 pDst2[i] = pSrc[3*i+2];
177         }
178 }
179 static void convert_32s_C4P4(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst, OPJ_SIZE_T length)
180 {
181         OPJ_SIZE_T i;
182         OPJ_INT32* pDst0 = pDst[0];
183         OPJ_INT32* pDst1 = pDst[1];
184         OPJ_INT32* pDst2 = pDst[2];
185         OPJ_INT32* pDst3 = pDst[3];
186         
187         for (i = 0; i < length; i++) {
188                 pDst0[i] = pSrc[4*i+0];
189                 pDst1[i] = pSrc[4*i+1];
190                 pDst2[i] = pSrc[4*i+2];
191                 pDst3[i] = pSrc[4*i+3];
192         }
193 }
194 const convert_32s_CXPX convert_32s_CXPX_LUT[5] = {
195         NULL,
196         convert_32s_C1P1,
197         convert_32s_C2P2,
198         convert_32s_C3P3,
199         convert_32s_C4P4
200 };
201
202 static void convert_32s_P1C1(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length, OPJ_INT32 adjust)
203 {
204         OPJ_SIZE_T i;
205         const OPJ_INT32* pSrc0 = pSrc[0];
206         
207         for (i = 0; i < length; i++) {
208                 pDst[i] = pSrc0[i] + adjust;
209         }
210 }
211 static void convert_32s_P2C2(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length, OPJ_INT32 adjust)
212 {
213         OPJ_SIZE_T i;
214         const OPJ_INT32* pSrc0 = pSrc[0];
215         const OPJ_INT32* pSrc1 = pSrc[1];
216         
217         for (i = 0; i < length; i++) {
218                 pDst[2*i+0] = pSrc0[i] + adjust;
219                 pDst[2*i+1] = pSrc1[i] + adjust;
220         }
221 }
222 static void convert_32s_P3C3(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length, OPJ_INT32 adjust)
223 {
224         OPJ_SIZE_T i;
225         const OPJ_INT32* pSrc0 = pSrc[0];
226         const OPJ_INT32* pSrc1 = pSrc[1];
227         const OPJ_INT32* pSrc2 = pSrc[2];
228         
229         for (i = 0; i < length; i++) {
230                 pDst[3*i+0] = pSrc0[i] + adjust;
231                 pDst[3*i+1] = pSrc1[i] + adjust;
232                 pDst[3*i+2] = pSrc2[i] + adjust;
233         }
234 }
235 static void convert_32s_P4C4(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length, OPJ_INT32 adjust)
236 {
237         OPJ_SIZE_T i;
238         const OPJ_INT32* pSrc0 = pSrc[0];
239         const OPJ_INT32* pSrc1 = pSrc[1];
240         const OPJ_INT32* pSrc2 = pSrc[2];
241         const OPJ_INT32* pSrc3 = pSrc[3];
242         
243         for (i = 0; i < length; i++) {
244                 pDst[4*i+0] = pSrc0[i] + adjust;
245                 pDst[4*i+1] = pSrc1[i] + adjust;
246                 pDst[4*i+2] = pSrc2[i] + adjust;
247                 pDst[4*i+3] = pSrc3[i] + adjust;
248         }
249 }
250 const convert_32s_PXCX convert_32s_PXCX_LUT[5] = {
251         NULL,
252         convert_32s_P1C1,
253         convert_32s_P2C2,
254         convert_32s_P3C3,
255         convert_32s_P4C4
256 };
257
258 /* bit depth conversions */
259 /* used by PNG/TIFF up to 8bpp */
260 static void convert_1u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length)
261 {
262         OPJ_SIZE_T i;
263         for (i = 0; i < (length & ~(OPJ_SIZE_T)7U); i+=8U) {
264                 OPJ_UINT32 val = *pSrc++;
265                 pDst[i+0] = (OPJ_INT32)( val >> 7);
266                 pDst[i+1] = (OPJ_INT32)((val >> 6) & 0x1U);
267                 pDst[i+2] = (OPJ_INT32)((val >> 5) & 0x1U);
268                 pDst[i+3] = (OPJ_INT32)((val >> 4) & 0x1U);
269                 pDst[i+4] = (OPJ_INT32)((val >> 3) & 0x1U);
270                 pDst[i+5] = (OPJ_INT32)((val >> 2) & 0x1U);
271                 pDst[i+6] = (OPJ_INT32)((val >> 1) & 0x1U);
272                 pDst[i+7] = (OPJ_INT32)(val & 0x1U);
273         }
274         if (length & 7U) {
275                 OPJ_UINT32 val = *pSrc++;
276                 length = length & 7U;
277                 pDst[i+0] = (OPJ_INT32)(val >> 7);
278                 
279                 if (length > 1U) {
280                         pDst[i+1] = (OPJ_INT32)((val >> 6) & 0x1U);
281                         if (length > 2U) {
282                                 pDst[i+2] = (OPJ_INT32)((val >> 5) & 0x1U);
283                                 if (length > 3U) {
284                                         pDst[i+3] = (OPJ_INT32)((val >> 4) & 0x1U);
285                                         if (length > 4U) {
286                                                 pDst[i+4] = (OPJ_INT32)((val >> 3) & 0x1U);
287                                                 if (length > 5U) {
288                                                         pDst[i+5] = (OPJ_INT32)((val >> 2) & 0x1U);
289                                                         if (length > 6U) {
290                                                                 pDst[i+6] = (OPJ_INT32)((val >> 1) & 0x1U);
291                                                         }
292                                                 }
293                                         }
294                                 }
295                         }
296                 }
297         }
298 }
299 static void convert_2u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length)
300 {
301         OPJ_SIZE_T i;
302         for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i+=4U) {
303                 OPJ_UINT32 val = *pSrc++;
304                 pDst[i+0] = (OPJ_INT32)( val >> 6);
305                 pDst[i+1] = (OPJ_INT32)((val >> 4) & 0x3U);
306                 pDst[i+2] = (OPJ_INT32)((val >> 2) & 0x3U);
307                 pDst[i+3] = (OPJ_INT32)(val & 0x3U);
308         }
309         if (length & 3U) {
310                 OPJ_UINT32 val = *pSrc++;
311                 length = length & 3U;
312                 pDst[i+0] =  (OPJ_INT32)(val >> 6);
313                 
314                 if (length > 1U) {
315                         pDst[i+1] = (OPJ_INT32)((val >> 4) & 0x3U);
316                         if (length > 2U) {
317                                 pDst[i+2] = (OPJ_INT32)((val >> 2) & 0x3U);
318                                 
319                         }
320                 }
321         }
322 }
323 static void convert_4u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length)
324 {
325         OPJ_SIZE_T i;
326         for (i = 0; i < (length & ~(OPJ_SIZE_T)1U); i+=2U) {
327                 OPJ_UINT32 val = *pSrc++;
328                 pDst[i+0] = (OPJ_INT32)(val >> 4);
329                 pDst[i+1] = (OPJ_INT32)(val & 0xFU);
330         }
331         if (length & 1U) {
332                 OPJ_UINT8 val = *pSrc++;
333                 pDst[i+0] = (OPJ_INT32)(val >> 4);
334         }
335 }
336 static void convert_6u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length)
337 {
338         OPJ_SIZE_T i;
339         for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i+=4U) {
340                 OPJ_UINT32 val0 = *pSrc++;
341                 OPJ_UINT32 val1 = *pSrc++;
342                 OPJ_UINT32 val2 = *pSrc++;
343                 pDst[i+0] = (OPJ_INT32)(val0 >> 2);
344                 pDst[i+1] = (OPJ_INT32)(((val0 & 0x3U) << 4) | (val1 >> 4));
345                 pDst[i+2] = (OPJ_INT32)(((val1 & 0xFU) << 2) | (val2 >> 6));
346                 pDst[i+3] = (OPJ_INT32)(val2 & 0x3FU);
347                 
348         }
349         if (length & 3U) {
350                 OPJ_UINT32 val0 = *pSrc++;
351                 length = length & 3U;
352                 pDst[i+0] = (OPJ_INT32)(val0 >> 2);
353                 
354                 if (length > 1U) {
355                         OPJ_UINT32 val1 = *pSrc++;
356                         pDst[i+1] = (OPJ_INT32)(((val0 & 0x3U) << 4) | (val1 >> 4));
357                         if (length > 2U) {
358                                 OPJ_UINT32 val2 = *pSrc++;
359                                 pDst[i+2] = (OPJ_INT32)(((val1 & 0xFU) << 2) | (val2 >> 6));
360                         }
361                 }
362         }
363 }
364 static void convert_8u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length)
365 {
366         OPJ_SIZE_T i;
367         for (i = 0; i < length; i++) {
368                 pDst[i] = pSrc[i];
369         }
370 }
371 const convert_XXx32s_C1R convert_XXu32s_C1R_LUT[9] = {
372         NULL,
373         convert_1u32s_C1R,
374         convert_2u32s_C1R,
375         NULL,
376         convert_4u32s_C1R,
377         NULL,
378         convert_6u32s_C1R,
379         NULL,
380         convert_8u32s_C1R
381 };
382
383
384 static void convert_32s1u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length)
385 {
386         OPJ_SIZE_T i;
387         for (i = 0; i < (length & ~(OPJ_SIZE_T)7U); i+=8U) {
388                 OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
389                 OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i+1];
390                 OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i+2];
391                 OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i+3];
392                 OPJ_UINT32 src4 = (OPJ_UINT32)pSrc[i+4];
393                 OPJ_UINT32 src5 = (OPJ_UINT32)pSrc[i+5];
394                 OPJ_UINT32 src6 = (OPJ_UINT32)pSrc[i+6];
395                 OPJ_UINT32 src7 = (OPJ_UINT32)pSrc[i+7];
396                 
397                 *pDst++ = (OPJ_BYTE)((src0 << 7) | (src1 << 6) | (src2 << 5) | (src3 << 4) | (src4 << 3) | (src5 << 2) | (src6 << 1) | src7);
398         }
399         
400         if (length & 7U) {
401                 OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
402                 OPJ_UINT32 src1 = 0U;
403                 OPJ_UINT32 src2 = 0U;
404                 OPJ_UINT32 src3 = 0U;
405                 OPJ_UINT32 src4 = 0U;
406                 OPJ_UINT32 src5 = 0U;
407                 OPJ_UINT32 src6 = 0U;
408                 length = length & 7U;
409                 
410                 if (length > 1U) {
411                         src1 = (OPJ_UINT32)pSrc[i+1];
412                         if (length > 2U) {
413                                 src2 = (OPJ_UINT32)pSrc[i+2];
414                                 if (length > 3U) {
415                                         src3 = (OPJ_UINT32)pSrc[i+3];
416                                         if (length > 4U) {
417                                                 src4 = (OPJ_UINT32)pSrc[i+4];
418                                                 if (length > 5U) {
419                                                         src5 = (OPJ_UINT32)pSrc[i+5];
420                                                         if (length > 6U) {
421                                                                 src6 = (OPJ_UINT32)pSrc[i+6];
422                                                         }
423                                                 }
424                                         }
425                                 }
426                         }
427                 }
428                 *pDst++ = (OPJ_BYTE)((src0 << 7) | (src1 << 6) | (src2 << 5) | (src3 << 4) | (src4 << 3) | (src5 << 2) | (src6 << 1));
429         }
430 }
431
432 static void convert_32s2u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length)
433 {
434         OPJ_SIZE_T i;
435         for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i+=4U) {
436                 OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
437                 OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i+1];
438                 OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i+2];
439                 OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i+3];
440                 
441                 *pDst++ = (OPJ_BYTE)((src0 << 6) | (src1 << 4) | (src2 << 2) | src3);
442         }
443         
444         if (length & 3U) {
445                 OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
446                 OPJ_UINT32 src1 = 0U;
447                 OPJ_UINT32 src2 = 0U;
448                 length = length & 3U;
449                 
450                 if (length > 1U) {
451                         src1 = (OPJ_UINT32)pSrc[i+1];
452                         if (length > 2U) {
453                                 src2 = (OPJ_UINT32)pSrc[i+2];
454                         }
455                 }
456                 *pDst++ = (OPJ_BYTE)((src0 << 6) | (src1 << 4) | (src2 << 2));
457         }
458 }
459
460 static void convert_32s4u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length)
461 {
462         OPJ_SIZE_T i;
463         for (i = 0; i < (length & ~(OPJ_SIZE_T)1U); i+=2U) {
464                 OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
465                 OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i+1];
466                 
467                 *pDst++ = (OPJ_BYTE)((src0 << 4) | src1);
468         }
469         
470         if (length & 1U) {
471                 OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
472                 *pDst++ = (OPJ_BYTE)((src0 << 4));
473         }
474 }
475
476 static void convert_32s6u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length)
477 {
478         OPJ_SIZE_T i;
479         for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i+=4U) {
480                 OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
481                 OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i+1];
482                 OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i+2];
483                 OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i+3];
484                 
485                 *pDst++ = (OPJ_BYTE)((src0 << 2) | (src1 >> 4));
486                 *pDst++ = (OPJ_BYTE)(((src1 & 0xFU) << 4) | (src2 >> 2));
487                 *pDst++ = (OPJ_BYTE)(((src2 & 0x3U) << 6) | src3);
488         }
489         
490         if (length & 3U) {
491                 OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i+0];
492                 OPJ_UINT32 src1 = 0U;
493                 OPJ_UINT32 src2 = 0U;
494                 length = length & 3U;
495                 
496                 if (length > 1U) {
497                         src1 = (OPJ_UINT32)pSrc[i+1];
498                         if (length > 2U) {
499                                 src2 = (OPJ_UINT32)pSrc[i+2];
500                         }
501                 }
502                 *pDst++ = (OPJ_BYTE)((src0 << 2) | (src1 >> 4));
503                 if (length > 1U) {
504                         *pDst++ = (OPJ_BYTE)(((src1 & 0xFU) << 4) | (src2 >> 2));
505                         if (length > 2U) {
506                                 *pDst++ = (OPJ_BYTE)(((src2 & 0x3U) << 6));
507                         }
508                 }
509         }
510 }
511 static void convert_32s8u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length)
512 {
513         OPJ_SIZE_T i;
514         for (i = 0; i < length; ++i) {
515                 pDst[i] = (OPJ_BYTE)pSrc[i];
516         }
517 }
518 const convert_32sXXx_C1R convert_32sXXu_C1R_LUT[9] = {
519         NULL,
520         convert_32s1u_C1R,
521         convert_32s2u_C1R,
522         NULL,
523         convert_32s4u_C1R,
524         NULL,
525         convert_32s6u_C1R,
526         NULL,
527         convert_32s8u_C1R
528 };
529
530 /* -->> -->> -->> -->>
531
532   TGA IMAGE FORMAT
533
534  <<-- <<-- <<-- <<-- */
535
536 #ifdef INFORMATION_ONLY
537 /* TGA header definition. */
538 struct tga_header
539 {                           
540     unsigned char   id_length;              /* Image id field length    */
541     unsigned char   colour_map_type;        /* Colour map type          */
542     unsigned char   image_type;             /* Image type               */
543     /*
544     ** Colour map specification
545     */
546     unsigned short  colour_map_index;       /* First entry index        */
547     unsigned short  colour_map_length;      /* Colour map length        */
548     unsigned char   colour_map_entry_size;  /* Colour map entry size    */
549     /*
550     ** Image specification
551     */
552     unsigned short  x_origin;               /* x origin of image        */
553     unsigned short  y_origin;               /* u origin of image        */
554     unsigned short  image_width;            /* Image width              */
555     unsigned short  image_height;           /* Image height             */
556     unsigned char   pixel_depth;            /* Pixel depth              */
557     unsigned char   image_desc;             /* Image descriptor         */
558 };
559 #endif /* INFORMATION_ONLY */
560
561 static unsigned short get_ushort(unsigned short val) {
562
563 #ifdef OPJ_BIG_ENDIAN
564     return (unsigned short)(((val & 0xffU) << 8) | (val >> 8));
565 #else
566     return val;
567 #endif
568
569 }
570
571 #define TGA_HEADER_SIZE 18
572
573 static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel, 
574                           unsigned int *width, unsigned int *height, int *flip_image)
575 {
576     int palette_size;
577     unsigned char tga[TGA_HEADER_SIZE];
578     unsigned char id_len, /*cmap_type,*/ image_type;
579     unsigned char pixel_depth, image_desc;
580     unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
581     unsigned short /*x_origin, y_origin,*/ image_w, image_h;
582
583     if (!bits_per_pixel || !width || !height || !flip_image)
584         return 0;
585
586     if ( fread(tga, TGA_HEADER_SIZE, 1, fp) != 1 )
587     {
588         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
589         return 0 ;
590     }
591     id_len = (unsigned char)tga[0];
592     /*cmap_type = (unsigned char)tga[1];*/
593     image_type = (unsigned char)tga[2];
594     /*cmap_index = get_ushort(*(unsigned short*)(&tga[3]));*/
595     cmap_len = get_ushort(*(unsigned short*)(&tga[5]));
596     cmap_entry_size = (unsigned char)tga[7];
597
598
599 #if 0
600     x_origin = get_ushort(*(unsigned short*)(&tga[8]));
601     y_origin = get_ushort(*(unsigned short*)(&tga[10]));
602 #endif
603     image_w = get_ushort(*(unsigned short*)(&tga[12]));
604     image_h = get_ushort(*(unsigned short*)(&tga[14]));
605     pixel_depth = (unsigned char)tga[16];
606     image_desc  = (unsigned char)tga[17];
607
608     *bits_per_pixel = (unsigned int)pixel_depth;
609     *width  = (unsigned int)image_w;
610     *height = (unsigned int)image_h;
611
612     /* Ignore tga identifier, if present ... */
613     if (id_len)
614     {
615         unsigned char *id = (unsigned char *) malloc(id_len);
616         if ( !fread(id, id_len, 1, fp) )
617         {
618             fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
619             free(id);
620             return 0 ;
621         }
622         free(id);
623     }
624
625     /* Test for compressed formats ... not yet supported ...
626     // Note :-  9 - RLE encoded palettized.
627     //             10 - RLE encoded RGB. */
628     if (image_type > 8)
629     {
630         fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
631         return 0 ;
632     }
633
634     *flip_image = !(image_desc & 32);
635
636     /* Palettized formats are not yet supported, skip over the palette, if present ... */
637     palette_size = cmap_len * (cmap_entry_size/8);
638
639     if (palette_size>0)
640     {
641         fprintf(stderr, "File contains a palette - not yet supported.");
642         fseek(fp, palette_size, SEEK_CUR);
643     }
644     return 1;
645 }
646
647 #ifdef OPJ_BIG_ENDIAN
648
649 static INLINE OPJ_UINT16 swap16(OPJ_UINT16 x)
650 {
651     return (OPJ_UINT16)(((x & 0x00ffU) <<  8) | ((x & 0xff00U) >>  8));
652 }
653
654 #endif
655
656 static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height, 
657                            OPJ_BOOL flip_image)
658 {
659     OPJ_UINT16 image_w, image_h, us0;
660     unsigned char uc0, image_type;
661     unsigned char pixel_depth, image_desc;
662
663     if (!bits_per_pixel || !width || !height)
664         return 0;
665
666     pixel_depth = 0;
667
668     if ( bits_per_pixel < 256 )
669         pixel_depth = (unsigned char)bits_per_pixel;
670     else{
671         fprintf(stderr,"ERROR: Wrong bits per pixel inside tga_header");
672         return 0;
673     }
674     uc0 = 0;
675
676     if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* id_length */
677     if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_type */
678
679     image_type = 2; /* Uncompressed. */
680     if(fwrite(&image_type, 1, 1, fp) != 1) goto fails;
681
682     us0 = 0;
683     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_index */
684     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_length */
685     if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_entry_size */
686
687     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* x_origin */
688     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* y_origin */
689
690     image_w = (unsigned short)width;
691     image_h = (unsigned short) height;
692
693 #ifndef OPJ_BIG_ENDIAN
694     if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
695     if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
696 #else
697     image_w = swap16(image_w);
698     image_h = swap16(image_h);
699     if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
700     if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
701 #endif
702
703     if(fwrite(&pixel_depth, 1, 1, fp) != 1) goto fails;
704
705     image_desc = 8; /* 8 bits per component. */
706
707     if (flip_image)
708         image_desc |= 32;
709     if(fwrite(&image_desc, 1, 1, fp) != 1) goto fails;
710
711     return 1;
712
713 fails:
714     fputs("\nwrite_tgaheader: write ERROR\n", stderr);
715     return 0;
716 }
717
718 opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
719     FILE *f;
720     opj_image_t *image;
721     unsigned int image_width, image_height, pixel_bit_depth;
722     unsigned int x, y;
723     int flip_image=0;
724     opj_image_cmptparm_t cmptparm[4];   /* maximum 4 components */
725     int numcomps;
726     OPJ_COLOR_SPACE color_space;
727     OPJ_BOOL mono ;
728     OPJ_BOOL save_alpha;
729     int subsampling_dx, subsampling_dy;
730     int i;
731
732     f = fopen(filename, "rb");
733     if (!f) {
734         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
735         return 0;
736     }
737
738     if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image)) {
739         fclose(f);
740         return NULL;
741     }
742
743     /* We currently only support 24 & 32 bit tga's ... */
744     if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) {
745         fclose(f);
746         return NULL;
747     }
748
749     /* initialize image components */
750     memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
751
752     mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16);  /* Mono with & without alpha. */
753     save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
754
755     if (mono) {
756         color_space = OPJ_CLRSPC_GRAY;
757         numcomps = save_alpha ? 2 : 1;
758     }
759     else {
760         numcomps = save_alpha ? 4 : 3;
761         color_space = OPJ_CLRSPC_SRGB;
762     }
763
764     subsampling_dx = parameters->subsampling_dx;
765     subsampling_dy = parameters->subsampling_dy;
766
767     for (i = 0; i < numcomps; i++) {
768         cmptparm[i].prec = 8;
769         cmptparm[i].bpp = 8;
770         cmptparm[i].sgnd = 0;
771         cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
772         cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
773         cmptparm[i].w = image_width;
774         cmptparm[i].h = image_height;
775     }
776
777     /* create the image */
778     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
779
780     if (!image) {
781         fclose(f);
782         return NULL;
783     }
784
785
786     /* set image offset and reference grid */
787     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
788     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
789     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;
790     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;
791
792     /* set image data */
793     for (y=0; y < image_height; y++)
794     {
795         int index;
796
797         if (flip_image)
798             index = (int)((image_height-y-1)*image_width);
799         else
800             index = (int)(y*image_width);
801
802         if (numcomps==3)
803         {
804             for (x=0;x<image_width;x++)
805             {
806                 unsigned char r,g,b;
807
808                 if( !fread(&b, 1, 1, f) )
809                 {
810                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
811                     opj_image_destroy(image);
812                     fclose(f);
813                     return NULL;
814                 }
815                 if ( !fread(&g, 1, 1, f) )
816                 {
817                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
818                     opj_image_destroy(image);
819                     fclose(f);
820                     return NULL;
821                 }
822                 if ( !fread(&r, 1, 1, f) )
823                 {
824                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
825                     opj_image_destroy(image);
826                     fclose(f);
827                     return NULL;
828                 }
829
830                 image->comps[0].data[index]=r;
831                 image->comps[1].data[index]=g;
832                 image->comps[2].data[index]=b;
833                 index++;
834             }
835         }
836         else if (numcomps==4)
837         {
838             for (x=0;x<image_width;x++)
839             {
840                 unsigned char r,g,b,a;
841                 if ( !fread(&b, 1, 1, f) )
842                 {
843                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
844                     opj_image_destroy(image);
845                     fclose(f);
846                     return NULL;
847                 }
848                 if ( !fread(&g, 1, 1, f) )
849                 {
850                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
851                     opj_image_destroy(image);
852                     fclose(f);
853                     return NULL;
854                 }
855                 if ( !fread(&r, 1, 1, f) )
856                 {
857                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
858                     opj_image_destroy(image);
859                     fclose(f);
860                     return NULL;
861                 }
862                 if ( !fread(&a, 1, 1, f) )
863                 {
864                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
865                     opj_image_destroy(image);
866                     fclose(f);
867                     return NULL;
868                 }
869
870                 image->comps[0].data[index]=r;
871                 image->comps[1].data[index]=g;
872                 image->comps[2].data[index]=b;
873                 image->comps[3].data[index]=a;
874                 index++;
875             }
876         }
877         else {
878             fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
879         }
880     }
881     fclose(f);
882     return image;
883 }
884
885 int imagetotga(opj_image_t * image, const char *outfile) {
886     int width, height, bpp, x, y;
887     OPJ_BOOL write_alpha;
888     unsigned int i;
889     int adjustR, adjustG, adjustB, fails;
890     unsigned int alpha_channel;
891     float r,g,b,a;
892     unsigned char value;
893     float scale;
894     FILE *fdest;
895     size_t res;
896     fails = 1;
897
898     fdest = fopen(outfile, "wb");
899     if (!fdest) {
900         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
901         return 1;
902     }
903
904     for (i = 0; i < image->numcomps-1; i++)     {
905         if ((image->comps[0].dx != image->comps[i+1].dx)
906                 ||(image->comps[0].dy != image->comps[i+1].dy)
907                 ||(image->comps[0].prec != image->comps[i+1].prec))     {
908             fclose(fdest);
909             fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
910             return 1;
911         }
912     }
913
914     width  = (int)image->comps[0].w;
915     height = (int)image->comps[0].h;
916
917     /* Mono with alpha, or RGB with alpha. */
918     write_alpha = (image->numcomps==2) || (image->numcomps==4);
919
920     /* Write TGA header  */
921     bpp = write_alpha ? 32 : 24;
922
923     if (!tga_writeheader(fdest, bpp, width , height, OPJ_TRUE))
924                 goto fin;
925
926     alpha_channel = image->numcomps-1;
927
928     scale = 255.0f / (float)((1<<image->comps[0].prec)-1);
929
930     adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
931     adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
932     adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
933
934         for (y=0; y < height; y++) 
935    {
936         unsigned int index= (unsigned int)(y*width);
937
938         for (x=0; x < width; x++, index++)      
939   {
940         r = (float)(image->comps[0].data[index] + adjustR);
941
942         if (image->numcomps > 2) 
943  {
944         g = (float)(image->comps[1].data[index] + adjustG);
945         b = (float)(image->comps[2].data[index] + adjustB);
946  }
947         else  
948  {/* Greyscale ... */
949         g = r;
950         b = r;
951  }
952
953 /* TGA format writes BGR ... */
954         if(b > 255.) b = 255.; else if(b < 0.) b = 0.;
955         value = (unsigned char)(b*scale);
956         res = fwrite(&value,1,1,fdest);
957
958         if( res < 1 ) 
959  {
960         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
961         goto fin;
962  }
963         if(g > 255.) g = 255.; else if(g < 0.) g = 0.;
964         value = (unsigned char)(g*scale);
965         res = fwrite(&value,1,1,fdest);
966
967         if( res < 1 ) 
968  {
969         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
970         goto fin;
971  }
972         if(r > 255.) r = 255.; else if(r < 0.) r = 0.;
973         value = (unsigned char)(r*scale);
974         res = fwrite(&value,1,1,fdest);
975
976         if( res < 1 ) 
977  {
978         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
979         goto fin;
980  }
981
982         if (write_alpha) 
983  {
984         a = (float)(image->comps[alpha_channel].data[index]);
985         if(a > 255.) a = 255.; else if(a < 0.) a = 0.;
986         value = (unsigned char)(a*scale);
987         res = fwrite(&value,1,1,fdest);
988
989                 if( res < 1 ) 
990            {
991                 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
992                 goto fin;
993            }
994  }
995   }
996    }
997         fails = 0;
998 fin:
999         fclose(fdest);
1000
1001         return fails;
1002 }
1003
1004 /* -->> -->> -->> -->>
1005
1006 PGX IMAGE FORMAT
1007
1008 <<-- <<-- <<-- <<-- */
1009
1010
1011 static unsigned char readuchar(FILE * f)
1012 {
1013     unsigned char c1;
1014     if ( !fread(&c1, 1, 1, f) )
1015     {
1016         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1017         return 0;
1018     }
1019     return c1;
1020 }
1021
1022 static unsigned short readushort(FILE * f, int bigendian)
1023 {
1024     unsigned char c1, c2;
1025     if ( !fread(&c1, 1, 1, f) )
1026     {
1027         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1028         return 0;
1029     }
1030     if ( !fread(&c2, 1, 1, f) )
1031     {
1032         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1033         return 0;
1034     }
1035     if (bigendian)
1036         return (unsigned short)((c1 << 8) + c2);
1037     else
1038         return (unsigned short)((c2 << 8) + c1);
1039 }
1040
1041 static unsigned int readuint(FILE * f, int bigendian)
1042 {
1043     unsigned char c1, c2, c3, c4;
1044     if ( !fread(&c1, 1, 1, f) )
1045     {
1046         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1047         return 0;
1048     }
1049     if ( !fread(&c2, 1, 1, f) )
1050     {
1051         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1052         return 0;
1053     }
1054     if ( !fread(&c3, 1, 1, f) )
1055     {
1056         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1057         return 0;
1058     }
1059     if ( !fread(&c4, 1, 1, f) )
1060     {
1061         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1062         return 0;
1063     }
1064     if (bigendian)
1065         return (unsigned int)(c1 << 24) + (unsigned int)(c2 << 16) + (unsigned int)(c3 << 8) + c4;
1066     else
1067         return (unsigned int)(c4 << 24) + (unsigned int)(c3 << 16) + (unsigned int)(c2 << 8) + c1;
1068 }
1069
1070 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
1071     FILE *f = NULL;
1072     int w, h, prec;
1073     int i, numcomps, max;
1074     OPJ_COLOR_SPACE color_space;
1075     opj_image_cmptparm_t cmptparm;      /* maximum of 1 component  */
1076     opj_image_t * image = NULL;
1077     int adjustS, ushift, dshift, force8;
1078
1079     char endian1,endian2,sign;
1080     char signtmp[32];
1081
1082     char temp[32];
1083     int bigendian;
1084     opj_image_comp_t *comp = NULL;
1085
1086     numcomps = 1;
1087     color_space = OPJ_CLRSPC_GRAY;
1088
1089     memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
1090
1091     max = 0;
1092
1093     f = fopen(filename, "rb");
1094     if (!f) {
1095         fprintf(stderr, "Failed to open %s for reading !\n", filename);
1096         return NULL;
1097     }
1098
1099     fseek(f, 0, SEEK_SET);
1100     if( fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h) != 9){
1101         fclose(f);
1102         fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n");
1103         return NULL;
1104     }
1105
1106     i=0;
1107     sign='+';
1108     while (signtmp[i]!='\0') {
1109         if (signtmp[i]=='-') sign='-';
1110         i++;
1111     }
1112
1113     fgetc(f);
1114     if (endian1=='M' && endian2=='L') {
1115         bigendian = 1;
1116     } else if (endian2=='M' && endian1=='L') {
1117         bigendian = 0;
1118     } else {
1119         fclose(f);
1120         fprintf(stderr, "Bad pgx header, please check input file\n");
1121         return NULL;
1122     }
1123
1124     /* initialize image component */
1125
1126     cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
1127     cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
1128     cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + 1;
1129     cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + 1;
1130
1131     if (sign == '-') {
1132         cmptparm.sgnd = 1;
1133     } else {
1134         cmptparm.sgnd = 0;
1135     }
1136     if(prec < 8)
1137     {
1138         force8 = 1;
1139         ushift = 8 - prec; dshift = prec - ushift;
1140         if(cmptparm.sgnd) adjustS = (1<<(prec - 1)); else adjustS = 0;
1141         cmptparm.sgnd = 0;
1142         prec = 8;
1143     }
1144     else ushift = dshift = force8 = adjustS = 0;
1145
1146     cmptparm.prec = (OPJ_UINT32)prec;
1147     cmptparm.bpp = (OPJ_UINT32)prec;
1148     cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
1149     cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;
1150
1151     /* create the image */
1152     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
1153     if(!image) {
1154         fclose(f);
1155         return NULL;
1156     }
1157     /* set image offset and reference grid */
1158     image->x0 = cmptparm.x0;
1159     image->y0 = cmptparm.x0;
1160     image->x1 = cmptparm.w;
1161     image->y1 = cmptparm.h;
1162
1163     /* set image data */
1164
1165     comp = &image->comps[0];
1166
1167     for (i = 0; i < w * h; i++) {
1168         int v;
1169         if(force8)
1170         {
1171             v = readuchar(f) + adjustS;
1172             v = (v<<ushift) + (v>>dshift);
1173             comp->data[i] = (unsigned char)v;
1174
1175             if(v > max) max = v;
1176
1177             continue;
1178         }
1179         if (comp->prec == 8) {
1180             if (!comp->sgnd) {
1181                 v = readuchar(f);
1182             } else {
1183                 v = (char) readuchar(f);
1184             }
1185         } else if (comp->prec <= 16) {
1186             if (!comp->sgnd) {
1187                 v = readushort(f, bigendian);
1188             } else {
1189                 v = (short) readushort(f, bigendian);
1190             }
1191         } else {
1192             if (!comp->sgnd) {
1193                 v = (int)readuint(f, bigendian);
1194             } else {
1195                 v = (int) readuint(f, bigendian);
1196             }
1197         }
1198         if (v > max)
1199             max = v;
1200         comp->data[i] = v;
1201     }
1202     fclose(f);
1203     comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;
1204
1205     return image;
1206 }
1207
1208 #define CLAMP(x,a,b) x < a ? a : (x > b ? b : x)
1209
1210 static INLINE int clamp( const int value, const int prec, const int sgnd )
1211 {
1212   if( sgnd )
1213     {
1214     if (prec <= 8)       return CLAMP(value,-128,127);
1215     else if (prec <= 16) return CLAMP(value,-32768,32767);
1216     else                 return CLAMP(value,-2147483647-1,2147483647);
1217     }
1218   else
1219     {
1220     if (prec <= 8)       return CLAMP(value,0,255);
1221     else if (prec <= 16) return CLAMP(value,0,65535);
1222     else                 return value; /*CLAMP(value,0,4294967295);*/
1223     }
1224 }
1225
1226 int imagetopgx(opj_image_t * image, const char *outfile) 
1227 {
1228   int w, h;
1229   int i, j, fails = 1;
1230   unsigned int compno;
1231   FILE *fdest = NULL;
1232
1233   for (compno = 0; compno < image->numcomps; compno++) 
1234         {
1235     opj_image_comp_t *comp = &image->comps[compno];
1236     char bname[256]; /* buffer for name */
1237     char *name = bname; /* pointer */
1238     int nbytes = 0;
1239     size_t res;
1240     const size_t olen = strlen(outfile);
1241     const size_t dotpos = olen - 4;
1242     const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
1243
1244     if( outfile[dotpos] != '.' ) 
1245                 {
1246       /* `pgx` was recognized but there is no dot at expected position */
1247       fprintf(stderr, "ERROR -> Impossible happen." );
1248       goto fin;
1249                 }
1250     if( total > 256 ) 
1251                 {
1252       name = (char*)malloc(total+1);
1253                         if (name == NULL) {
1254                                 goto fin;
1255                         }
1256                 }
1257     strncpy(name, outfile, dotpos);
1258     sprintf(name+dotpos, "_%d.pgx", compno);
1259     fdest = fopen(name, "wb");
1260     /* don't need name anymore */
1261                         
1262     if (!fdest) 
1263                 {
1264                                 
1265       fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
1266                         if( total > 256 ) free(name);
1267       goto fin;
1268                 }
1269
1270     w = (int)image->comps[compno].w;
1271     h = (int)image->comps[compno].h;
1272
1273     fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
1274       w, h);
1275
1276     if (comp->prec <= 8) 
1277       nbytes = 1;
1278     else if (comp->prec <= 16)
1279       nbytes = 2;
1280     else
1281       nbytes = 4;
1282
1283     for (i = 0; i < w * h; i++) 
1284                 {
1285       /* FIXME: clamp func is being called within a loop */
1286       const int val = clamp(image->comps[compno].data[i],
1287         (int)comp->prec, (int)comp->sgnd);
1288
1289       for (j = nbytes - 1; j >= 0; j--) 
1290                         {
1291         int v = (int)(val >> (j * 8));
1292         unsigned char byte = (unsigned char)v;
1293         res = fwrite(&byte, 1, 1, fdest);
1294
1295         if( res < 1 ) 
1296                                 {
1297           fprintf(stderr, "failed to write 1 byte for %s\n", name);
1298                                         if( total > 256 ) free(name);
1299           goto fin;
1300                                 }
1301                         }
1302                 }
1303                 if( total > 256 ) free(name);
1304     fclose(fdest); fdest = NULL;
1305         }
1306   fails = 0;
1307 fin:
1308   if(fdest) fclose(fdest);
1309
1310   return fails;
1311 }
1312
1313 /* -->> -->> -->> -->>
1314
1315 PNM IMAGE FORMAT
1316
1317 <<-- <<-- <<-- <<-- */
1318
1319 struct pnm_header
1320 {
1321     int width, height, maxval, depth, format;
1322     char rgb, rgba, gray, graya, bw;
1323     char ok;
1324 };
1325
1326 static char *skip_white(char *s)
1327 {
1328     while(*s)
1329     {
1330         if(*s == '\n' || *s == '\r') return NULL;
1331         if(isspace(*s)) { ++s; continue; }
1332         return s;
1333     }
1334     return NULL;
1335 }
1336
1337 static char *skip_int(char *start, int *out_n)
1338 {
1339     char *s;
1340     char c;
1341
1342     *out_n = 0; s = start;
1343
1344     s = skip_white(start);
1345     if(s == NULL) return NULL;
1346     start = s;
1347
1348     while(*s)
1349     {
1350         if( !isdigit(*s)) break;
1351         ++s;
1352     }
1353     c = *s; *s = 0; *out_n = atoi(start); *s = c;
1354     return s;
1355 }
1356
1357 static char *skip_idf(char *start, char out_idf[256])
1358 {
1359     char *s;
1360     char c;
1361
1362     s = skip_white(start);
1363     if(s == NULL) return NULL;
1364     start = s;
1365
1366     while(*s)
1367     {
1368         if(isalpha(*s) || *s == '_') { ++s; continue; }
1369         break;
1370     }
1371     c = *s; *s = 0; strncpy(out_idf, start, 255); *s = c;
1372     return s;
1373 }
1374
1375 static void read_pnm_header(FILE *reader, struct pnm_header *ph)
1376 {
1377     int format, have_wh, end, ttype;
1378     char idf[256], type[256];
1379     char line[256];
1380
1381     if (fgets(line, 250, reader) == NULL)
1382     {
1383         fprintf(stderr,"\nWARNING: fgets return a NULL value");
1384         return;
1385     }
1386
1387     if(line[0] != 'P')
1388     {
1389         fprintf(stderr,"read_pnm_header:PNM:magic P missing\n"); return;
1390     }
1391     format = atoi(line + 1);
1392     if(format < 1 || format > 7)
1393     {
1394         fprintf(stderr,"read_pnm_header:magic format %d invalid\n", format);
1395         return;
1396     }
1397     ph->format = format;
1398     ttype = end = have_wh = 0;
1399
1400     while(fgets(line, 250, reader))
1401     {
1402         char *s;
1403
1404         if(*line == '#') continue;
1405
1406         s = line;
1407
1408         if(format == 7)
1409         {
1410             s = skip_idf(s, idf);
1411
1412             if(s == NULL || *s == 0) return;
1413
1414             if(strcmp(idf, "ENDHDR") == 0)
1415             {
1416                 end = 1; break;
1417             }
1418             if(strcmp(idf, "WIDTH") == 0)
1419             {
1420                 s = skip_int(s, &ph->width);
1421                 if(s == NULL || *s == 0) return;
1422
1423                 continue;
1424             }
1425             if(strcmp(idf, "HEIGHT") == 0)
1426             {
1427                 s = skip_int(s, &ph->height);
1428                 if(s == NULL || *s == 0) return;
1429
1430                 continue;
1431             }
1432             if(strcmp(idf, "DEPTH") == 0)
1433             {
1434                 s = skip_int(s, &ph->depth);
1435                 if(s == NULL || *s == 0) return;
1436
1437                 continue;
1438             }
1439             if(strcmp(idf, "MAXVAL") == 0)
1440             {
1441                 s = skip_int(s, &ph->maxval);
1442                 if(s == NULL || *s == 0) return;
1443
1444                 continue;
1445             }
1446             if(strcmp(idf, "TUPLTYPE") == 0)
1447             {
1448                 s = skip_idf(s, type);
1449                 if(s == NULL || *s == 0) return;
1450
1451                 if(strcmp(type, "BLACKANDWHITE") == 0)
1452                 {
1453                     ph->bw = 1; ttype = 1; continue;
1454                 }
1455                 if(strcmp(type, "GRAYSCALE") == 0)
1456                 {
1457                     ph->gray = 1; ttype = 1; continue;
1458                 }
1459                 if(strcmp(type, "GRAYSCALE_ALPHA") == 0)
1460                 {
1461                     ph->graya = 1; ttype = 1; continue;
1462                 }
1463                 if(strcmp(type, "RGB") == 0)
1464                 {
1465                     ph->rgb = 1; ttype = 1; continue;
1466                 }
1467                 if(strcmp(type, "RGB_ALPHA") == 0)
1468                 {
1469                     ph->rgba = 1; ttype = 1; continue;
1470                 }
1471                 fprintf(stderr,"read_pnm_header:unknown P7 TUPLTYPE %s\n",type);
1472                 return;
1473             }
1474             fprintf(stderr,"read_pnm_header:unknown P7 idf %s\n",idf);
1475             return;
1476         } /* if(format == 7) */
1477
1478         if( !have_wh)
1479         {
1480             s = skip_int(s, &ph->width);
1481
1482             s = skip_int(s, &ph->height);
1483
1484             have_wh = 1;
1485
1486             if(format == 1 || format == 4) break;
1487                                         
1488             if(format == 2 || format == 3 || format == 5 || format == 6)
1489             {
1490                 if (skip_int(s, &ph->maxval) != NULL) {
1491                     if(ph->maxval > 65535) {
1492                         return;
1493                     }
1494                     else {
1495                         break;
1496                     }
1497                 }
1498             }
1499             continue;
1500         }
1501         if(format == 2 || format == 3 || format == 5 || format == 6)
1502         {
1503             /* P2, P3, P5, P6: */
1504             s = skip_int(s, &ph->maxval);
1505
1506             if(ph->maxval > 65535) return;
1507         }
1508         break;
1509     }/* while(fgets( ) */
1510     if(format == 2 || format == 3 || format > 4)
1511     {
1512         if(ph->maxval < 1 || ph->maxval > 65535) return;
1513     }
1514     if(ph->width < 1 || ph->height < 1) return;
1515
1516     if(format == 7)
1517     {
1518         if(!end)
1519         {
1520             fprintf(stderr,"read_pnm_header:P7 without ENDHDR\n"); return;
1521         }
1522         if(ph->depth < 1 || ph->depth > 4) return;
1523
1524         if(ph->width && ph->height && ph->depth && ph->maxval && ttype)
1525             ph->ok = 1;
1526     }
1527     else
1528     {
1529         if(format != 1 && format != 4)
1530         {
1531             if(ph->width && ph->height && ph->maxval) ph->ok = 1;
1532         }
1533         else
1534         {
1535             if(ph->width && ph->height) ph->ok = 1;
1536             ph->maxval = 255;
1537         }
1538     }
1539 }
1540
1541 static int has_prec(int val)
1542 {
1543     if(val < 2) return 1;
1544     if(val < 4) return 2;
1545     if(val < 8) return 3;
1546     if(val < 16) return 4;
1547     if(val < 32) return 5;
1548     if(val < 64) return 6;
1549     if(val < 128) return 7;
1550     if(val < 256) return 8;
1551     if(val < 512) return 9;
1552     if(val < 1024) return 10;
1553     if(val < 2048) return 11;
1554     if(val < 4096) return 12;
1555     if(val < 8192) return 13;
1556     if(val < 16384) return 14;
1557     if(val < 32768) return 15;
1558     return 16;
1559 }
1560
1561 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
1562     int subsampling_dx = parameters->subsampling_dx;
1563     int subsampling_dy = parameters->subsampling_dy;
1564
1565     FILE *fp = NULL;
1566     int i, compno, numcomps, w, h, prec, format;
1567     OPJ_COLOR_SPACE color_space;
1568     opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
1569     opj_image_t * image = NULL;
1570     struct pnm_header header_info;
1571
1572     if((fp = fopen(filename, "rb")) == NULL)
1573     {
1574         fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n",filename);
1575         return NULL;
1576     }
1577     memset(&header_info, 0, sizeof(struct pnm_header));
1578
1579     read_pnm_header(fp, &header_info);
1580
1581     if(!header_info.ok) { fclose(fp); return NULL; }
1582
1583     format = header_info.format;
1584
1585     switch(format)
1586     {
1587     case 1: /* ascii bitmap */
1588     case 4: /* raw bitmap */
1589         numcomps = 1;
1590         break;
1591
1592     case 2: /* ascii greymap */
1593     case 5: /* raw greymap */
1594         numcomps = 1;
1595         break;
1596
1597     case 3: /* ascii pixmap */
1598     case 6: /* raw pixmap */
1599         numcomps = 3;
1600         break;
1601
1602     case 7: /* arbitrary map */
1603         numcomps = header_info.depth;
1604         break;
1605
1606     default: fclose(fp); return NULL;
1607     }
1608     if(numcomps < 3)
1609         color_space = OPJ_CLRSPC_GRAY;/* GRAY, GRAYA */
1610     else
1611         color_space = OPJ_CLRSPC_SRGB;/* RGB, RGBA */
1612
1613     prec = has_prec(header_info.maxval);
1614
1615     if(prec < 8) prec = 8;
1616
1617     w = header_info.width;
1618     h = header_info.height;
1619     subsampling_dx = parameters->subsampling_dx;
1620     subsampling_dy = parameters->subsampling_dy;
1621
1622     memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
1623
1624     for(i = 0; i < numcomps; i++)
1625     {
1626         cmptparm[i].prec = (OPJ_UINT32)prec;
1627         cmptparm[i].bpp = (OPJ_UINT32)prec;
1628         cmptparm[i].sgnd = 0;
1629         cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
1630         cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
1631         cmptparm[i].w = (OPJ_UINT32)w;
1632         cmptparm[i].h = (OPJ_UINT32)h;
1633     }
1634     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
1635
1636     if(!image) { fclose(fp); return NULL; }
1637
1638     /* set image offset and reference grid */
1639     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
1640     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
1641     image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx + 1);
1642     image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy + 1);
1643
1644     if((format == 2) || (format == 3)) /* ascii pixmap */
1645     {
1646         unsigned int index;
1647
1648         for (i = 0; i < w * h; i++)
1649         {
1650             for(compno = 0; compno < numcomps; compno++)
1651             {
1652                 index = 0;
1653                 if (fscanf(fp, "%u", &index) != 1)
1654                     fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1655
1656                 image->comps[compno].data[i] = (OPJ_INT32)(index * 255)/header_info.maxval;
1657             }
1658         }
1659     }
1660     else
1661         if((format == 5)
1662                 || (format == 6)
1663                 ||((format == 7)
1664                    && (   header_info.gray || header_info.graya
1665                           || header_info.rgb || header_info.rgba)))/* binary pixmap */
1666         {
1667             unsigned char c0, c1, one;
1668
1669             one = (prec < 9);
1670
1671             for (i = 0; i < w * h; i++)
1672             {
1673                 for(compno = 0; compno < numcomps; compno++)
1674                 {
1675                 if ( !fread(&c0, 1, 1, fp) )
1676                   {
1677                   fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1678                   opj_image_destroy(image);
1679                   fclose(fp);
1680                   return NULL;
1681                   }
1682                     if(one)
1683                     {
1684                         image->comps[compno].data[i] = c0;
1685                     }
1686                     else
1687                     {
1688                         if ( !fread(&c1, 1, 1, fp) )
1689                             fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1690                         /* netpbm: */
1691                         image->comps[compno].data[i] = ((c0<<8) | c1);
1692                     }
1693                 }
1694             }
1695         }
1696         else
1697             if(format == 1) /* ascii bitmap */
1698             {
1699                 for (i = 0; i < w * h; i++)
1700                 {
1701                     unsigned int index;
1702
1703                     if ( fscanf(fp, "%u", &index) != 1)
1704                         fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1705
1706                     image->comps[0].data[i] = (index?0:255);
1707                 }
1708             }
1709             else
1710                 if(format == 4)
1711                 {
1712                     int x, y, bit;
1713                     unsigned char uc;
1714
1715                     i = 0;
1716                     for(y = 0; y < h; ++y)
1717                     {
1718                         bit = -1; uc = 0;
1719
1720                         for(x = 0; x < w; ++x)
1721                         {
1722                             if(bit == -1)
1723                             {
1724                                 bit = 7;
1725                                 uc = (unsigned char)getc(fp);
1726                             }
1727                             image->comps[0].data[i] = (((uc>>bit) & 1)?0:255);
1728                             --bit; ++i;
1729                         }
1730                     }
1731                 }
1732                 else
1733                     if((format == 7 && header_info.bw)) /*MONO*/
1734                     {
1735                         unsigned char uc;
1736
1737                         for(i = 0; i < w * h; ++i)
1738                         {
1739                             if ( !fread(&uc, 1, 1, fp) )
1740                                 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1741                             image->comps[0].data[i] = (uc & 1)?0:255;
1742                         }
1743                     }
1744     fclose(fp);
1745
1746     return image;
1747 }/* pnmtoimage() */
1748
1749 int imagetopnm(opj_image_t * image, const char *outfile, int force_split)
1750 {
1751     int *red, *green, *blue, *alpha;
1752     int wr, hr, max;
1753     int i;
1754     unsigned int compno, ncomp;
1755     int adjustR, adjustG, adjustB, adjustA;
1756     int fails, two, want_gray, has_alpha, triple;
1757     int prec, v;
1758     FILE *fdest = NULL;
1759     const char *tmp = outfile;
1760     char *destname;
1761
1762         alpha = NULL;
1763
1764     if((prec = (int)image->comps[0].prec) > 16)
1765     {
1766         fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
1767                 "\n\t: refused.\n",__FILE__,__LINE__,prec);
1768         return 1;
1769     }
1770     two = has_alpha = 0; fails = 1;
1771     ncomp = image->numcomps;
1772
1773     while (*tmp) ++tmp; tmp -= 2;
1774     want_gray = (*tmp == 'g' || *tmp == 'G');
1775     ncomp = image->numcomps;
1776
1777     if(want_gray) ncomp = 1;
1778
1779     if ((force_split == 0) &&
1780                                 (ncomp == 2 /* GRAYA */
1781             || (ncomp > 2 /* RGB, RGBA */
1782                 && image->comps[0].dx == image->comps[1].dx
1783                 && image->comps[1].dx == image->comps[2].dx
1784                 && image->comps[0].dy == image->comps[1].dy
1785                 && image->comps[1].dy == image->comps[2].dy
1786                 && image->comps[0].prec == image->comps[1].prec
1787                 && image->comps[1].prec == image->comps[2].prec
1788                 )))
1789                 {
1790         fdest = fopen(outfile, "wb");
1791
1792         if (!fdest)
1793         {
1794             fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1795             return fails;
1796         }
1797         two = (prec > 8);
1798         triple = (ncomp > 2);
1799         wr = (int)image->comps[0].w; hr = (int)image->comps[0].h;
1800         max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);
1801
1802         red = image->comps[0].data;
1803
1804         if(triple)
1805         {
1806             green = image->comps[1].data;
1807             blue = image->comps[2].data;
1808         }
1809         else green = blue = NULL;
1810
1811         if(has_alpha)
1812         {
1813             const char *tt = (triple?"RGB_ALPHA":"GRAYSCALE_ALPHA");
1814
1815             fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %d\n"
1816                     "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
1817                     wr, hr, ncomp, max, tt);
1818             alpha = image->comps[ncomp - 1].data;
1819             adjustA = (image->comps[ncomp - 1].sgnd ?
1820                         1 << (image->comps[ncomp - 1].prec - 1) : 0);
1821         }
1822         else
1823         {
1824             fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
1825                     opj_version(), wr, hr, max);
1826             adjustA = 0;
1827         }
1828         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1829
1830         if(triple)
1831         {
1832             adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1833             adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1834         }
1835         else adjustG = adjustB = 0;
1836
1837         for(i = 0; i < wr * hr; ++i)
1838         {
1839             if(two)
1840             {
1841                 v = *red + adjustR; ++red;
1842 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1843
1844                 /* netpbm: */
1845                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1846
1847                 if(triple)
1848                 {
1849                     v = *green + adjustG; ++green;
1850 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1851
1852                     /* netpbm: */
1853                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1854
1855                     v =  *blue + adjustB; ++blue;
1856 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1857
1858                     /* netpbm: */
1859                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1860
1861                 }/* if(triple) */
1862
1863                 if(has_alpha)
1864                 {
1865                     v = *alpha + adjustA; ++alpha;
1866                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1867
1868                     /* netpbm: */
1869                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1870                 }
1871                 continue;
1872
1873             }   /* if(two) */
1874
1875             /* prec <= 8: */
1876         v = *red++;
1877         if(v > 255) v = 255; else if(v < 0) v = 0;
1878
1879         fprintf(fdest, "%c", (unsigned char)v);
1880             if(triple)
1881  {
1882         v = *green++;
1883         if(v > 255) v = 255; else if(v < 0) v = 0;
1884
1885         fprintf(fdest, "%c", (unsigned char)v);
1886         v = *blue++;
1887         if(v > 255) v = 255; else if(v < 0) v = 0;
1888
1889         fprintf(fdest, "%c", (unsigned char)v);
1890  }
1891             if(has_alpha)
1892  {
1893         v = *alpha++;
1894         if(v > 255) v = 255; else if(v < 0) v = 0;
1895
1896         fprintf(fdest, "%c", (unsigned char)v);
1897  }
1898         }       /* for(i */
1899
1900         fclose(fdest); return 0;
1901     }
1902
1903     /* YUV or MONO: */
1904
1905     if (image->numcomps > ncomp)
1906     {
1907         fprintf(stderr,"WARNING -> [PGM file] Only the first component\n");
1908         fprintf(stderr,"           is written to the file\n");
1909     }
1910     destname = (char*)malloc(strlen(outfile) + 8);
1911
1912     for (compno = 0; compno < ncomp; compno++)
1913     {
1914     if (ncomp > 1)
1915       {
1916       /*sprintf(destname, "%d.%s", compno, outfile);*/
1917       const size_t olen = strlen(outfile);
1918       const size_t dotpos = olen - 4;
1919
1920       strncpy(destname, outfile, dotpos);
1921       sprintf(destname+dotpos, "_%d.pgm", compno);
1922       }
1923         else
1924             sprintf(destname, "%s", outfile);
1925
1926         fdest = fopen(destname, "wb");
1927         if (!fdest)
1928         {
1929             fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
1930             free(destname);
1931             return 1;
1932         }
1933         wr = (int)image->comps[compno].w; hr = (int)image->comps[compno].h;
1934         prec = (int)image->comps[compno].prec;
1935         max = (1<<prec) - 1;
1936
1937         fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
1938                 opj_version(), wr, hr, max);
1939
1940         red = image->comps[compno].data;
1941         adjustR =
1942                 (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
1943
1944         if(prec > 8)
1945         {
1946             for (i = 0; i < wr * hr; i++)
1947             {
1948                 v = *red + adjustR; ++red;
1949 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1950
1951                 /* netpbm: */
1952                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1953
1954                 if(has_alpha)
1955                 {
1956                     v = *alpha++;
1957 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1958
1959                     /* netpbm: */
1960                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1961                 }
1962             }/* for(i */
1963         }
1964         else /* prec <= 8 */
1965         {
1966             for(i = 0; i < wr * hr; ++i)
1967             {
1968         v = *red + adjustR; ++red;
1969         if(v > 255) v = 255; else if(v < 0) v = 0;
1970
1971          fprintf(fdest, "%c", (unsigned char)v);
1972             }
1973         }
1974         fclose(fdest);
1975     } /* for (compno */
1976     free(destname);
1977
1978     return 0;
1979 }/* imagetopnm() */
1980
1981 /* -->> -->> -->> -->>
1982
1983     RAW IMAGE FORMAT
1984
1985  <<-- <<-- <<-- <<-- */
1986 static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian) {
1987     int subsampling_dx = parameters->subsampling_dx;
1988     int subsampling_dy = parameters->subsampling_dy;
1989
1990     FILE *f = NULL;
1991     int i, compno, numcomps, w, h;
1992     OPJ_COLOR_SPACE color_space;
1993     opj_image_cmptparm_t *cmptparm;
1994     opj_image_t * image = NULL;
1995     unsigned short ch;
1996
1997     if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
1998     {
1999         fprintf(stderr,"\nError: invalid raw image parameters\n");
2000         fprintf(stderr,"Please use the Format option -F:\n");
2001         fprintf(stderr,"-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
2002         fprintf(stderr,"If subsampling is omitted, 1x1 is assumed for all components\n");
2003         fprintf(stderr,"Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
2004         fprintf(stderr,"         for raw 512x512 image with 4:2:0 subsampling\n");
2005         fprintf(stderr,"Aborting.\n");
2006         return NULL;
2007     }
2008
2009     f = fopen(filename, "rb");
2010     if (!f) {
2011         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
2012         fprintf(stderr,"Aborting\n");
2013         return NULL;
2014     }
2015     numcomps = raw_cp->rawComp;
2016
2017     /* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
2018     if (numcomps == 1) {
2019         color_space = OPJ_CLRSPC_GRAY;
2020     } else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
2021         color_space = OPJ_CLRSPC_SYCC;
2022     } else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
2023         color_space = OPJ_CLRSPC_SRGB;
2024     } else {
2025         color_space = OPJ_CLRSPC_UNKNOWN;
2026     }
2027     w = raw_cp->rawWidth;
2028     h = raw_cp->rawHeight;
2029     cmptparm = (opj_image_cmptparm_t*) calloc((OPJ_UINT32)numcomps,sizeof(opj_image_cmptparm_t));
2030     if (!cmptparm) {
2031         fprintf(stderr, "Failed to allocate image components parameters !!\n");
2032         fprintf(stderr,"Aborting\n");
2033         fclose(f);
2034         return NULL;
2035     }
2036     /* initialize image components */
2037     for(i = 0; i < numcomps; i++) {
2038         cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
2039         cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
2040         cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
2041         cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
2042         cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
2043         cmptparm[i].w = (OPJ_UINT32)w;
2044         cmptparm[i].h = (OPJ_UINT32)h;
2045     }
2046     /* create the image */
2047     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2048     free(cmptparm);
2049     if(!image) {
2050         fclose(f);
2051         return NULL;
2052     }
2053     /* set image offset and reference grid */
2054     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2055     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2056     image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
2057     image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
2058
2059     if(raw_cp->rawBitDepth <= 8)
2060     {
2061         unsigned char value = 0;
2062         for(compno = 0; compno < numcomps; compno++) {
2063             int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dy);
2064             for (i = 0; i < nloop; i++) {
2065                 if (!fread(&value, 1, 1, f)) {
2066                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2067                     opj_image_destroy(image);
2068                     fclose(f);
2069                     return NULL;
2070                 }
2071                 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
2072             }
2073         }
2074     }
2075     else if(raw_cp->rawBitDepth <= 16)
2076     {
2077         unsigned short value;
2078         for(compno = 0; compno < numcomps; compno++) {
2079             int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dy);
2080             for (i = 0; i < nloop; i++) {
2081                 unsigned char temp1;
2082                 unsigned char temp2;
2083                 if (!fread(&temp1, 1, 1, f)) {
2084                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2085                     opj_image_destroy(image);
2086                     fclose(f);
2087                     return NULL;
2088                 }
2089                 if (!fread(&temp2, 1, 1, f)) {
2090                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2091                     opj_image_destroy(image);
2092                     fclose(f);
2093                     return NULL;
2094                 }
2095                 if( big_endian )
2096                 {
2097                     value = (unsigned short)((temp1 << 8) + temp2);
2098                 }
2099                 else
2100                 {
2101                     value = (unsigned short)((temp2 << 8) + temp1);
2102                 }
2103                 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
2104             }
2105         }
2106     }
2107     else {
2108         fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
2109         opj_image_destroy(image);
2110         fclose(f);
2111         return NULL;
2112     }
2113
2114     if (fread(&ch, 1, 1, f)) {
2115         fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
2116     }
2117     fclose(f);
2118
2119     return image;
2120 }
2121
2122 opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
2123     return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
2124 }
2125
2126 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
2127     return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
2128 }
2129
2130 static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL big_endian)
2131 {
2132     FILE *rawFile = NULL;
2133     size_t res;
2134     unsigned int compno;
2135     int w, h, fails;
2136     int line, row, curr, mask;
2137     int *ptr;
2138     unsigned char uc;
2139     (void)big_endian;
2140
2141     if((image->numcomps * image->x1 * image->y1) == 0)
2142     {
2143         fprintf(stderr,"\nError: invalid raw image parameters\n");
2144         return 1;
2145     }
2146
2147     rawFile = fopen(outfile, "wb");
2148     if (!rawFile) {
2149         fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
2150         return 1;
2151     }
2152
2153     fails = 1;
2154     fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
2155
2156     for(compno = 0; compno < image->numcomps; compno++)
2157     {
2158         fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
2159                 image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
2160
2161         w = (int)image->comps[compno].w;
2162         h = (int)image->comps[compno].h;
2163
2164         if(image->comps[compno].prec <= 8)
2165         {
2166             if(image->comps[compno].sgnd == 1)
2167             {
2168                 mask = (1 << image->comps[compno].prec) - 1;
2169                 ptr = image->comps[compno].data;
2170                 for (line = 0; line < h; line++) {
2171                     for(row = 0; row < w; row++)        {
2172                         curr = *ptr;
2173                         if(curr > 127) curr = 127; else if(curr < -128) curr = -128;
2174                         uc = (unsigned char) (curr & mask);
2175                         res = fwrite(&uc, 1, 1, rawFile);
2176                         if( res < 1 ) {
2177                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2178                             goto fin;
2179                         }
2180                         ptr++;
2181                     }
2182                 }
2183             }
2184             else if(image->comps[compno].sgnd == 0)
2185             {
2186                 mask = (1 << image->comps[compno].prec) - 1;
2187                 ptr = image->comps[compno].data;
2188                 for (line = 0; line < h; line++) {
2189                     for(row = 0; row < w; row++)        {
2190                         curr = *ptr;
2191                         if(curr > 255) curr = 255; else if(curr < 0) curr = 0;
2192                         uc = (unsigned char) (curr & mask);
2193                         res = fwrite(&uc, 1, 1, rawFile);
2194                         if( res < 1 ) {
2195                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2196                             goto fin;
2197                         }
2198                         ptr++;
2199                     }
2200                 }
2201             }
2202         }
2203         else if(image->comps[compno].prec <= 16)
2204         {
2205             if(image->comps[compno].sgnd == 1)
2206             {
2207                 union { signed short val; signed char vals[2]; } uc16;
2208                 mask = (1 << image->comps[compno].prec) - 1;
2209                 ptr = image->comps[compno].data;
2210                 for (line = 0; line < h; line++) {
2211                     for(row = 0; row < w; row++)        {
2212                         curr = *ptr;
2213                         if(curr > 32767 ) curr = 32767; else if( curr < -32768) curr = -32768;
2214                         uc16.val = (signed short)(curr & mask);
2215                         res = fwrite(uc16.vals, 1, 2, rawFile);
2216                         if( res < 2 ) {
2217                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2218                             goto fin;
2219                         }
2220                         ptr++;
2221                     }
2222                 }
2223             }
2224             else if(image->comps[compno].sgnd == 0)
2225             {
2226                 union { unsigned short val; unsigned char vals[2]; } uc16;
2227                 mask = (1 << image->comps[compno].prec) - 1;
2228                 ptr = image->comps[compno].data;
2229                 for (line = 0; line < h; line++) {
2230                     for(row = 0; row < w; row++)        {
2231                         curr = *ptr;
2232                         if(curr > 65535 ) curr = 65535; else if( curr < 0) curr = 0;
2233                         uc16.val = (unsigned short)(curr & mask);
2234                         res = fwrite(uc16.vals, 1, 2, rawFile);
2235                         if( res < 2 ) {
2236                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2237                             goto fin;
2238                         }
2239                         ptr++;
2240                     }
2241                 }
2242             }
2243         }
2244         else if (image->comps[compno].prec <= 32)
2245         {
2246             fprintf(stderr,"More than 16 bits per component no handled yet\n");
2247             goto fin;
2248         }
2249         else
2250         {
2251             fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
2252             goto fin;
2253         }
2254     }
2255   fails = 0;
2256 fin:
2257     fclose(rawFile);
2258     return fails;
2259 }
2260
2261 int imagetoraw(opj_image_t * image, const char *outfile)
2262 {
2263     return imagetoraw_common(image, outfile, OPJ_TRUE);
2264 }
2265
2266 int imagetorawl(opj_image_t * image, const char *outfile)
2267 {
2268     return imagetoraw_common(image, outfile, OPJ_FALSE);
2269 }
2270