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