6f3e0a22c6d650436df7d49069d46420548ff886
[openjpeg.git] / src / bin / jp2 / convert.c
1 /*
2  * The copyright in this software is being made available under the 2-clauses 
3  * BSD License, included below. This software may be subject to other third 
4  * party and contributor rights, including patent rights, and no such rights
5  * are granted under this license.
6  *
7  * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
8  * Copyright (c) 2002-2014, Professor Benoit Macq
9  * Copyright (c) 2001-2003, David Janssens
10  * Copyright (c) 2002-2003, Yannick Verschueren
11  * Copyright (c) 2003-2007, Francois-Olivier Devaux 
12  * Copyright (c) 2003-2014, Antonin Descampe
13  * Copyright (c) 2005, Herve Drolon, FreeImage Team
14  * Copyright (c) 2006-2007, Parvatha Elangovan
15  * All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
27  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
30  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 #include "opj_apps_config.h"
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <ctype.h>
44
45 #include "openjpeg.h"
46 #include "convert.h"
47
48 /*
49  * Get logarithm of an integer and round downwards.
50  *
51  * log2(a)
52  */
53 static int int_floorlog2(int a) {
54     int l;
55     for (l = 0; a > 1; l++) {
56         a >>= 1;
57     }
58     return l;
59 }
60
61 /* Component precision scaling */
62 void clip_component(opj_image_comp_t* component, OPJ_UINT32 precision)
63 {
64         OPJ_SIZE_T i;
65         OPJ_SIZE_T len;
66         OPJ_UINT32 umax = (OPJ_UINT32)((OPJ_INT32)-1);
67         
68         len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
69         if (precision < 32) {
70                 umax = (1U << precision) - 1U;
71         }
72         
73         if (component->sgnd) {
74                 OPJ_INT32* l_data = component->data;
75                 OPJ_INT32 max = (OPJ_INT32)(umax / 2U);
76                 OPJ_INT32 min = -max - 1;
77                 for (i = 0; i < len; ++i) {
78                         if (l_data[i] > max) {
79                                 l_data[i] = max;
80                         } else if (l_data[i] < min) {
81                                 l_data[i] = min;
82                         }
83                 }
84         } else {
85                 OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
86                 for (i = 0; i < len; ++i) {
87                         if (l_data[i] > umax) {
88                                 l_data[i] = umax;
89                         }
90                 }
91         }
92         component->prec = precision;
93 }
94
95 /* Component precision scaling */
96 static void scale_component_up(opj_image_comp_t* component, OPJ_UINT32 precision)
97 {
98         OPJ_SIZE_T i, len;
99         
100         len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
101         if (component->sgnd) {
102                 OPJ_INT64  newMax = (OPJ_INT64)(1U << (precision - 1));
103                 OPJ_INT64  oldMax = (OPJ_INT64)(1U << (component->prec - 1));
104                 OPJ_INT32* l_data = component->data;
105                 for (i = 0; i < len; ++i) {
106                         l_data[i] = (OPJ_INT32)(((OPJ_INT64)l_data[i] * newMax) / oldMax);
107                 }
108         } else {
109                 OPJ_UINT64  newMax = (OPJ_UINT64)((1U << precision) - 1U);
110                 OPJ_UINT64  oldMax = (OPJ_UINT64)((1U << component->prec) - 1U);
111                 OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
112                 for (i = 0; i < len; ++i) {
113                         l_data[i] = (OPJ_UINT32)(((OPJ_UINT64)l_data[i] * newMax) / oldMax);
114                 }
115         }
116         component->prec = precision;
117 }
118 void scale_component(opj_image_comp_t* component, OPJ_UINT32 precision)
119 {
120         int shift;
121         OPJ_SIZE_T i, len;
122         
123         if (component->prec == precision) {
124                 return;
125         }
126         if (component->prec < precision) {
127                 scale_component_up(component, precision);
128                 return;
129         }
130         shift = (int)(component->prec - precision);
131         len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
132         if (component->sgnd) {
133                 OPJ_INT32* l_data = component->data;
134                 for (i = 0; i < len; ++i) {
135                         l_data[i] >>= shift;
136                 }
137         } else {
138                 OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
139                 for (i = 0; i < len; ++i) {
140                         l_data[i] >>= shift;
141                 }
142         }
143         component->bpp = precision;
144         component->prec = precision;
145 }
146
147
148 /* -->> -->> -->> -->>
149
150   TGA IMAGE FORMAT
151
152  <<-- <<-- <<-- <<-- */
153
154 #ifdef INFORMATION_ONLY
155 /* TGA header definition. */
156 struct tga_header
157 {                           
158     unsigned char   id_length;              /* Image id field length    */
159     unsigned char   colour_map_type;        /* Colour map type          */
160     unsigned char   image_type;             /* Image type               */
161     /*
162     ** Colour map specification
163     */
164     unsigned short  colour_map_index;       /* First entry index        */
165     unsigned short  colour_map_length;      /* Colour map length        */
166     unsigned char   colour_map_entry_size;  /* Colour map entry size    */
167     /*
168     ** Image specification
169     */
170     unsigned short  x_origin;               /* x origin of image        */
171     unsigned short  y_origin;               /* u origin of image        */
172     unsigned short  image_width;            /* Image width              */
173     unsigned short  image_height;           /* Image height             */
174     unsigned char   pixel_depth;            /* Pixel depth              */
175     unsigned char   image_desc;             /* Image descriptor         */
176 };
177 #endif /* INFORMATION_ONLY */
178
179 static unsigned short get_ushort(unsigned short val) {
180
181 #ifdef OPJ_BIG_ENDIAN
182     return( ((val & 0xff) << 8) + (val >> 8) );
183 #else
184     return( val );
185 #endif
186
187 }
188
189 #define TGA_HEADER_SIZE 18
190
191 static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel, 
192                           unsigned int *width, unsigned int *height, int *flip_image)
193 {
194     int palette_size;
195     unsigned char *tga ;
196     unsigned char id_len, /*cmap_type,*/ image_type;
197     unsigned char pixel_depth, image_desc;
198     unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
199     unsigned short /*x_origin, y_origin,*/ image_w, image_h;
200
201     if (!bits_per_pixel || !width || !height || !flip_image)
202         return 0;
203     tga = (unsigned char*)malloc(18);
204
205     if ( fread(tga, TGA_HEADER_SIZE, 1, fp) != 1 )
206     {
207         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
208         return 0 ;
209     }
210     id_len = (unsigned char)tga[0];
211     /*cmap_type = (unsigned char)tga[1];*/
212     image_type = (unsigned char)tga[2];
213     /*cmap_index = get_ushort(*(unsigned short*)(&tga[3]));*/
214     cmap_len = get_ushort(*(unsigned short*)(&tga[5]));
215     cmap_entry_size = (unsigned char)tga[7];
216
217
218 #if 0
219     x_origin = get_ushort(*(unsigned short*)(&tga[8]));
220     y_origin = get_ushort(*(unsigned short*)(&tga[10]));
221 #endif
222     image_w = get_ushort(*(unsigned short*)(&tga[12]));
223     image_h = get_ushort(*(unsigned short*)(&tga[14]));
224     pixel_depth = (unsigned char)tga[16];
225     image_desc  = (unsigned char)tga[17];
226
227     free(tga);
228
229     *bits_per_pixel = (unsigned int)pixel_depth;
230     *width  = (unsigned int)image_w;
231     *height = (unsigned int)image_h;
232
233     /* Ignore tga identifier, if present ... */
234     if (id_len)
235     {
236         unsigned char *id = (unsigned char *) malloc(id_len);
237         if ( !fread(id, id_len, 1, fp) )
238         {
239             fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
240             free(id);
241             return 0 ;
242         }
243         free(id);
244     }
245
246     /* Test for compressed formats ... not yet supported ...
247     // Note :-  9 - RLE encoded palettized.
248     //             10 - RLE encoded RGB. */
249     if (image_type > 8)
250     {
251         fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
252         return 0 ;
253     }
254
255     *flip_image = !(image_desc & 32);
256
257     /* Palettized formats are not yet supported, skip over the palette, if present ... */
258     palette_size = cmap_len * (cmap_entry_size/8);
259
260     if (palette_size>0)
261     {
262         fprintf(stderr, "File contains a palette - not yet supported.");
263         fseek(fp, palette_size, SEEK_CUR);
264     }
265     return 1;
266 }
267
268 #ifdef OPJ_BIG_ENDIAN
269
270 static INLINE int16_t swap16(int16_t x)
271 {
272     return((((u_int16_t)x & 0x00ffU) <<  8) |
273            (((u_int16_t)x & 0xff00U) >>  8));
274 }
275
276 #endif
277
278 static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height, 
279                            OPJ_BOOL flip_image)
280 {
281     unsigned short image_w, image_h, us0;
282     unsigned char uc0, image_type;
283     unsigned char pixel_depth, image_desc;
284
285     if (!bits_per_pixel || !width || !height)
286         return 0;
287
288     pixel_depth = 0;
289
290     if ( bits_per_pixel < 256 )
291         pixel_depth = (unsigned char)bits_per_pixel;
292     else{
293         fprintf(stderr,"ERROR: Wrong bits per pixel inside tga_header");
294         return 0;
295     }
296     uc0 = 0;
297
298     if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* id_length */
299     if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_type */
300
301     image_type = 2; /* Uncompressed. */
302     if(fwrite(&image_type, 1, 1, fp) != 1) goto fails;
303
304     us0 = 0;
305     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_index */
306     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_length */
307     if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_entry_size */
308
309     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* x_origin */
310     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* y_origin */
311
312     image_w = (unsigned short)width;
313     image_h = (unsigned short) height;
314
315 #ifndef OPJ_BIG_ENDIAN
316     if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
317     if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
318 #else
319     image_w = swap16(image_w);
320     image_h = swap16(image_h);
321     if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
322     if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
323 #endif
324
325     if(fwrite(&pixel_depth, 1, 1, fp) != 1) goto fails;
326
327     image_desc = 8; /* 8 bits per component. */
328
329     if (flip_image)
330         image_desc |= 32;
331     if(fwrite(&image_desc, 1, 1, fp) != 1) goto fails;
332
333     return 1;
334
335 fails:
336     fputs("\nwrite_tgaheader: write ERROR\n", stderr);
337     return 0;
338 }
339
340 opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
341     FILE *f;
342     opj_image_t *image;
343     unsigned int image_width, image_height, pixel_bit_depth;
344     unsigned int x, y;
345     int flip_image=0;
346     opj_image_cmptparm_t cmptparm[4];   /* maximum 4 components */
347     int numcomps;
348     OPJ_COLOR_SPACE color_space;
349     OPJ_BOOL mono ;
350     OPJ_BOOL save_alpha;
351     int subsampling_dx, subsampling_dy;
352     int i;
353
354     f = fopen(filename, "rb");
355     if (!f) {
356         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
357         return 0;
358     }
359
360     if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image))
361         return NULL;
362
363     /* We currently only support 24 & 32 bit tga's ... */
364     if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32)))
365         return NULL;
366
367     /* initialize image components */
368     memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
369
370     mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16);  /* Mono with & without alpha. */
371     save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
372
373     if (mono) {
374         color_space = OPJ_CLRSPC_GRAY;
375         numcomps = save_alpha ? 2 : 1;
376     }
377     else {
378         numcomps = save_alpha ? 4 : 3;
379         color_space = OPJ_CLRSPC_SRGB;
380     }
381
382     subsampling_dx = parameters->subsampling_dx;
383     subsampling_dy = parameters->subsampling_dy;
384
385     for (i = 0; i < numcomps; i++) {
386         cmptparm[i].prec = 8;
387         cmptparm[i].bpp = 8;
388         cmptparm[i].sgnd = 0;
389         cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
390         cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
391         cmptparm[i].w = image_width;
392         cmptparm[i].h = image_height;
393     }
394
395     /* create the image */
396     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
397
398     if (!image)
399         return NULL;
400
401     /* set image offset and reference grid */
402     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
403     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
404     image->x1 = !image->x0 ? (OPJ_UINT32)(image_width - 1)  * (OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1)  * (OPJ_UINT32)subsampling_dx + 1;
405     image->y1 = !image->y0 ? (OPJ_UINT32)(image_height - 1) * (OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) * (OPJ_UINT32)subsampling_dy + 1;
406
407     /* set image data */
408     for (y=0; y < image_height; y++)
409     {
410         int index;
411
412         if (flip_image)
413             index = (int)((image_height-y-1)*image_width);
414         else
415             index = (int)(y*image_width);
416
417         if (numcomps==3)
418         {
419             for (x=0;x<image_width;x++)
420             {
421                 unsigned char r,g,b;
422
423                 if( !fread(&b, 1, 1, f) )
424                 {
425                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
426                     opj_image_destroy(image);
427                     return NULL;
428                 }
429                 if ( !fread(&g, 1, 1, f) )
430                 {
431                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
432                     opj_image_destroy(image);
433                     return NULL;
434                 }
435                 if ( !fread(&r, 1, 1, f) )
436                 {
437                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
438                     opj_image_destroy(image);
439                     return NULL;
440                 }
441
442                 image->comps[0].data[index]=r;
443                 image->comps[1].data[index]=g;
444                 image->comps[2].data[index]=b;
445                 index++;
446             }
447         }
448         else if (numcomps==4)
449         {
450             for (x=0;x<image_width;x++)
451             {
452                 unsigned char r,g,b,a;
453                 if ( !fread(&b, 1, 1, f) )
454                 {
455                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
456                     opj_image_destroy(image);
457                     return NULL;
458                 }
459                 if ( !fread(&g, 1, 1, f) )
460                 {
461                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
462                     opj_image_destroy(image);
463                     return NULL;
464                 }
465                 if ( !fread(&r, 1, 1, f) )
466                 {
467                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
468                     opj_image_destroy(image);
469                     return NULL;
470                 }
471                 if ( !fread(&a, 1, 1, f) )
472                 {
473                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
474                     opj_image_destroy(image);
475                     return NULL;
476                 }
477
478                 image->comps[0].data[index]=r;
479                 image->comps[1].data[index]=g;
480                 image->comps[2].data[index]=b;
481                 image->comps[3].data[index]=a;
482                 index++;
483             }
484         }
485         else {
486             fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
487         }
488     }
489     return image;
490 }
491
492 int imagetotga(opj_image_t * image, const char *outfile) {
493     int width, height, bpp, x, y;
494     OPJ_BOOL write_alpha;
495     unsigned int i;
496     int adjustR, adjustG, adjustB, fails;
497     unsigned int alpha_channel;
498     float r,g,b,a;
499     unsigned char value;
500     float scale;
501     FILE *fdest;
502     size_t res;
503     fails = 1;
504
505     fdest = fopen(outfile, "wb");
506     if (!fdest) {
507         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
508         return 1;
509     }
510
511     for (i = 0; i < image->numcomps-1; i++)     {
512         if ((image->comps[0].dx != image->comps[i+1].dx)
513                 ||(image->comps[0].dy != image->comps[i+1].dy)
514                 ||(image->comps[0].prec != image->comps[i+1].prec))     {
515             fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
516             return 1;
517         }
518     }
519
520     width  = (int)image->comps[0].w;
521     height = (int)image->comps[0].h;
522
523     /* Mono with alpha, or RGB with alpha. */
524     write_alpha = (image->numcomps==2) || (image->numcomps==4);
525
526     /* Write TGA header  */
527     bpp = write_alpha ? 32 : 24;
528
529     if (!tga_writeheader(fdest, bpp, width , height, OPJ_TRUE))
530                 goto fin;
531
532     alpha_channel = image->numcomps-1;
533
534     scale = 255.0f / (float)((1<<image->comps[0].prec)-1);
535
536     adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
537     adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
538     adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
539
540         for (y=0; y < height; y++) 
541    {
542         unsigned int index= (unsigned int)(y*width);
543
544         for (x=0; x < width; x++, index++)      
545   {
546         r = (float)(image->comps[0].data[index] + adjustR);
547
548         if (image->numcomps > 2) 
549  {
550         g = (float)(image->comps[1].data[index] + adjustG);
551         b = (float)(image->comps[2].data[index] + adjustB);
552  }
553         else  
554  {/* Greyscale ... */
555         g = r;
556         b = r;
557  }
558
559 /* TGA format writes BGR ... */
560         if(b > 255.) b = 255.; else if(b < 0.) b = 0.;
561         value = (unsigned char)(b*scale);
562         res = fwrite(&value,1,1,fdest);
563
564         if( res < 1 ) 
565  {
566         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
567         goto fin;
568  }
569         if(g > 255.) g = 255.; else if(g < 0.) g = 0.;
570         value = (unsigned char)(g*scale);
571         res = fwrite(&value,1,1,fdest);
572
573         if( res < 1 ) 
574  {
575         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
576         goto fin;
577  }
578         if(r > 255.) r = 255.; else if(r < 0.) r = 0.;
579         value = (unsigned char)(r*scale);
580         res = fwrite(&value,1,1,fdest);
581
582         if( res < 1 ) 
583  {
584         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
585         goto fin;
586  }
587
588         if (write_alpha) 
589  {
590         a = (float)(image->comps[alpha_channel].data[index]);
591         if(a > 255.) a = 255.; else if(a < 0.) a = 0.;
592         value = (unsigned char)(a*scale);
593         res = fwrite(&value,1,1,fdest);
594
595                 if( res < 1 ) 
596            {
597                 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
598                 goto fin;
599            }
600  }
601   }
602    }
603         fails = 0;
604 fin:
605         fclose(fdest);
606
607         return fails;
608 }
609
610 /* -->> -->> -->> -->>
611
612 PGX IMAGE FORMAT
613
614 <<-- <<-- <<-- <<-- */
615
616
617 static unsigned char readuchar(FILE * f)
618 {
619     unsigned char c1;
620     if ( !fread(&c1, 1, 1, f) )
621     {
622         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
623         return 0;
624     }
625     return c1;
626 }
627
628 static unsigned short readushort(FILE * f, int bigendian)
629 {
630     unsigned char c1, c2;
631     if ( !fread(&c1, 1, 1, f) )
632     {
633         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
634         return 0;
635     }
636     if ( !fread(&c2, 1, 1, f) )
637     {
638         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
639         return 0;
640     }
641     if (bigendian)
642         return (unsigned short)((c1 << 8) + c2);
643     else
644         return (unsigned short)((c2 << 8) + c1);
645 }
646
647 static unsigned int readuint(FILE * f, int bigendian)
648 {
649     unsigned char c1, c2, c3, c4;
650     if ( !fread(&c1, 1, 1, f) )
651     {
652         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
653         return 0;
654     }
655     if ( !fread(&c2, 1, 1, f) )
656     {
657         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
658         return 0;
659     }
660     if ( !fread(&c3, 1, 1, f) )
661     {
662         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
663         return 0;
664     }
665     if ( !fread(&c4, 1, 1, f) )
666     {
667         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
668         return 0;
669     }
670     if (bigendian)
671         return (unsigned int)(c1 << 24) + (unsigned int)(c2 << 16) + (unsigned int)(c3 << 8) + c4;
672     else
673         return (unsigned int)(c4 << 24) + (unsigned int)(c3 << 16) + (unsigned int)(c2 << 8) + c1;
674 }
675
676 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
677     FILE *f = NULL;
678     int w, h, prec;
679     int i, numcomps, max;
680     OPJ_COLOR_SPACE color_space;
681     opj_image_cmptparm_t cmptparm;      /* maximum of 1 component  */
682     opj_image_t * image = NULL;
683     int adjustS, ushift, dshift, force8;
684
685     char endian1,endian2,sign;
686     char signtmp[32];
687
688     char temp[32];
689     int bigendian;
690     opj_image_comp_t *comp = NULL;
691
692     numcomps = 1;
693     color_space = OPJ_CLRSPC_GRAY;
694
695     memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
696
697     max = 0;
698
699     f = fopen(filename, "rb");
700     if (!f) {
701         fprintf(stderr, "Failed to open %s for reading !\n", filename);
702         return NULL;
703     }
704
705     fseek(f, 0, SEEK_SET);
706     if( fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h) != 9){
707         fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n");
708         return NULL;
709     }
710
711     i=0;
712     sign='+';
713     while (signtmp[i]!='\0') {
714         if (signtmp[i]=='-') sign='-';
715         i++;
716     }
717
718     fgetc(f);
719     if (endian1=='M' && endian2=='L') {
720         bigendian = 1;
721     } else if (endian2=='M' && endian1=='L') {
722         bigendian = 0;
723     } else {
724         fprintf(stderr, "Bad pgx header, please check input file\n");
725         return NULL;
726     }
727
728     /* initialize image component */
729
730     cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
731     cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
732     cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + 1;
733     cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + 1;
734
735     if (sign == '-') {
736         cmptparm.sgnd = 1;
737     } else {
738         cmptparm.sgnd = 0;
739     }
740     if(prec < 8)
741     {
742         force8 = 1;
743         ushift = 8 - prec; dshift = prec - ushift;
744         if(cmptparm.sgnd) adjustS = (1<<(prec - 1)); else adjustS = 0;
745         cmptparm.sgnd = 0;
746         prec = 8;
747     }
748     else ushift = dshift = force8 = adjustS = 0;
749
750     cmptparm.prec = (OPJ_UINT32)prec;
751     cmptparm.bpp = (OPJ_UINT32)prec;
752     cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
753     cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;
754
755     /* create the image */
756     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
757     if(!image) {
758         fclose(f);
759         return NULL;
760     }
761     /* set image offset and reference grid */
762     image->x0 = cmptparm.x0;
763     image->y0 = cmptparm.x0;
764     image->x1 = cmptparm.w;
765     image->y1 = cmptparm.h;
766
767     /* set image data */
768
769     comp = &image->comps[0];
770
771     for (i = 0; i < w * h; i++) {
772         int v;
773         if(force8)
774         {
775             v = readuchar(f) + adjustS;
776             v = (v<<ushift) + (v>>dshift);
777             comp->data[i] = (unsigned char)v;
778
779             if(v > max) max = v;
780
781             continue;
782         }
783         if (comp->prec == 8) {
784             if (!comp->sgnd) {
785                 v = readuchar(f);
786             } else {
787                 v = (char) readuchar(f);
788             }
789         } else if (comp->prec <= 16) {
790             if (!comp->sgnd) {
791                 v = readushort(f, bigendian);
792             } else {
793                 v = (short) readushort(f, bigendian);
794             }
795         } else {
796             if (!comp->sgnd) {
797                 v = (int)readuint(f, bigendian);
798             } else {
799                 v = (int) readuint(f, bigendian);
800             }
801         }
802         if (v > max)
803             max = v;
804         comp->data[i] = v;
805     }
806     fclose(f);
807     comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;
808
809     return image;
810 }
811
812 #define CLAMP(x,a,b) x < a ? a : (x > b ? b : x)
813
814 static INLINE int clamp( const int value, const int prec, const int sgnd )
815 {
816   if( sgnd )
817     {
818     if (prec <= 8)       return CLAMP(value,-128,127);
819     else if (prec <= 16) return CLAMP(value,-32768,32767);
820     else                 return CLAMP(value,-2147483647-1,2147483647);
821     }
822   else
823     {
824     if (prec <= 8)       return CLAMP(value,0,255);
825     else if (prec <= 16) return CLAMP(value,0,65535);
826     else                 return value; /*CLAMP(value,0,4294967295);*/
827     }
828 }
829
830 int imagetopgx(opj_image_t * image, const char *outfile) 
831 {
832   int w, h;
833   int i, j, fails = 1;
834   unsigned int compno;
835   FILE *fdest = NULL;
836
837   for (compno = 0; compno < image->numcomps; compno++) 
838     {
839     opj_image_comp_t *comp = &image->comps[compno];
840     char bname[256]; /* buffer for name */
841     char *name = bname; /* pointer */
842     int nbytes = 0;
843     size_t res;
844     const size_t olen = strlen(outfile);
845     const size_t dotpos = olen - 4;
846     const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
847
848     if( outfile[dotpos] != '.' ) 
849       {
850       /* `pgx` was recognized but there is no dot at expected position */
851       fprintf(stderr, "ERROR -> Impossible happen." );
852       goto fin;
853       }
854     if( total > 256 ) 
855       {
856       name = (char*)malloc(total+1);
857       }
858     strncpy(name, outfile, dotpos);
859     sprintf(name+dotpos, "_%d.pgx", compno);
860     fdest = fopen(name, "wb");
861     /* dont need name anymore */
862     if( total > 256 ) free(name);
863     if (!fdest) 
864       {
865       fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
866       goto fin;
867       }
868
869     w = (int)image->comps[compno].w;
870     h = (int)image->comps[compno].h;
871
872     fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
873       w, h);
874
875     if (comp->prec <= 8) 
876       nbytes = 1;
877     else if (comp->prec <= 16)
878       nbytes = 2;
879     else
880       nbytes = 4;
881
882     for (i = 0; i < w * h; i++) 
883       {
884       /* FIXME: clamp func is being called within a loop */
885       const int val = clamp(image->comps[compno].data[i],
886         (int)comp->prec, (int)comp->sgnd);
887
888       for (j = nbytes - 1; j >= 0; j--) 
889         {
890         int v = (int)(val >> (j * 8));
891         unsigned char byte = (unsigned char)v;
892         res = fwrite(&byte, 1, 1, fdest);
893
894         if( res < 1 ) 
895           {
896           fprintf(stderr, "failed to write 1 byte for %s\n", name);
897           goto fin;
898           }
899         }
900       }
901     fclose(fdest); fdest = NULL;
902     }
903   fails = 0;
904 fin:
905   if(fdest) fclose(fdest);
906
907   return fails;
908 }
909
910 /* -->> -->> -->> -->>
911
912 PNM IMAGE FORMAT
913
914 <<-- <<-- <<-- <<-- */
915
916 struct pnm_header
917 {
918     int width, height, maxval, depth, format;
919     char rgb, rgba, gray, graya, bw;
920     char ok;
921 };
922
923 static char *skip_white(char *s)
924 {
925     while(*s)
926     {
927         if(*s == '\n' || *s == '\r') return NULL;
928         if(isspace(*s)) { ++s; continue; }
929         return s;
930     }
931     return NULL;
932 }
933
934 static char *skip_int(char *start, int *out_n)
935 {
936     char *s;
937     char c;
938
939     *out_n = 0; s = start;
940
941     s = skip_white(start);
942     if(s == NULL) return NULL;
943     start = s;
944
945     while(*s)
946     {
947         if( !isdigit(*s)) break;
948         ++s;
949     }
950     c = *s; *s = 0; *out_n = atoi(start); *s = c;
951     return s;
952 }
953
954 static char *skip_idf(char *start, char out_idf[256])
955 {
956     char *s;
957     char c;
958
959     s = skip_white(start);
960     if(s == NULL) return NULL;
961     start = s;
962
963     while(*s)
964     {
965         if(isalpha(*s) || *s == '_') { ++s; continue; }
966         break;
967     }
968     c = *s; *s = 0; strncpy(out_idf, start, 255); *s = c;
969     return s;
970 }
971
972 static void read_pnm_header(FILE *reader, struct pnm_header *ph)
973 {
974     int format, have_wh, end, ttype;
975     char idf[256], type[256];
976     char line[256];
977
978     if (fgets(line, 250, reader) == NULL)
979     {
980         fprintf(stderr,"\nWARNING: fgets return a NULL value");
981         return;
982     }
983
984     if(line[0] != 'P')
985     {
986         fprintf(stderr,"read_pnm_header:PNM:magic P missing\n"); return;
987     }
988     format = atoi(line + 1);
989     if(format < 1 || format > 7)
990     {
991         fprintf(stderr,"read_pnm_header:magic format %d invalid\n", format);
992         return;
993     }
994     ph->format = format;
995     ttype = end = have_wh = 0;
996
997     while(fgets(line, 250, reader))
998     {
999         char *s;
1000
1001         if(*line == '#') continue;
1002
1003         s = line;
1004
1005         if(format == 7)
1006         {
1007             s = skip_idf(s, idf);
1008
1009             if(s == NULL || *s == 0) return;
1010
1011             if(strcmp(idf, "ENDHDR") == 0)
1012             {
1013                 end = 1; break;
1014             }
1015             if(strcmp(idf, "WIDTH") == 0)
1016             {
1017                 s = skip_int(s, &ph->width);
1018                 if(s == NULL || *s == 0) return;
1019
1020                 continue;
1021             }
1022             if(strcmp(idf, "HEIGHT") == 0)
1023             {
1024                 s = skip_int(s, &ph->height);
1025                 if(s == NULL || *s == 0) return;
1026
1027                 continue;
1028             }
1029             if(strcmp(idf, "DEPTH") == 0)
1030             {
1031                 s = skip_int(s, &ph->depth);
1032                 if(s == NULL || *s == 0) return;
1033
1034                 continue;
1035             }
1036             if(strcmp(idf, "MAXVAL") == 0)
1037             {
1038                 s = skip_int(s, &ph->maxval);
1039                 if(s == NULL || *s == 0) return;
1040
1041                 continue;
1042             }
1043             if(strcmp(idf, "TUPLTYPE") == 0)
1044             {
1045                 s = skip_idf(s, type);
1046                 if(s == NULL || *s == 0) return;
1047
1048                 if(strcmp(type, "BLACKANDWHITE") == 0)
1049                 {
1050                     ph->bw = 1; ttype = 1; continue;
1051                 }
1052                 if(strcmp(type, "GRAYSCALE") == 0)
1053                 {
1054                     ph->gray = 1; ttype = 1; continue;
1055                 }
1056                 if(strcmp(type, "GRAYSCALE_ALPHA") == 0)
1057                 {
1058                     ph->graya = 1; ttype = 1; continue;
1059                 }
1060                 if(strcmp(type, "RGB") == 0)
1061                 {
1062                     ph->rgb = 1; ttype = 1; continue;
1063                 }
1064                 if(strcmp(type, "RGB_ALPHA") == 0)
1065                 {
1066                     ph->rgba = 1; ttype = 1; continue;
1067                 }
1068                 fprintf(stderr,"read_pnm_header:unknown P7 TUPLTYPE %s\n",type);
1069                 return;
1070             }
1071             fprintf(stderr,"read_pnm_header:unknown P7 idf %s\n",idf);
1072             return;
1073         } /* if(format == 7) */
1074
1075         if( !have_wh)
1076         {
1077             s = skip_int(s, &ph->width);
1078
1079             s = skip_int(s, &ph->height);
1080
1081             have_wh = 1;
1082
1083             if(format == 1 || format == 4) break;
1084                                         
1085             if(format == 2 || format == 3 || format == 5 || format == 6)
1086             {
1087                 if (skip_int(s, &ph->maxval) != NULL) {
1088                     if(ph->maxval > 65535) {
1089                         return;
1090                     }
1091                     else {
1092                         break;
1093                     }
1094                 }
1095             }
1096             continue;
1097         }
1098         if(format == 2 || format == 3 || format == 5 || format == 6)
1099         {
1100             /* P2, P3, P5, P6: */
1101             s = skip_int(s, &ph->maxval);
1102
1103             if(ph->maxval > 65535) return;
1104         }
1105         break;
1106     }/* while(fgets( ) */
1107     if(format == 2 || format == 3 || format > 4)
1108     {
1109         if(ph->maxval < 1 || ph->maxval > 65535) return;
1110     }
1111     if(ph->width < 1 || ph->height < 1) return;
1112
1113     if(format == 7)
1114     {
1115         if(!end)
1116         {
1117             fprintf(stderr,"read_pnm_header:P7 without ENDHDR\n"); return;
1118         }
1119         if(ph->depth < 1 || ph->depth > 4) return;
1120
1121         if(ph->width && ph->height && ph->depth && ph->maxval && ttype)
1122             ph->ok = 1;
1123     }
1124     else
1125     {
1126         if(format != 1 && format != 4)
1127         {
1128             if(ph->width && ph->height && ph->maxval) ph->ok = 1;
1129         }
1130         else
1131         {
1132             if(ph->width && ph->height) ph->ok = 1;
1133             ph->maxval = 255;
1134         }
1135     }
1136 }
1137
1138 static int has_prec(int val)
1139 {
1140     if(val < 2) return 1;
1141     if(val < 4) return 2;
1142     if(val < 8) return 3;
1143     if(val < 16) return 4;
1144     if(val < 32) return 5;
1145     if(val < 64) return 6;
1146     if(val < 128) return 7;
1147     if(val < 256) return 8;
1148     if(val < 512) return 9;
1149     if(val < 1024) return 10;
1150     if(val < 2048) return 11;
1151     if(val < 4096) return 12;
1152     if(val < 8192) return 13;
1153     if(val < 16384) return 14;
1154     if(val < 32768) return 15;
1155     return 16;
1156 }
1157
1158 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
1159     int subsampling_dx = parameters->subsampling_dx;
1160     int subsampling_dy = parameters->subsampling_dy;
1161
1162     FILE *fp = NULL;
1163     int i, compno, numcomps, w, h, prec, format;
1164     OPJ_COLOR_SPACE color_space;
1165     opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
1166     opj_image_t * image = NULL;
1167     struct pnm_header header_info;
1168
1169     if((fp = fopen(filename, "rb")) == NULL)
1170     {
1171         fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n",filename);
1172         return NULL;
1173     }
1174     memset(&header_info, 0, sizeof(struct pnm_header));
1175
1176     read_pnm_header(fp, &header_info);
1177
1178     if(!header_info.ok) { fclose(fp); return NULL; }
1179
1180     format = header_info.format;
1181
1182     switch(format)
1183     {
1184     case 1: /* ascii bitmap */
1185     case 4: /* raw bitmap */
1186         numcomps = 1;
1187         break;
1188
1189     case 2: /* ascii greymap */
1190     case 5: /* raw greymap */
1191         numcomps = 1;
1192         break;
1193
1194     case 3: /* ascii pixmap */
1195     case 6: /* raw pixmap */
1196         numcomps = 3;
1197         break;
1198
1199     case 7: /* arbitrary map */
1200         numcomps = header_info.depth;
1201         break;
1202
1203     default: fclose(fp); return NULL;
1204     }
1205     if(numcomps < 3)
1206         color_space = OPJ_CLRSPC_GRAY;/* GRAY, GRAYA */
1207     else
1208         color_space = OPJ_CLRSPC_SRGB;/* RGB, RGBA */
1209
1210     prec = has_prec(header_info.maxval);
1211
1212     if(prec < 8) prec = 8;
1213
1214     w = header_info.width;
1215     h = header_info.height;
1216     subsampling_dx = parameters->subsampling_dx;
1217     subsampling_dy = parameters->subsampling_dy;
1218
1219     memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
1220
1221     for(i = 0; i < numcomps; i++)
1222     {
1223         cmptparm[i].prec = (OPJ_UINT32)prec;
1224         cmptparm[i].bpp = (OPJ_UINT32)prec;
1225         cmptparm[i].sgnd = 0;
1226         cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
1227         cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
1228         cmptparm[i].w = (OPJ_UINT32)w;
1229         cmptparm[i].h = (OPJ_UINT32)h;
1230     }
1231     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
1232
1233     if(!image) { fclose(fp); return NULL; }
1234
1235     /* set image offset and reference grid */
1236     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
1237     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
1238     image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx + 1);
1239     image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy + 1);
1240
1241     if((format == 2) || (format == 3)) /* ascii pixmap */
1242     {
1243         unsigned int index;
1244
1245         for (i = 0; i < w * h; i++)
1246         {
1247             for(compno = 0; compno < numcomps; compno++)
1248             {
1249                 index = 0;
1250                 if (fscanf(fp, "%u", &index) != 1)
1251                     fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1252
1253                 image->comps[compno].data[i] = (OPJ_INT32)(index * 255)/header_info.maxval;
1254             }
1255         }
1256     }
1257     else
1258         if((format == 5)
1259                 || (format == 6)
1260                 ||((format == 7)
1261                    && (   header_info.gray || header_info.graya
1262                           || header_info.rgb || header_info.rgba)))/* binary pixmap */
1263         {
1264             unsigned char c0, c1, one;
1265
1266             one = (prec < 9);
1267
1268             for (i = 0; i < w * h; i++)
1269             {
1270                 for(compno = 0; compno < numcomps; compno++)
1271                 {
1272                 if ( !fread(&c0, 1, 1, fp) )
1273                   {
1274                   fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1275                   opj_image_destroy(image);
1276                   return NULL;
1277                   }
1278                     if(one)
1279                     {
1280                         image->comps[compno].data[i] = c0;
1281                     }
1282                     else
1283                     {
1284                         if ( !fread(&c1, 1, 1, fp) )
1285                             fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1286                         /* netpbm: */
1287                         image->comps[compno].data[i] = ((c0<<8) | c1);
1288                     }
1289                 }
1290             }
1291         }
1292         else
1293             if(format == 1) /* ascii bitmap */
1294             {
1295                 for (i = 0; i < w * h; i++)
1296                 {
1297                     unsigned int index;
1298
1299                     if ( fscanf(fp, "%u", &index) != 1)
1300                         fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1301
1302                     image->comps[0].data[i] = (index?0:255);
1303                 }
1304             }
1305             else
1306                 if(format == 4)
1307                 {
1308                     int x, y, bit;
1309                     unsigned char uc;
1310
1311                     i = 0;
1312                     for(y = 0; y < h; ++y)
1313                     {
1314                         bit = -1; uc = 0;
1315
1316                         for(x = 0; x < w; ++x)
1317                         {
1318                             if(bit == -1)
1319                             {
1320                                 bit = 7;
1321                                 uc = (unsigned char)getc(fp);
1322                             }
1323                             image->comps[0].data[i] = (((uc>>bit) & 1)?0:255);
1324                             --bit; ++i;
1325                         }
1326                     }
1327                 }
1328                 else
1329                     if((format == 7 && header_info.bw)) /*MONO*/
1330                     {
1331                         unsigned char uc;
1332
1333                         for(i = 0; i < w * h; ++i)
1334                         {
1335                             if ( !fread(&uc, 1, 1, fp) )
1336                                 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1337                             image->comps[0].data[i] = (uc & 1)?0:255;
1338                         }
1339                     }
1340     fclose(fp);
1341
1342     return image;
1343 }/* pnmtoimage() */
1344
1345 int imagetopnm(opj_image_t * image, const char *outfile, int force_split)
1346 {
1347     int *red, *green, *blue, *alpha;
1348     int wr, hr, max;
1349     int i;
1350     unsigned int compno, ncomp;
1351     int adjustR, adjustG, adjustB, adjustA;
1352     int fails, two, want_gray, has_alpha, triple;
1353     int prec, v;
1354     FILE *fdest = NULL;
1355     const char *tmp = outfile;
1356     char *destname;
1357
1358         alpha = NULL;
1359
1360     if((prec = (int)image->comps[0].prec) > 16)
1361     {
1362         fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
1363                 "\n\t: refused.\n",__FILE__,__LINE__,prec);
1364         return 1;
1365     }
1366     two = has_alpha = 0; fails = 1;
1367     ncomp = image->numcomps;
1368
1369     while (*tmp) ++tmp; tmp -= 2;
1370     want_gray = (*tmp == 'g' || *tmp == 'G');
1371     ncomp = image->numcomps;
1372
1373     if(want_gray) ncomp = 1;
1374
1375     if ((force_split == 0) &&
1376                                 (ncomp == 2 /* GRAYA */
1377             || (ncomp > 2 /* RGB, RGBA */
1378                 && image->comps[0].dx == image->comps[1].dx
1379                 && image->comps[1].dx == image->comps[2].dx
1380                 && image->comps[0].dy == image->comps[1].dy
1381                 && image->comps[1].dy == image->comps[2].dy
1382                 && image->comps[0].prec == image->comps[1].prec
1383                 && image->comps[1].prec == image->comps[2].prec
1384                 )))
1385                 {
1386         fdest = fopen(outfile, "wb");
1387
1388         if (!fdest)
1389         {
1390             fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1391             return fails;
1392         }
1393         two = (prec > 8);
1394         triple = (ncomp > 2);
1395         wr = (int)image->comps[0].w; hr = (int)image->comps[0].h;
1396         max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);
1397
1398         red = image->comps[0].data;
1399
1400         if(triple)
1401         {
1402             green = image->comps[1].data;
1403             blue = image->comps[2].data;
1404         }
1405         else green = blue = NULL;
1406
1407         if(has_alpha)
1408         {
1409             const char *tt = (triple?"RGB_ALPHA":"GRAYSCALE_ALPHA");
1410
1411             fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %d\n"
1412                     "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
1413                     wr, hr, ncomp, max, tt);
1414             alpha = image->comps[ncomp - 1].data;
1415             adjustA = (image->comps[ncomp - 1].sgnd ?
1416                         1 << (image->comps[ncomp - 1].prec - 1) : 0);
1417         }
1418         else
1419         {
1420             fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
1421                     opj_version(), wr, hr, max);
1422             adjustA = 0;
1423         }
1424         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1425
1426         if(triple)
1427         {
1428             adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1429             adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1430         }
1431         else adjustG = adjustB = 0;
1432
1433         for(i = 0; i < wr * hr; ++i)
1434         {
1435             if(two)
1436             {
1437                 v = *red + adjustR; ++red;
1438 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1439
1440                 /* netpbm: */
1441                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1442
1443                 if(triple)
1444                 {
1445                     v = *green + adjustG; ++green;
1446 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1447
1448                     /* netpbm: */
1449                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1450
1451                     v =  *blue + adjustB; ++blue;
1452 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1453
1454                     /* netpbm: */
1455                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1456
1457                 }/* if(triple) */
1458
1459                 if(has_alpha)
1460                 {
1461                     v = *alpha + adjustA; ++alpha;
1462                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1463
1464                     /* netpbm: */
1465                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1466                 }
1467                 continue;
1468
1469             }   /* if(two) */
1470
1471             /* prec <= 8: */
1472         v = *red++;
1473         if(v > 255) v = 255; else if(v < 0) v = 0;
1474
1475         fprintf(fdest, "%c", (unsigned char)v);
1476             if(triple)
1477  {
1478         v = *green++;
1479         if(v > 255) v = 255; else if(v < 0) v = 0;
1480
1481         fprintf(fdest, "%c", (unsigned char)v);
1482         v = *blue++;
1483         if(v > 255) v = 255; else if(v < 0) v = 0;
1484
1485         fprintf(fdest, "%c", (unsigned char)v);
1486  }
1487             if(has_alpha)
1488  {
1489         v = *alpha++;
1490         if(v > 255) v = 255; else if(v < 0) v = 0;
1491
1492         fprintf(fdest, "%c", (unsigned char)v);
1493  }
1494         }       /* for(i */
1495
1496         fclose(fdest); return 0;
1497     }
1498
1499     /* YUV or MONO: */
1500
1501     if (image->numcomps > ncomp)
1502     {
1503         fprintf(stderr,"WARNING -> [PGM file] Only the first component\n");
1504         fprintf(stderr,"           is written to the file\n");
1505     }
1506     destname = (char*)malloc(strlen(outfile) + 8);
1507
1508     for (compno = 0; compno < ncomp; compno++)
1509     {
1510     if (ncomp > 1)
1511       {
1512       /*sprintf(destname, "%d.%s", compno, outfile);*/
1513       const size_t olen = strlen(outfile);
1514       const size_t dotpos = olen - 4;
1515
1516       strncpy(destname, outfile, dotpos);
1517       sprintf(destname+dotpos, "_%d.pgm", compno);
1518       }
1519         else
1520             sprintf(destname, "%s", outfile);
1521
1522         fdest = fopen(destname, "wb");
1523         if (!fdest)
1524         {
1525             fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
1526             free(destname);
1527             return 1;
1528         }
1529         wr = (int)image->comps[compno].w; hr = (int)image->comps[compno].h;
1530         prec = (int)image->comps[compno].prec;
1531         max = (1<<prec) - 1;
1532
1533         fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
1534                 opj_version(), wr, hr, max);
1535
1536         red = image->comps[compno].data;
1537         adjustR =
1538                 (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
1539
1540         if(prec > 8)
1541         {
1542             for (i = 0; i < wr * hr; i++)
1543             {
1544                 v = *red + adjustR; ++red;
1545 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1546
1547                 /* netpbm: */
1548                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1549
1550                 if(has_alpha)
1551                 {
1552                     v = *alpha++;
1553 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1554
1555                     /* netpbm: */
1556                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1557                 }
1558             }/* for(i */
1559         }
1560         else /* prec <= 8 */
1561         {
1562             for(i = 0; i < wr * hr; ++i)
1563             {
1564         v = *red + adjustR; ++red;
1565         if(v > 255) v = 255; else if(v < 0) v = 0;
1566
1567          fprintf(fdest, "%c", (unsigned char)v);
1568             }
1569         }
1570         fclose(fdest);
1571     } /* for (compno */
1572     free(destname);
1573
1574     return 0;
1575 }/* imagetopnm() */
1576
1577 /* -->> -->> -->> -->>
1578
1579     RAW IMAGE FORMAT
1580
1581  <<-- <<-- <<-- <<-- */
1582 static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian) {
1583     int subsampling_dx = parameters->subsampling_dx;
1584     int subsampling_dy = parameters->subsampling_dy;
1585
1586     FILE *f = NULL;
1587     int i, compno, numcomps, w, h;
1588     OPJ_COLOR_SPACE color_space;
1589     opj_image_cmptparm_t *cmptparm;
1590     opj_image_t * image = NULL;
1591     unsigned short ch;
1592
1593     if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
1594     {
1595         fprintf(stderr,"\nError: invalid raw image parameters\n");
1596         fprintf(stderr,"Please use the Format option -F:\n");
1597         fprintf(stderr,"-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
1598         fprintf(stderr,"If subsampling is omitted, 1x1 is assumed for all components\n");
1599         fprintf(stderr,"Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
1600         fprintf(stderr,"         for raw 512x512 image with 4:2:0 subsampling\n");
1601         fprintf(stderr,"Aborting.\n");
1602         return NULL;
1603     }
1604
1605     f = fopen(filename, "rb");
1606     if (!f) {
1607         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
1608         fprintf(stderr,"Aborting\n");
1609         return NULL;
1610     }
1611     numcomps = raw_cp->rawComp;
1612
1613     /* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
1614     if (numcomps == 1) {
1615         color_space = OPJ_CLRSPC_GRAY;
1616     } else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
1617         color_space = OPJ_CLRSPC_SYCC;
1618     } else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
1619         color_space = OPJ_CLRSPC_SRGB;
1620     } else {
1621         color_space = OPJ_CLRSPC_UNKNOWN;
1622     }
1623     w = raw_cp->rawWidth;
1624     h = raw_cp->rawHeight;
1625     cmptparm = (opj_image_cmptparm_t*) calloc((OPJ_UINT32)numcomps,sizeof(opj_image_cmptparm_t));
1626     if (!cmptparm) {
1627         fprintf(stderr, "Failed to allocate image components parameters !!\n");
1628         fprintf(stderr,"Aborting\n");
1629         return NULL;
1630     }
1631     /* initialize image components */
1632     for(i = 0; i < numcomps; i++) {
1633         cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
1634         cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
1635         cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
1636         cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
1637         cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
1638         cmptparm[i].w = (OPJ_UINT32)w;
1639         cmptparm[i].h = (OPJ_UINT32)h;
1640     }
1641     /* create the image */
1642     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
1643     free(cmptparm);
1644     if(!image) {
1645         fclose(f);
1646         return NULL;
1647     }
1648     /* set image offset and reference grid */
1649     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
1650     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
1651     image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
1652     image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
1653
1654     if(raw_cp->rawBitDepth <= 8)
1655     {
1656         unsigned char value = 0;
1657         for(compno = 0; compno < numcomps; compno++) {
1658             int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dy);
1659             for (i = 0; i < nloop; i++) {
1660                 if (!fread(&value, 1, 1, f)) {
1661                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
1662                     return NULL;
1663                 }
1664                 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
1665             }
1666         }
1667     }
1668     else if(raw_cp->rawBitDepth <= 16)
1669     {
1670         unsigned short value;
1671         for(compno = 0; compno < numcomps; compno++) {
1672             int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dx);
1673             for (i = 0; i < nloop; i++) {
1674                 unsigned char temp1;
1675                 unsigned char temp2;
1676                 if (!fread(&temp1, 1, 1, f)) {
1677                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
1678                     return NULL;
1679                 }
1680                 if (!fread(&temp2, 1, 1, f)) {
1681                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
1682                     return NULL;
1683                 }
1684                 if( big_endian )
1685                 {
1686                     value = (unsigned short)((temp1 << 8) + temp2);
1687                 }
1688                 else
1689                 {
1690                     value = (unsigned short)((temp2 << 8) + temp1);
1691                 }
1692                 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
1693             }
1694         }
1695     }
1696     else {
1697         fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
1698         return NULL;
1699     }
1700
1701     if (fread(&ch, 1, 1, f)) {
1702         fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
1703     }
1704     fclose(f);
1705
1706     return image;
1707 }
1708
1709 opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
1710     return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
1711 }
1712
1713 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
1714     return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
1715 }
1716
1717 static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL big_endian)
1718 {
1719     FILE *rawFile = NULL;
1720     size_t res;
1721     unsigned int compno;
1722     int w, h, fails;
1723     int line, row, curr, mask;
1724     int *ptr;
1725     unsigned char uc;
1726     (void)big_endian;
1727
1728     if((image->numcomps * image->x1 * image->y1) == 0)
1729     {
1730         fprintf(stderr,"\nError: invalid raw image parameters\n");
1731         return 1;
1732     }
1733
1734     rawFile = fopen(outfile, "wb");
1735     if (!rawFile) {
1736         fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
1737         return 1;
1738     }
1739
1740     fails = 1;
1741     fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
1742
1743     for(compno = 0; compno < image->numcomps; compno++)
1744     {
1745         fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
1746                 image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
1747
1748         w = (int)image->comps[compno].w;
1749         h = (int)image->comps[compno].h;
1750
1751         if(image->comps[compno].prec <= 8)
1752         {
1753             if(image->comps[compno].sgnd == 1)
1754             {
1755                 mask = (1 << image->comps[compno].prec) - 1;
1756                 ptr = image->comps[compno].data;
1757                 for (line = 0; line < h; line++) {
1758                     for(row = 0; row < w; row++)        {
1759                         curr = *ptr;
1760                         if(curr > 127) curr = 127; else if(curr < -128) curr = -128;
1761                         uc = (unsigned char) (curr & mask);
1762                         res = fwrite(&uc, 1, 1, rawFile);
1763                         if( res < 1 ) {
1764                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
1765                             goto fin;
1766                         }
1767                         ptr++;
1768                     }
1769                 }
1770             }
1771             else if(image->comps[compno].sgnd == 0)
1772             {
1773                 mask = (1 << image->comps[compno].prec) - 1;
1774                 ptr = image->comps[compno].data;
1775                 for (line = 0; line < h; line++) {
1776                     for(row = 0; row < w; row++)        {
1777                         curr = *ptr;
1778                         if(curr > 255) curr = 255; else if(curr < 0) curr = 0;
1779                         uc = (unsigned char) (curr & mask);
1780                         res = fwrite(&uc, 1, 1, rawFile);
1781                         if( res < 1 ) {
1782                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
1783                             goto fin;
1784                         }
1785                         ptr++;
1786                     }
1787                 }
1788             }
1789         }
1790         else if(image->comps[compno].prec <= 16)
1791         {
1792             if(image->comps[compno].sgnd == 1)
1793             {
1794                 union { signed short val; signed char vals[2]; } uc16;
1795                 mask = (1 << image->comps[compno].prec) - 1;
1796                 ptr = image->comps[compno].data;
1797                 for (line = 0; line < h; line++) {
1798                     for(row = 0; row < w; row++)        {
1799                         curr = *ptr;
1800                         if(curr > 32767 ) curr = 32767; else if( curr < -32768) curr = -32768;
1801                         uc16.val = (signed short)(curr & mask);
1802                         res = fwrite(uc16.vals, 1, 2, rawFile);
1803                         if( res < 2 ) {
1804                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
1805                             goto fin;
1806                         }
1807                         ptr++;
1808                     }
1809                 }
1810             }
1811             else if(image->comps[compno].sgnd == 0)
1812             {
1813                 union { unsigned short val; unsigned char vals[2]; } uc16;
1814                 mask = (1 << image->comps[compno].prec) - 1;
1815                 ptr = image->comps[compno].data;
1816                 for (line = 0; line < h; line++) {
1817                     for(row = 0; row < w; row++)        {
1818                         curr = *ptr;
1819                         if(curr > 65535 ) curr = 65535; else if( curr < 0) curr = 0;
1820                         uc16.val = (unsigned short)(curr & mask);
1821                         res = fwrite(uc16.vals, 1, 2, rawFile);
1822                         if( res < 2 ) {
1823                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
1824                             goto fin;
1825                         }
1826                         ptr++;
1827                     }
1828                 }
1829             }
1830         }
1831         else if (image->comps[compno].prec <= 32)
1832         {
1833             fprintf(stderr,"More than 16 bits per component no handled yet\n");
1834             goto fin;
1835         }
1836         else
1837         {
1838             fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
1839             goto fin;
1840         }
1841     }
1842   fails = 0;
1843 fin:
1844     fclose(rawFile);
1845     return fails;
1846 }
1847
1848 int imagetoraw(opj_image_t * image, const char *outfile)
1849 {
1850     return imagetoraw_common(image, outfile, OPJ_TRUE);
1851 }
1852
1853 int imagetorawl(opj_image_t * image, const char *outfile)
1854 {
1855     return imagetoraw_common(image, outfile, OPJ_FALSE);
1856 }
1857