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