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