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