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