940ac2fa80d7cd0faa7ace64d0ab7581223460b4
[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(const unsigned char *data) {
562     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 #define TGA_HEADER_SIZE 18
570
571 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     unsigned char id_len, /*cmap_type,*/ image_type;
577     unsigned char pixel_depth, image_desc;
578     unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
579     unsigned short /*x_origin, y_origin,*/ image_w, image_h;
580
581     if (!bits_per_pixel || !width || !height || !flip_image)
582         return 0;
583
584     if ( fread(tga, TGA_HEADER_SIZE, 1, fp) != 1 )
585     {
586         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
587         return 0 ;
588     }
589     id_len = tga[0];
590     /*cmap_type = tga[1];*/
591     image_type = tga[2];
592     /*cmap_index = get_ushort(&tga[3]);*/
593     cmap_len = get_ushort(&tga[5]);
594     cmap_entry_size = tga[7];
595
596
597 #if 0
598     x_origin = get_ushort(&tga[8]);
599     y_origin = get_ushort(&tga[10]);
600 #endif
601     image_w = get_ushort(&tga[12]);
602     image_h = get_ushort(&tga[14]);
603     pixel_depth = tga[16];
604     image_desc  = tga[17];
605
606     *bits_per_pixel = (unsigned int)pixel_depth;
607     *width  = (unsigned int)image_w;
608     *height = (unsigned int)image_h;
609
610     /* Ignore tga identifier, if present ... */
611     if (id_len)
612     {
613         unsigned char *id = (unsigned char *) malloc(id_len);
614                 if(id == 0){
615                         fprintf(stderr, "tga_readheader: memory out\n");
616                         return 0;
617                 }
618         if ( !fread(id, id_len, 1, fp) )
619         {
620             fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
621             free(id);
622             return 0 ;
623         }
624         free(id);
625     }
626
627     /* Test for compressed formats ... not yet supported ...
628     // Note :-  9 - RLE encoded palettized.
629     //             10 - RLE encoded RGB. */
630     if (image_type > 8)
631     {
632         fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
633         return 0 ;
634     }
635
636     *flip_image = !(image_desc & 32);
637
638     /* Palettized formats are not yet supported, skip over the palette, if present ... */
639     palette_size = cmap_len * (cmap_entry_size/8);
640
641     if (palette_size>0)
642     {
643         fprintf(stderr, "File contains a palette - not yet supported.");
644         fseek(fp, palette_size, SEEK_CUR);
645     }
646     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 #endif
657
658 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     unsigned char uc0, image_type;
663     unsigned char pixel_depth, image_desc;
664
665     if (!bits_per_pixel || !width || !height)
666         return 0;
667
668     pixel_depth = 0;
669
670     if ( bits_per_pixel < 256 )
671         pixel_depth = (unsigned char)bits_per_pixel;
672     else{
673         fprintf(stderr,"ERROR: Wrong bits per pixel inside tga_header");
674         return 0;
675     }
676     uc0 = 0;
677
678     if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* id_length */
679     if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_type */
680
681     image_type = 2; /* Uncompressed. */
682     if(fwrite(&image_type, 1, 1, fp) != 1) goto fails;
683
684     us0 = 0;
685     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_index */
686     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_length */
687     if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_entry_size */
688
689     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* x_origin */
690     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* y_origin */
691
692     image_w = (unsigned short)width;
693     image_h = (unsigned short) height;
694
695 #ifndef OPJ_BIG_ENDIAN
696     if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
697     if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
698 #else
699     image_w = swap16(image_w);
700     image_h = swap16(image_h);
701     if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
702     if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
703 #endif
704
705     if(fwrite(&pixel_depth, 1, 1, fp) != 1) goto fails;
706
707     image_desc = 8; /* 8 bits per component. */
708
709     if (flip_image)
710         image_desc |= 32;
711     if(fwrite(&image_desc, 1, 1, fp) != 1) goto fails;
712
713     return 1;
714
715 fails:
716     fputs("\nwrite_tgaheader: write ERROR\n", stderr);
717     return 0;
718 }
719
720 opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
721     FILE *f;
722     opj_image_t *image;
723     unsigned int image_width, image_height, pixel_bit_depth;
724     unsigned int x, y;
725     int flip_image=0;
726     opj_image_cmptparm_t cmptparm[4];   /* maximum 4 components */
727     int numcomps;
728     OPJ_COLOR_SPACE color_space;
729     OPJ_BOOL mono ;
730     OPJ_BOOL save_alpha;
731     int subsampling_dx, subsampling_dy;
732     int i;
733
734     f = fopen(filename, "rb");
735     if (!f) {
736         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
737         return 0;
738     }
739
740     if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image)) {
741         fclose(f);
742         return NULL;
743     }
744
745     /* We currently only support 24 & 32 bit tga's ... */
746     if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) {
747         fclose(f);
748         return NULL;
749     }
750
751     /* initialize image components */
752     memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
753
754     mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16);  /* Mono with & without alpha. */
755     save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
756
757     if (mono) {
758         color_space = OPJ_CLRSPC_GRAY;
759         numcomps = save_alpha ? 2 : 1;
760     }
761     else {
762         numcomps = save_alpha ? 4 : 3;
763         color_space = OPJ_CLRSPC_SRGB;
764     }
765
766     subsampling_dx = parameters->subsampling_dx;
767     subsampling_dy = parameters->subsampling_dy;
768
769     for (i = 0; i < numcomps; i++) {
770         cmptparm[i].prec = 8;
771         cmptparm[i].bpp = 8;
772         cmptparm[i].sgnd = 0;
773         cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
774         cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
775         cmptparm[i].w = image_width;
776         cmptparm[i].h = image_height;
777     }
778
779     /* create the image */
780     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
781
782     if (!image) {
783         fclose(f);
784         return NULL;
785     }
786
787
788     /* set image offset and reference grid */
789     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
790     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
791     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;
792     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     /* set image data */
795     for (y=0; y < image_height; y++)
796     {
797         int index;
798
799         if (flip_image)
800             index = (int)((image_height-y-1)*image_width);
801         else
802             index = (int)(y*image_width);
803
804         if (numcomps==3)
805         {
806             for (x=0;x<image_width;x++)
807             {
808                 unsigned char r,g,b;
809
810                 if( !fread(&b, 1, 1, f) )
811                 {
812                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
813                     opj_image_destroy(image);
814                     fclose(f);
815                     return NULL;
816                 }
817                 if ( !fread(&g, 1, 1, f) )
818                 {
819                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
820                     opj_image_destroy(image);
821                     fclose(f);
822                     return NULL;
823                 }
824                 if ( !fread(&r, 1, 1, f) )
825                 {
826                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
827                     opj_image_destroy(image);
828                     fclose(f);
829                     return NULL;
830                 }
831
832                 image->comps[0].data[index]=r;
833                 image->comps[1].data[index]=g;
834                 image->comps[2].data[index]=b;
835                 index++;
836             }
837         }
838         else if (numcomps==4)
839         {
840             for (x=0;x<image_width;x++)
841             {
842                 unsigned char r,g,b,a;
843                 if ( !fread(&b, 1, 1, f) )
844                 {
845                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
846                     opj_image_destroy(image);
847                     fclose(f);
848                     return NULL;
849                 }
850                 if ( !fread(&g, 1, 1, f) )
851                 {
852                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
853                     opj_image_destroy(image);
854                     fclose(f);
855                     return NULL;
856                 }
857                 if ( !fread(&r, 1, 1, f) )
858                 {
859                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
860                     opj_image_destroy(image);
861                     fclose(f);
862                     return NULL;
863                 }
864                 if ( !fread(&a, 1, 1, f) )
865                 {
866                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
867                     opj_image_destroy(image);
868                     fclose(f);
869                     return NULL;
870                 }
871
872                 image->comps[0].data[index]=r;
873                 image->comps[1].data[index]=g;
874                 image->comps[2].data[index]=b;
875                 image->comps[3].data[index]=a;
876                 index++;
877             }
878         }
879         else {
880             fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
881         }
882     }
883     fclose(f);
884     return image;
885 }
886
887 int imagetotga(opj_image_t * image, const char *outfile) {
888     int width, height, bpp, x, y;
889     OPJ_BOOL write_alpha;
890     unsigned int i;
891     int adjustR, adjustG, adjustB, fails;
892     unsigned int alpha_channel;
893     float r,g,b,a;
894     unsigned char value;
895     float scale;
896     FILE *fdest;
897     size_t res;
898     fails = 1;
899
900     fdest = fopen(outfile, "wb");
901     if (!fdest) {
902         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
903         return 1;
904     }
905
906     for (i = 0; i < image->numcomps-1; i++)     {
907         if ((image->comps[0].dx != image->comps[i+1].dx)
908                 ||(image->comps[0].dy != image->comps[i+1].dy)
909                 ||(image->comps[0].prec != image->comps[i+1].prec))     {
910             fclose(fdest);
911             fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
912             return 1;
913         }
914     }
915
916     width  = (int)image->comps[0].w;
917     height = (int)image->comps[0].h;
918
919     /* Mono with alpha, or RGB with alpha. */
920     write_alpha = (image->numcomps==2) || (image->numcomps==4);
921
922     /* Write TGA header  */
923     bpp = write_alpha ? 32 : 24;
924
925     if (!tga_writeheader(fdest, bpp, width , height, OPJ_TRUE))
926                 goto fin;
927
928     alpha_channel = image->numcomps-1;
929
930     scale = 255.0f / (float)((1<<image->comps[0].prec)-1);
931
932     adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
933     adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
934     adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
935
936         for (y=0; y < height; y++) 
937    {
938         unsigned int index= (unsigned int)(y*width);
939
940         for (x=0; x < width; x++, index++)      
941   {
942         r = (float)(image->comps[0].data[index] + adjustR);
943
944         if (image->numcomps > 2) 
945  {
946         g = (float)(image->comps[1].data[index] + adjustG);
947         b = (float)(image->comps[2].data[index] + adjustB);
948  }
949         else  
950  {/* Greyscale ... */
951         g = r;
952         b = r;
953  }
954
955 /* TGA format writes BGR ... */
956         if(b > 255.) b = 255.; else if(b < 0.) b = 0.;
957         value = (unsigned char)(b*scale);
958         res = fwrite(&value,1,1,fdest);
959
960         if( res < 1 ) 
961  {
962         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
963         goto fin;
964  }
965         if(g > 255.) g = 255.; else if(g < 0.) g = 0.;
966         value = (unsigned char)(g*scale);
967         res = fwrite(&value,1,1,fdest);
968
969         if( res < 1 ) 
970  {
971         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
972         goto fin;
973  }
974         if(r > 255.) r = 255.; else if(r < 0.) r = 0.;
975         value = (unsigned char)(r*scale);
976         res = fwrite(&value,1,1,fdest);
977
978         if( res < 1 ) 
979  {
980         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
981         goto fin;
982  }
983
984         if (write_alpha) 
985  {
986         a = (float)(image->comps[alpha_channel].data[index]);
987         if(a > 255.) a = 255.; else if(a < 0.) a = 0.;
988         value = (unsigned char)(a*scale);
989         res = fwrite(&value,1,1,fdest);
990
991                 if( res < 1 ) 
992            {
993                 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
994                 goto fin;
995            }
996  }
997   }
998    }
999         fails = 0;
1000 fin:
1001         fclose(fdest);
1002
1003         return fails;
1004 }
1005
1006 /* -->> -->> -->> -->>
1007
1008 PGX IMAGE FORMAT
1009
1010 <<-- <<-- <<-- <<-- */
1011
1012
1013 static unsigned char readuchar(FILE * f)
1014 {
1015     unsigned char c1;
1016     if ( !fread(&c1, 1, 1, f) )
1017     {
1018         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1019         return 0;
1020     }
1021     return c1;
1022 }
1023
1024 static unsigned short readushort(FILE * f, int bigendian)
1025 {
1026     unsigned char c1, c2;
1027     if ( !fread(&c1, 1, 1, f) )
1028     {
1029         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1030         return 0;
1031     }
1032     if ( !fread(&c2, 1, 1, f) )
1033     {
1034         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1035         return 0;
1036     }
1037     if (bigendian)
1038         return (unsigned short)((c1 << 8) + c2);
1039     else
1040         return (unsigned short)((c2 << 8) + c1);
1041 }
1042
1043 static unsigned int readuint(FILE * f, int bigendian)
1044 {
1045     unsigned char c1, c2, c3, c4;
1046     if ( !fread(&c1, 1, 1, f) )
1047     {
1048         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1049         return 0;
1050     }
1051     if ( !fread(&c2, 1, 1, f) )
1052     {
1053         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1054         return 0;
1055     }
1056     if ( !fread(&c3, 1, 1, f) )
1057     {
1058         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1059         return 0;
1060     }
1061     if ( !fread(&c4, 1, 1, f) )
1062     {
1063         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1064         return 0;
1065     }
1066     if (bigendian)
1067         return (unsigned int)(c1 << 24) + (unsigned int)(c2 << 16) + (unsigned int)(c3 << 8) + c4;
1068     else
1069         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     FILE *f = NULL;
1074     int w, h, prec;
1075     int i, numcomps, max;
1076     OPJ_COLOR_SPACE color_space;
1077     opj_image_cmptparm_t cmptparm;      /* maximum of 1 component  */
1078     opj_image_t * image = NULL;
1079     int adjustS, ushift, dshift, force8;
1080
1081     char endian1,endian2,sign;
1082     char signtmp[32];
1083
1084     char temp[32];
1085     int bigendian;
1086     opj_image_comp_t *comp = NULL;
1087
1088     numcomps = 1;
1089     color_space = OPJ_CLRSPC_GRAY;
1090
1091     memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
1092
1093     max = 0;
1094
1095     f = fopen(filename, "rb");
1096     if (!f) {
1097         fprintf(stderr, "Failed to open %s for reading !\n", filename);
1098         return NULL;
1099     }
1100
1101     fseek(f, 0, SEEK_SET);
1102     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         fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n");
1105         return NULL;
1106     }
1107
1108     i=0;
1109     sign='+';
1110     while (signtmp[i]!='\0') {
1111         if (signtmp[i]=='-') sign='-';
1112         i++;
1113     }
1114
1115     fgetc(f);
1116     if (endian1=='M' && endian2=='L') {
1117         bigendian = 1;
1118     } else if (endian2=='M' && endian1=='L') {
1119         bigendian = 0;
1120     } else {
1121         fclose(f);
1122         fprintf(stderr, "Bad pgx header, please check input file\n");
1123         return NULL;
1124     }
1125
1126     /* initialize image component */
1127
1128     cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
1129     cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
1130     cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + 1;
1131     cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + 1;
1132
1133     if (sign == '-') {
1134         cmptparm.sgnd = 1;
1135     } else {
1136         cmptparm.sgnd = 0;
1137     }
1138     if(prec < 8)
1139     {
1140         force8 = 1;
1141         ushift = 8 - prec; dshift = prec - ushift;
1142         if(cmptparm.sgnd) adjustS = (1<<(prec - 1)); else adjustS = 0;
1143         cmptparm.sgnd = 0;
1144         prec = 8;
1145     }
1146     else ushift = dshift = force8 = adjustS = 0;
1147
1148     cmptparm.prec = (OPJ_UINT32)prec;
1149     cmptparm.bpp = (OPJ_UINT32)prec;
1150     cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
1151     cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;
1152
1153     /* create the image */
1154     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
1155     if(!image) {
1156         fclose(f);
1157         return NULL;
1158     }
1159     /* set image offset and reference grid */
1160     image->x0 = cmptparm.x0;
1161     image->y0 = cmptparm.x0;
1162     image->x1 = cmptparm.w;
1163     image->y1 = cmptparm.h;
1164
1165     /* set image data */
1166
1167     comp = &image->comps[0];
1168
1169     for (i = 0; i < w * h; i++) {
1170         int v;
1171         if(force8)
1172         {
1173             v = readuchar(f) + adjustS;
1174             v = (v<<ushift) + (v>>dshift);
1175             comp->data[i] = (unsigned char)v;
1176
1177             if(v > max) max = v;
1178
1179             continue;
1180         }
1181         if (comp->prec == 8) {
1182             if (!comp->sgnd) {
1183                 v = readuchar(f);
1184             } else {
1185                 v = (char) readuchar(f);
1186             }
1187         } else if (comp->prec <= 16) {
1188             if (!comp->sgnd) {
1189                 v = readushort(f, bigendian);
1190             } else {
1191                 v = (short) readushort(f, bigendian);
1192             }
1193         } else {
1194             if (!comp->sgnd) {
1195                 v = (int)readuint(f, bigendian);
1196             } else {
1197                 v = (int) readuint(f, bigendian);
1198             }
1199         }
1200         if (v > max)
1201             max = v;
1202         comp->data[i] = v;
1203     }
1204     fclose(f);
1205     comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;
1206
1207     return image;
1208 }
1209
1210 #define CLAMP(x,a,b) x < a ? a : (x > b ? b : x)
1211
1212 static INLINE int clamp( const int value, const int prec, const int sgnd )
1213 {
1214   if( sgnd )
1215     {
1216     if (prec <= 8)       return CLAMP(value,-128,127);
1217     else if (prec <= 16) return CLAMP(value,-32768,32767);
1218     else                 return CLAMP(value,-2147483647-1,2147483647);
1219     }
1220   else
1221     {
1222     if (prec <= 8)       return CLAMP(value,0,255);
1223     else if (prec <= 16) return CLAMP(value,0,65535);
1224     else                 return value; /*CLAMP(value,0,4294967295);*/
1225     }
1226 }
1227
1228 int imagetopgx(opj_image_t * image, const char *outfile) 
1229 {
1230   int w, h;
1231   int i, j, fails = 1;
1232   unsigned int compno;
1233   FILE *fdest = NULL;
1234
1235   for (compno = 0; compno < image->numcomps; compno++) 
1236         {
1237     opj_image_comp_t *comp = &image->comps[compno];
1238     char bname[256]; /* buffer for name */
1239     char *name = bname; /* pointer */
1240     int nbytes = 0;
1241     size_t res;
1242     const size_t olen = strlen(outfile);
1243     const size_t dotpos = olen - 4;
1244     const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
1245
1246     if( outfile[dotpos] != '.' ) 
1247                 {
1248       /* `pgx` was recognized but there is no dot at expected position */
1249       fprintf(stderr, "ERROR -> Impossible happen." );
1250       goto fin;
1251                 }
1252     if( total > 256 ) 
1253                 {
1254       name = (char*)malloc(total+1);
1255                         if (name == NULL) {
1256                                 fprintf(stderr, "imagetopgx: memory out\n");
1257                                 goto fin;
1258                         }
1259                 }
1260     strncpy(name, outfile, dotpos);
1261     sprintf(name+dotpos, "_%u.pgx", compno);
1262     fdest = fopen(name, "wb");
1263     /* don't need name anymore */
1264                         
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     w = (int)image->comps[compno].w;
1274     h = (int)image->comps[compno].h;
1275
1276     fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
1277       w, h);
1278
1279     if (comp->prec <= 8) 
1280       nbytes = 1;
1281     else if (comp->prec <= 16)
1282       nbytes = 2;
1283     else
1284       nbytes = 4;
1285
1286     for (i = 0; i < w * h; i++) 
1287                 {
1288       /* FIXME: clamp func is being called within a loop */
1289       const int val = clamp(image->comps[compno].data[i],
1290         (int)comp->prec, (int)comp->sgnd);
1291
1292       for (j = nbytes - 1; j >= 0; j--) 
1293                         {
1294         int v = (int)(val >> (j * 8));
1295         unsigned char byte = (unsigned char)v;
1296         res = fwrite(&byte, 1, 1, fdest);
1297
1298         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   fails = 0;
1310 fin:
1311   if(fdest) fclose(fdest);
1312
1313   return fails;
1314 }
1315
1316 /* -->> -->> -->> -->>
1317
1318 PNM IMAGE FORMAT
1319
1320 <<-- <<-- <<-- <<-- */
1321
1322 struct pnm_header
1323 {
1324     int width, height, maxval, depth, format;
1325     char rgb, rgba, gray, graya, bw;
1326     char ok;
1327 };
1328
1329 static char *skip_white(char *s)
1330 {
1331     while(*s)
1332     {
1333         if(*s == '\n' || *s == '\r') return NULL;
1334         if(isspace(*s)) { ++s; continue; }
1335         return s;
1336     }
1337     return NULL;
1338 }
1339
1340 static char *skip_int(char *start, int *out_n)
1341 {
1342     char *s;
1343     char c;
1344
1345     *out_n = 0;
1346
1347     s = skip_white(start);
1348     if(s == NULL) return NULL;
1349     start = s;
1350
1351     while(*s)
1352     {
1353         if( !isdigit(*s)) break;
1354         ++s;
1355     }
1356     c = *s; *s = 0; *out_n = atoi(start); *s = c;
1357     return s;
1358 }
1359
1360 static char *skip_idf(char *start, char out_idf[256])
1361 {
1362     char *s;
1363     char c;
1364
1365     s = skip_white(start);
1366     if(s == NULL) return NULL;
1367     start = s;
1368
1369     while(*s)
1370     {
1371         if(isalpha(*s) || *s == '_') { ++s; continue; }
1372         break;
1373     }
1374     c = *s; *s = 0; strncpy(out_idf, start, 255); *s = c;
1375     return s;
1376 }
1377
1378 static void read_pnm_header(FILE *reader, struct pnm_header *ph)
1379 {
1380     int format, have_wh, end, ttype;
1381     char idf[256], type[256];
1382     char line[256];
1383
1384     if (fgets(line, 250, reader) == NULL)
1385     {
1386         fprintf(stderr,"\nWARNING: fgets return a NULL value");
1387         return;
1388     }
1389
1390     if(line[0] != 'P')
1391     {
1392         fprintf(stderr,"read_pnm_header:PNM:magic P missing\n"); return;
1393     }
1394     format = atoi(line + 1);
1395     if(format < 1 || format > 7)
1396     {
1397         fprintf(stderr,"read_pnm_header:magic format %d invalid\n", format);
1398         return;
1399     }
1400     ph->format = format;
1401     ttype = end = have_wh = 0;
1402
1403     while(fgets(line, 250, reader))
1404     {
1405         char *s;
1406
1407         if(*line == '#') continue;
1408
1409         s = line;
1410
1411         if(format == 7)
1412         {
1413             s = skip_idf(s, idf);
1414
1415             if(s == NULL || *s == 0) return;
1416
1417             if(strcmp(idf, "ENDHDR") == 0)
1418             {
1419                 end = 1; break;
1420             }
1421             if(strcmp(idf, "WIDTH") == 0)
1422             {
1423                 s = skip_int(s, &ph->width);
1424                 if(s == NULL || *s == 0) return;
1425
1426                 continue;
1427             }
1428             if(strcmp(idf, "HEIGHT") == 0)
1429             {
1430                 s = skip_int(s, &ph->height);
1431                 if(s == NULL || *s == 0) return;
1432
1433                 continue;
1434             }
1435             if(strcmp(idf, "DEPTH") == 0)
1436             {
1437                 s = skip_int(s, &ph->depth);
1438                 if(s == NULL || *s == 0) return;
1439
1440                 continue;
1441             }
1442             if(strcmp(idf, "MAXVAL") == 0)
1443             {
1444                 s = skip_int(s, &ph->maxval);
1445                 if(s == NULL || *s == 0) return;
1446
1447                 continue;
1448             }
1449             if(strcmp(idf, "TUPLTYPE") == 0)
1450             {
1451                 s = skip_idf(s, type);
1452                 if(s == NULL || *s == 0) return;
1453
1454                 if(strcmp(type, "BLACKANDWHITE") == 0)
1455                 {
1456                     ph->bw = 1; ttype = 1; continue;
1457                 }
1458                 if(strcmp(type, "GRAYSCALE") == 0)
1459                 {
1460                     ph->gray = 1; ttype = 1; continue;
1461                 }
1462                 if(strcmp(type, "GRAYSCALE_ALPHA") == 0)
1463                 {
1464                     ph->graya = 1; ttype = 1; continue;
1465                 }
1466                 if(strcmp(type, "RGB") == 0)
1467                 {
1468                     ph->rgb = 1; ttype = 1; continue;
1469                 }
1470                 if(strcmp(type, "RGB_ALPHA") == 0)
1471                 {
1472                     ph->rgba = 1; ttype = 1; continue;
1473                 }
1474                 fprintf(stderr,"read_pnm_header:unknown P7 TUPLTYPE %s\n",type);
1475                 return;
1476             }
1477             fprintf(stderr,"read_pnm_header:unknown P7 idf %s\n",idf);
1478             return;
1479         } /* if(format == 7) */
1480
1481         if( !have_wh)
1482         {
1483             s = skip_int(s, &ph->width);
1484
1485             s = skip_int(s, &ph->height);
1486
1487             have_wh = 1;
1488
1489             if(format == 1 || format == 4) break;
1490                                         
1491             if(format == 2 || format == 3 || format == 5 || format == 6)
1492             {
1493                 if (skip_int(s, &ph->maxval) != NULL) {
1494                     if(ph->maxval > 65535) {
1495                         return;
1496                     }
1497                     else {
1498                         break;
1499                     }
1500                 }
1501             }
1502             continue;
1503         }
1504         if(format == 2 || format == 3 || format == 5 || format == 6)
1505         {
1506             /* P2, P3, P5, P6: */
1507             s = skip_int(s, &ph->maxval);
1508
1509             if(ph->maxval > 65535) return;
1510         }
1511         break;
1512     }/* while(fgets( ) */
1513     if(format == 2 || format == 3 || format > 4)
1514     {
1515         if(ph->maxval < 1 || ph->maxval > 65535) return;
1516     }
1517     if(ph->width < 1 || ph->height < 1) return;
1518
1519     if(format == 7)
1520     {
1521         if(!end)
1522         {
1523             fprintf(stderr,"read_pnm_header:P7 without ENDHDR\n"); return;
1524         }
1525         if(ph->depth < 1 || ph->depth > 4) return;
1526
1527         if(ph->width && ph->height && ph->depth && ph->maxval && ttype)
1528             ph->ok = 1;
1529     }
1530     else
1531     {
1532         if(format != 1 && format != 4)
1533         {
1534             if(ph->width && ph->height && ph->maxval) ph->ok = 1;
1535         }
1536         else
1537         {
1538             if(ph->width && ph->height) ph->ok = 1;
1539             ph->maxval = 255;
1540         }
1541     }
1542 }
1543
1544 static int has_prec(int val)
1545 {
1546     if(val < 2) return 1;
1547     if(val < 4) return 2;
1548     if(val < 8) return 3;
1549     if(val < 16) return 4;
1550     if(val < 32) return 5;
1551     if(val < 64) return 6;
1552     if(val < 128) return 7;
1553     if(val < 256) return 8;
1554     if(val < 512) return 9;
1555     if(val < 1024) return 10;
1556     if(val < 2048) return 11;
1557     if(val < 4096) return 12;
1558     if(val < 8192) return 13;
1559     if(val < 16384) return 14;
1560     if(val < 32768) return 15;
1561     return 16;
1562 }
1563
1564 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
1565     int subsampling_dx = parameters->subsampling_dx;
1566     int subsampling_dy = parameters->subsampling_dy;
1567
1568     FILE *fp = NULL;
1569     int i, compno, numcomps, w, h, prec, format;
1570     OPJ_COLOR_SPACE color_space;
1571     opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
1572     opj_image_t * image = NULL;
1573     struct pnm_header header_info;
1574
1575     if((fp = fopen(filename, "rb")) == NULL)
1576     {
1577         fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n",filename);
1578         return NULL;
1579     }
1580     memset(&header_info, 0, sizeof(struct pnm_header));
1581
1582     read_pnm_header(fp, &header_info);
1583
1584     if(!header_info.ok) { fclose(fp); return NULL; }
1585
1586     format = header_info.format;
1587
1588     switch(format)
1589     {
1590     case 1: /* ascii bitmap */
1591     case 4: /* raw bitmap */
1592         numcomps = 1;
1593         break;
1594
1595     case 2: /* ascii greymap */
1596     case 5: /* raw greymap */
1597         numcomps = 1;
1598         break;
1599
1600     case 3: /* ascii pixmap */
1601     case 6: /* raw pixmap */
1602         numcomps = 3;
1603         break;
1604
1605     case 7: /* arbitrary map */
1606         numcomps = header_info.depth;
1607         break;
1608
1609     default: fclose(fp); return NULL;
1610     }
1611     if(numcomps < 3)
1612         color_space = OPJ_CLRSPC_GRAY;/* GRAY, GRAYA */
1613     else
1614         color_space = OPJ_CLRSPC_SRGB;/* RGB, RGBA */
1615
1616     prec = has_prec(header_info.maxval);
1617
1618     if(prec < 8) prec = 8;
1619
1620     w = header_info.width;
1621     h = header_info.height;
1622     subsampling_dx = parameters->subsampling_dx;
1623     subsampling_dy = parameters->subsampling_dy;
1624
1625     memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
1626
1627     for(i = 0; i < numcomps; i++)
1628     {
1629         cmptparm[i].prec = (OPJ_UINT32)prec;
1630         cmptparm[i].bpp = (OPJ_UINT32)prec;
1631         cmptparm[i].sgnd = 0;
1632         cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
1633         cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
1634         cmptparm[i].w = (OPJ_UINT32)w;
1635         cmptparm[i].h = (OPJ_UINT32)h;
1636     }
1637     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
1638
1639     if(!image) { fclose(fp); return NULL; }
1640
1641     /* set image offset and reference grid */
1642     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
1643     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
1644     image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx + 1);
1645     image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy + 1);
1646
1647     if((format == 2) || (format == 3)) /* ascii pixmap */
1648     {
1649         unsigned int index;
1650
1651         for (i = 0; i < w * h; i++)
1652         {
1653             for(compno = 0; compno < numcomps; compno++)
1654             {
1655                 index = 0;
1656                 if (fscanf(fp, "%u", &index) != 1)
1657                     fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1658
1659                 image->comps[compno].data[i] = (OPJ_INT32)(index * 255)/header_info.maxval;
1660             }
1661         }
1662     }
1663     else
1664         if((format == 5)
1665                 || (format == 6)
1666                 ||((format == 7)
1667                    && (   header_info.gray || header_info.graya
1668                           || header_info.rgb || header_info.rgba)))/* binary pixmap */
1669         {
1670             unsigned char c0, c1, one;
1671
1672             one = (prec < 9);
1673
1674             for (i = 0; i < w * h; i++)
1675             {
1676                 for(compno = 0; compno < numcomps; compno++)
1677                 {
1678                 if ( !fread(&c0, 1, 1, fp) )
1679                   {
1680                   fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1681                   opj_image_destroy(image);
1682                   fclose(fp);
1683                   return NULL;
1684                   }
1685                     if(one)
1686                     {
1687                         image->comps[compno].data[i] = c0;
1688                     }
1689                     else
1690                     {
1691                         if ( !fread(&c1, 1, 1, fp) )
1692                             fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1693                         /* netpbm: */
1694                         image->comps[compno].data[i] = ((c0<<8) | c1);
1695                     }
1696                 }
1697             }
1698         }
1699         else
1700             if(format == 1) /* ascii bitmap */
1701             {
1702                 for (i = 0; i < w * h; i++)
1703                 {
1704                     unsigned int index;
1705
1706                     if ( fscanf(fp, "%u", &index) != 1)
1707                         fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1708
1709                     image->comps[0].data[i] = (index?0:255);
1710                 }
1711             }
1712             else
1713                 if(format == 4)
1714                 {
1715                     int x, y, bit;
1716                     unsigned char uc;
1717
1718                     i = 0;
1719                     for(y = 0; y < h; ++y)
1720                     {
1721                         bit = -1; uc = 0;
1722
1723                         for(x = 0; x < w; ++x)
1724                         {
1725                             if(bit == -1)
1726                             {
1727                                 bit = 7;
1728                                 uc = (unsigned char)getc(fp);
1729                             }
1730                             image->comps[0].data[i] = (((uc>>bit) & 1)?0:255);
1731                             --bit; ++i;
1732                         }
1733                     }
1734                 }
1735                 else
1736                     if((format == 7 && header_info.bw)) /*MONO*/
1737                     {
1738                         unsigned char uc;
1739
1740                         for(i = 0; i < w * h; ++i)
1741                         {
1742                             if ( !fread(&uc, 1, 1, fp) )
1743                                 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1744                             image->comps[0].data[i] = (uc & 1)?0:255;
1745                         }
1746                     }
1747     fclose(fp);
1748
1749     return image;
1750 }/* pnmtoimage() */
1751
1752 int imagetopnm(opj_image_t * image, const char *outfile, int force_split)
1753 {
1754     int *red, *green, *blue, *alpha;
1755     int wr, hr, max;
1756     int i;
1757     unsigned int compno, ncomp;
1758     int adjustR, adjustG, adjustB, adjustA;
1759     int fails, two, want_gray, has_alpha, triple;
1760     int prec, v;
1761     FILE *fdest = NULL;
1762     const char *tmp = outfile;
1763     char *destname;
1764
1765         alpha = NULL;
1766
1767     if((prec = (int)image->comps[0].prec) > 16)
1768     {
1769         fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
1770                 "\n\t: refused.\n",__FILE__,__LINE__,prec);
1771         return 1;
1772     }
1773     two = has_alpha = 0; fails = 1;
1774     ncomp = image->numcomps;
1775
1776     while (*tmp) ++tmp; tmp -= 2;
1777     want_gray = (*tmp == 'g' || *tmp == 'G');
1778     ncomp = image->numcomps;
1779
1780     if(want_gray) ncomp = 1;
1781
1782     if ((force_split == 0) &&
1783                                 (ncomp == 2 /* GRAYA */
1784             || (ncomp > 2 /* RGB, RGBA */
1785                 && image->comps[0].dx == image->comps[1].dx
1786                 && image->comps[1].dx == image->comps[2].dx
1787                 && image->comps[0].dy == image->comps[1].dy
1788                 && image->comps[1].dy == image->comps[2].dy
1789                 && image->comps[0].prec == image->comps[1].prec
1790                 && image->comps[1].prec == image->comps[2].prec
1791                 )))
1792                 {
1793         fdest = fopen(outfile, "wb");
1794
1795         if (!fdest)
1796         {
1797             fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1798             return fails;
1799         }
1800         two = (prec > 8);
1801         triple = (ncomp > 2);
1802         wr = (int)image->comps[0].w; hr = (int)image->comps[0].h;
1803         max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);
1804
1805         red = image->comps[0].data;
1806
1807         if(triple)
1808         {
1809             green = image->comps[1].data;
1810             blue = image->comps[2].data;
1811         }
1812         else green = blue = NULL;
1813
1814         if(has_alpha)
1815         {
1816             const char *tt = (triple?"RGB_ALPHA":"GRAYSCALE_ALPHA");
1817
1818             fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %u\n"
1819                     "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
1820                     wr, hr, ncomp, max, tt);
1821             alpha = image->comps[ncomp - 1].data;
1822             adjustA = (image->comps[ncomp - 1].sgnd ?
1823                         1 << (image->comps[ncomp - 1].prec - 1) : 0);
1824         }
1825         else
1826         {
1827             fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
1828                     opj_version(), wr, hr, max);
1829             adjustA = 0;
1830         }
1831         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1832
1833         if(triple)
1834         {
1835             adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1836             adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1837         }
1838         else adjustG = adjustB = 0;
1839
1840         for(i = 0; i < wr * hr; ++i)
1841         {
1842             if(two)
1843             {
1844                 v = *red + adjustR; ++red;
1845 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1846
1847                 /* netpbm: */
1848                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1849
1850                 if(triple)
1851                 {
1852                     v = *green + adjustG; ++green;
1853 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1854
1855                     /* netpbm: */
1856                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1857
1858                     v =  *blue + adjustB; ++blue;
1859 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1860
1861                     /* netpbm: */
1862                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1863
1864                 }/* if(triple) */
1865
1866                 if(has_alpha)
1867                 {
1868                     v = *alpha + adjustA; ++alpha;
1869                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1870
1871                     /* netpbm: */
1872                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1873                 }
1874                 continue;
1875
1876             }   /* if(two) */
1877
1878             /* prec <= 8: */
1879         v = *red++;
1880         if(v > 255) v = 255; else if(v < 0) v = 0;
1881
1882         fprintf(fdest, "%c", (unsigned char)v);
1883             if(triple)
1884  {
1885         v = *green++;
1886         if(v > 255) v = 255; else if(v < 0) v = 0;
1887
1888         fprintf(fdest, "%c", (unsigned char)v);
1889         v = *blue++;
1890         if(v > 255) v = 255; else if(v < 0) v = 0;
1891
1892         fprintf(fdest, "%c", (unsigned char)v);
1893  }
1894             if(has_alpha)
1895  {
1896         v = *alpha++;
1897         if(v > 255) v = 255; else if(v < 0) v = 0;
1898
1899         fprintf(fdest, "%c", (unsigned char)v);
1900  }
1901         }       /* for(i */
1902
1903         fclose(fdest); return 0;
1904     }
1905
1906     /* YUV or MONO: */
1907
1908     if (image->numcomps > ncomp)
1909     {
1910         fprintf(stderr,"WARNING -> [PGM file] Only the first component\n");
1911         fprintf(stderr,"           is written to the file\n");
1912     }
1913     destname = (char*)malloc(strlen(outfile) + 8);
1914         if(destname == NULL){
1915                 fprintf(stderr, "imagetopnm: memory out\n");
1916                 fclose(fdest);
1917                 return 1;
1918         }
1919     for (compno = 0; compno < ncomp; compno++)
1920     {
1921     if (ncomp > 1)
1922       {
1923       /*sprintf(destname, "%d.%s", compno, outfile);*/
1924       const size_t olen = strlen(outfile);
1925       const size_t dotpos = olen - 4;
1926
1927       strncpy(destname, outfile, dotpos);
1928       sprintf(destname+dotpos, "_%u.pgm", compno);
1929       }
1930         else
1931             sprintf(destname, "%s", outfile);
1932
1933         fdest = fopen(destname, "wb");
1934         if (!fdest)
1935         {
1936             fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
1937             free(destname);
1938             return 1;
1939         }
1940         wr = (int)image->comps[compno].w; hr = (int)image->comps[compno].h;
1941         prec = (int)image->comps[compno].prec;
1942         max = (1<<prec) - 1;
1943
1944         fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
1945                 opj_version(), wr, hr, max);
1946
1947         red = image->comps[compno].data;
1948         adjustR =
1949                 (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
1950
1951         if(prec > 8)
1952         {
1953             for (i = 0; i < wr * hr; i++)
1954             {
1955                 v = *red + adjustR; ++red;
1956 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1957
1958                 /* netpbm: */
1959                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1960
1961                 if(has_alpha)
1962                 {
1963                     v = *alpha++;
1964 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1965
1966                     /* netpbm: */
1967                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1968                 }
1969             }/* for(i */
1970         }
1971         else /* prec <= 8 */
1972         {
1973             for(i = 0; i < wr * hr; ++i)
1974             {
1975         v = *red + adjustR; ++red;
1976         if(v > 255) v = 255; else if(v < 0) v = 0;
1977
1978          fprintf(fdest, "%c", (unsigned char)v);
1979             }
1980         }
1981         fclose(fdest);
1982     } /* for (compno */
1983     free(destname);
1984
1985     return 0;
1986 }/* imagetopnm() */
1987
1988 /* -->> -->> -->> -->>
1989
1990     RAW IMAGE FORMAT
1991
1992  <<-- <<-- <<-- <<-- */
1993 static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian) {
1994     int subsampling_dx = parameters->subsampling_dx;
1995     int subsampling_dy = parameters->subsampling_dy;
1996
1997     FILE *f = NULL;
1998     int i, compno, numcomps, w, h;
1999     OPJ_COLOR_SPACE color_space;
2000     opj_image_cmptparm_t *cmptparm;
2001     opj_image_t * image = NULL;
2002     unsigned short ch;
2003
2004     if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
2005     {
2006         fprintf(stderr,"\nError: invalid raw image parameters\n");
2007         fprintf(stderr,"Please use the Format option -F:\n");
2008         fprintf(stderr,"-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
2009         fprintf(stderr,"If subsampling is omitted, 1x1 is assumed for all components\n");
2010         fprintf(stderr,"Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
2011         fprintf(stderr,"         for raw 512x512 image with 4:2:0 subsampling\n");
2012         fprintf(stderr,"Aborting.\n");
2013         return NULL;
2014     }
2015
2016     f = fopen(filename, "rb");
2017     if (!f) {
2018         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
2019         fprintf(stderr,"Aborting\n");
2020         return NULL;
2021     }
2022     numcomps = raw_cp->rawComp;
2023
2024     /* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
2025     if (numcomps == 1) {
2026         color_space = OPJ_CLRSPC_GRAY;
2027     } else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
2028         color_space = OPJ_CLRSPC_SYCC;
2029     } else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
2030         color_space = OPJ_CLRSPC_SRGB;
2031     } else {
2032         color_space = OPJ_CLRSPC_UNKNOWN;
2033     }
2034     w = raw_cp->rawWidth;
2035     h = raw_cp->rawHeight;
2036     cmptparm = (opj_image_cmptparm_t*) calloc((OPJ_UINT32)numcomps,sizeof(opj_image_cmptparm_t));
2037     if (!cmptparm) {
2038         fprintf(stderr, "Failed to allocate image components parameters !!\n");
2039         fprintf(stderr,"Aborting\n");
2040         fclose(f);
2041         return NULL;
2042     }
2043     /* initialize image components */
2044     for(i = 0; i < numcomps; i++) {
2045         cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
2046         cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
2047         cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
2048         cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
2049         cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
2050         cmptparm[i].w = (OPJ_UINT32)w;
2051         cmptparm[i].h = (OPJ_UINT32)h;
2052     }
2053     /* create the image */
2054     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2055     free(cmptparm);
2056     if(!image) {
2057         fclose(f);
2058         return NULL;
2059     }
2060     /* set image offset and reference grid */
2061     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2062     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2063     image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
2064     image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
2065
2066     if(raw_cp->rawBitDepth <= 8)
2067     {
2068         unsigned char value = 0;
2069         for(compno = 0; compno < numcomps; compno++) {
2070             int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dy);
2071             for (i = 0; i < nloop; i++) {
2072                 if (!fread(&value, 1, 1, f)) {
2073                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2074                     opj_image_destroy(image);
2075                     fclose(f);
2076                     return NULL;
2077                 }
2078                 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
2079             }
2080         }
2081     }
2082     else if(raw_cp->rawBitDepth <= 16)
2083     {
2084         unsigned short value;
2085         for(compno = 0; compno < numcomps; compno++) {
2086             int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dy);
2087             for (i = 0; i < nloop; i++) {
2088                 unsigned char temp1;
2089                 unsigned char temp2;
2090                 if (!fread(&temp1, 1, 1, f)) {
2091                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2092                     opj_image_destroy(image);
2093                     fclose(f);
2094                     return NULL;
2095                 }
2096                 if (!fread(&temp2, 1, 1, f)) {
2097                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2098                     opj_image_destroy(image);
2099                     fclose(f);
2100                     return NULL;
2101                 }
2102                 if( big_endian )
2103                 {
2104                     value = (unsigned short)((temp1 << 8) + temp2);
2105                 }
2106                 else
2107                 {
2108                     value = (unsigned short)((temp2 << 8) + temp1);
2109                 }
2110                 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
2111             }
2112         }
2113     }
2114     else {
2115         fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
2116         opj_image_destroy(image);
2117         fclose(f);
2118         return NULL;
2119     }
2120
2121     if (fread(&ch, 1, 1, f)) {
2122         fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
2123     }
2124     fclose(f);
2125
2126     return image;
2127 }
2128
2129 opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
2130     return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
2131 }
2132
2133 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
2134     return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
2135 }
2136
2137 static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL big_endian)
2138 {
2139     FILE *rawFile = NULL;
2140     size_t res;
2141     unsigned int compno;
2142     int w, h, fails;
2143     int line, row, curr, mask;
2144     int *ptr;
2145     unsigned char uc;
2146     (void)big_endian;
2147
2148     if((image->numcomps * image->x1 * image->y1) == 0)
2149     {
2150         fprintf(stderr,"\nError: invalid raw image parameters\n");
2151         return 1;
2152     }
2153
2154     rawFile = fopen(outfile, "wb");
2155     if (!rawFile) {
2156         fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
2157         return 1;
2158     }
2159
2160     fails = 1;
2161     fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
2162
2163     for(compno = 0; compno < image->numcomps; compno++)
2164     {
2165         fprintf(stdout,"Component %u characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
2166                 image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
2167
2168         w = (int)image->comps[compno].w;
2169         h = (int)image->comps[compno].h;
2170
2171         if(image->comps[compno].prec <= 8)
2172         {
2173             if(image->comps[compno].sgnd == 1)
2174             {
2175                 mask = (1 << image->comps[compno].prec) - 1;
2176                 ptr = image->comps[compno].data;
2177                 for (line = 0; line < h; line++) {
2178                     for(row = 0; row < w; row++)        {
2179                         curr = *ptr;
2180                         if(curr > 127) curr = 127; else if(curr < -128) curr = -128;
2181                         uc = (unsigned char) (curr & mask);
2182                         res = fwrite(&uc, 1, 1, rawFile);
2183                         if( res < 1 ) {
2184                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2185                             goto fin;
2186                         }
2187                         ptr++;
2188                     }
2189                 }
2190             }
2191             else if(image->comps[compno].sgnd == 0)
2192             {
2193                 mask = (1 << image->comps[compno].prec) - 1;
2194                 ptr = image->comps[compno].data;
2195                 for (line = 0; line < h; line++) {
2196                     for(row = 0; row < w; row++)        {
2197                         curr = *ptr;
2198                         if(curr > 255) curr = 255; else if(curr < 0) curr = 0;
2199                         uc = (unsigned char) (curr & mask);
2200                         res = fwrite(&uc, 1, 1, rawFile);
2201                         if( res < 1 ) {
2202                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2203                             goto fin;
2204                         }
2205                         ptr++;
2206                     }
2207                 }
2208             }
2209         }
2210         else if(image->comps[compno].prec <= 16)
2211         {
2212             if(image->comps[compno].sgnd == 1)
2213             {
2214                 union { signed short val; signed char vals[2]; } uc16;
2215                 mask = (1 << image->comps[compno].prec) - 1;
2216                 ptr = image->comps[compno].data;
2217                 for (line = 0; line < h; line++) {
2218                     for(row = 0; row < w; row++)        {
2219                         curr = *ptr;
2220                         if(curr > 32767 ) curr = 32767; else if( curr < -32768) curr = -32768;
2221                         uc16.val = (signed short)(curr & mask);
2222                         res = fwrite(uc16.vals, 1, 2, rawFile);
2223                         if( res < 2 ) {
2224                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2225                             goto fin;
2226                         }
2227                         ptr++;
2228                     }
2229                 }
2230             }
2231             else if(image->comps[compno].sgnd == 0)
2232             {
2233                 union { unsigned short val; unsigned char vals[2]; } uc16;
2234                 mask = (1 << image->comps[compno].prec) - 1;
2235                 ptr = image->comps[compno].data;
2236                 for (line = 0; line < h; line++) {
2237                     for(row = 0; row < w; row++)        {
2238                         curr = *ptr;
2239                         if(curr > 65535 ) curr = 65535; else if( curr < 0) curr = 0;
2240                         uc16.val = (unsigned short)(curr & mask);
2241                         res = fwrite(uc16.vals, 1, 2, rawFile);
2242                         if( res < 2 ) {
2243                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2244                             goto fin;
2245                         }
2246                         ptr++;
2247                     }
2248                 }
2249             }
2250         }
2251         else if (image->comps[compno].prec <= 32)
2252         {
2253             fprintf(stderr,"More than 16 bits per component no handled yet\n");
2254             goto fin;
2255         }
2256         else
2257         {
2258             fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
2259             goto fin;
2260         }
2261     }
2262   fails = 0;
2263 fin:
2264     fclose(rawFile);
2265     return fails;
2266 }
2267
2268 int imagetoraw(opj_image_t * image, const char *outfile)
2269 {
2270     return imagetoraw_common(image, outfile, OPJ_TRUE);
2271 }
2272
2273 int imagetorawl(opj_image_t * image, const char *outfile)
2274 {
2275     return imagetoraw_common(image, outfile, OPJ_FALSE);
2276 }
2277