26af53f241bc3ef598fb73fb31a0baef5ede6300
[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] | (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     OPJ_UINT64 expected_file_size;
1167
1168     char endian1, endian2, sign;
1169     char signtmp[32];
1170
1171     char temp[32];
1172     int bigendian;
1173     opj_image_comp_t *comp = NULL;
1174
1175     numcomps = 1;
1176     color_space = OPJ_CLRSPC_GRAY;
1177
1178     memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
1179
1180     max = 0;
1181
1182     f = fopen(filename, "rb");
1183     if (!f) {
1184         fprintf(stderr, "Failed to open %s for reading !\n", filename);
1185         return NULL;
1186     }
1187
1188     fseek(f, 0, SEEK_SET);
1189     if (fscanf(f, "PG%31[ \t]%c%c%31[ \t+-]%d%31[ \t]%d%31[ \t]%d", temp, &endian1,
1190                &endian2, signtmp, &prec, temp, &w, temp, &h) != 9) {
1191         fclose(f);
1192         fprintf(stderr,
1193                 "ERROR: Failed to read the right number of element from the fscanf() function!\n");
1194         return NULL;
1195     }
1196
1197     i = 0;
1198     sign = '+';
1199     while (signtmp[i] != '\0') {
1200         if (signtmp[i] == '-') {
1201             sign = '-';
1202         }
1203         i++;
1204     }
1205
1206     fgetc(f);
1207     if (endian1 == 'M' && endian2 == 'L') {
1208         bigendian = 1;
1209     } else if (endian2 == 'M' && endian1 == 'L') {
1210         bigendian = 0;
1211     } else {
1212         fclose(f);
1213         fprintf(stderr, "Bad pgx header, please check input file\n");
1214         return NULL;
1215     }
1216
1217     if (w < 1 || h < 1 || prec < 1 || prec > 31) {
1218         fclose(f);
1219         fprintf(stderr, "Bad pgx header, please check input file\n");
1220         return NULL;
1221     }
1222
1223     expected_file_size =
1224         (OPJ_UINT64)w * (OPJ_UINT64)h * (prec > 16 ? 4 : prec > 8 ? 2 : 1);
1225     if (expected_file_size > 10000000U) {
1226         char ch;
1227         long curpos = ftell(f);
1228         if (expected_file_size > (OPJ_UINT64)INT_MAX) {
1229             expected_file_size = (OPJ_UINT64)INT_MAX;
1230         }
1231         fseek(f, (long)expected_file_size - 1, SEEK_SET);
1232         if (fread(&ch, 1, 1, f) != 1) {
1233             fprintf(stderr, "File too short\n");
1234             fclose(f);
1235             return NULL;
1236         }
1237         fseek(f, curpos, SEEK_SET);
1238     }
1239
1240     /* initialize image component */
1241
1242     cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
1243     cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
1244     cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx +
1245                  1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx
1246                  + 1;
1247     cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy +
1248                  1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy
1249                  + 1;
1250
1251     if (sign == '-') {
1252         cmptparm.sgnd = 1;
1253     } else {
1254         cmptparm.sgnd = 0;
1255     }
1256     if (prec < 8) {
1257         force8 = 1;
1258         ushift = 8 - prec;
1259         dshift = prec - ushift;
1260         if (cmptparm.sgnd) {
1261             adjustS = (1 << (prec - 1));
1262         } else {
1263             adjustS = 0;
1264         }
1265         cmptparm.sgnd = 0;
1266         prec = 8;
1267     } else {
1268         ushift = dshift = force8 = adjustS = 0;
1269     }
1270
1271     cmptparm.prec = (OPJ_UINT32)prec;
1272     cmptparm.bpp = (OPJ_UINT32)prec;
1273     cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
1274     cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;
1275
1276     /* create the image */
1277     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
1278     if (!image) {
1279         fclose(f);
1280         return NULL;
1281     }
1282     /* set image offset and reference grid */
1283     image->x0 = cmptparm.x0;
1284     image->y0 = cmptparm.x0;
1285     image->x1 = cmptparm.w;
1286     image->y1 = cmptparm.h;
1287
1288     /* set image data */
1289
1290     comp = &image->comps[0];
1291
1292     for (i = 0; i < w * h; i++) {
1293         int v;
1294         if (force8) {
1295             v = readuchar(f) + adjustS;
1296             v = (v << ushift) + (v >> dshift);
1297             comp->data[i] = (unsigned char)v;
1298
1299             if (v > max) {
1300                 max = v;
1301             }
1302
1303             continue;
1304         }
1305         if (comp->prec == 8) {
1306             if (!comp->sgnd) {
1307                 v = readuchar(f);
1308             } else {
1309                 v = (char) readuchar(f);
1310             }
1311         } else if (comp->prec <= 16) {
1312             if (!comp->sgnd) {
1313                 v = readushort(f, bigendian);
1314             } else {
1315                 v = (short) readushort(f, bigendian);
1316             }
1317         } else {
1318             if (!comp->sgnd) {
1319                 v = (int)readuint(f, bigendian);
1320             } else {
1321                 v = (int) readuint(f, bigendian);
1322             }
1323         }
1324         if (v > max) {
1325             max = v;
1326         }
1327         comp->data[i] = v;
1328     }
1329     fclose(f);
1330     comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;
1331
1332     return image;
1333 }
1334
1335 #define CLAMP(x,a,b) ((x) < (a) ? (a) : ((x) > (b) ? (b) : (x)))
1336
1337 static INLINE int clamp(const int value, const int prec, const int sgnd)
1338 {
1339     if (sgnd) {
1340         if (prec <= 8) {
1341             return CLAMP(value, -128, 127);
1342         } else if (prec <= 16) {
1343             return CLAMP(value, -32768, 32767);
1344         } else {
1345             return CLAMP(value, -2147483647 - 1, 2147483647);
1346         }
1347     } else {
1348         if (prec <= 8) {
1349             return CLAMP(value, 0, 255);
1350         } else if (prec <= 16) {
1351             return CLAMP(value, 0, 65535);
1352         } else {
1353             return value;    /*CLAMP(value,0,4294967295);*/
1354         }
1355     }
1356 }
1357
1358 int imagetopgx(opj_image_t * image, const char *outfile)
1359 {
1360     int w, h;
1361     int i, j, fails = 1;
1362     unsigned int compno;
1363     FILE *fdest = NULL;
1364
1365     for (compno = 0; compno < image->numcomps; compno++) {
1366         opj_image_comp_t *comp = &image->comps[compno];
1367         char bname[256]; /* buffer for name */
1368         char *name = bname; /* pointer */
1369         int nbytes = 0;
1370         size_t res;
1371         const size_t olen = strlen(outfile);
1372         const size_t dotpos = olen - 4;
1373         const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
1374
1375         if (outfile[dotpos] != '.') {
1376             /* `pgx` was recognized but there is no dot at expected position */
1377             fprintf(stderr, "ERROR -> Impossible happen.");
1378             goto fin;
1379         }
1380         if (total > 256) {
1381             name = (char*)malloc(total + 1);
1382             if (name == NULL) {
1383                 fprintf(stderr, "imagetopgx: memory out\n");
1384                 goto fin;
1385             }
1386         }
1387         strncpy(name, outfile, dotpos);
1388         sprintf(name + dotpos, "_%u.pgx", compno);
1389         fdest = fopen(name, "wb");
1390         /* don't need name anymore */
1391
1392         if (!fdest) {
1393
1394             fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
1395             if (total > 256) {
1396                 free(name);
1397             }
1398             goto fin;
1399         }
1400
1401         w = (int)image->comps[compno].w;
1402         h = (int)image->comps[compno].h;
1403
1404         fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
1405                 w, h);
1406
1407         if (comp->prec <= 8) {
1408             nbytes = 1;
1409         } else if (comp->prec <= 16) {
1410             nbytes = 2;
1411         } else {
1412             nbytes = 4;
1413         }
1414
1415         if (nbytes == 1) {
1416             unsigned char* line_buffer = malloc((size_t)w);
1417             if (line_buffer == NULL) {
1418                 fprintf(stderr, "Out of memory");
1419                 if (total > 256) {
1420                     free(name);
1421                 }
1422                 goto fin;
1423             }
1424             for (j = 0; j < h; j++) {
1425                 if (comp->prec == 8 && comp->sgnd == 0) {
1426                     for (i = 0; i < w; i++) {
1427                         line_buffer[i] = (unsigned char)CLAMP(image->comps[compno].data[j * w + i], 0,
1428                                                               255);
1429                     }
1430                 } else {
1431                     for (i = 0; i < w; i++) {
1432                         line_buffer[i] = (unsigned char)
1433                                          clamp(image->comps[compno].data[j * w + i],
1434                                                (int)comp->prec, (int)comp->sgnd);
1435                     }
1436                 }
1437                 res = fwrite(line_buffer, 1, (size_t)w, fdest);
1438                 if (res != (size_t)w) {
1439                     fprintf(stderr, "failed to write %d bytes for %s\n", w, name);
1440                     if (total > 256) {
1441                         free(name);
1442                     }
1443                     free(line_buffer);
1444                     goto fin;
1445                 }
1446             }
1447             free(line_buffer);
1448         } else {
1449
1450             for (i = 0; i < w * h; i++) {
1451                 /* FIXME: clamp func is being called within a loop */
1452                 const int val = clamp(image->comps[compno].data[i],
1453                                       (int)comp->prec, (int)comp->sgnd);
1454
1455                 for (j = nbytes - 1; j >= 0; j--) {
1456                     int v = (int)(val >> (j * 8));
1457                     unsigned char byte = (unsigned char)v;
1458                     res = fwrite(&byte, 1, 1, fdest);
1459
1460                     if (res < 1) {
1461                         fprintf(stderr, "failed to write 1 byte for %s\n", name);
1462                         if (total > 256) {
1463                             free(name);
1464                         }
1465                         goto fin;
1466                     }
1467                 }
1468             }
1469         }
1470
1471         if (total > 256) {
1472             free(name);
1473         }
1474         fclose(fdest);
1475         fdest = NULL;
1476     }
1477     fails = 0;
1478 fin:
1479     if (fdest) {
1480         fclose(fdest);
1481     }
1482
1483     return fails;
1484 }
1485
1486 /* -->> -->> -->> -->>
1487
1488 PNM IMAGE FORMAT
1489
1490 <<-- <<-- <<-- <<-- */
1491
1492 struct pnm_header {
1493     int width, height, maxval, depth, format;
1494     char rgb, rgba, gray, graya, bw;
1495     char ok;
1496 };
1497
1498 static char *skip_white(char *s)
1499 {
1500     if (s != NULL) {
1501         while (*s) {
1502             if (*s == '\n' || *s == '\r') {
1503                 return NULL;
1504             }
1505             if (isspace(*s)) {
1506                 ++s;
1507                 continue;
1508             }
1509             return s;
1510         }
1511     }
1512     return NULL;
1513 }
1514
1515 static char *skip_int(char *start, int *out_n)
1516 {
1517     char *s;
1518     char c;
1519
1520     *out_n = 0;
1521
1522     s = skip_white(start);
1523     if (s == NULL) {
1524         return NULL;
1525     }
1526     start = s;
1527
1528     while (*s) {
1529         if (!isdigit(*s)) {
1530             break;
1531         }
1532         ++s;
1533     }
1534     c = *s;
1535     *s = 0;
1536     *out_n = atoi(start);
1537     *s = c;
1538     return s;
1539 }
1540
1541 static char *skip_idf(char *start, char out_idf[256])
1542 {
1543     char *s;
1544     char c;
1545
1546     s = skip_white(start);
1547     if (s == NULL) {
1548         return NULL;
1549     }
1550     start = s;
1551
1552     while (*s) {
1553         if (isalpha(*s) || *s == '_') {
1554             ++s;
1555             continue;
1556         }
1557         break;
1558     }
1559     c = *s;
1560     *s = 0;
1561     strncpy(out_idf, start, 255);
1562     *s = c;
1563     return s;
1564 }
1565
1566 static void read_pnm_header(FILE *reader, struct pnm_header *ph)
1567 {
1568     int format, end, ttype;
1569     char idf[256], type[256];
1570     char line[256];
1571
1572     if (fgets(line, 250, reader) == NULL) {
1573         fprintf(stderr, "\nWARNING: fgets return a NULL value");
1574         return;
1575     }
1576
1577     if (line[0] != 'P') {
1578         fprintf(stderr, "read_pnm_header:PNM:magic P missing\n");
1579         return;
1580     }
1581     format = atoi(line + 1);
1582     if (format < 1 || format > 7) {
1583         fprintf(stderr, "read_pnm_header:magic format %d invalid\n", format);
1584         return;
1585     }
1586     ph->format = format;
1587     ttype = end = 0;
1588
1589     while (fgets(line, 250, reader)) {
1590         char *s;
1591         int allow_null = 0;
1592
1593         if (*line == '#') {
1594             continue;
1595         }
1596
1597         s = line;
1598
1599         if (format == 7) {
1600             s = skip_idf(s, idf);
1601
1602             if (s == NULL || *s == 0) {
1603                 return;
1604             }
1605
1606             if (strcmp(idf, "ENDHDR") == 0) {
1607                 end = 1;
1608                 break;
1609             }
1610             if (strcmp(idf, "WIDTH") == 0) {
1611                 s = skip_int(s, &ph->width);
1612                 if (s == NULL || *s == 0) {
1613                     return;
1614                 }
1615
1616                 continue;
1617             }
1618             if (strcmp(idf, "HEIGHT") == 0) {
1619                 s = skip_int(s, &ph->height);
1620                 if (s == NULL || *s == 0) {
1621                     return;
1622                 }
1623
1624                 continue;
1625             }
1626             if (strcmp(idf, "DEPTH") == 0) {
1627                 s = skip_int(s, &ph->depth);
1628                 if (s == NULL || *s == 0) {
1629                     return;
1630                 }
1631
1632                 continue;
1633             }
1634             if (strcmp(idf, "MAXVAL") == 0) {
1635                 s = skip_int(s, &ph->maxval);
1636                 if (s == NULL || *s == 0) {
1637                     return;
1638                 }
1639
1640                 continue;
1641             }
1642             if (strcmp(idf, "TUPLTYPE") == 0) {
1643                 s = skip_idf(s, type);
1644                 if (s == NULL || *s == 0) {
1645                     return;
1646                 }
1647
1648                 if (strcmp(type, "BLACKANDWHITE") == 0) {
1649                     ph->bw = 1;
1650                     ttype = 1;
1651                     continue;
1652                 }
1653                 if (strcmp(type, "GRAYSCALE") == 0) {
1654                     ph->gray = 1;
1655                     ttype = 1;
1656                     continue;
1657                 }
1658                 if (strcmp(type, "GRAYSCALE_ALPHA") == 0) {
1659                     ph->graya = 1;
1660                     ttype = 1;
1661                     continue;
1662                 }
1663                 if (strcmp(type, "RGB") == 0) {
1664                     ph->rgb = 1;
1665                     ttype = 1;
1666                     continue;
1667                 }
1668                 if (strcmp(type, "RGB_ALPHA") == 0) {
1669                     ph->rgba = 1;
1670                     ttype = 1;
1671                     continue;
1672                 }
1673                 fprintf(stderr, "read_pnm_header:unknown P7 TUPLTYPE %s\n", type);
1674                 return;
1675             }
1676             fprintf(stderr, "read_pnm_header:unknown P7 idf %s\n", idf);
1677             return;
1678         } /* if(format == 7) */
1679
1680         /* Here format is in range [1,6] */
1681         if (ph->width == 0) {
1682             s = skip_int(s, &ph->width);
1683             if ((s == NULL) || (*s == 0) || (ph->width < 1)) {
1684                 return;
1685             }
1686             allow_null = 1;
1687         }
1688         if (ph->height == 0) {
1689             s = skip_int(s, &ph->height);
1690             if ((s == NULL) && allow_null) {
1691                 continue;
1692             }
1693             if ((s == NULL) || (*s == 0) || (ph->height < 1)) {
1694                 return;
1695             }
1696             if (format == 1 || format == 4) {
1697                 break;
1698             }
1699             allow_null = 1;
1700         }
1701         /* here, format is in P2, P3, P5, P6 */
1702         s = skip_int(s, &ph->maxval);
1703         if ((s == NULL) && allow_null) {
1704             continue;
1705         }
1706         if ((s == NULL) || (*s == 0)) {
1707             return;
1708         }
1709         break;
1710     }/* while(fgets( ) */
1711     if (format == 2 || format == 3 || format > 4) {
1712         if (ph->maxval < 1 || ph->maxval > 65535) {
1713             return;
1714         }
1715     }
1716     if (ph->width < 1 || ph->height < 1) {
1717         return;
1718     }
1719
1720     if (format == 7) {
1721         if (!end) {
1722             fprintf(stderr, "read_pnm_header:P7 without ENDHDR\n");
1723             return;
1724         }
1725         if (ph->depth < 1 || ph->depth > 4) {
1726             return;
1727         }
1728
1729         if (ttype) {
1730             ph->ok = 1;
1731         }
1732     } else {
1733         ph->ok = 1;
1734         if (format == 1 || format == 4) {
1735             ph->maxval = 255;
1736         }
1737     }
1738 }
1739
1740 static int has_prec(int val)
1741 {
1742     if (val < 2) {
1743         return 1;
1744     }
1745     if (val < 4) {
1746         return 2;
1747     }
1748     if (val < 8) {
1749         return 3;
1750     }
1751     if (val < 16) {
1752         return 4;
1753     }
1754     if (val < 32) {
1755         return 5;
1756     }
1757     if (val < 64) {
1758         return 6;
1759     }
1760     if (val < 128) {
1761         return 7;
1762     }
1763     if (val < 256) {
1764         return 8;
1765     }
1766     if (val < 512) {
1767         return 9;
1768     }
1769     if (val < 1024) {
1770         return 10;
1771     }
1772     if (val < 2048) {
1773         return 11;
1774     }
1775     if (val < 4096) {
1776         return 12;
1777     }
1778     if (val < 8192) {
1779         return 13;
1780     }
1781     if (val < 16384) {
1782         return 14;
1783     }
1784     if (val < 32768) {
1785         return 15;
1786     }
1787     return 16;
1788 }
1789
1790 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters)
1791 {
1792     int subsampling_dx = parameters->subsampling_dx;
1793     int subsampling_dy = parameters->subsampling_dy;
1794
1795     FILE *fp = NULL;
1796     int i, compno, numcomps, w, h, prec, format;
1797     OPJ_COLOR_SPACE color_space;
1798     opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
1799     opj_image_t * image = NULL;
1800     struct pnm_header header_info;
1801
1802     if ((fp = fopen(filename, "rb")) == NULL) {
1803         fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n", filename);
1804         return NULL;
1805     }
1806     memset(&header_info, 0, sizeof(struct pnm_header));
1807
1808     read_pnm_header(fp, &header_info);
1809
1810     if (!header_info.ok) {
1811         fclose(fp);
1812         return NULL;
1813     }
1814
1815     /* This limitation could be removed by making sure to use size_t below */
1816     if (header_info.height != 0 &&
1817             header_info.width > INT_MAX / header_info.height) {
1818         fprintf(stderr, "pnmtoimage:Image %dx%d too big!\n",
1819                 header_info.width, header_info.height);
1820         fclose(fp);
1821         return NULL;
1822     }
1823
1824     format = header_info.format;
1825
1826     switch (format) {
1827     case 1: /* ascii bitmap */
1828     case 4: /* raw bitmap */
1829         numcomps = 1;
1830         break;
1831
1832     case 2: /* ascii greymap */
1833     case 5: /* raw greymap */
1834         numcomps = 1;
1835         break;
1836
1837     case 3: /* ascii pixmap */
1838     case 6: /* raw pixmap */
1839         numcomps = 3;
1840         break;
1841
1842     case 7: /* arbitrary map */
1843         numcomps = header_info.depth;
1844         break;
1845
1846     default:
1847         fclose(fp);
1848         return NULL;
1849     }
1850     if (numcomps < 3) {
1851         color_space = OPJ_CLRSPC_GRAY;    /* GRAY, GRAYA */
1852     } else {
1853         color_space = OPJ_CLRSPC_SRGB;    /* RGB, RGBA */
1854     }
1855
1856     prec = has_prec(header_info.maxval);
1857
1858     if (prec < 8) {
1859         prec = 8;
1860     }
1861
1862     w = header_info.width;
1863     h = header_info.height;
1864     subsampling_dx = parameters->subsampling_dx;
1865     subsampling_dy = parameters->subsampling_dy;
1866
1867     memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
1868
1869     for (i = 0; i < numcomps; i++) {
1870         cmptparm[i].prec = (OPJ_UINT32)prec;
1871         cmptparm[i].bpp = (OPJ_UINT32)prec;
1872         cmptparm[i].sgnd = 0;
1873         cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
1874         cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
1875         cmptparm[i].w = (OPJ_UINT32)w;
1876         cmptparm[i].h = (OPJ_UINT32)h;
1877     }
1878     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
1879
1880     if (!image) {
1881         fclose(fp);
1882         return NULL;
1883     }
1884
1885     /* set image offset and reference grid */
1886     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
1887     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
1888     image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx
1889                              + 1);
1890     image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy
1891                              + 1);
1892
1893     if ((format == 2) || (format == 3)) { /* ascii pixmap */
1894         unsigned int index;
1895
1896         for (i = 0; i < w * h; i++) {
1897             for (compno = 0; compno < numcomps; compno++) {
1898                 index = 0;
1899                 if (fscanf(fp, "%u", &index) != 1) {
1900                     fprintf(stderr,
1901                             "\nWARNING: fscanf return a number of element different from the expected.\n");
1902                 }
1903
1904                 image->comps[compno].data[i] = (OPJ_INT32)(index * 255) / header_info.maxval;
1905             }
1906         }
1907     } else if ((format == 5)
1908                || (format == 6)
1909                || ((format == 7)
1910                    && (header_info.gray || header_info.graya
1911                        || header_info.rgb || header_info.rgba))) { /* binary pixmap */
1912         unsigned char c0, c1, one;
1913
1914         one = (prec < 9);
1915
1916         for (i = 0; i < w * h; i++) {
1917             for (compno = 0; compno < numcomps; compno++) {
1918                 if (!fread(&c0, 1, 1, fp)) {
1919                     fprintf(stderr,
1920                             "\nError: fread return a number of element different from the expected.\n");
1921                     opj_image_destroy(image);
1922                     fclose(fp);
1923                     return NULL;
1924                 }
1925                 if (one) {
1926                     image->comps[compno].data[i] = c0;
1927                 } else {
1928                     if (!fread(&c1, 1, 1, fp)) {
1929                         fprintf(stderr,
1930                                 "\nError: fread return a number of element different from the expected.\n");
1931                     }
1932                     /* netpbm: */
1933                     image->comps[compno].data[i] = ((c0 << 8) | c1);
1934                 }
1935             }
1936         }
1937     } else if (format == 1) { /* ascii bitmap */
1938         for (i = 0; i < w * h; i++) {
1939             unsigned int index;
1940
1941             if (fscanf(fp, "%u", &index) != 1) {
1942                 fprintf(stderr,
1943                         "\nWARNING: fscanf return a number of element different from the expected.\n");
1944             }
1945
1946             image->comps[0].data[i] = (index ? 0 : 255);
1947         }
1948     } else if (format == 4) {
1949         int x, y, bit;
1950         unsigned char uc;
1951
1952         i = 0;
1953         for (y = 0; y < h; ++y) {
1954             bit = -1;
1955             uc = 0;
1956
1957             for (x = 0; x < w; ++x) {
1958                 if (bit == -1) {
1959                     bit = 7;
1960                     uc = (unsigned char)getc(fp);
1961                 }
1962                 image->comps[0].data[i] = (((uc >> bit) & 1) ? 0 : 255);
1963                 --bit;
1964                 ++i;
1965             }
1966         }
1967     } else if ((format == 7 && header_info.bw)) { /*MONO*/
1968         unsigned char uc;
1969
1970         for (i = 0; i < w * h; ++i) {
1971             if (!fread(&uc, 1, 1, fp)) {
1972                 fprintf(stderr,
1973                         "\nError: fread return a number of element different from the expected.\n");
1974             }
1975             image->comps[0].data[i] = (uc & 1) ? 0 : 255;
1976         }
1977     }
1978     fclose(fp);
1979
1980     return image;
1981 }/* pnmtoimage() */
1982
1983 static int are_comps_similar(opj_image_t * image)
1984 {
1985     unsigned int i;
1986     for (i = 1; i < image->numcomps; i++) {
1987         if (image->comps[0].dx != image->comps[i].dx ||
1988                 image->comps[0].dy != image->comps[i].dy ||
1989                 (i <= 2 &&
1990                  (image->comps[0].prec != image->comps[i].prec ||
1991                   image->comps[0].sgnd != image->comps[i].sgnd))) {
1992             return OPJ_FALSE;
1993         }
1994     }
1995     return OPJ_TRUE;
1996 }
1997
1998
1999 int imagetopnm(opj_image_t * image, const char *outfile, int force_split)
2000 {
2001     int *red, *green, *blue, *alpha;
2002     int wr, hr, max;
2003     int i;
2004     unsigned int compno, ncomp;
2005     int adjustR, adjustG, adjustB, adjustA;
2006     int fails, two, want_gray, has_alpha, triple;
2007     int prec, v;
2008     FILE *fdest = NULL;
2009     const char *tmp = outfile;
2010     char *destname;
2011
2012     alpha = NULL;
2013
2014     if ((prec = (int)image->comps[0].prec) > 16) {
2015         fprintf(stderr, "%s:%d:imagetopnm\n\tprecision %d is larger than 16"
2016                 "\n\t: refused.\n", __FILE__, __LINE__, prec);
2017         return 1;
2018     }
2019     two = has_alpha = 0;
2020     fails = 1;
2021     ncomp = image->numcomps;
2022
2023     while (*tmp) {
2024         ++tmp;
2025     }
2026     tmp -= 2;
2027     want_gray = (*tmp == 'g' || *tmp == 'G');
2028     ncomp = image->numcomps;
2029
2030     if (want_gray) {
2031         ncomp = 1;
2032     }
2033
2034     if ((force_split == 0) && ncomp >= 2 &&
2035             are_comps_similar(image)) {
2036         fdest = fopen(outfile, "wb");
2037
2038         if (!fdest) {
2039             fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
2040             return fails;
2041         }
2042         two = (prec > 8);
2043         triple = (ncomp > 2);
2044         wr = (int)image->comps[0].w;
2045         hr = (int)image->comps[0].h;
2046         max = (1 << prec) - 1;
2047         has_alpha = (ncomp == 4 || ncomp == 2);
2048
2049         red = image->comps[0].data;
2050
2051         if (triple) {
2052             green = image->comps[1].data;
2053             blue = image->comps[2].data;
2054         } else {
2055             green = blue = NULL;
2056         }
2057
2058         if (has_alpha) {
2059             const char *tt = (triple ? "RGB_ALPHA" : "GRAYSCALE_ALPHA");
2060
2061             fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %u\n"
2062                     "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
2063                     wr, hr, ncomp, max, tt);
2064             alpha = image->comps[ncomp - 1].data;
2065             adjustA = (image->comps[ncomp - 1].sgnd ?
2066                        1 << (image->comps[ncomp - 1].prec - 1) : 0);
2067         } else {
2068             fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
2069                     opj_version(), wr, hr, max);
2070             adjustA = 0;
2071         }
2072         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
2073
2074         if (triple) {
2075             adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
2076             adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
2077         } else {
2078             adjustG = adjustB = 0;
2079         }
2080
2081         for (i = 0; i < wr * hr; ++i) {
2082             if (two) {
2083                 v = *red + adjustR;
2084                 ++red;
2085                 if (v > 65535) {
2086                     v = 65535;
2087                 } else if (v < 0) {
2088                     v = 0;
2089                 }
2090
2091                 /* netpbm: */
2092                 fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
2093
2094                 if (triple) {
2095                     v = *green + adjustG;
2096                     ++green;
2097                     if (v > 65535) {
2098                         v = 65535;
2099                     } else if (v < 0) {
2100                         v = 0;
2101                     }
2102
2103                     /* netpbm: */
2104                     fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
2105
2106                     v =  *blue + adjustB;
2107                     ++blue;
2108                     if (v > 65535) {
2109                         v = 65535;
2110                     } else if (v < 0) {
2111                         v = 0;
2112                     }
2113
2114                     /* netpbm: */
2115                     fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
2116
2117                 }/* if(triple) */
2118
2119                 if (has_alpha) {
2120                     v = *alpha + adjustA;
2121                     ++alpha;
2122                     if (v > 65535) {
2123                         v = 65535;
2124                     } else if (v < 0) {
2125                         v = 0;
2126                     }
2127
2128                     /* netpbm: */
2129                     fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
2130                 }
2131                 continue;
2132
2133             }   /* if(two) */
2134
2135             /* prec <= 8: */
2136             v = *red++;
2137             if (v > 255) {
2138                 v = 255;
2139             } else if (v < 0) {
2140                 v = 0;
2141             }
2142
2143             fprintf(fdest, "%c", (unsigned char)v);
2144             if (triple) {
2145                 v = *green++;
2146                 if (v > 255) {
2147                     v = 255;
2148                 } else if (v < 0) {
2149                     v = 0;
2150                 }
2151
2152                 fprintf(fdest, "%c", (unsigned char)v);
2153                 v = *blue++;
2154                 if (v > 255) {
2155                     v = 255;
2156                 } else if (v < 0) {
2157                     v = 0;
2158                 }
2159
2160                 fprintf(fdest, "%c", (unsigned char)v);
2161             }
2162             if (has_alpha) {
2163                 v = *alpha++;
2164                 if (v > 255) {
2165                     v = 255;
2166                 } else if (v < 0) {
2167                     v = 0;
2168                 }
2169
2170                 fprintf(fdest, "%c", (unsigned char)v);
2171             }
2172         }   /* for(i */
2173
2174         fclose(fdest);
2175         return 0;
2176     }
2177
2178     /* YUV or MONO: */
2179
2180     if (image->numcomps > ncomp) {
2181         fprintf(stderr, "WARNING -> [PGM file] Only the first component\n");
2182         fprintf(stderr, "           is written to the file\n");
2183     }
2184     destname = (char*)malloc(strlen(outfile) + 8);
2185     if (destname == NULL) {
2186         fprintf(stderr, "imagetopnm: memory out\n");
2187         return 1;
2188     }
2189     for (compno = 0; compno < ncomp; compno++) {
2190         if (ncomp > 1) {
2191             /*sprintf(destname, "%d.%s", compno, outfile);*/
2192             const size_t olen = strlen(outfile);
2193             const size_t dotpos = olen - 4;
2194
2195             strncpy(destname, outfile, dotpos);
2196             sprintf(destname + dotpos, "_%u.pgm", compno);
2197         } else {
2198             sprintf(destname, "%s", outfile);
2199         }
2200
2201         fdest = fopen(destname, "wb");
2202         if (!fdest) {
2203             fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
2204             free(destname);
2205             return 1;
2206         }
2207         wr = (int)image->comps[compno].w;
2208         hr = (int)image->comps[compno].h;
2209         prec = (int)image->comps[compno].prec;
2210         max = (1 << prec) - 1;
2211
2212         fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
2213                 opj_version(), wr, hr, max);
2214
2215         red = image->comps[compno].data;
2216         adjustR =
2217             (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
2218
2219         if (prec > 8) {
2220             for (i = 0; i < wr * hr; i++) {
2221                 v = *red + adjustR;
2222                 ++red;
2223                 if (v > 65535) {
2224                     v = 65535;
2225                 } else if (v < 0) {
2226                     v = 0;
2227                 }
2228
2229                 /* netpbm: */
2230                 fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
2231
2232                 if (has_alpha) {
2233                     v = *alpha++;
2234                     if (v > 65535) {
2235                         v = 65535;
2236                     } else if (v < 0) {
2237                         v = 0;
2238                     }
2239
2240                     /* netpbm: */
2241                     fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
2242                 }
2243             }/* for(i */
2244         } else { /* prec <= 8 */
2245             for (i = 0; i < wr * hr; ++i) {
2246                 v = *red + adjustR;
2247                 ++red;
2248                 if (v > 255) {
2249                     v = 255;
2250                 } else if (v < 0) {
2251                     v = 0;
2252                 }
2253
2254                 fprintf(fdest, "%c", (unsigned char)v);
2255             }
2256         }
2257         fclose(fdest);
2258     } /* for (compno */
2259     free(destname);
2260
2261     return 0;
2262 }/* imagetopnm() */
2263
2264 /* -->> -->> -->> -->>
2265
2266     RAW IMAGE FORMAT
2267
2268  <<-- <<-- <<-- <<-- */
2269 static opj_image_t* rawtoimage_common(const char *filename,
2270                                       opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian)
2271 {
2272     int subsampling_dx = parameters->subsampling_dx;
2273     int subsampling_dy = parameters->subsampling_dy;
2274
2275     FILE *f = NULL;
2276     int i, compno, numcomps, w, h;
2277     OPJ_COLOR_SPACE color_space;
2278     opj_image_cmptparm_t *cmptparm;
2279     opj_image_t * image = NULL;
2280     unsigned short ch;
2281
2282     if ((!(raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp &
2283             raw_cp->rawBitDepth)) == 0) {
2284         fprintf(stderr, "\nError: invalid raw image parameters\n");
2285         fprintf(stderr, "Please use the Format option -F:\n");
2286         fprintf(stderr,
2287                 "-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
2288         fprintf(stderr,
2289                 "If subsampling is omitted, 1x1 is assumed for all components\n");
2290         fprintf(stderr,
2291                 "Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
2292         fprintf(stderr, "         for raw 512x512 image with 4:2:0 subsampling\n");
2293         fprintf(stderr, "Aborting.\n");
2294         return NULL;
2295     }
2296
2297     f = fopen(filename, "rb");
2298     if (!f) {
2299         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
2300         fprintf(stderr, "Aborting\n");
2301         return NULL;
2302     }
2303     numcomps = raw_cp->rawComp;
2304
2305     /* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
2306     if (numcomps == 1) {
2307         color_space = OPJ_CLRSPC_GRAY;
2308     } else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
2309         color_space = OPJ_CLRSPC_SYCC;
2310     } else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
2311         color_space = OPJ_CLRSPC_SRGB;
2312     } else {
2313         color_space = OPJ_CLRSPC_UNKNOWN;
2314     }
2315     w = raw_cp->rawWidth;
2316     h = raw_cp->rawHeight;
2317     cmptparm = (opj_image_cmptparm_t*) calloc((OPJ_UINT32)numcomps,
2318                sizeof(opj_image_cmptparm_t));
2319     if (!cmptparm) {
2320         fprintf(stderr, "Failed to allocate image components parameters !!\n");
2321         fprintf(stderr, "Aborting\n");
2322         fclose(f);
2323         return NULL;
2324     }
2325     /* initialize image components */
2326     for (i = 0; i < numcomps; i++) {
2327         cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
2328         cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
2329         cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
2330         cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
2331         cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
2332         cmptparm[i].w = (OPJ_UINT32)w;
2333         cmptparm[i].h = (OPJ_UINT32)h;
2334     }
2335     /* create the image */
2336     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2337     free(cmptparm);
2338     if (!image) {
2339         fclose(f);
2340         return NULL;
2341     }
2342     /* set image offset and reference grid */
2343     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2344     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2345     image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) *
2346                 (OPJ_UINT32)subsampling_dx + 1;
2347     image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) *
2348                 (OPJ_UINT32)subsampling_dy + 1;
2349
2350     if (raw_cp->rawBitDepth <= 8) {
2351         unsigned char value = 0;
2352         for (compno = 0; compno < numcomps; compno++) {
2353             int nloop = (w * h) / (raw_cp->rawComps[compno].dx *
2354                                    raw_cp->rawComps[compno].dy);
2355             for (i = 0; i < nloop; i++) {
2356                 if (!fread(&value, 1, 1, f)) {
2357                     fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
2358                     opj_image_destroy(image);
2359                     fclose(f);
2360                     return NULL;
2361                 }
2362                 image->comps[compno].data[i] = raw_cp->rawSigned ? (char)value : value;
2363             }
2364         }
2365     } else if (raw_cp->rawBitDepth <= 16) {
2366         unsigned short value;
2367         for (compno = 0; compno < numcomps; compno++) {
2368             int nloop = (w * h) / (raw_cp->rawComps[compno].dx *
2369                                    raw_cp->rawComps[compno].dy);
2370             for (i = 0; i < nloop; i++) {
2371                 unsigned char temp1;
2372                 unsigned char temp2;
2373                 if (!fread(&temp1, 1, 1, f)) {
2374                     fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
2375                     opj_image_destroy(image);
2376                     fclose(f);
2377                     return NULL;
2378                 }
2379                 if (!fread(&temp2, 1, 1, f)) {
2380                     fprintf(stderr, "Error reading raw file. End of file probably reached.\n");
2381                     opj_image_destroy(image);
2382                     fclose(f);
2383                     return NULL;
2384                 }
2385                 if (big_endian) {
2386                     value = (unsigned short)((temp1 << 8) + temp2);
2387                 } else {
2388                     value = (unsigned short)((temp2 << 8) + temp1);
2389                 }
2390                 image->comps[compno].data[i] = raw_cp->rawSigned ? (short)value : value;
2391             }
2392         }
2393     } else {
2394         fprintf(stderr,
2395                 "OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
2396         opj_image_destroy(image);
2397         fclose(f);
2398         return NULL;
2399     }
2400
2401     if (fread(&ch, 1, 1, f)) {
2402         fprintf(stderr, "Warning. End of raw file not reached... processing anyway\n");
2403     }
2404     fclose(f);
2405
2406     return image;
2407 }
2408
2409 opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters,
2410                          raw_cparameters_t *raw_cp)
2411 {
2412     return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
2413 }
2414
2415 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters,
2416                         raw_cparameters_t *raw_cp)
2417 {
2418     return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
2419 }
2420
2421 static int imagetoraw_common(opj_image_t * image, const char *outfile,
2422                              OPJ_BOOL big_endian)
2423 {
2424     FILE *rawFile = NULL;
2425     size_t res;
2426     unsigned int compno, numcomps;
2427     int w, h, fails;
2428     int line, row, curr, mask;
2429     int *ptr;
2430     unsigned char uc;
2431     (void)big_endian;
2432
2433     if ((image->numcomps * image->x1 * image->y1) == 0) {
2434         fprintf(stderr, "\nError: invalid raw image parameters\n");
2435         return 1;
2436     }
2437
2438     numcomps = image->numcomps;
2439
2440     if (numcomps > 4) {
2441         numcomps = 4;
2442     }
2443
2444     for (compno = 1; compno < numcomps; ++compno) {
2445         if (image->comps[0].dx != image->comps[compno].dx) {
2446             break;
2447         }
2448         if (image->comps[0].dy != image->comps[compno].dy) {
2449             break;
2450         }
2451         if (image->comps[0].prec != image->comps[compno].prec) {
2452             break;
2453         }
2454         if (image->comps[0].sgnd != image->comps[compno].sgnd) {
2455             break;
2456         }
2457     }
2458     if (compno != numcomps) {
2459         fprintf(stderr,
2460                 "imagetoraw_common: All components shall have the same subsampling, same bit depth, same sign.\n");
2461         fprintf(stderr, "\tAborting\n");
2462         return 1;
2463     }
2464
2465     rawFile = fopen(outfile, "wb");
2466     if (!rawFile) {
2467         fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
2468         return 1;
2469     }
2470
2471     fails = 1;
2472     fprintf(stdout, "Raw image characteristics: %d components\n", image->numcomps);
2473
2474     for (compno = 0; compno < image->numcomps; compno++) {
2475         fprintf(stdout, "Component %u characteristics: %dx%dx%d %s\n", compno,
2476                 image->comps[compno].w,
2477                 image->comps[compno].h, image->comps[compno].prec,
2478                 image->comps[compno].sgnd == 1 ? "signed" : "unsigned");
2479
2480         w = (int)image->comps[compno].w;
2481         h = (int)image->comps[compno].h;
2482
2483         if (image->comps[compno].prec <= 8) {
2484             if (image->comps[compno].sgnd == 1) {
2485                 mask = (1 << image->comps[compno].prec) - 1;
2486                 ptr = image->comps[compno].data;
2487                 for (line = 0; line < h; line++) {
2488                     for (row = 0; row < w; row++)    {
2489                         curr = *ptr;
2490                         if (curr > 127) {
2491                             curr = 127;
2492                         } else if (curr < -128) {
2493                             curr = -128;
2494                         }
2495                         uc = (unsigned char)(curr & mask);
2496                         res = fwrite(&uc, 1, 1, rawFile);
2497                         if (res < 1) {
2498                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2499                             goto fin;
2500                         }
2501                         ptr++;
2502                     }
2503                 }
2504             } else if (image->comps[compno].sgnd == 0) {
2505                 mask = (1 << image->comps[compno].prec) - 1;
2506                 ptr = image->comps[compno].data;
2507                 for (line = 0; line < h; line++) {
2508                     for (row = 0; row < w; row++)    {
2509                         curr = *ptr;
2510                         if (curr > 255) {
2511                             curr = 255;
2512                         } else if (curr < 0) {
2513                             curr = 0;
2514                         }
2515                         uc = (unsigned char)(curr & mask);
2516                         res = fwrite(&uc, 1, 1, rawFile);
2517                         if (res < 1) {
2518                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2519                             goto fin;
2520                         }
2521                         ptr++;
2522                     }
2523                 }
2524             }
2525         } else if (image->comps[compno].prec <= 16) {
2526             if (image->comps[compno].sgnd == 1) {
2527                 union {
2528                     signed short val;
2529                     signed char vals[2];
2530                 } uc16;
2531                 mask = (1 << image->comps[compno].prec) - 1;
2532                 ptr = image->comps[compno].data;
2533                 for (line = 0; line < h; line++) {
2534                     for (row = 0; row < w; row++)    {
2535                         curr = *ptr;
2536                         if (curr > 32767) {
2537                             curr = 32767;
2538                         } else if (curr < -32768) {
2539                             curr = -32768;
2540                         }
2541                         uc16.val = (signed short)(curr & mask);
2542                         res = fwrite(uc16.vals, 1, 2, rawFile);
2543                         if (res < 2) {
2544                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2545                             goto fin;
2546                         }
2547                         ptr++;
2548                     }
2549                 }
2550             } else if (image->comps[compno].sgnd == 0) {
2551                 union {
2552                     unsigned short val;
2553                     unsigned char vals[2];
2554                 } uc16;
2555                 mask = (1 << image->comps[compno].prec) - 1;
2556                 ptr = image->comps[compno].data;
2557                 for (line = 0; line < h; line++) {
2558                     for (row = 0; row < w; row++)    {
2559                         curr = *ptr;
2560                         if (curr > 65535) {
2561                             curr = 65535;
2562                         } else if (curr < 0) {
2563                             curr = 0;
2564                         }
2565                         uc16.val = (unsigned short)(curr & mask);
2566                         res = fwrite(uc16.vals, 1, 2, rawFile);
2567                         if (res < 2) {
2568                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2569                             goto fin;
2570                         }
2571                         ptr++;
2572                     }
2573                 }
2574             }
2575         } else if (image->comps[compno].prec <= 32) {
2576             fprintf(stderr, "More than 16 bits per component not handled yet\n");
2577             goto fin;
2578         } else {
2579             fprintf(stderr, "Error: invalid precision: %d\n", image->comps[compno].prec);
2580             goto fin;
2581         }
2582     }
2583     fails = 0;
2584 fin:
2585     fclose(rawFile);
2586     return fails;
2587 }
2588
2589 int imagetoraw(opj_image_t * image, const char *outfile)
2590 {
2591     return imagetoraw_common(image, outfile, OPJ_TRUE);
2592 }
2593
2594 int imagetorawl(opj_image_t * image, const char *outfile)
2595 {
2596     return imagetoraw_common(image, outfile, OPJ_FALSE);
2597 }
2598