convert.c: fix recently introduced -Wsign-conversion warnings
[openjpeg.git] / src / bin / jp2 / convert.c
1 /*
2  * The copyright in this software is being made available under the 2-clauses
3  * BSD License, included below. This software may be subject to other third
4  * party and contributor rights, including patent rights, and no such rights
5  * are granted under this license.
6  *
7  * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
8  * Copyright (c) 2002-2014, Professor Benoit Macq
9  * Copyright (c) 2001-2003, David Janssens
10  * Copyright (c) 2002-2003, Yannick Verschueren
11  * Copyright (c) 2003-2007, Francois-Olivier Devaux
12  * Copyright (c) 2003-2014, Antonin Descampe
13  * Copyright (c) 2005, Herve Drolon, FreeImage Team
14  * Copyright (c) 2006-2007, Parvatha Elangovan
15  * All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
27  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
30  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 #include "opj_apps_config.h"
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <ctype.h>
44 #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 /* Returns a ushort from a little-endian serialized value */
584 static unsigned short get_tga_ushort(const unsigned char *data)
585 {
586     return (unsigned short)data[0] | (unsigned short)(data[1] << 8);
587 }
588
589 #define TGA_HEADER_SIZE 18
590
591 static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel,
592                           unsigned int *width, unsigned int *height, int *flip_image)
593 {
594     int palette_size;
595     unsigned char tga[TGA_HEADER_SIZE];
596     unsigned char id_len, /*cmap_type,*/ image_type;
597     unsigned char pixel_depth, image_desc;
598     unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
599     unsigned short /*x_origin, y_origin,*/ image_w, image_h;
600
601     if (!bits_per_pixel || !width || !height || !flip_image) {
602         return 0;
603     }
604
605     if (fread(tga, TGA_HEADER_SIZE, 1, fp) != 1) {
606         fprintf(stderr,
607                 "\nError: fread return a number of element different from the expected.\n");
608         return 0 ;
609     }
610     id_len = tga[0];
611     /*cmap_type = tga[1];*/
612     image_type = tga[2];
613     /*cmap_index = get_tga_ushort(&tga[3]);*/
614     cmap_len = get_tga_ushort(&tga[5]);
615     cmap_entry_size = tga[7];
616
617
618 #if 0
619     x_origin = get_tga_ushort(&tga[8]);
620     y_origin = get_tga_ushort(&tga[10]);
621 #endif
622     image_w = get_tga_ushort(&tga[12]);
623     image_h = get_tga_ushort(&tga[14]);
624     pixel_depth = tga[16];
625     image_desc  = tga[17];
626
627     *bits_per_pixel = (unsigned int)pixel_depth;
628     *width  = (unsigned int)image_w;
629     *height = (unsigned int)image_h;
630
631     /* Ignore tga identifier, if present ... */
632     if (id_len) {
633         unsigned char *id = (unsigned char *) malloc(id_len);
634         if (id == 0) {
635             fprintf(stderr, "tga_readheader: memory out\n");
636             return 0;
637         }
638         if (!fread(id, id_len, 1, fp)) {
639             fprintf(stderr,
640                     "\nError: fread return a number of element different from the expected.\n");
641             free(id);
642             return 0 ;
643         }
644         free(id);
645     }
646
647     /* Test for compressed formats ... not yet supported ...
648     // Note :-  9 - RLE encoded palettized.
649     //         10 - RLE encoded RGB. */
650     if (image_type > 8) {
651         fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
652         return 0 ;
653     }
654
655     *flip_image = !(image_desc & 32);
656
657     /* Palettized formats are not yet supported, skip over the palette, if present ... */
658     palette_size = cmap_len * (cmap_entry_size / 8);
659
660     if (palette_size > 0) {
661         fprintf(stderr, "File contains a palette - not yet supported.");
662         fseek(fp, palette_size, SEEK_CUR);
663     }
664     return 1;
665 }
666
667 #ifdef OPJ_BIG_ENDIAN
668
669 static INLINE OPJ_UINT16 swap16(OPJ_UINT16 x)
670 {
671     return (OPJ_UINT16)(((x & 0x00ffU) <<  8) | ((x & 0xff00U) >>  8));
672 }
673
674 #endif
675
676 static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height,
677                            OPJ_BOOL flip_image)
678 {
679     OPJ_UINT16 image_w, image_h, us0;
680     unsigned char uc0, image_type;
681     unsigned char pixel_depth, image_desc;
682
683     if (!bits_per_pixel || !width || !height) {
684         return 0;
685     }
686
687     pixel_depth = 0;
688
689     if (bits_per_pixel < 256) {
690         pixel_depth = (unsigned char)bits_per_pixel;
691     } else {
692         fprintf(stderr, "ERROR: Wrong bits per pixel inside tga_header");
693         return 0;
694     }
695     uc0 = 0;
696
697     if (fwrite(&uc0, 1, 1, fp) != 1) {
698         goto fails;    /* id_length */
699     }
700     if (fwrite(&uc0, 1, 1, fp) != 1) {
701         goto fails;    /* colour_map_type */
702     }
703
704     image_type = 2; /* Uncompressed. */
705     if (fwrite(&image_type, 1, 1, fp) != 1) {
706         goto fails;
707     }
708
709     us0 = 0;
710     if (fwrite(&us0, 2, 1, fp) != 1) {
711         goto fails;    /* colour_map_index */
712     }
713     if (fwrite(&us0, 2, 1, fp) != 1) {
714         goto fails;    /* colour_map_length */
715     }
716     if (fwrite(&uc0, 1, 1, fp) != 1) {
717         goto fails;    /* colour_map_entry_size */
718     }
719
720     if (fwrite(&us0, 2, 1, fp) != 1) {
721         goto fails;    /* x_origin */
722     }
723     if (fwrite(&us0, 2, 1, fp) != 1) {
724         goto fails;    /* y_origin */
725     }
726
727     image_w = (unsigned short)width;
728     image_h = (unsigned short) height;
729
730 #ifndef OPJ_BIG_ENDIAN
731     if (fwrite(&image_w, 2, 1, fp) != 1) {
732         goto fails;
733     }
734     if (fwrite(&image_h, 2, 1, fp) != 1) {
735         goto fails;
736     }
737 #else
738     image_w = swap16(image_w);
739     image_h = swap16(image_h);
740     if (fwrite(&image_w, 2, 1, fp) != 1) {
741         goto fails;
742     }
743     if (fwrite(&image_h, 2, 1, fp) != 1) {
744         goto fails;
745     }
746 #endif
747
748     if (fwrite(&pixel_depth, 1, 1, fp) != 1) {
749         goto fails;
750     }
751
752     image_desc = 8; /* 8 bits per component. */
753
754     if (flip_image) {
755         image_desc |= 32;
756     }
757     if (fwrite(&image_desc, 1, 1, fp) != 1) {
758         goto fails;
759     }
760
761     return 1;
762
763 fails:
764     fputs("\nwrite_tgaheader: write ERROR\n", stderr);
765     return 0;
766 }
767
768 opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters)
769 {
770     FILE *f;
771     opj_image_t *image;
772     unsigned int image_width, image_height, pixel_bit_depth;
773     unsigned int x, y;
774     int flip_image = 0;
775     opj_image_cmptparm_t cmptparm[4];   /* maximum 4 components */
776     int numcomps;
777     OPJ_COLOR_SPACE color_space;
778     OPJ_BOOL mono ;
779     OPJ_BOOL save_alpha;
780     int subsampling_dx, subsampling_dy;
781     int i;
782
783     f = fopen(filename, "rb");
784     if (!f) {
785         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
786         return 0;
787     }
788
789     if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height,
790                         &flip_image)) {
791         fclose(f);
792         return NULL;
793     }
794
795     /* We currently only support 24 & 32 bit tga's ... */
796     if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) {
797         fclose(f);
798         return NULL;
799     }
800
801     /* initialize image components */
802     memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
803
804     mono = (pixel_bit_depth == 8) ||
805            (pixel_bit_depth == 16);  /* Mono with & without alpha. */
806     save_alpha = (pixel_bit_depth == 16) ||
807                  (pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
808
809     if (mono) {
810         color_space = OPJ_CLRSPC_GRAY;
811         numcomps = save_alpha ? 2 : 1;
812     } else {
813         numcomps = save_alpha ? 4 : 3;
814         color_space = OPJ_CLRSPC_SRGB;
815     }
816
817     /* If the declared file size is > 10 MB, check that the file is big */
818     /* enough to avoid excessive memory allocations */
819     if (image_height != 0 &&
820             image_width > 10000000U / image_height / (OPJ_UINT32)numcomps) {
821         char ch;
822         OPJ_UINT64 expected_file_size =
823             (OPJ_UINT64)image_width * image_height * (OPJ_UINT32)numcomps;
824         long curpos = ftell(f);
825         if (expected_file_size > (OPJ_UINT64)INT_MAX) {
826             expected_file_size = (OPJ_UINT64)INT_MAX;
827         }
828         fseek(f, (long)expected_file_size - 1, SEEK_SET);
829         if (fread(&ch, 1, 1, f) != 1) {
830             fclose(f);
831             return NULL;
832         }
833         fseek(f, curpos, SEEK_SET);
834     }
835
836     subsampling_dx = parameters->subsampling_dx;
837     subsampling_dy = parameters->subsampling_dy;
838
839     for (i = 0; i < numcomps; i++) {
840         cmptparm[i].prec = 8;
841         cmptparm[i].bpp = 8;
842         cmptparm[i].sgnd = 0;
843         cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
844         cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
845         cmptparm[i].w = image_width;
846         cmptparm[i].h = image_height;
847     }
848
849     /* create the image */
850     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
851
852     if (!image) {
853         fclose(f);
854         return NULL;
855     }
856
857
858     /* set image offset and reference grid */
859     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
860     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
861     image->x1 = !image->x0 ? (OPJ_UINT32)(image_width - 1)  *
862                 (OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1)  *
863                 (OPJ_UINT32)subsampling_dx + 1;
864     image->y1 = !image->y0 ? (OPJ_UINT32)(image_height - 1) *
865                 (OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) *
866                 (OPJ_UINT32)subsampling_dy + 1;
867
868     /* set image data */
869     for (y = 0; y < image_height; y++) {
870         int index;
871
872         if (flip_image) {
873             index = (int)((image_height - y - 1) * image_width);
874         } else {
875             index = (int)(y * image_width);
876         }
877
878         if (numcomps == 3) {
879             for (x = 0; x < image_width; x++) {
880                 unsigned char r, g, b;
881
882                 if (!fread(&b, 1, 1, f)) {
883                     fprintf(stderr,
884                             "\nError: fread return a number of element different from the expected.\n");
885                     opj_image_destroy(image);
886                     fclose(f);
887                     return NULL;
888                 }
889                 if (!fread(&g, 1, 1, f)) {
890                     fprintf(stderr,
891                             "\nError: fread return a number of element different from the expected.\n");
892                     opj_image_destroy(image);
893                     fclose(f);
894                     return NULL;
895                 }
896                 if (!fread(&r, 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
904                 image->comps[0].data[index] = r;
905                 image->comps[1].data[index] = g;
906                 image->comps[2].data[index] = b;
907                 index++;
908             }
909         } else if (numcomps == 4) {
910             for (x = 0; x < image_width; x++) {
911                 unsigned char r, g, b, a;
912                 if (!fread(&b, 1, 1, f)) {
913                     fprintf(stderr,
914                             "\nError: fread return a number of element different from the expected.\n");
915                     opj_image_destroy(image);
916                     fclose(f);
917                     return NULL;
918                 }
919                 if (!fread(&g, 1, 1, f)) {
920                     fprintf(stderr,
921                             "\nError: fread return a number of element different from the expected.\n");
922                     opj_image_destroy(image);
923                     fclose(f);
924                     return NULL;
925                 }
926                 if (!fread(&r, 1, 1, f)) {
927                     fprintf(stderr,
928                             "\nError: fread return a number of element different from the expected.\n");
929                     opj_image_destroy(image);
930                     fclose(f);
931                     return NULL;
932                 }
933                 if (!fread(&a, 1, 1, f)) {
934                     fprintf(stderr,
935                             "\nError: fread return a number of element different from the expected.\n");
936                     opj_image_destroy(image);
937                     fclose(f);
938                     return NULL;
939                 }
940
941                 image->comps[0].data[index] = r;
942                 image->comps[1].data[index] = g;
943                 image->comps[2].data[index] = b;
944                 image->comps[3].data[index] = a;
945                 index++;
946             }
947         } else {
948             fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
949         }
950     }
951     fclose(f);
952     return image;
953 }
954
955 int imagetotga(opj_image_t * image, const char *outfile)
956 {
957     int width, height, bpp, x, y;
958     OPJ_BOOL write_alpha;
959     unsigned int i;
960     int adjustR, adjustG = 0, adjustB = 0, fails;
961     unsigned int alpha_channel;
962     float r, g, b, a;
963     unsigned char value;
964     float scale;
965     FILE *fdest;
966     size_t res;
967     fails = 1;
968
969     fdest = fopen(outfile, "wb");
970     if (!fdest) {
971         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
972         return 1;
973     }
974
975     for (i = 0; i < image->numcomps - 1; i++) {
976         if ((image->comps[0].dx != image->comps[i + 1].dx)
977                 || (image->comps[0].dy != image->comps[i + 1].dy)
978                 || (image->comps[0].prec != image->comps[i + 1].prec)
979                 || (image->comps[0].sgnd != image->comps[i + 1].sgnd)) {
980             fclose(fdest);
981             fprintf(stderr,
982                     "Unable to create a tga file with such J2K image charateristics.\n");
983             return 1;
984         }
985     }
986
987     width  = (int)image->comps[0].w;
988     height = (int)image->comps[0].h;
989
990     /* Mono with alpha, or RGB with alpha. */
991     write_alpha = (image->numcomps == 2) || (image->numcomps == 4);
992
993     /* Write TGA header  */
994     bpp = write_alpha ? 32 : 24;
995
996     if (!tga_writeheader(fdest, bpp, width, height, OPJ_TRUE)) {
997         goto fin;
998     }
999
1000     alpha_channel = image->numcomps - 1;
1001
1002     scale = 255.0f / (float)((1 << image->comps[0].prec) - 1);
1003
1004     adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1005     if (image->numcomps >= 3) {
1006         adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1007         adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1008     }
1009
1010     for (y = 0; y < height; y++) {
1011         unsigned int index = (unsigned int)(y * width);
1012
1013         for (x = 0; x < width; x++, index++) {
1014             r = (float)(image->comps[0].data[index] + adjustR);
1015
1016             if (image->numcomps > 2) {
1017                 g = (float)(image->comps[1].data[index] + adjustG);
1018                 b = (float)(image->comps[2].data[index] + adjustB);
1019             } else {
1020                 /* Greyscale ... */
1021                 g = r;
1022                 b = r;
1023             }
1024
1025             /* TGA format writes BGR ... */
1026             if (b > 255.) {
1027                 b = 255.;
1028             } else if (b < 0.) {
1029                 b = 0.;
1030             }
1031             value = (unsigned char)(b * scale);
1032             res = fwrite(&value, 1, 1, fdest);
1033
1034             if (res < 1) {
1035                 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
1036                 goto fin;
1037             }
1038             if (g > 255.) {
1039                 g = 255.;
1040             } else if (g < 0.) {
1041                 g = 0.;
1042             }
1043             value = (unsigned char)(g * scale);
1044             res = fwrite(&value, 1, 1, fdest);
1045
1046             if (res < 1) {
1047                 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
1048                 goto fin;
1049             }
1050             if (r > 255.) {
1051                 r = 255.;
1052             } else if (r < 0.) {
1053                 r = 0.;
1054             }
1055             value = (unsigned char)(r * scale);
1056             res = fwrite(&value, 1, 1, fdest);
1057
1058             if (res < 1) {
1059                 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
1060                 goto fin;
1061             }
1062
1063             if (write_alpha) {
1064                 a = (float)(image->comps[alpha_channel].data[index]);
1065                 if (a > 255.) {
1066                     a = 255.;
1067                 } else if (a < 0.) {
1068                     a = 0.;
1069                 }
1070                 value = (unsigned char)(a * scale);
1071                 res = fwrite(&value, 1, 1, fdest);
1072
1073                 if (res < 1) {
1074                     fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
1075                     goto fin;
1076                 }
1077             }
1078         }
1079     }
1080     fails = 0;
1081 fin:
1082     fclose(fdest);
1083
1084     return fails;
1085 }
1086
1087 /* -->> -->> -->> -->>
1088
1089 PGX IMAGE FORMAT
1090
1091 <<-- <<-- <<-- <<-- */
1092
1093
1094 static unsigned char readuchar(FILE * f)
1095 {
1096     unsigned char c1;
1097     if (!fread(&c1, 1, 1, f)) {
1098         fprintf(stderr,
1099                 "\nError: fread return a number of element different from the expected.\n");
1100         return 0;
1101     }
1102     return c1;
1103 }
1104
1105 static unsigned short readushort(FILE * f, int bigendian)
1106 {
1107     unsigned char c1, c2;
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 (bigendian) {
1119         return (unsigned short)((c1 << 8) + c2);
1120     } else {
1121         return (unsigned short)((c2 << 8) + c1);
1122     }
1123 }
1124
1125 static unsigned int readuint(FILE * f, int bigendian)
1126 {
1127     unsigned char c1, c2, c3, c4;
1128     if (!fread(&c1, 1, 1, f)) {
1129         fprintf(stderr,
1130                 "\nError: fread return a number of element different from the expected.\n");
1131         return 0;
1132     }
1133     if (!fread(&c2, 1, 1, f)) {
1134         fprintf(stderr,
1135                 "\nError: fread return a number of element different from the expected.\n");
1136         return 0;
1137     }
1138     if (!fread(&c3, 1, 1, f)) {
1139         fprintf(stderr,
1140                 "\nError: fread return a number of element different from the expected.\n");
1141         return 0;
1142     }
1143     if (!fread(&c4, 1, 1, f)) {
1144         fprintf(stderr,
1145                 "\nError: fread return a number of element different from the expected.\n");
1146         return 0;
1147     }
1148     if (bigendian) {
1149         return (unsigned int)(c1 << 24) + (unsigned int)(c2 << 16) + (unsigned int)(
1150                    c3 << 8) + c4;
1151     } else {
1152         return (unsigned int)(c4 << 24) + (unsigned int)(c3 << 16) + (unsigned int)(
1153                    c2 << 8) + c1;
1154     }
1155 }
1156
1157 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters)
1158 {
1159     FILE *f = NULL;
1160     int w, h, prec;
1161     int i, numcomps, max;
1162     OPJ_COLOR_SPACE color_space;
1163     opj_image_cmptparm_t cmptparm;  /* maximum of 1 component  */
1164     opj_image_t * image = NULL;
1165     int adjustS, ushift, dshift, force8;
1166
1167     char endian1, endian2, sign;
1168     char signtmp[32];
1169
1170     char temp[32];
1171     int bigendian;
1172     opj_image_comp_t *comp = NULL;
1173
1174     numcomps = 1;
1175     color_space = OPJ_CLRSPC_GRAY;
1176
1177     memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
1178
1179     max = 0;
1180
1181     f = fopen(filename, "rb");
1182     if (!f) {
1183         fprintf(stderr, "Failed to open %s for reading !\n", filename);
1184         return NULL;
1185     }
1186
1187     fseek(f, 0, SEEK_SET);
1188     if (fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d", temp, &endian1,
1189                &endian2, signtmp, &prec, temp, &w, temp, &h) != 9) {
1190         fclose(f);
1191         fprintf(stderr,
1192                 "ERROR: Failed to read the right number of element from the fscanf() function!\n");
1193         return NULL;
1194     }
1195
1196     i = 0;
1197     sign = '+';
1198     while (signtmp[i] != '\0') {
1199         if (signtmp[i] == '-') {
1200             sign = '-';
1201         }
1202         i++;
1203     }
1204
1205     fgetc(f);
1206     if (endian1 == 'M' && endian2 == 'L') {
1207         bigendian = 1;
1208     } else if (endian2 == 'M' && endian1 == 'L') {
1209         bigendian = 0;
1210     } else {
1211         fclose(f);
1212         fprintf(stderr, "Bad pgx header, please check input file\n");
1213         return NULL;
1214     }
1215
1216     /* initialize image component */
1217
1218     cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
1219     cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
1220     cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx +
1221                  1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx
1222                  + 1;
1223     cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy +
1224                  1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy
1225                  + 1;
1226
1227     if (sign == '-') {
1228         cmptparm.sgnd = 1;
1229     } else {
1230         cmptparm.sgnd = 0;
1231     }
1232     if (prec < 8) {
1233         force8 = 1;
1234         ushift = 8 - prec;
1235         dshift = prec - ushift;
1236         if (cmptparm.sgnd) {
1237             adjustS = (1 << (prec - 1));
1238         } else {
1239             adjustS = 0;
1240         }
1241         cmptparm.sgnd = 0;
1242         prec = 8;
1243     } else {
1244         ushift = dshift = force8 = adjustS = 0;
1245     }
1246
1247     cmptparm.prec = (OPJ_UINT32)prec;
1248     cmptparm.bpp = (OPJ_UINT32)prec;
1249     cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
1250     cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;
1251
1252     /* create the image */
1253     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
1254     if (!image) {
1255         fclose(f);
1256         return NULL;
1257     }
1258     /* set image offset and reference grid */
1259     image->x0 = cmptparm.x0;
1260     image->y0 = cmptparm.x0;
1261     image->x1 = cmptparm.w;
1262     image->y1 = cmptparm.h;
1263
1264     /* set image data */
1265
1266     comp = &image->comps[0];
1267
1268     for (i = 0; i < w * h; i++) {
1269         int v;
1270         if (force8) {
1271             v = readuchar(f) + adjustS;
1272             v = (v << ushift) + (v >> dshift);
1273             comp->data[i] = (unsigned char)v;
1274
1275             if (v > max) {
1276                 max = v;
1277             }
1278
1279             continue;
1280         }
1281         if (comp->prec == 8) {
1282             if (!comp->sgnd) {
1283                 v = readuchar(f);
1284             } else {
1285                 v = (char) readuchar(f);
1286             }
1287         } else if (comp->prec <= 16) {
1288             if (!comp->sgnd) {
1289                 v = readushort(f, bigendian);
1290             } else {
1291                 v = (short) readushort(f, bigendian);
1292             }
1293         } else {
1294             if (!comp->sgnd) {
1295                 v = (int)readuint(f, bigendian);
1296             } else {
1297                 v = (int) readuint(f, bigendian);
1298             }
1299         }
1300         if (v > max) {
1301             max = v;
1302         }
1303         comp->data[i] = v;
1304     }
1305     fclose(f);
1306     comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;
1307
1308     return image;
1309 }
1310
1311 #define CLAMP(x,a,b) x < a ? a : (x > b ? b : x)
1312
1313 static INLINE int clamp(const int value, const int prec, const int sgnd)
1314 {
1315     if (sgnd) {
1316         if (prec <= 8) {
1317             return CLAMP(value, -128, 127);
1318         } else if (prec <= 16) {
1319             return CLAMP(value, -32768, 32767);
1320         } else {
1321             return CLAMP(value, -2147483647 - 1, 2147483647);
1322         }
1323     } else {
1324         if (prec <= 8) {
1325             return CLAMP(value, 0, 255);
1326         } else if (prec <= 16) {
1327             return CLAMP(value, 0, 65535);
1328         } else {
1329             return value;    /*CLAMP(value,0,4294967295);*/
1330         }
1331     }
1332 }
1333
1334 int imagetopgx(opj_image_t * image, const char *outfile)
1335 {
1336     int w, h;
1337     int i, j, fails = 1;
1338     unsigned int compno;
1339     FILE *fdest = NULL;
1340
1341     for (compno = 0; compno < image->numcomps; compno++) {
1342         opj_image_comp_t *comp = &image->comps[compno];
1343         char bname[256]; /* buffer for name */
1344         char *name = bname; /* pointer */
1345         int nbytes = 0;
1346         size_t res;
1347         const size_t olen = strlen(outfile);
1348         const size_t dotpos = olen - 4;
1349         const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
1350
1351         if (outfile[dotpos] != '.') {
1352             /* `pgx` was recognized but there is no dot at expected position */
1353             fprintf(stderr, "ERROR -> Impossible happen.");
1354             goto fin;
1355         }
1356         if (total > 256) {
1357             name = (char*)malloc(total + 1);
1358             if (name == NULL) {
1359                 fprintf(stderr, "imagetopgx: memory out\n");
1360                 goto fin;
1361             }
1362         }
1363         strncpy(name, outfile, dotpos);
1364         sprintf(name + dotpos, "_%u.pgx", compno);
1365         fdest = fopen(name, "wb");
1366         /* don't need name anymore */
1367
1368         if (!fdest) {
1369
1370             fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
1371             if (total > 256) {
1372                 free(name);
1373             }
1374             goto fin;
1375         }
1376
1377         w = (int)image->comps[compno].w;
1378         h = (int)image->comps[compno].h;
1379
1380         fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
1381                 w, h);
1382
1383         if (comp->prec <= 8) {
1384             nbytes = 1;
1385         } else if (comp->prec <= 16) {
1386             nbytes = 2;
1387         } else {
1388             nbytes = 4;
1389         }
1390
1391         for (i = 0; i < w * h; i++) {
1392             /* FIXME: clamp func is being called within a loop */
1393             const int val = clamp(image->comps[compno].data[i],
1394                                   (int)comp->prec, (int)comp->sgnd);
1395
1396             for (j = nbytes - 1; j >= 0; j--) {
1397                 int v = (int)(val >> (j * 8));
1398                 unsigned char byte = (unsigned char)v;
1399                 res = fwrite(&byte, 1, 1, fdest);
1400
1401                 if (res < 1) {
1402                     fprintf(stderr, "failed to write 1 byte for %s\n", name);
1403                     if (total > 256) {
1404                         free(name);
1405                     }
1406                     goto fin;
1407                 }
1408             }
1409         }
1410         if (total > 256) {
1411             free(name);
1412         }
1413         fclose(fdest);
1414         fdest = NULL;
1415     }
1416     fails = 0;
1417 fin:
1418     if (fdest) {
1419         fclose(fdest);
1420     }
1421
1422     return fails;
1423 }
1424
1425 /* -->> -->> -->> -->>
1426
1427 PNM IMAGE FORMAT
1428
1429 <<-- <<-- <<-- <<-- */
1430
1431 struct pnm_header {
1432     int width, height, maxval, depth, format;
1433     char rgb, rgba, gray, graya, bw;
1434     char ok;
1435 };
1436
1437 static char *skip_white(char *s)
1438 {
1439     if (s != NULL) {
1440         while (*s) {
1441             if (*s == '\n' || *s == '\r') {
1442                 return NULL;
1443             }
1444             if (isspace(*s)) {
1445                 ++s;
1446                 continue;
1447             }
1448             return s;
1449         }
1450     }
1451     return NULL;
1452 }
1453
1454 static char *skip_int(char *start, int *out_n)
1455 {
1456     char *s;
1457     char c;
1458
1459     *out_n = 0;
1460
1461     s = skip_white(start);
1462     if (s == NULL) {
1463         return NULL;
1464     }
1465     start = s;
1466
1467     while (*s) {
1468         if (!isdigit(*s)) {
1469             break;
1470         }
1471         ++s;
1472     }
1473     c = *s;
1474     *s = 0;
1475     *out_n = atoi(start);
1476     *s = c;
1477     return s;
1478 }
1479
1480 static char *skip_idf(char *start, char out_idf[256])
1481 {
1482     char *s;
1483     char c;
1484
1485     s = skip_white(start);
1486     if (s == NULL) {
1487         return NULL;
1488     }
1489     start = s;
1490
1491     while (*s) {
1492         if (isalpha(*s) || *s == '_') {
1493             ++s;
1494             continue;
1495         }
1496         break;
1497     }
1498     c = *s;
1499     *s = 0;
1500     strncpy(out_idf, start, 255);
1501     *s = c;
1502     return s;
1503 }
1504
1505 static void read_pnm_header(FILE *reader, struct pnm_header *ph)
1506 {
1507     int format, end, ttype;
1508     char idf[256], type[256];
1509     char line[256];
1510
1511     if (fgets(line, 250, reader) == NULL) {
1512         fprintf(stderr, "\nWARNING: fgets return a NULL value");
1513         return;
1514     }
1515
1516     if (line[0] != 'P') {
1517         fprintf(stderr, "read_pnm_header:PNM:magic P missing\n");
1518         return;
1519     }
1520     format = atoi(line + 1);
1521     if (format < 1 || format > 7) {
1522         fprintf(stderr, "read_pnm_header:magic format %d invalid\n", format);
1523         return;
1524     }
1525     ph->format = format;
1526     ttype = end = 0;
1527
1528     while (fgets(line, 250, reader)) {
1529         char *s;
1530         int allow_null = 0;
1531
1532         if (*line == '#') {
1533             continue;
1534         }
1535
1536         s = line;
1537
1538         if (format == 7) {
1539             s = skip_idf(s, idf);
1540
1541             if (s == NULL || *s == 0) {
1542                 return;
1543             }
1544
1545             if (strcmp(idf, "ENDHDR") == 0) {
1546                 end = 1;
1547                 break;
1548             }
1549             if (strcmp(idf, "WIDTH") == 0) {
1550                 s = skip_int(s, &ph->width);
1551                 if (s == NULL || *s == 0) {
1552                     return;
1553                 }
1554
1555                 continue;
1556             }
1557             if (strcmp(idf, "HEIGHT") == 0) {
1558                 s = skip_int(s, &ph->height);
1559                 if (s == NULL || *s == 0) {
1560                     return;
1561                 }
1562
1563                 continue;
1564             }
1565             if (strcmp(idf, "DEPTH") == 0) {
1566                 s = skip_int(s, &ph->depth);
1567                 if (s == NULL || *s == 0) {
1568                     return;
1569                 }
1570
1571                 continue;
1572             }
1573             if (strcmp(idf, "MAXVAL") == 0) {
1574                 s = skip_int(s, &ph->maxval);
1575                 if (s == NULL || *s == 0) {
1576                     return;
1577                 }
1578
1579                 continue;
1580             }
1581             if (strcmp(idf, "TUPLTYPE") == 0) {
1582                 s = skip_idf(s, type);
1583                 if (s == NULL || *s == 0) {
1584                     return;
1585                 }
1586
1587                 if (strcmp(type, "BLACKANDWHITE") == 0) {
1588                     ph->bw = 1;
1589                     ttype = 1;
1590                     continue;
1591                 }
1592                 if (strcmp(type, "GRAYSCALE") == 0) {
1593                     ph->gray = 1;
1594                     ttype = 1;
1595                     continue;
1596                 }
1597                 if (strcmp(type, "GRAYSCALE_ALPHA") == 0) {
1598                     ph->graya = 1;
1599                     ttype = 1;
1600                     continue;
1601                 }
1602                 if (strcmp(type, "RGB") == 0) {
1603                     ph->rgb = 1;
1604                     ttype = 1;
1605                     continue;
1606                 }
1607                 if (strcmp(type, "RGB_ALPHA") == 0) {
1608                     ph->rgba = 1;
1609                     ttype = 1;
1610                     continue;
1611                 }
1612                 fprintf(stderr, "read_pnm_header:unknown P7 TUPLTYPE %s\n", type);
1613                 return;
1614             }
1615             fprintf(stderr, "read_pnm_header:unknown P7 idf %s\n", idf);
1616             return;
1617         } /* if(format == 7) */
1618
1619         /* Here format is in range [1,6] */
1620         if (ph->width == 0) {
1621             s = skip_int(s, &ph->width);
1622             if ((s == NULL) || (*s == 0) || (ph->width < 1)) {
1623                 return;
1624             }
1625             allow_null = 1;
1626         }
1627         if (ph->height == 0) {
1628             s = skip_int(s, &ph->height);
1629             if ((s == NULL) && allow_null) {
1630                 continue;
1631             }
1632             if ((s == NULL) || (*s == 0) || (ph->height < 1)) {
1633                 return;
1634             }
1635             if (format == 1 || format == 4) {
1636                 break;
1637             }
1638             allow_null = 1;
1639         }
1640         /* here, format is in P2, P3, P5, P6 */
1641         s = skip_int(s, &ph->maxval);
1642         if ((s == NULL) && allow_null) {
1643             continue;
1644         }
1645         if ((s == NULL) || (*s == 0)) {
1646             return;
1647         }
1648         break;
1649     }/* while(fgets( ) */
1650     if (format == 2 || format == 3 || format > 4) {
1651         if (ph->maxval < 1 || ph->maxval > 65535) {
1652             return;
1653         }
1654     }
1655     if (ph->width < 1 || ph->height < 1) {
1656         return;
1657     }
1658
1659     if (format == 7) {
1660         if (!end) {
1661             fprintf(stderr, "read_pnm_header:P7 without ENDHDR\n");
1662             return;
1663         }
1664         if (ph->depth < 1 || ph->depth > 4) {
1665             return;
1666         }
1667
1668         if (ttype) {
1669             ph->ok = 1;
1670         }
1671     } else {
1672         ph->ok = 1;
1673         if (format == 1 || format == 4) {
1674             ph->maxval = 255;
1675         }
1676     }
1677 }
1678
1679 static int has_prec(int val)
1680 {
1681     if (val < 2) {
1682         return 1;
1683     }
1684     if (val < 4) {
1685         return 2;
1686     }
1687     if (val < 8) {
1688         return 3;
1689     }
1690     if (val < 16) {
1691         return 4;
1692     }
1693     if (val < 32) {
1694         return 5;
1695     }
1696     if (val < 64) {
1697         return 6;
1698     }
1699     if (val < 128) {
1700         return 7;
1701     }
1702     if (val < 256) {
1703         return 8;
1704     }
1705     if (val < 512) {
1706         return 9;
1707     }
1708     if (val < 1024) {
1709         return 10;
1710     }
1711     if (val < 2048) {
1712         return 11;
1713     }
1714     if (val < 4096) {
1715         return 12;
1716     }
1717     if (val < 8192) {
1718         return 13;
1719     }
1720     if (val < 16384) {
1721         return 14;
1722     }
1723     if (val < 32768) {
1724         return 15;
1725     }
1726     return 16;
1727 }
1728
1729 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters)
1730 {
1731     int subsampling_dx = parameters->subsampling_dx;
1732     int subsampling_dy = parameters->subsampling_dy;
1733
1734     FILE *fp = NULL;
1735     int i, compno, numcomps, w, h, prec, format;
1736     OPJ_COLOR_SPACE color_space;
1737     opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
1738     opj_image_t * image = NULL;
1739     struct pnm_header header_info;
1740
1741     if ((fp = fopen(filename, "rb")) == NULL) {
1742         fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n", filename);
1743         return NULL;
1744     }
1745     memset(&header_info, 0, sizeof(struct pnm_header));
1746
1747     read_pnm_header(fp, &header_info);
1748
1749     if (!header_info.ok) {
1750         fclose(fp);
1751         return NULL;
1752     }
1753
1754     /* This limitation could be removed by making sure to use size_t below */
1755     if (header_info.height != 0 &&
1756             header_info.width > INT_MAX / header_info.height) {
1757         fprintf(stderr, "pnmtoimage:Image %dx%d too big!\n",
1758                 header_info.width, header_info.height);
1759         fclose(fp);
1760         return NULL;
1761     }
1762
1763     format = header_info.format;
1764
1765     switch (format) {
1766     case 1: /* ascii bitmap */
1767     case 4: /* raw bitmap */
1768         numcomps = 1;
1769         break;
1770
1771     case 2: /* ascii greymap */
1772     case 5: /* raw greymap */
1773         numcomps = 1;
1774         break;
1775
1776     case 3: /* ascii pixmap */
1777     case 6: /* raw pixmap */
1778         numcomps = 3;
1779         break;
1780
1781     case 7: /* arbitrary map */
1782         numcomps = header_info.depth;
1783         break;
1784
1785     default:
1786         fclose(fp);
1787         return NULL;
1788     }
1789     if (numcomps < 3) {
1790         color_space = OPJ_CLRSPC_GRAY;    /* GRAY, GRAYA */
1791     } else {
1792         color_space = OPJ_CLRSPC_SRGB;    /* RGB, RGBA */
1793     }
1794
1795     prec = has_prec(header_info.maxval);
1796
1797     if (prec < 8) {
1798         prec = 8;
1799     }
1800
1801     w = header_info.width;
1802     h = header_info.height;
1803     subsampling_dx = parameters->subsampling_dx;
1804     subsampling_dy = parameters->subsampling_dy;
1805
1806     memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
1807
1808     for (i = 0; i < numcomps; i++) {
1809         cmptparm[i].prec = (OPJ_UINT32)prec;
1810         cmptparm[i].bpp = (OPJ_UINT32)prec;
1811         cmptparm[i].sgnd = 0;
1812         cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
1813         cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
1814         cmptparm[i].w = (OPJ_UINT32)w;
1815         cmptparm[i].h = (OPJ_UINT32)h;
1816     }
1817     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
1818
1819     if (!image) {
1820         fclose(fp);
1821         return NULL;
1822     }
1823
1824     /* set image offset and reference grid */
1825     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
1826     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
1827     image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx
1828                              + 1);
1829     image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy
1830                              + 1);
1831
1832     if ((format == 2) || (format == 3)) { /* ascii pixmap */
1833         unsigned int index;
1834
1835         for (i = 0; i < w * h; i++) {
1836             for (compno = 0; compno < numcomps; compno++) {
1837                 index = 0;
1838                 if (fscanf(fp, "%u", &index) != 1) {
1839                     fprintf(stderr,
1840                             "\nWARNING: fscanf return a number of element different from the expected.\n");
1841                 }
1842
1843                 image->comps[compno].data[i] = (OPJ_INT32)(index * 255) / header_info.maxval;
1844             }
1845         }
1846     } else if ((format == 5)
1847                || (format == 6)
1848                || ((format == 7)
1849                    && (header_info.gray || header_info.graya
1850                        || header_info.rgb || header_info.rgba))) { /* binary pixmap */
1851         unsigned char c0, c1, one;
1852
1853         one = (prec < 9);
1854
1855         for (i = 0; i < w * h; i++) {
1856             for (compno = 0; compno < numcomps; compno++) {
1857                 if (!fread(&c0, 1, 1, fp)) {
1858                     fprintf(stderr,
1859                             "\nError: fread return a number of element different from the expected.\n");
1860                     opj_image_destroy(image);
1861                     fclose(fp);
1862                     return NULL;
1863                 }
1864                 if (one) {
1865                     image->comps[compno].data[i] = c0;
1866                 } else {
1867                     if (!fread(&c1, 1, 1, fp)) {
1868                         fprintf(stderr,
1869                                 "\nError: fread return a number of element different from the expected.\n");
1870                     }
1871                     /* netpbm: */
1872                     image->comps[compno].data[i] = ((c0 << 8) | c1);
1873                 }
1874             }
1875         }
1876     } else if (format == 1) { /* ascii bitmap */
1877         for (i = 0; i < w * h; i++) {
1878             unsigned int index;
1879
1880             if (fscanf(fp, "%u", &index) != 1) {
1881                 fprintf(stderr,
1882                         "\nWARNING: fscanf return a number of element different from the expected.\n");
1883             }
1884
1885             image->comps[0].data[i] = (index ? 0 : 255);
1886         }
1887     } else if (format == 4) {
1888         int x, y, bit;
1889         unsigned char uc;
1890
1891         i = 0;
1892         for (y = 0; y < h; ++y) {
1893             bit = -1;
1894             uc = 0;
1895
1896             for (x = 0; x < w; ++x) {
1897                 if (bit == -1) {
1898                     bit = 7;
1899                     uc = (unsigned char)getc(fp);
1900                 }
1901                 image->comps[0].data[i] = (((uc >> bit) & 1) ? 0 : 255);
1902                 --bit;
1903                 ++i;
1904             }
1905         }
1906     } else if ((format == 7 && header_info.bw)) { /*MONO*/
1907         unsigned char uc;
1908
1909         for (i = 0; i < w * h; ++i) {
1910             if (!fread(&uc, 1, 1, fp)) {
1911                 fprintf(stderr,
1912                         "\nError: fread return a number of element different from the expected.\n");
1913             }
1914             image->comps[0].data[i] = (uc & 1) ? 0 : 255;
1915         }
1916     }
1917     fclose(fp);
1918
1919     return image;
1920 }/* pnmtoimage() */
1921
1922 static int are_comps_similar(opj_image_t * image)
1923 {
1924     unsigned int i;
1925     for (i = 1; i < image->numcomps; i++) {
1926         if (image->comps[0].dx != image->comps[i].dx ||
1927                 image->comps[0].dy != image->comps[i].dy ||
1928                 (i <= 2 &&
1929                  (image->comps[0].prec != image->comps[i].prec ||
1930                   image->comps[0].sgnd != image->comps[i].sgnd))) {
1931             return OPJ_FALSE;
1932         }
1933     }
1934     return OPJ_TRUE;
1935 }
1936
1937
1938 int imagetopnm(opj_image_t * image, const char *outfile, int force_split)
1939 {
1940     int *red, *green, *blue, *alpha;
1941     int wr, hr, max;
1942     int i;
1943     unsigned int compno, ncomp;
1944     int adjustR, adjustG, adjustB, adjustA;
1945     int fails, two, want_gray, has_alpha, triple;
1946     int prec, v;
1947     FILE *fdest = NULL;
1948     const char *tmp = outfile;
1949     char *destname;
1950
1951     alpha = NULL;
1952
1953     if ((prec = (int)image->comps[0].prec) > 16) {
1954         fprintf(stderr, "%s:%d:imagetopnm\n\tprecision %d is larger than 16"
1955                 "\n\t: refused.\n", __FILE__, __LINE__, prec);
1956         return 1;
1957     }
1958     two = has_alpha = 0;
1959     fails = 1;
1960     ncomp = image->numcomps;
1961
1962     while (*tmp) {
1963         ++tmp;
1964     }
1965     tmp -= 2;
1966     want_gray = (*tmp == 'g' || *tmp == 'G');
1967     ncomp = image->numcomps;
1968
1969     if (want_gray) {
1970         ncomp = 1;
1971     }
1972
1973     if ((force_split == 0) && ncomp >= 2 &&
1974             are_comps_similar(image)) {
1975         fdest = fopen(outfile, "wb");
1976
1977         if (!fdest) {
1978             fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1979             return fails;
1980         }
1981         two = (prec > 8);
1982         triple = (ncomp > 2);
1983         wr = (int)image->comps[0].w;
1984         hr = (int)image->comps[0].h;
1985         max = (1 << prec) - 1;
1986         has_alpha = (ncomp == 4 || ncomp == 2);
1987
1988         red = image->comps[0].data;
1989
1990         if (triple) {
1991             green = image->comps[1].data;
1992             blue = image->comps[2].data;
1993         } else {
1994             green = blue = NULL;
1995         }
1996
1997         if (has_alpha) {
1998             const char *tt = (triple ? "RGB_ALPHA" : "GRAYSCALE_ALPHA");
1999
2000             fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %u\n"
2001                     "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
2002                     wr, hr, ncomp, max, tt);
2003             alpha = image->comps[ncomp - 1].data;
2004             adjustA = (image->comps[ncomp - 1].sgnd ?
2005                        1 << (image->comps[ncomp - 1].prec - 1) : 0);
2006         } else {
2007             fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
2008                     opj_version(), wr, hr, max);
2009             adjustA = 0;
2010         }
2011         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
2012
2013         if (triple) {
2014             adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
2015             adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
2016         } else {
2017             adjustG = adjustB = 0;
2018         }
2019
2020         for (i = 0; i < wr * hr; ++i) {
2021             if (two) {
2022                 v = *red + adjustR;
2023                 ++red;
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                 if (triple) {
2034                     v = *green + adjustG;
2035                     ++green;
2036                     if (v > 65535) {
2037                         v = 65535;
2038                     } else if (v < 0) {
2039                         v = 0;
2040                     }
2041
2042                     /* netpbm: */
2043                     fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
2044
2045                     v =  *blue + adjustB;
2046                     ++blue;
2047                     if (v > 65535) {
2048                         v = 65535;
2049                     } else if (v < 0) {
2050                         v = 0;
2051                     }
2052
2053                     /* netpbm: */
2054                     fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
2055
2056                 }/* if(triple) */
2057
2058                 if (has_alpha) {
2059                     v = *alpha + adjustA;
2060                     ++alpha;
2061                     if (v > 65535) {
2062                         v = 65535;
2063                     } else if (v < 0) {
2064                         v = 0;
2065                     }
2066
2067                     /* netpbm: */
2068                     fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
2069                 }
2070                 continue;
2071
2072             }   /* if(two) */
2073
2074             /* prec <= 8: */
2075             v = *red++;
2076             if (v > 255) {
2077                 v = 255;
2078             } else if (v < 0) {
2079                 v = 0;
2080             }
2081
2082             fprintf(fdest, "%c", (unsigned char)v);
2083             if (triple) {
2084                 v = *green++;
2085                 if (v > 255) {
2086                     v = 255;
2087                 } else if (v < 0) {
2088                     v = 0;
2089                 }
2090
2091                 fprintf(fdest, "%c", (unsigned char)v);
2092                 v = *blue++;
2093                 if (v > 255) {
2094                     v = 255;
2095                 } else if (v < 0) {
2096                     v = 0;
2097                 }
2098
2099                 fprintf(fdest, "%c", (unsigned char)v);
2100             }
2101             if (has_alpha) {
2102                 v = *alpha++;
2103                 if (v > 255) {
2104                     v = 255;
2105                 } else if (v < 0) {
2106                     v = 0;
2107                 }
2108
2109                 fprintf(fdest, "%c", (unsigned char)v);
2110             }
2111         }   /* for(i */
2112
2113         fclose(fdest);
2114         return 0;
2115     }
2116
2117     /* YUV or MONO: */
2118
2119     if (image->numcomps > ncomp) {
2120         fprintf(stderr, "WARNING -> [PGM file] Only the first component\n");
2121         fprintf(stderr, "           is written to the file\n");
2122     }
2123     destname = (char*)malloc(strlen(outfile) + 8);
2124     if (destname == NULL) {
2125         fprintf(stderr, "imagetopnm: memory out\n");
2126         return 1;
2127     }
2128     for (compno = 0; compno < ncomp; compno++) {
2129         if (ncomp > 1) {
2130             /*sprintf(destname, "%d.%s", compno, outfile);*/
2131             const size_t olen = strlen(outfile);
2132             const size_t dotpos = olen - 4;
2133
2134             strncpy(destname, outfile, dotpos);
2135             sprintf(destname + dotpos, "_%u.pgm", compno);
2136         } else {
2137             sprintf(destname, "%s", outfile);
2138         }
2139
2140         fdest = fopen(destname, "wb");
2141         if (!fdest) {
2142             fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
2143             free(destname);
2144             return 1;
2145         }
2146         wr = (int)image->comps[compno].w;
2147         hr = (int)image->comps[compno].h;
2148         prec = (int)image->comps[compno].prec;
2149         max = (1 << prec) - 1;
2150
2151         fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
2152                 opj_version(), wr, hr, max);
2153
2154         red = image->comps[compno].data;
2155         adjustR =
2156             (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
2157
2158         if (prec > 8) {
2159             for (i = 0; i < wr * hr; i++) {
2160                 v = *red + adjustR;
2161                 ++red;
2162                 if (v > 65535) {
2163                     v = 65535;
2164                 } else if (v < 0) {
2165                     v = 0;
2166                 }
2167
2168                 /* netpbm: */
2169                 fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
2170
2171                 if (has_alpha) {
2172                     v = *alpha++;
2173                     if (v > 65535) {
2174                         v = 65535;
2175                     } else if (v < 0) {
2176                         v = 0;
2177                     }
2178
2179                     /* netpbm: */
2180                     fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
2181                 }
2182             }/* for(i */
2183         } else { /* prec <= 8 */
2184             for (i = 0; i < wr * hr; ++i) {
2185                 v = *red + adjustR;
2186                 ++red;
2187                 if (v > 255) {
2188                     v = 255;
2189                 } else if (v < 0) {
2190                     v = 0;
2191                 }
2192
2193                 fprintf(fdest, "%c", (unsigned char)v);
2194             }
2195         }
2196         fclose(fdest);
2197     } /* for (compno */
2198     free(destname);
2199
2200     return 0;
2201 }/* imagetopnm() */
2202
2203 /* -->> -->> -->> -->>
2204
2205     RAW IMAGE FORMAT
2206
2207  <<-- <<-- <<-- <<-- */
2208 static opj_image_t* rawtoimage_common(const char *filename,
2209                                       opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian)
2210 {
2211     int subsampling_dx = parameters->subsampling_dx;
2212     int subsampling_dy = parameters->subsampling_dy;
2213
2214     FILE *f = NULL;
2215     int i, compno, numcomps, w, h;
2216     OPJ_COLOR_SPACE color_space;
2217     opj_image_cmptparm_t *cmptparm;
2218     opj_image_t * image = NULL;
2219     unsigned short ch;
2220
2221     if ((!(raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp &
2222             raw_cp->rawBitDepth)) == 0) {
2223         fprintf(stderr, "\nError: invalid raw image parameters\n");
2224         fprintf(stderr, "Please use the Format option -F:\n");
2225         fprintf(stderr,
2226                 "-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
2227         fprintf(stderr,
2228                 "If subsampling is omitted, 1x1 is assumed for all components\n");
2229         fprintf(stderr,
2230                 "Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
2231         fprintf(stderr, "         for raw 512x512 image with 4:2:0 subsampling\n");
2232         fprintf(stderr, "Aborting.\n");
2233         return NULL;
2234     }
2235
2236     f = fopen(filename, "rb");
2237     if (!f) {
2238         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
2239         fprintf(stderr, "Aborting\n");
2240         return NULL;
2241     }
2242     numcomps = raw_cp->rawComp;
2243
2244     /* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
2245     if (numcomps == 1) {
2246         color_space = OPJ_CLRSPC_GRAY;
2247     } else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
2248         color_space = OPJ_CLRSPC_SYCC;
2249     } else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
2250         color_space = OPJ_CLRSPC_SRGB;
2251     } else {
2252         color_space = OPJ_CLRSPC_UNKNOWN;
2253     }
2254     w = raw_cp->rawWidth;
2255     h = raw_cp->rawHeight;
2256     cmptparm = (opj_image_cmptparm_t*) calloc((OPJ_UINT32)numcomps,
2257                sizeof(opj_image_cmptparm_t));
2258     if (!cmptparm) {
2259         fprintf(stderr, "Failed to allocate image components parameters !!\n");
2260         fprintf(stderr, "Aborting\n");
2261         fclose(f);
2262         return NULL;
2263     }
2264     /* initialize image components */
2265     for (i = 0; i < numcomps; i++) {
2266         cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
2267         cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
2268         cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
2269         cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
2270         cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
2271         cmptparm[i].w = (OPJ_UINT32)w;
2272         cmptparm[i].h = (OPJ_UINT32)h;
2273     }
2274     /* create the image */
2275     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2276     free(cmptparm);
2277     if (!image) {
2278         fclose(f);
2279         return NULL;
2280     }
2281     /* set image offset and reference grid */
2282     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2283     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2284     image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) *
2285                 (OPJ_UINT32)subsampling_dx + 1;
2286     image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) *
2287                 (OPJ_UINT32)subsampling_dy + 1;
2288
2289     if (raw_cp->rawBitDepth <= 8) {
2290         unsigned char value = 0;
2291         for (compno = 0; compno < numcomps; compno++) {
2292             int nloop = (w * h) / (raw_cp->rawComps[compno].dx *
2293                                    raw_cp->rawComps[compno].dy);
2294             for (i = 0; i < nloop; i++) {
2295                 if (!fread(&value, 1, 1, f)) {
2296                     fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
2297                     opj_image_destroy(image);
2298                     fclose(f);
2299                     return NULL;
2300                 }
2301                 image->comps[compno].data[i] = raw_cp->rawSigned ? (char)value : value;
2302             }
2303         }
2304     } else if (raw_cp->rawBitDepth <= 16) {
2305         unsigned short value;
2306         for (compno = 0; compno < numcomps; compno++) {
2307             int nloop = (w * h) / (raw_cp->rawComps[compno].dx *
2308                                    raw_cp->rawComps[compno].dy);
2309             for (i = 0; i < nloop; i++) {
2310                 unsigned char temp1;
2311                 unsigned char temp2;
2312                 if (!fread(&temp1, 1, 1, f)) {
2313                     fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
2314                     opj_image_destroy(image);
2315                     fclose(f);
2316                     return NULL;
2317                 }
2318                 if (!fread(&temp2, 1, 1, f)) {
2319                     fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
2320                     opj_image_destroy(image);
2321                     fclose(f);
2322                     return NULL;
2323                 }
2324                 if (big_endian) {
2325                     value = (unsigned short)((temp1 << 8) + temp2);
2326                 } else {
2327                     value = (unsigned short)((temp2 << 8) + temp1);
2328                 }
2329                 image->comps[compno].data[i] = raw_cp->rawSigned ? (short)value : value;
2330             }
2331         }
2332     } else {
2333         fprintf(stderr,
2334                 "OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
2335         opj_image_destroy(image);
2336         fclose(f);
2337         return NULL;
2338     }
2339
2340     if (fread(&ch, 1, 1, f)) {
2341         fprintf(stderr, "Warning. End of raw file not reached... processing anyway\n");
2342     }
2343     fclose(f);
2344
2345     return image;
2346 }
2347
2348 opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters,
2349                          raw_cparameters_t *raw_cp)
2350 {
2351     return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
2352 }
2353
2354 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters,
2355                         raw_cparameters_t *raw_cp)
2356 {
2357     return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
2358 }
2359
2360 static int imagetoraw_common(opj_image_t * image, const char *outfile,
2361                              OPJ_BOOL big_endian)
2362 {
2363     FILE *rawFile = NULL;
2364     size_t res;
2365     unsigned int compno, numcomps;
2366     int w, h, fails;
2367     int line, row, curr, mask;
2368     int *ptr;
2369     unsigned char uc;
2370     (void)big_endian;
2371
2372     if ((image->numcomps * image->x1 * image->y1) == 0) {
2373         fprintf(stderr, "\nError: invalid raw image parameters\n");
2374         return 1;
2375     }
2376
2377     numcomps = image->numcomps;
2378
2379     if (numcomps > 4) {
2380         numcomps = 4;
2381     }
2382
2383     for (compno = 1; compno < numcomps; ++compno) {
2384         if (image->comps[0].dx != image->comps[compno].dx) {
2385             break;
2386         }
2387         if (image->comps[0].dy != image->comps[compno].dy) {
2388             break;
2389         }
2390         if (image->comps[0].prec != image->comps[compno].prec) {
2391             break;
2392         }
2393         if (image->comps[0].sgnd != image->comps[compno].sgnd) {
2394             break;
2395         }
2396     }
2397     if (compno != numcomps) {
2398         fprintf(stderr,
2399                 "imagetoraw_common: All components shall have the same subsampling, same bit depth, same sign.\n");
2400         fprintf(stderr, "\tAborting\n");
2401         return 1;
2402     }
2403
2404     rawFile = fopen(outfile, "wb");
2405     if (!rawFile) {
2406         fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
2407         return 1;
2408     }
2409
2410     fails = 1;
2411     fprintf(stdout, "Raw image characteristics: %d components\n", image->numcomps);
2412
2413     for (compno = 0; compno < image->numcomps; compno++) {
2414         fprintf(stdout, "Component %u characteristics: %dx%dx%d %s\n", compno,
2415                 image->comps[compno].w,
2416                 image->comps[compno].h, image->comps[compno].prec,
2417                 image->comps[compno].sgnd == 1 ? "signed" : "unsigned");
2418
2419         w = (int)image->comps[compno].w;
2420         h = (int)image->comps[compno].h;
2421
2422         if (image->comps[compno].prec <= 8) {
2423             if (image->comps[compno].sgnd == 1) {
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 > 127) {
2430                             curr = 127;
2431                         } else if (curr < -128) {
2432                             curr = -128;
2433                         }
2434                         uc = (unsigned char)(curr & mask);
2435                         res = fwrite(&uc, 1, 1, rawFile);
2436                         if (res < 1) {
2437                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2438                             goto fin;
2439                         }
2440                         ptr++;
2441                     }
2442                 }
2443             } else if (image->comps[compno].sgnd == 0) {
2444                 mask = (1 << image->comps[compno].prec) - 1;
2445                 ptr = image->comps[compno].data;
2446                 for (line = 0; line < h; line++) {
2447                     for (row = 0; row < w; row++)    {
2448                         curr = *ptr;
2449                         if (curr > 255) {
2450                             curr = 255;
2451                         } else if (curr < 0) {
2452                             curr = 0;
2453                         }
2454                         uc = (unsigned char)(curr & mask);
2455                         res = fwrite(&uc, 1, 1, rawFile);
2456                         if (res < 1) {
2457                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2458                             goto fin;
2459                         }
2460                         ptr++;
2461                     }
2462                 }
2463             }
2464         } else if (image->comps[compno].prec <= 16) {
2465             if (image->comps[compno].sgnd == 1) {
2466                 union {
2467                     signed short val;
2468                     signed char vals[2];
2469                 } uc16;
2470                 mask = (1 << image->comps[compno].prec) - 1;
2471                 ptr = image->comps[compno].data;
2472                 for (line = 0; line < h; line++) {
2473                     for (row = 0; row < w; row++)    {
2474                         curr = *ptr;
2475                         if (curr > 32767) {
2476                             curr = 32767;
2477                         } else if (curr < -32768) {
2478                             curr = -32768;
2479                         }
2480                         uc16.val = (signed short)(curr & mask);
2481                         res = fwrite(uc16.vals, 1, 2, rawFile);
2482                         if (res < 2) {
2483                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2484                             goto fin;
2485                         }
2486                         ptr++;
2487                     }
2488                 }
2489             } else if (image->comps[compno].sgnd == 0) {
2490                 union {
2491                     unsigned short val;
2492                     unsigned char vals[2];
2493                 } uc16;
2494                 mask = (1 << image->comps[compno].prec) - 1;
2495                 ptr = image->comps[compno].data;
2496                 for (line = 0; line < h; line++) {
2497                     for (row = 0; row < w; row++)    {
2498                         curr = *ptr;
2499                         if (curr > 65535) {
2500                             curr = 65535;
2501                         } else if (curr < 0) {
2502                             curr = 0;
2503                         }
2504                         uc16.val = (unsigned short)(curr & mask);
2505                         res = fwrite(uc16.vals, 1, 2, rawFile);
2506                         if (res < 2) {
2507                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2508                             goto fin;
2509                         }
2510                         ptr++;
2511                     }
2512                 }
2513             }
2514         } else if (image->comps[compno].prec <= 32) {
2515             fprintf(stderr, "More than 16 bits per component not handled yet\n");
2516             goto fin;
2517         } else {
2518             fprintf(stderr, "Error: invalid precision: %d\n", image->comps[compno].prec);
2519             goto fin;
2520         }
2521     }
2522     fails = 0;
2523 fin:
2524     fclose(rawFile);
2525     return fails;
2526 }
2527
2528 int imagetoraw(opj_image_t * image, const char *outfile)
2529 {
2530     return imagetoraw_common(image, outfile, OPJ_TRUE);
2531 }
2532
2533 int imagetorawl(opj_image_t * image, const char *outfile)
2534 {
2535     return imagetoraw_common(image, outfile, OPJ_FALSE);
2536 }
2537