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