d56f3904b9a9a3c87fa46cbfac809e63933ea276
[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 void scale_component(opj_image_comp_t* component, OPJ_UINT32 precision)
106 {
107         int shift;
108         OPJ_SIZE_T i;
109         OPJ_SIZE_T len;
110         
111         if (component->prec == precision) {
112                 return;
113         }
114         if (component->prec < precision) {
115                 shift = (int)(precision - component->prec);
116         } else {
117                 shift = (int)(component->prec - precision);
118         }
119         len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h;
120         
121         if (component->sgnd) {
122                 OPJ_INT32* l_data = component->data;
123                 if (component->prec < precision) {
124                         for (i = 0; i < len; ++i) {
125                                 l_data[i] <<= shift;
126                         }
127                 } else {
128                         for (i = 0; i < len; ++i) {
129                                 l_data[i] >>= shift;
130                         }
131                 }
132         } else {
133                 OPJ_UINT32* l_data = (OPJ_UINT32*)component->data;
134                 if (component->prec < precision) {
135                         for (i = 0; i < len; ++i) {
136                                 l_data[i] <<= shift;
137                         }
138                 } else {
139                         for (i = 0; i < len; ++i) {
140                                 l_data[i] >>= shift;
141                         }
142                 }
143         }
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) 
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 (ncomp == 2 /* GRAYA */
1376             || (ncomp > 2 /* RGB, RGBA */
1377                 && image->comps[0].dx == image->comps[1].dx
1378                 && image->comps[1].dx == image->comps[2].dx
1379                 && image->comps[0].dy == image->comps[1].dy
1380                 && image->comps[1].dy == image->comps[2].dy
1381                 && image->comps[0].prec == image->comps[1].prec
1382                 && image->comps[1].prec == image->comps[2].prec
1383                 ))
1384     {
1385         fdest = fopen(outfile, "wb");
1386
1387         if (!fdest)
1388         {
1389             fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1390             return fails;
1391         }
1392         two = (prec > 8);
1393         triple = (ncomp > 2);
1394         wr = (int)image->comps[0].w; hr = (int)image->comps[0].h;
1395         max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);
1396
1397         red = image->comps[0].data;
1398
1399         if(triple)
1400         {
1401             green = image->comps[1].data;
1402             blue = image->comps[2].data;
1403         }
1404         else green = blue = NULL;
1405
1406         if(has_alpha)
1407         {
1408             const char *tt = (triple?"RGB_ALPHA":"GRAYSCALE_ALPHA");
1409
1410             fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %d\n"
1411                     "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
1412                     wr, hr, ncomp, max, tt);
1413             alpha = image->comps[ncomp - 1].data;
1414             adjustA = (image->comps[ncomp - 1].sgnd ?
1415                         1 << (image->comps[ncomp - 1].prec - 1) : 0);
1416         }
1417         else
1418         {
1419             fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
1420                     opj_version(), wr, hr, max);
1421             adjustA = 0;
1422         }
1423         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1424
1425         if(triple)
1426         {
1427             adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1428             adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1429         }
1430         else adjustG = adjustB = 0;
1431
1432         for(i = 0; i < wr * hr; ++i)
1433         {
1434             if(two)
1435             {
1436                 v = *red + adjustR; ++red;
1437 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1438
1439                 /* netpbm: */
1440                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1441
1442                 if(triple)
1443                 {
1444                     v = *green + adjustG; ++green;
1445 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1446
1447                     /* netpbm: */
1448                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1449
1450                     v =  *blue + adjustB; ++blue;
1451 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1452
1453                     /* netpbm: */
1454                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1455
1456                 }/* if(triple) */
1457
1458                 if(has_alpha)
1459                 {
1460                     v = *alpha + adjustA; ++alpha;
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                 continue;
1467
1468             }   /* if(two) */
1469
1470             /* prec <= 8: */
1471         v = *red++;
1472         if(v > 255) v = 255; else if(v < 0) v = 0;
1473
1474         fprintf(fdest, "%c", (unsigned char)v);
1475             if(triple)
1476  {
1477         v = *green++;
1478         if(v > 255) v = 255; else if(v < 0) v = 0;
1479
1480         fprintf(fdest, "%c", (unsigned char)v);
1481         v = *blue++;
1482         if(v > 255) v = 255; else if(v < 0) v = 0;
1483
1484         fprintf(fdest, "%c", (unsigned char)v);
1485  }
1486             if(has_alpha)
1487  {
1488         v = *alpha++;
1489         if(v > 255) v = 255; else if(v < 0) v = 0;
1490
1491         fprintf(fdest, "%c", (unsigned char)v);
1492  }
1493         }       /* for(i */
1494
1495         fclose(fdest); return 0;
1496     }
1497
1498     /* YUV or MONO: */
1499
1500     if (image->numcomps > ncomp)
1501     {
1502         fprintf(stderr,"WARNING -> [PGM file] Only the first component\n");
1503         fprintf(stderr,"           is written to the file\n");
1504     }
1505     destname = (char*)malloc(strlen(outfile) + 8);
1506
1507     for (compno = 0; compno < ncomp; compno++)
1508     {
1509     if (ncomp > 1)
1510       {
1511       /*sprintf(destname, "%d.%s", compno, outfile);*/
1512       const size_t olen = strlen(outfile);
1513       const size_t dotpos = olen - 4;
1514
1515       strncpy(destname, outfile, dotpos);
1516       sprintf(destname+dotpos, "_%d.pgm", compno);
1517       }
1518         else
1519             sprintf(destname, "%s", outfile);
1520
1521         fdest = fopen(destname, "wb");
1522         if (!fdest)
1523         {
1524             fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
1525             free(destname);
1526             return 1;
1527         }
1528         wr = (int)image->comps[compno].w; hr = (int)image->comps[compno].h;
1529         prec = (int)image->comps[compno].prec;
1530         max = (1<<prec) - 1;
1531
1532         fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
1533                 opj_version(), wr, hr, max);
1534
1535         red = image->comps[compno].data;
1536         adjustR =
1537                 (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
1538
1539         if(prec > 8)
1540         {
1541             for (i = 0; i < wr * hr; i++)
1542             {
1543                 v = *red + adjustR; ++red;
1544 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1545
1546                 /* netpbm: */
1547                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1548
1549                 if(has_alpha)
1550                 {
1551                     v = *alpha++;
1552 if(v > 65535) v = 65535; else if(v < 0) v = 0;
1553
1554                     /* netpbm: */
1555                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
1556                 }
1557             }/* for(i */
1558         }
1559         else /* prec <= 8 */
1560         {
1561             for(i = 0; i < wr * hr; ++i)
1562             {
1563         v = *red + adjustR; ++red;
1564         if(v > 255) v = 255; else if(v < 0) v = 0;
1565
1566          fprintf(fdest, "%c", (unsigned char)v);
1567             }
1568         }
1569         fclose(fdest);
1570     } /* for (compno */
1571     free(destname);
1572
1573     return 0;
1574 }/* imagetopnm() */
1575
1576 #ifdef OPJ_HAVE_LIBTIFF
1577 /* -->> -->> -->> -->>
1578
1579     TIFF IMAGE FORMAT
1580
1581  <<-- <<-- <<-- <<-- */
1582
1583 int imagetotif(opj_image_t * image, const char *outfile) 
1584 {
1585     int width, height, imgsize;
1586     int bps,index,adjust, sgnd;
1587     int ushift, dshift, has_alpha, force16;
1588     TIFF *tif;
1589     tdata_t buf;
1590     tstrip_t strip;
1591     tsize_t strip_size;
1592
1593     ushift = dshift = force16 = has_alpha = 0;
1594     bps = (int)image->comps[0].prec;
1595
1596     if(bps > 8 && bps < 16)
1597     {
1598         ushift = 16 - bps; dshift = bps - ushift;
1599         bps = 16; force16 = 1;
1600     }
1601
1602     if(bps != 8 && bps != 16)
1603     {
1604         fprintf(stderr,"imagetotif: Bits=%d, Only 8 and 16 bits implemented\n",
1605                 bps);
1606         fprintf(stderr,"\tAborting\n");
1607         return 1;
1608     }
1609     tif = TIFFOpen(outfile, "wb");
1610
1611     if (!tif)
1612     {
1613         fprintf(stderr, "imagetotif:failed to open %s for writing\n", outfile);
1614         return 1;
1615     }
1616     sgnd = (int)image->comps[0].sgnd;
1617     adjust = sgnd ? 1 << (image->comps[0].prec - 1) : 0;
1618
1619     if(image->numcomps >= 3
1620             && image->comps[0].dx == image->comps[1].dx
1621             && image->comps[1].dx == image->comps[2].dx
1622             && image->comps[0].dy == image->comps[1].dy
1623             && image->comps[1].dy == image->comps[2].dy
1624             && image->comps[0].prec == image->comps[1].prec
1625             && image->comps[1].prec == image->comps[2].prec)
1626     {
1627         has_alpha = (image->numcomps == 4);
1628
1629         width   = (int)image->comps[0].w;
1630         height  = (int)image->comps[0].h;
1631         imgsize = width * height ;
1632
1633         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
1634         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
1635         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3 + has_alpha);
1636         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1637         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
1638         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
1639         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
1640         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
1641         strip_size = TIFFStripSize(tif);
1642         buf = _TIFFmalloc(strip_size);
1643         index=0;
1644
1645         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
1646         {
1647             unsigned char *dat8;
1648             tsize_t i, ssize, last_i = 0;
1649             int step, restx;
1650             ssize = TIFFStripSize(tif);
1651             dat8 = (unsigned char*)buf;
1652
1653             if(bps == 8)
1654             {
1655                 step = 3 + has_alpha;
1656                 restx = step - 1;
1657
1658                 for(i=0; i < ssize - restx; i += step)
1659                 {
1660                     int r, g, b, a = 0;
1661
1662                     if(index < imgsize)
1663                     {
1664                         r = image->comps[0].data[index];
1665                         g = image->comps[1].data[index];
1666                         b = image->comps[2].data[index];
1667                         if(has_alpha) a = image->comps[3].data[index];
1668
1669                         if(sgnd)
1670                         {
1671                             r += adjust;
1672                             g += adjust;
1673                             b += adjust;
1674                             if(has_alpha) a += adjust;
1675                         }
1676                 if(r > 255) r = 255; else if(r < 0) r = 0;
1677                         dat8[i+0] = (unsigned char)r ;
1678                 if(g > 255) g = 255; else if(g < 0) g = 0;
1679                         dat8[i+1] = (unsigned char)g ;
1680                 if(b > 255) b = 255; else if(b < 0) b = 0;
1681                         dat8[i+2] = (unsigned char)b ;
1682                 if(has_alpha) 
1683          {
1684                 if(a > 255) a = 255; else if(a < 0) a = 0;
1685                 dat8[i+3] = (unsigned char)a;
1686          }
1687
1688                         index++;
1689                         last_i = i + step;
1690                     }
1691                     else
1692                         break;
1693                 }/*for(i = 0;)*/
1694
1695                 if(last_i < ssize)
1696                 {
1697                     for(i = last_i; i < ssize; i += step)
1698                     {
1699                         int r, g, b, a = 0;
1700
1701                         if(index < imgsize)
1702                         {
1703                             r = image->comps[0].data[index];
1704                             g = image->comps[1].data[index];
1705                             b = image->comps[2].data[index];
1706                             if(has_alpha) a = image->comps[3].data[index];
1707
1708                             if(sgnd)
1709                             {
1710                                 r += adjust;
1711                                 g += adjust;
1712                                 b += adjust;
1713                                 if(has_alpha) a += adjust;
1714                             }
1715                 if(r > 255) r = 255; else if(r < 0) r = 0;
1716                 if(g > 255) g = 255; else if(g < 0) g = 0;
1717                 if(b > 255) b = 255; else if(b < 0) b = 0;
1718
1719                             dat8[i+0] = (unsigned char)r ;
1720                             if(i+1 < ssize) dat8[i+1] = (unsigned char)g ;  else break;
1721                             if(i+2 < ssize) dat8[i+2] = (unsigned char)b ;  else break;
1722                             if(has_alpha)
1723                             {
1724                 if(a > 255) a = 255; else if(a < 0) a = 0;
1725
1726                                 if(i+3 < ssize) dat8[i+3] = (unsigned char)a ;  else break;
1727                             }
1728                             index++;
1729                         }
1730                         else
1731                             break;
1732                     }/*for(i)*/
1733                 }/*if(last_i < ssize)*/
1734
1735             }   /*if(bps == 8)*/
1736             else
1737                 if(bps == 16)
1738                 {
1739                     step = 6 + has_alpha + has_alpha;
1740                     restx = step - 1;
1741
1742                     for(i = 0; i < ssize - restx ; i += step)
1743                     {
1744                         int r, g, b, a = 0;
1745
1746                         if(index < imgsize)
1747                         {
1748                             r = image->comps[0].data[index];
1749                             g = image->comps[1].data[index];
1750                             b = image->comps[2].data[index];
1751                             if(has_alpha) a = image->comps[3].data[index];
1752
1753                             if(sgnd)
1754                             {
1755                                 r += adjust;
1756                                 g += adjust;
1757                                 b += adjust;
1758                                 if(has_alpha) a += adjust;
1759                             }
1760                             if(force16)
1761                             {
1762                                 r = (r<<ushift) + (r>>dshift);
1763                                 g = (g<<ushift) + (g>>dshift);
1764                                 b = (b<<ushift) + (b>>dshift);
1765                                 if(has_alpha) a = (a<<ushift) + (a>>dshift);
1766                             }
1767                 if(r > 65535) r = 65535; else if(r < 0) r = 0;
1768                 if(g > 65535) g = 65535; else if(g < 0) g = 0;
1769                 if(b > 65535) b = 65535; else if(b < 0) b = 0;
1770
1771                             dat8[i+0] =  (unsigned char)r;/*LSB*/
1772                             dat8[i+1] = (unsigned char)(r >> 8);/*MSB*/
1773                             dat8[i+2] =  (unsigned char)g;
1774                             dat8[i+3] = (unsigned char)(g >> 8);
1775                             dat8[i+4] =  (unsigned char)b;
1776                             dat8[i+5] = (unsigned char)(b >> 8);
1777                             if(has_alpha)
1778                             {
1779                 if(a > 65535) a = 65535; else if(a < 0) a = 0;
1780                                 dat8[i+6] =  (unsigned char)a;
1781                                 dat8[i+7] = (unsigned char)(a >> 8);
1782                             }
1783                             index++;
1784                             last_i = i + step;
1785                         }
1786                         else
1787                             break;
1788                     }/*for(i = 0;)*/
1789
1790                     if(last_i < ssize)
1791                     {
1792                         for(i = last_i ; i < ssize ; i += step)
1793                         {
1794                             int r, g, b, a = 0;
1795
1796                             if(index < imgsize)
1797                             {
1798                                 r = image->comps[0].data[index];
1799                                 g = image->comps[1].data[index];
1800                                 b = image->comps[2].data[index];
1801                                 if(has_alpha) a = image->comps[3].data[index];
1802
1803                                 if(sgnd)
1804                                 {
1805                                     r += adjust;
1806                                     g += adjust;
1807                                     b += adjust;
1808                                     if(has_alpha) a += adjust;
1809                                 }
1810                                 if(force16)
1811                                 {
1812                                     r = (r<<ushift) + (r>>dshift);
1813                                     g = (g<<ushift) + (g>>dshift);
1814                                     b = (b<<ushift) + (b>>dshift);
1815                                     if(has_alpha) a = (a<<ushift) + (a>>dshift);
1816                                 }
1817                 if(r > 65535) r = 65535; else if(r < 0) r = 0;
1818                 if(g > 65535) g = 65535; else if(g < 0) g = 0;
1819                 if(b > 65535) b = 65535; else if(b < 0) b = 0;
1820
1821                                 dat8[i+0] = (unsigned char) r;/*LSB*/
1822                                 if(i+1 < ssize) dat8[i+1] = (unsigned char)(r >> 8);else break;/*MSB*/
1823                                 if(i+2 < ssize) dat8[i+2] = (unsigned char) g;      else break;
1824                                 if(i+3 < ssize) dat8[i+3] = (unsigned char)(g >> 8);else break;
1825                                 if(i+4 < ssize) dat8[i+4] = (unsigned char) b;      else break;
1826                                 if(i+5 < ssize) dat8[i+5] = (unsigned char)(b >> 8);else break;
1827
1828                                 if(has_alpha)
1829                                 {
1830                 if(a > 65535) a = 65535; else if(a < 0) a = 0;
1831                                     if(i+6 < ssize) dat8[i+6] = (unsigned char)a; else break;
1832                                     if(i+7 < ssize) dat8[i+7] = (unsigned char)(a >> 8); else break;
1833                                 }
1834                                 index++;
1835                             }
1836                             else
1837                                 break;
1838                         }/*for(i)*/
1839                     }/*if(last_i < ssize)*/
1840
1841                 }/*if(bps == 16)*/
1842             (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
1843         }/*for(strip = 0; )*/
1844
1845         _TIFFfree((void*)buf);
1846         TIFFClose(tif);
1847
1848         return 0;
1849     }/*RGB(A)*/
1850
1851     if(image->numcomps == 1 /* GRAY */
1852             || (   image->numcomps == 2 /* GRAY_ALPHA */
1853                    && image->comps[0].dx == image->comps[1].dx
1854                    && image->comps[0].dy == image->comps[1].dy
1855                    && image->comps[0].prec == image->comps[1].prec))
1856     {
1857         int step;
1858
1859         has_alpha = (image->numcomps == 2);
1860
1861         width   = (int)image->comps[0].w;
1862         height  = (int)image->comps[0].h;
1863         imgsize = width * height;
1864
1865         /* Set tags */
1866         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
1867         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
1868         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1 + has_alpha);
1869         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
1870         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
1871         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
1872         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
1873         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
1874
1875         /* Get a buffer for the data */
1876         strip_size = TIFFStripSize(tif);
1877         buf = _TIFFmalloc(strip_size);
1878         index = 0;
1879
1880         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
1881         {
1882             unsigned char *dat8;
1883             tsize_t i, ssize = TIFFStripSize(tif);
1884             dat8 = (unsigned char*)buf;
1885
1886             if(bps == 8)
1887             {
1888                 step = 1 + has_alpha;
1889
1890                 for(i=0; i < ssize; i += step)
1891                 {
1892                     if(index < imgsize)
1893                     {
1894                         int r, a = 0;
1895
1896                         r = image->comps[0].data[index];
1897                         if(has_alpha) a = image->comps[1].data[index];
1898
1899                         if(sgnd)
1900                         {
1901                             r += adjust;
1902                             if(has_alpha) a += adjust;
1903                         }
1904                 if(r > 255) r = 255; else if(r < 0) r = 0;
1905                         dat8[i+0] = (unsigned char)r;
1906
1907                 if(has_alpha) 
1908          {
1909                 if(a > 255) a = 255; else if(a < 0) a = 0;
1910                 dat8[i+1] = (unsigned char)a;
1911                     }
1912                 index++;
1913           }
1914                     else
1915                         break;
1916            }/*for(i )*/
1917             }/*if(bps == 8*/
1918             else
1919                 if(bps == 16)
1920                 {
1921                     step = 2 + has_alpha + has_alpha;
1922
1923                     for(i=0; i < ssize; i += step)
1924                     {
1925                         if(index < imgsize)
1926                         {
1927                             int r, a = 0;
1928
1929                             r = image->comps[0].data[index];
1930                             if(has_alpha) a = image->comps[1].data[index];
1931
1932                             if(sgnd)
1933                             {
1934                                 r += adjust;
1935                                 if(has_alpha) a += adjust;
1936                             }
1937                             if(force16)
1938                             {
1939                                 r = (r<<ushift) + (r>>dshift);
1940                                 if(has_alpha) a = (a<<ushift) + (a>>dshift);
1941                             }
1942                 if(r > 65535) r = 65535; else if(r < 0) r = 0;
1943                             dat8[i+0] = (unsigned char)r;/*LSB*/
1944                             dat8[i+1] = (unsigned char)(r >> 8);/*MSB*/
1945                             if(has_alpha)
1946                             {
1947                 if(a > 65535) a = 65535; else if(a < 0) a = 0;
1948                                 dat8[i+2] = (unsigned char)a;
1949                                 dat8[i+3] = (unsigned char)(a >> 8);
1950                             }
1951                             index++;
1952                         }/*if(index < imgsize)*/
1953                         else
1954                             break;
1955                     }/*for(i )*/
1956                 }
1957             (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
1958         }/*for(strip*/
1959
1960         _TIFFfree(buf);
1961         TIFFClose(tif);
1962
1963         return 0;
1964     }
1965
1966     TIFFClose(tif);
1967
1968     fprintf(stderr,"imagetotif: Bad color format.\n"
1969             "\tOnly RGB(A) and GRAY(A) has been implemented\n");
1970     fprintf(stderr,"\tFOUND: numcomps(%d)\n\tAborting\n",
1971             image->numcomps);
1972
1973     return 1;
1974 }/* imagetotif() */
1975
1976 /*
1977  * libtiff/tif_getimage.c : 1,2,4,8,16 bitspersample accepted
1978  * CINEMA                 : 12 bit precision
1979 */
1980 opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
1981 {
1982     int subsampling_dx = parameters->subsampling_dx;
1983     int subsampling_dy = parameters->subsampling_dy;
1984     TIFF *tif;
1985     tdata_t buf;
1986     tstrip_t strip;
1987     tsize_t strip_size;
1988     int j, numcomps, w, h,index;
1989     OPJ_COLOR_SPACE color_space;
1990     opj_image_cmptparm_t cmptparm[4]; /* RGBA */
1991     opj_image_t *image = NULL;
1992     int imgsize = 0;
1993     int has_alpha = 0;
1994     unsigned short tiBps, tiPhoto, tiSf, tiSpp, tiPC;
1995     unsigned int tiWidth, tiHeight;
1996     OPJ_BOOL is_cinema = OPJ_IS_CINEMA(parameters->rsiz);
1997
1998     tif = TIFFOpen(filename, "r");
1999
2000     if(!tif)
2001     {
2002         fprintf(stderr, "tiftoimage:Failed to open %s for reading\n", filename);
2003         return 0;
2004     }
2005     tiBps = tiPhoto = tiSf = tiSpp = tiPC = 0;
2006     tiWidth = tiHeight = 0;
2007
2008     TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &tiWidth);
2009     TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &tiHeight);
2010     TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &tiBps);
2011     TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &tiSf);
2012     TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &tiSpp);
2013     TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &tiPhoto);
2014     TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &tiPC);
2015     w= (int)tiWidth;
2016     h= (int)tiHeight;
2017
2018     if(tiBps != 8 && tiBps != 16 && tiBps != 12) tiBps = 0;
2019     if(tiPhoto != 1 && tiPhoto != 2) tiPhoto = 0;
2020
2021     if( !tiBps || !tiPhoto)
2022     {
2023         if( !tiBps)
2024      fprintf(stderr,"tiftoimage: Bits=%d, Only 8 and 16 bits"
2025                     " implemented\n",tiBps);
2026         else
2027             if( !tiPhoto)
2028                 fprintf(stderr,"tiftoimage: Bad color format %d.\n\tOnly RGB(A)"
2029                         " and GRAY(A) has been implemented\n",(int) tiPhoto);
2030
2031         fprintf(stderr,"\tAborting\n");
2032         TIFFClose(tif);
2033
2034         return NULL;
2035     }
2036
2037     {/* From: tiff-4.0.x/libtiff/tif_getimage.c : */
2038         uint16* sampleinfo;
2039         uint16 extrasamples;
2040
2041         TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
2042                               &extrasamples, &sampleinfo);
2043
2044         if(extrasamples >= 1)
2045         {
2046             switch(sampleinfo[0])
2047             {
2048             case EXTRASAMPLE_UNSPECIFIED:
2049                 /* Workaround for some images without correct info about alpha channel
2050 */
2051                 if(tiSpp > 3)
2052                     has_alpha = 1;
2053                 break;
2054
2055             case EXTRASAMPLE_ASSOCALPHA: /* data pre-multiplied */
2056             case EXTRASAMPLE_UNASSALPHA: /* data not pre-multiplied */
2057                 has_alpha = 1;
2058                 break;
2059             }
2060         }
2061         else /* extrasamples == 0 */
2062             if(tiSpp == 4 || tiSpp == 2) has_alpha = 1;
2063     }
2064
2065     /* initialize image components
2066 */ 
2067     memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
2068
2069     if ((tiPhoto == PHOTOMETRIC_RGB) && (is_cinema)) {
2070         fprintf(stdout,"WARNING:\n"
2071                 "Input image bitdepth is %d bits\n"
2072                 "TIF conversion has automatically rescaled to 12-bits\n"
2073                 "to comply with cinema profiles.\n",
2074                 tiBps);
2075     }
2076
2077     if(tiPhoto == PHOTOMETRIC_RGB) /* RGB(A) */
2078     {
2079         numcomps = 3 + has_alpha;
2080         color_space = OPJ_CLRSPC_SRGB;
2081
2082         /*#define USETILEMODE*/
2083         for(j = 0; j < numcomps; j++)
2084         {
2085             if(is_cinema)
2086             {
2087                 cmptparm[j].prec = 12;
2088                 cmptparm[j].bpp = 12;
2089             }
2090             else
2091             {
2092                 cmptparm[j].prec = tiBps;
2093                 cmptparm[j].bpp = tiBps;
2094             }
2095             cmptparm[j].dx = (OPJ_UINT32)subsampling_dx;
2096             cmptparm[j].dy = (OPJ_UINT32)subsampling_dy;
2097             cmptparm[j].w = (OPJ_UINT32)w;
2098             cmptparm[j].h = (OPJ_UINT32)h;
2099 #ifdef USETILEMODE
2100             cmptparm[j].x0 = 0;
2101             cmptparm[j].y0 = 0;
2102 #endif
2103         }
2104
2105 #ifdef USETILEMODE
2106         image = opj_image_tile_create(numcomps,&cmptparm[0],color_space);
2107 #else
2108         image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2109 #endif
2110
2111         if(!image)
2112         {
2113             TIFFClose(tif);
2114             return NULL;
2115         }
2116         /* set image offset and reference grid
2117 */
2118         image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2119         image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2120         image->x1 =     !image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 :
2121                                  image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
2122         image->y1 =     !image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 :
2123                                  image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
2124
2125         buf = _TIFFmalloc(TIFFStripSize(tif));
2126
2127         strip_size=TIFFStripSize(tif);
2128         index = 0;
2129         imgsize = (int)(image->comps[0].w * image->comps[0].h);
2130         /* Read the Image components
2131 */
2132         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
2133         {
2134             unsigned char *dat8;
2135             int step;
2136             tsize_t i, ssize;
2137             ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2138             dat8 = (unsigned char*)buf;
2139
2140             if(tiBps == 16)
2141             {
2142                 step = 6 + has_alpha + has_alpha;
2143
2144                 for(i = 0; i < ssize; i += step)
2145                 {
2146                     if(index < imgsize)
2147                     {
2148                         image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0]; /* R */
2149                         image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2]; /* G */
2150                         image->comps[2].data[index] = ( dat8[i+5] << 8 ) | dat8[i+4]; /* B */
2151                         if(has_alpha)
2152                             image->comps[3].data[index] = ( dat8[i+7] << 8 ) | dat8[i+6];
2153
2154                         if(is_cinema)
2155                         {
2156                             /* Rounding 16 to 12 bits
2157 */
2158                             image->comps[0].data[index] =
2159                                     (image->comps[0].data[index] + 0x08) >> 4 ;
2160                             image->comps[1].data[index] =
2161                                     (image->comps[1].data[index] + 0x08) >> 4 ;
2162                             image->comps[2].data[index] =
2163                                     (image->comps[2].data[index] + 0x08) >> 4 ;
2164                             if(has_alpha)
2165                                 image->comps[3].data[index] =
2166                                         (image->comps[3].data[index] + 0x08) >> 4 ;
2167                         }
2168                         index++;
2169                     }
2170                     else
2171                         break;
2172                 }/*for(i = 0)*/
2173             }/*if(tiBps == 16)*/
2174             else
2175                 if(tiBps == 8)
2176                 {
2177                     step = 3 + has_alpha;
2178
2179                     for(i = 0; i < ssize; i += step)
2180                     {
2181                         if(index < imgsize)
2182                         {
2183 #ifndef USETILEMODE
2184                             image->comps[0].data[index] = dat8[i+0];/* R */
2185                             image->comps[1].data[index] = dat8[i+1];/* G */
2186                             image->comps[2].data[index] = dat8[i+2];/* B */
2187                             if(has_alpha)
2188                                 image->comps[3].data[index] = dat8[i+3];
2189 #endif
2190
2191                             if(is_cinema)
2192                             {
2193                                 /* Rounding 8 to 12 bits
2194 */
2195 #ifndef USETILEMODE
2196                                 image->comps[0].data[index] = image->comps[0].data[index] << 4 ;
2197                                 image->comps[1].data[index] = image->comps[1].data[index] << 4 ;
2198                                 image->comps[2].data[index] = image->comps[2].data[index] << 4 ;
2199                                 if(has_alpha)
2200                                     image->comps[3].data[index] = image->comps[3].data[index] << 4 ;
2201 #endif
2202                             }
2203                             index++;
2204                         }/*if(index*/
2205                         else
2206                             break;
2207                     }/*for(i )*/
2208                 }/*if( tiBps == 8)*/
2209                 else
2210                     if(tiBps == 12)/* CINEMA file */
2211                     {
2212                         step = 9;
2213
2214                         for(i = 0; i < ssize; i += step)
2215                         {
2216                             if((index < imgsize)&&(index+1 < imgsize))
2217                             {
2218                                 image->comps[0].data[index]   = ( dat8[i+0]<<4 )        |(dat8[i+1]>>4);
2219                                 image->comps[1].data[index]   = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
2220
2221                                 image->comps[2].data[index]   = ( dat8[i+3]<<4)         |(dat8[i+4]>>4);
2222                                 image->comps[0].data[index+1] = ((dat8[i+4]& 0x0f)<< 8) | dat8[i+5];
2223
2224                                 image->comps[1].data[index+1] = ( dat8[i+6] <<4)        |(dat8[i+7]>>4);
2225                                 image->comps[2].data[index+1] = ((dat8[i+7]& 0x0f)<< 8) | dat8[i+8];
2226
2227                                 index += 2;
2228                             }
2229                             else
2230                                 break;
2231                         }/*for(i )*/
2232                     }
2233         }/*for(strip = 0; )*/
2234
2235         _TIFFfree(buf);
2236         TIFFClose(tif);
2237
2238         return image;
2239     }/*RGB(A)*/
2240
2241     if(tiPhoto == PHOTOMETRIC_MINISBLACK) /* GRAY(A) */
2242     {
2243         numcomps = 1 + has_alpha;
2244         color_space = OPJ_CLRSPC_GRAY;
2245
2246         for(j = 0; j < numcomps; ++j)
2247         {
2248             cmptparm[j].prec = tiBps;
2249             cmptparm[j].bpp = tiBps;
2250             cmptparm[j].dx = (OPJ_UINT32)subsampling_dx;
2251             cmptparm[j].dy = (OPJ_UINT32)subsampling_dy;
2252             cmptparm[j].w = (OPJ_UINT32)w;
2253             cmptparm[j].h = (OPJ_UINT32)h;
2254         }
2255 #ifdef USETILEMODE
2256         image = opj_image_tile_create(numcomps,&cmptparm[0],color_space);
2257 #else
2258         image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2259 #endif
2260
2261         if(!image)
2262         {
2263             TIFFClose(tif);
2264             return NULL;
2265         }
2266         /* set image offset and reference grid
2267 */
2268         image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2269         image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2270         image->x1 =     !image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 :
2271                                  image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
2272         image->y1 =     !image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 :
2273                                  image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
2274
2275         buf = _TIFFmalloc(TIFFStripSize(tif));
2276
2277         strip_size = TIFFStripSize(tif);
2278         index = 0;
2279         imgsize = (int)(image->comps[0].w * image->comps[0].h);
2280         /* Read the Image components
2281 */
2282         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
2283         {
2284             unsigned char *dat8;
2285             tsize_t i, ssize;
2286             int step;
2287
2288             ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2289             dat8 = (unsigned char*)buf;
2290
2291             if(tiBps == 16)
2292             {
2293                 step = 2 + has_alpha + has_alpha;
2294
2295                 for(i = 0; i < ssize; i += step)
2296                 {
2297                     if(index < imgsize)
2298                     {
2299                         image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0];
2300                         if(has_alpha)
2301                             image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2];
2302                         index++;
2303                     }
2304                     else
2305                         break;
2306                 }/*for(i )*/
2307             }
2308             else
2309                 if(tiBps == 8)
2310                 {
2311                     step = 1 + has_alpha;
2312
2313                     for(i = 0; i < ssize; i += step)
2314                     {
2315                         if(index < imgsize)
2316                         {
2317                             image->comps[0].data[index] = dat8[i+0];
2318                             if(has_alpha)
2319                                 image->comps[1].data[index] = dat8[i+1];
2320                             index++;
2321                         }
2322                         else
2323                             break;
2324                     }/*for(i )*/
2325                 }
2326         }/*for(strip = 0;*/
2327
2328         _TIFFfree(buf);
2329         TIFFClose(tif);
2330
2331     }/*GRAY(A)*/
2332
2333     return image;
2334
2335 }/* tiftoimage() */
2336
2337 #endif /* OPJ_HAVE_LIBTIFF */
2338
2339 /* -->> -->> -->> -->>
2340
2341     RAW IMAGE FORMAT
2342
2343  <<-- <<-- <<-- <<-- */
2344 static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian) {
2345     int subsampling_dx = parameters->subsampling_dx;
2346     int subsampling_dy = parameters->subsampling_dy;
2347
2348     FILE *f = NULL;
2349     int i, compno, numcomps, w, h;
2350     OPJ_COLOR_SPACE color_space;
2351     opj_image_cmptparm_t *cmptparm;
2352     opj_image_t * image = NULL;
2353     unsigned short ch;
2354
2355     if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
2356     {
2357         fprintf(stderr,"\nError: invalid raw image parameters\n");
2358         fprintf(stderr,"Please use the Format option -F:\n");
2359         fprintf(stderr,"-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
2360         fprintf(stderr,"If subsampling is omitted, 1x1 is assumed for all components\n");
2361         fprintf(stderr,"Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
2362         fprintf(stderr,"         for raw 512x512 image with 4:2:0 subsampling\n");
2363         fprintf(stderr,"Aborting.\n");
2364         return NULL;
2365     }
2366
2367     f = fopen(filename, "rb");
2368     if (!f) {
2369         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
2370         fprintf(stderr,"Aborting\n");
2371         return NULL;
2372     }
2373     numcomps = raw_cp->rawComp;
2374
2375     /* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
2376     if (numcomps == 0) {
2377         color_space = OPJ_CLRSPC_GRAY;
2378     } else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
2379         color_space = OPJ_CLRSPC_SYCC;
2380     } else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
2381         color_space = OPJ_CLRSPC_SRGB;
2382     } else {
2383         color_space = OPJ_CLRSPC_UNKNOWN;
2384     }
2385     w = raw_cp->rawWidth;
2386     h = raw_cp->rawHeight;
2387     cmptparm = (opj_image_cmptparm_t*) calloc((OPJ_UINT32)numcomps,sizeof(opj_image_cmptparm_t));
2388     if (!cmptparm) {
2389         fprintf(stderr, "Failed to allocate image components parameters !!\n");
2390         fprintf(stderr,"Aborting\n");
2391         return NULL;
2392     }
2393     /* initialize image components */
2394     for(i = 0; i < numcomps; i++) {
2395         cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
2396         cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
2397         cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
2398         cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
2399         cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
2400         cmptparm[i].w = (OPJ_UINT32)w;
2401         cmptparm[i].h = (OPJ_UINT32)h;
2402     }
2403     /* create the image */
2404     image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
2405     free(cmptparm);
2406     if(!image) {
2407         fclose(f);
2408         return NULL;
2409     }
2410     /* set image offset and reference grid */
2411     image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
2412     image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
2413     image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
2414     image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
2415
2416     if(raw_cp->rawBitDepth <= 8)
2417     {
2418         unsigned char value = 0;
2419         for(compno = 0; compno < numcomps; compno++) {
2420             int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dy);
2421             for (i = 0; i < nloop; i++) {
2422                 if (!fread(&value, 1, 1, f)) {
2423                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2424                     return NULL;
2425                 }
2426                 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
2427             }
2428         }
2429     }
2430     else if(raw_cp->rawBitDepth <= 16)
2431     {
2432         unsigned short value;
2433         for(compno = 0; compno < numcomps; compno++) {
2434             int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dx);
2435             for (i = 0; i < nloop; i++) {
2436                 unsigned char temp1;
2437                 unsigned char temp2;
2438                 if (!fread(&temp1, 1, 1, f)) {
2439                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2440                     return NULL;
2441                 }
2442                 if (!fread(&temp2, 1, 1, f)) {
2443                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2444                     return NULL;
2445                 }
2446                 if( big_endian )
2447                 {
2448                     value = (unsigned short)((temp1 << 8) + temp2);
2449                 }
2450                 else
2451                 {
2452                     value = (unsigned short)((temp2 << 8) + temp1);
2453                 }
2454                 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
2455             }
2456         }
2457     }
2458     else {
2459         fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
2460         return NULL;
2461     }
2462
2463     if (fread(&ch, 1, 1, f)) {
2464         fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
2465     }
2466     fclose(f);
2467
2468     return image;
2469 }
2470
2471 opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
2472     return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
2473 }
2474
2475 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
2476     return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
2477 }
2478
2479 static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL big_endian)
2480 {
2481     FILE *rawFile = NULL;
2482     size_t res;
2483     unsigned int compno;
2484     int w, h, fails;
2485     int line, row, curr, mask;
2486     int *ptr;
2487     unsigned char uc;
2488     (void)big_endian;
2489
2490     if((image->numcomps * image->x1 * image->y1) == 0)
2491     {
2492         fprintf(stderr,"\nError: invalid raw image parameters\n");
2493         return 1;
2494     }
2495
2496     rawFile = fopen(outfile, "wb");
2497     if (!rawFile) {
2498         fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
2499         return 1;
2500     }
2501
2502     fails = 1;
2503     fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
2504
2505     for(compno = 0; compno < image->numcomps; compno++)
2506     {
2507         fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
2508                 image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
2509
2510         w = (int)image->comps[compno].w;
2511         h = (int)image->comps[compno].h;
2512
2513         if(image->comps[compno].prec <= 8)
2514         {
2515             if(image->comps[compno].sgnd == 1)
2516             {
2517                 mask = (1 << image->comps[compno].prec) - 1;
2518                 ptr = image->comps[compno].data;
2519                 for (line = 0; line < h; line++) {
2520                     for(row = 0; row < w; row++)        {
2521                         curr = *ptr;
2522                         if(curr > 127) curr = 127; else if(curr < -128) curr = -128;
2523                         uc = (unsigned char) (curr & mask);
2524                         res = fwrite(&uc, 1, 1, rawFile);
2525                         if( res < 1 ) {
2526                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2527                             goto fin;
2528                         }
2529                         ptr++;
2530                     }
2531                 }
2532             }
2533             else if(image->comps[compno].sgnd == 0)
2534             {
2535                 mask = (1 << image->comps[compno].prec) - 1;
2536                 ptr = image->comps[compno].data;
2537                 for (line = 0; line < h; line++) {
2538                     for(row = 0; row < w; row++)        {
2539                         curr = *ptr;
2540                         if(curr > 255) curr = 255; else if(curr < 0) curr = 0;
2541                         uc = (unsigned char) (curr & mask);
2542                         res = fwrite(&uc, 1, 1, rawFile);
2543                         if( res < 1 ) {
2544                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
2545                             goto fin;
2546                         }
2547                         ptr++;
2548                     }
2549                 }
2550             }
2551         }
2552         else if(image->comps[compno].prec <= 16)
2553         {
2554             if(image->comps[compno].sgnd == 1)
2555             {
2556                 union { signed short val; signed char vals[2]; } uc16;
2557                 mask = (1 << image->comps[compno].prec) - 1;
2558                 ptr = image->comps[compno].data;
2559                 for (line = 0; line < h; line++) {
2560                     for(row = 0; row < w; row++)        {
2561                         curr = *ptr;
2562                         if(curr > 32767 ) curr = 32767; else if( curr < -32768) curr = -32768;
2563                         uc16.val = (signed short)(curr & mask);
2564                         res = fwrite(uc16.vals, 1, 2, rawFile);
2565                         if( res < 2 ) {
2566                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2567                             goto fin;
2568                         }
2569                         ptr++;
2570                     }
2571                 }
2572             }
2573             else if(image->comps[compno].sgnd == 0)
2574             {
2575                 union { unsigned short val; unsigned char vals[2]; } uc16;
2576                 mask = (1 << image->comps[compno].prec) - 1;
2577                 ptr = image->comps[compno].data;
2578                 for (line = 0; line < h; line++) {
2579                     for(row = 0; row < w; row++)        {
2580                         curr = *ptr;
2581                         if(curr > 65536 ) curr = 65536; else if( curr < 0) curr = 0;
2582                         uc16.val = (unsigned short)(curr & mask);
2583                         res = fwrite(uc16.vals, 1, 2, rawFile);
2584                         if( res < 2 ) {
2585                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
2586                             goto fin;
2587                         }
2588                         ptr++;
2589                     }
2590                 }
2591             }
2592         }
2593         else if (image->comps[compno].prec <= 32)
2594         {
2595             fprintf(stderr,"More than 16 bits per component no handled yet\n");
2596             goto fin;
2597         }
2598         else
2599         {
2600             fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
2601             goto fin;
2602         }
2603     }
2604   fails = 0;
2605 fin:
2606     fclose(rawFile);
2607     return fails;
2608 }
2609
2610 int imagetoraw(opj_image_t * image, const char *outfile)
2611 {
2612     return imagetoraw_common(image, outfile, OPJ_TRUE);
2613 }
2614
2615 int imagetorawl(opj_image_t * image, const char *outfile)
2616 {
2617     return imagetoraw_common(image, outfile, OPJ_FALSE);
2618 }
2619
2620 #ifdef OPJ_HAVE_LIBPNG
2621
2622 #define PNG_MAGIC "\x89PNG\x0d\x0a\x1a\x0a"
2623 #define MAGIC_SIZE 8
2624 /* PNG allows bits per sample: 1, 2, 4, 8, 16 */
2625
2626 opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
2627 {
2628     png_structp  png;
2629     png_infop    info;
2630     double gamma, display_exponent;
2631     int bit_depth, interlace_type,compression_type, filter_type;
2632     int unit;
2633     png_uint_32 resx, resy;
2634     unsigned int i, j;
2635     png_uint_32  width, height;
2636     int color_type, has_alpha, is16;
2637     unsigned char *s;
2638     FILE *reader;
2639     unsigned char **rows;
2640     /* j2k: */
2641     opj_image_t *image;
2642     opj_image_cmptparm_t cmptparm[4];
2643     int sub_dx, sub_dy;
2644     unsigned int nr_comp;
2645     int *r, *g, *b, *a = NULL;
2646     unsigned char sigbuf[8];
2647
2648     if((reader = fopen(read_idf, "rb")) == NULL)
2649     {
2650         fprintf(stderr,"pngtoimage: can not open %s\n",read_idf);
2651         return NULL;
2652     }
2653     image = NULL; png = NULL; rows = NULL;
2654
2655     if(fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE
2656             || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0)
2657     {
2658         fprintf(stderr,"pngtoimage: %s is no valid PNG file\n",read_idf);
2659         goto fin;
2660     }
2661     /* libpng-VERSION/example.c:
2662  * PC : screen_gamma = 2.2;
2663  * Mac: screen_gamma = 1.7 or 1.0;
2664 */
2665     display_exponent = 2.2;
2666
2667     if((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,
2668                                      NULL, NULL, NULL)) == NULL)
2669         goto fin;
2670     if((info = png_create_info_struct(png)) == NULL)
2671         goto fin;
2672
2673     if(setjmp(png_jmpbuf(png)))
2674         goto fin;
2675
2676     png_init_io(png, reader);
2677     png_set_sig_bytes(png, MAGIC_SIZE);
2678
2679     png_read_info(png, info);
2680
2681     if(png_get_IHDR(png, info, &width, &height,
2682                     &bit_depth, &color_type, &interlace_type,
2683                     &compression_type, &filter_type) == 0)
2684         goto fin;
2685
2686     /* png_set_expand():
2687  * expand paletted images to RGB, expand grayscale images of
2688  * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
2689  * to alpha channels.
2690 */
2691     if(color_type == PNG_COLOR_TYPE_PALETTE)
2692         png_set_expand(png);
2693     else
2694         if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
2695             png_set_expand(png);
2696
2697     if(png_get_valid(png, info, PNG_INFO_tRNS))
2698         png_set_expand(png);
2699
2700     is16 = (bit_depth == 16);
2701
2702     /* GRAY => RGB; GRAY_ALPHA => RGBA
2703 */
2704     if(color_type == PNG_COLOR_TYPE_GRAY
2705             || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
2706     {
2707         png_set_gray_to_rgb(png);
2708         color_type =
2709                 (color_type == PNG_COLOR_TYPE_GRAY? PNG_COLOR_TYPE_RGB:
2710                                                     PNG_COLOR_TYPE_RGB_ALPHA);
2711     }
2712     if( !png_get_gAMA(png, info, &gamma))
2713         gamma = 0.45455;
2714
2715     png_set_gamma(png, display_exponent, gamma);
2716
2717     png_read_update_info(png, info);
2718
2719     png_get_pHYs(png, info, &resx, &resy, &unit);
2720
2721     color_type = png_get_color_type(png, info);
2722
2723     has_alpha = (color_type == PNG_COLOR_TYPE_RGB_ALPHA);
2724
2725     nr_comp = 3 + (unsigned int)has_alpha;
2726
2727     bit_depth = png_get_bit_depth(png, info);
2728
2729     rows = (unsigned char**)calloc(height+1, sizeof(unsigned char*));
2730     for(i = 0; i < height; ++i)
2731         rows[i] = (unsigned char*)malloc(png_get_rowbytes(png,info));
2732
2733     png_read_image(png, rows);
2734
2735     memset(cmptparm, 0, sizeof(cmptparm));
2736
2737     sub_dx = params->subsampling_dx; sub_dy = params->subsampling_dy;
2738
2739     for(i = 0; i < nr_comp; ++i)
2740     {
2741         cmptparm[i].prec = (OPJ_UINT32)bit_depth;
2742         /* bits_per_pixel: 8 or 16 */
2743         cmptparm[i].bpp = (OPJ_UINT32)bit_depth;
2744         cmptparm[i].sgnd = 0;
2745         cmptparm[i].dx = (OPJ_UINT32)sub_dx;
2746         cmptparm[i].dy = (OPJ_UINT32)sub_dy;
2747         cmptparm[i].w = (OPJ_UINT32)width;
2748         cmptparm[i].h = (OPJ_UINT32)height;
2749     }
2750
2751     image = opj_image_create(nr_comp, &cmptparm[0], OPJ_CLRSPC_SRGB);
2752
2753     if(image == NULL) goto fin;
2754
2755     image->x0 = (OPJ_UINT32)params->image_offset_x0;
2756     image->y0 = (OPJ_UINT32)params->image_offset_y0;
2757     image->x1 = (OPJ_UINT32)(image->x0 + (width  - 1) * (OPJ_UINT32)sub_dx + 1 + image->x0);
2758     image->y1 = (OPJ_UINT32)(image->y0 + (height - 1) * (OPJ_UINT32)sub_dy + 1 + image->y0);
2759
2760     r = image->comps[0].data;
2761     g = image->comps[1].data;
2762     b = image->comps[2].data;
2763     if(has_alpha) {
2764         a = image->comps[3].data;
2765         image->comps[3].alpha = 1;
2766     }
2767
2768     for(i = 0; i < height; ++i)
2769     {
2770         s = rows[i];
2771
2772         for(j = 0; j < width; ++j)
2773         {
2774             if(is16)
2775             {
2776                 *r++ = s[0]<<8|s[1]; s += 2;
2777
2778                 *g++ = s[0]<<8|s[1]; s += 2;
2779
2780                 *b++ = s[0]<<8|s[1]; s += 2;
2781
2782                 if(has_alpha) { *a++ = s[0]<<8|s[1]; s += 2; }
2783
2784                 continue;
2785             }
2786             *r++ = *s++; *g++ = *s++; *b++ = *s++;
2787
2788             if(has_alpha) *a++ = *s++;
2789         }
2790     }
2791 fin:
2792     if(rows)
2793     {
2794         for(i = 0; i < height; ++i)
2795             free(rows[i]);
2796         free(rows);
2797     }
2798     if(png)
2799         png_destroy_read_struct(&png, &info, NULL);
2800
2801     fclose(reader);
2802
2803     return image;
2804
2805 }/* pngtoimage() */
2806
2807 int imagetopng(opj_image_t * image, const char *write_idf)
2808 {
2809     FILE *writer;
2810     png_structp png;
2811     png_infop info;
2812     int *red, *green, *blue, *alpha;
2813     unsigned char *row_buf, *d;
2814     int has_alpha, width, height, nr_comp, color_type;
2815     int adjustR, adjustG, adjustB, adjustA, x, y, fails;
2816     int prec, ushift, dshift, is16, force16, force8;
2817     unsigned short mask = 0xffff;
2818     png_color_8 sig_bit;
2819
2820     is16 = force16 = force8 = ushift = dshift = 0; fails = 1;
2821     prec = (int)image->comps[0].prec;
2822     nr_comp = (int)image->numcomps;
2823
2824     if(prec > 8 && prec < 16)
2825     {
2826         ushift = 16 - prec; dshift = prec - ushift;
2827         prec = 16; force16 = 1;
2828     }
2829     else
2830         if(prec < 8 && nr_comp > 1)/* GRAY_ALPHA, RGB, RGB_ALPHA */
2831         {
2832             ushift = 8 - prec; dshift = 8 - ushift;
2833             prec = 8; force8 = 1;
2834         }
2835
2836     if(prec != 1 && prec != 2 && prec != 4 && prec != 8 && prec != 16)
2837     {
2838         fprintf(stderr,"imagetopng: can not create %s"
2839                 "\n\twrong bit_depth %d\n", write_idf, prec);
2840         return fails;
2841     }
2842     writer = fopen(write_idf, "wb");
2843
2844     if(writer == NULL) return fails;
2845
2846     info = NULL; has_alpha = 0;
2847
2848     /* Create and initialize the png_struct with the desired error handler
2849  * functions.  If you want to use the default stderr and longjump method,
2850  * you can supply NULL for the last three parameters.  We also check that
2851  * the library version is compatible with the one used at compile time,
2852  * in case we are using dynamically linked libraries.  REQUIRED.
2853 */
2854     png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
2855                                   NULL, NULL, NULL);
2856     /*png_voidp user_error_ptr, user_error_fn, user_warning_fn); */
2857
2858     if(png == NULL) goto fin;
2859
2860     /* Allocate/initialize the image information data.  REQUIRED
2861 */
2862     info = png_create_info_struct(png);
2863
2864     if(info == NULL) goto fin;
2865
2866     /* Set error handling.  REQUIRED if you are not supplying your own
2867  * error handling functions in the png_create_write_struct() call.
2868 */
2869     if(setjmp(png_jmpbuf(png))) goto fin;
2870
2871     /* I/O initialization functions is REQUIRED
2872 */
2873     png_init_io(png, writer);
2874
2875     /* Set the image information here.  Width and height are up to 2^31,
2876  * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
2877  * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
2878  * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
2879  * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
2880  * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
2881  * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE.
2882  * REQUIRED
2883  *
2884  * ERRORS:
2885  *
2886  * color_type == PNG_COLOR_TYPE_PALETTE && bit_depth > 8
2887  * color_type == PNG_COLOR_TYPE_RGB && bit_depth < 8
2888  * color_type == PNG_COLOR_TYPE_GRAY_ALPHA && bit_depth < 8
2889  * color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8
2890  *
2891 */
2892     png_set_compression_level(png, Z_BEST_COMPRESSION);
2893
2894     if(prec == 16) mask = 0xffff;
2895     else
2896         if(prec == 8) mask = 0x00ff;
2897         else
2898             if(prec == 4) mask = 0x000f;
2899             else
2900                 if(prec == 2) mask = 0x0003;
2901                 else
2902                     if(prec == 1) mask = 0x0001;
2903
2904     if(nr_comp >= 3
2905             && image->comps[0].dx == image->comps[1].dx
2906             && image->comps[1].dx == image->comps[2].dx
2907             && image->comps[0].dy == image->comps[1].dy
2908             && image->comps[1].dy == image->comps[2].dy
2909             && image->comps[0].prec == image->comps[1].prec
2910             && image->comps[1].prec == image->comps[2].prec)
2911     {
2912         int v;
2913
2914         has_alpha = (nr_comp > 3);
2915
2916         is16 = (prec == 16);
2917
2918         width = (int)image->comps[0].w;
2919         height = (int)image->comps[0].h;
2920
2921         red = image->comps[0].data;
2922         green = image->comps[1].data;
2923         blue = image->comps[2].data;
2924
2925         sig_bit.red = sig_bit.green = sig_bit.blue = (png_byte)prec;
2926
2927         if(has_alpha)
2928         {
2929             sig_bit.alpha = (png_byte)prec;
2930             alpha = image->comps[3].data;
2931             color_type = PNG_COLOR_TYPE_RGB_ALPHA;
2932             adjustA = (image->comps[3].sgnd ? 1 << (image->comps[3].prec - 1) : 0);
2933         }
2934         else
2935         {
2936             sig_bit.alpha = 0; alpha = NULL;
2937             color_type = PNG_COLOR_TYPE_RGB;
2938             adjustA = 0;
2939         }
2940         png_set_sBIT(png, info, &sig_bit);
2941
2942         png_set_IHDR(png, info, (png_uint_32)width, (png_uint_32)height, prec,
2943                      color_type,
2944                      PNG_INTERLACE_NONE,
2945                      PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
2946
2947         png_set_gamma(png, 2.2, 1./2.2);
2948         png_set_sRGB(png, info, PNG_sRGB_INTENT_PERCEPTUAL);
2949         /*=============================*/
2950         png_write_info(png, info);
2951         /*=============================*/
2952         if(prec < 8)
2953         {
2954             png_set_packing(png);
2955         }
2956 printf("%s:%d:sgnd(%d,%d,%d) w(%d) h(%d) alpha(%d)\n",__FILE__,__LINE__,
2957 image->comps[0].sgnd,
2958 image->comps[1].sgnd,image->comps[2].sgnd,width,height,has_alpha);
2959
2960         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
2961         adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
2962         adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
2963
2964         row_buf = (unsigned char*)malloc((size_t)width * (size_t)nr_comp * 2);
2965
2966         for(y = 0; y < height; ++y)
2967         {
2968             d = row_buf;
2969
2970             for(x = 0; x < width; ++x)
2971             {
2972                 if(is16)
2973                 {
2974                     v = *red + adjustR; ++red;
2975                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2976
2977                     if(force16) { v = (v<<ushift) + (v>>dshift); }
2978
2979                     *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2980
2981                     v = *green + adjustG; ++green;
2982                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2983
2984                     if(force16) { v = (v<<ushift) + (v>>dshift); }
2985
2986                     *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2987
2988                     v =  *blue + adjustB; ++blue;
2989                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2990
2991                     if(force16) { v = (v<<ushift) + (v>>dshift); }
2992
2993                     *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
2994
2995                     if(has_alpha)
2996                     {
2997                         v = *alpha + adjustA; ++alpha;
2998                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2999
3000                         if(force16) { v = (v<<ushift) + (v>>dshift); }
3001
3002                         *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3003                     }
3004                     continue;
3005                 }/* if(is16) */
3006
3007                 v = *red + adjustR; ++red;
3008                 if(v > 255) v = 255; else if(v < 0) v = 0;
3009
3010                 if(force8) { v = (v<<ushift) + (v>>dshift); }
3011
3012                 *d++ = (unsigned char)(v & mask);
3013
3014                 v = *green + adjustG; ++green;
3015                 if(v > 255) v = 255; else if(v < 0) v = 0;
3016
3017                 if(force8) { v = (v<<ushift) + (v>>dshift); }
3018
3019                 *d++ = (unsigned char)(v & mask);
3020
3021                 v = *blue + adjustB; ++blue;
3022                 if(v > 255) v = 255; else if(v < 0) v = 0;
3023
3024                 if(force8) { v = (v<<ushift) + (v>>dshift); }
3025
3026                 *d++ = (unsigned char)(v & mask);
3027
3028                 if(has_alpha)
3029                 {
3030                     v = *alpha + adjustA; ++alpha;
3031                 if(v > 255) v = 255; else if(v < 0) v = 0;
3032
3033                     if(force8) { v = (v<<ushift) + (v>>dshift); }
3034
3035                     *d++ = (unsigned char)(v & mask);
3036                 }
3037             }   /* for(x) */
3038
3039             png_write_row(png, row_buf);
3040
3041         }       /* for(y) */
3042         free(row_buf);
3043
3044     }/* nr_comp >= 3 */
3045     else
3046         if(nr_comp == 1 /* GRAY */
3047                 || (   nr_comp == 2 /* GRAY_ALPHA */
3048                        && image->comps[0].dx == image->comps[1].dx
3049                        && image->comps[0].dy == image->comps[1].dy
3050                        && image->comps[0].prec == image->comps[1].prec))
3051         {
3052             int v;
3053
3054             red = image->comps[0].data;
3055
3056             sig_bit.gray = (png_byte)prec;
3057             sig_bit.red = sig_bit.green = sig_bit.blue = sig_bit.alpha = 0;
3058             alpha = NULL; adjustA = 0;
3059             color_type = PNG_COLOR_TYPE_GRAY;
3060
3061             if(nr_comp == 2)
3062             {
3063                 has_alpha = 1; sig_bit.alpha = (png_byte)prec;
3064                 alpha = image->comps[1].data;
3065                 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
3066                 adjustA = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
3067             }
3068             width = (int)image->comps[0].w;
3069             height = (int)image->comps[0].h;
3070
3071             png_set_IHDR(png, info, (png_uint_32)width, (png_uint_32)height, sig_bit.gray,
3072                          color_type,
3073                          PNG_INTERLACE_NONE,
3074                          PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
3075
3076             png_set_sBIT(png, info, &sig_bit);
3077
3078             png_set_gamma(png, 2.2, 1./2.2);
3079             png_set_sRGB(png, info, PNG_sRGB_INTENT_PERCEPTUAL);
3080             /*=============================*/
3081             png_write_info(png, info);
3082             /*=============================*/
3083             adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
3084
3085             if(prec < 8)
3086             {
3087                 png_set_packing(png);
3088             }
3089
3090             if(prec > 8)
3091             {
3092                 row_buf = (unsigned char*)
3093                         malloc((size_t)width * (size_t)nr_comp * sizeof(unsigned short));
3094
3095                 for(y = 0; y < height; ++y)
3096                 {
3097                     d = row_buf;
3098
3099                     for(x = 0; x < width; ++x)
3100                     {
3101                         v = *red + adjustR; ++red;
3102                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3103
3104                         if(force16) { v = (v<<ushift) + (v>>dshift); }
3105
3106                         *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3107
3108                         if(has_alpha)
3109                         {
3110                             v = *alpha++;
3111                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3112
3113                             if(force16) { v = (v<<ushift) + (v>>dshift); }
3114
3115                             *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3116                         }
3117                     }/* for(x) */
3118                     png_write_row(png, row_buf);
3119
3120                 }       /* for(y) */
3121                 free(row_buf);
3122             }
3123             else /* prec <= 8 */
3124             {
3125                 row_buf = (unsigned char*)calloc((size_t)width, (size_t)nr_comp * 2);
3126
3127                 for(y = 0; y < height; ++y)
3128                 {
3129                     d = row_buf;
3130
3131                     for(x = 0; x < width; ++x)
3132                     {
3133                         v = *red + adjustR; ++red;
3134                 if(v > 255) v = 255; else if(v < 0) v = 0;
3135
3136                         if(force8) { v = (v<<ushift) + (v>>dshift); }
3137
3138                         *d++ = (unsigned char)(v & mask);
3139
3140                         if(has_alpha)
3141                         {
3142                             v = *alpha + adjustA; ++alpha;
3143                 if(v > 255) v = 255; else if(v < 0) v = 0;
3144
3145                             if(force8) { v = (v<<ushift) + (v>>dshift); }
3146
3147                             *d++ = (unsigned char)(v & mask);
3148                         }
3149                     }/* for(x) */
3150
3151                     png_write_row(png, row_buf);
3152
3153                 }       /* for(y) */
3154                 free(row_buf);
3155             }
3156         }
3157         else
3158         {
3159             fprintf(stderr,"imagetopng: can not create %s\n",write_idf);
3160             goto fin;
3161         }
3162     png_write_end(png, info);
3163
3164     fails = 0;
3165
3166 fin:
3167
3168     if(png)
3169     {
3170         png_destroy_write_struct(&png, &info);
3171     }
3172     fclose(writer);
3173
3174     if(fails) remove(write_idf);
3175
3176     return fails;
3177 }/* imagetopng() */
3178 #endif /* OPJ_HAVE_LIBPNG */