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