[trunk] remove some simple warnings about unused params
[openjpeg.git] / src / bin / jp2 / convert.c
1 /*
2  * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
3  * Copyright (c) 2002-2007, Professor Benoit Macq
4  * Copyright (c) 2001-2003, David Janssens
5  * Copyright (c) 2002-2003, Yannick Verschueren
6  * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
7  * Copyright (c) 2005, Herve Drolon, FreeImage Team
8  * Copyright (c) 2006-2007, Parvatha Elangovan
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 #include "opj_apps_config.h"
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <ctype.h>
38
39 #ifdef OPJ_HAVE_LIBTIFF
40 #include <tiffio.h>
41 #endif /* OPJ_HAVE_LIBTIFF */
42
43 #ifdef OPJ_HAVE_LIBPNG
44 #include <zlib.h>
45 #include <png.h>
46 #endif /* OPJ_HAVE_LIBPNG */
47
48 #include "openjpeg.h"
49 #include "convert.h"
50
51 /*
52  * Get logarithm of an integer and round downwards.
53  *
54  * log2(a)
55  */
56 static int int_floorlog2(int a) {
57     int l;
58     for (l = 0; a > 1; l++) {
59         a >>= 1;
60     }
61     return l;
62 }
63
64 /* -->> -->> -->> -->>
65
66   TGA IMAGE FORMAT
67
68  <<-- <<-- <<-- <<-- */
69
70 #ifdef INFORMATION_ONLY
71 /* TGA header definition. */
72 struct tga_header
73 {                           
74     unsigned char   id_length;              /* Image id field length    */
75     unsigned char   colour_map_type;        /* Colour map type          */
76     unsigned char   image_type;             /* Image type               */
77     /*
78     ** Colour map specification
79     */
80     unsigned short  colour_map_index;       /* First entry index        */
81     unsigned short  colour_map_length;      /* Colour map length        */
82     unsigned char   colour_map_entry_size;  /* Colour map entry size    */
83     /*
84     ** Image specification
85     */
86     unsigned short  x_origin;               /* x origin of image        */
87     unsigned short  y_origin;               /* u origin of image        */
88     unsigned short  image_width;            /* Image width              */
89     unsigned short  image_height;           /* Image height             */
90     unsigned char   pixel_depth;            /* Pixel depth              */
91     unsigned char   image_desc;             /* Image descriptor         */
92 };
93 #endif /* INFORMATION_ONLY */
94
95 static unsigned short get_ushort(unsigned short val) {
96
97 #ifdef WORDS_BIGENDIAN
98     return( ((val & 0xff) << 8) + (val >> 8) );
99 #else
100     return( val );
101 #endif
102
103 }
104
105 #define TGA_HEADER_SIZE 18
106
107 static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel, 
108                           unsigned int *width, unsigned int *height, int *flip_image)
109 {
110     int palette_size;
111     unsigned char *tga ;
112     unsigned char id_len, /*cmap_type,*/ image_type;
113     unsigned char pixel_depth, image_desc;
114     unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
115     unsigned short /*x_origin, y_origin,*/ image_w, image_h;
116
117     if (!bits_per_pixel || !width || !height || !flip_image)
118         return 0;
119     tga = (unsigned char*)malloc(18);
120
121     if ( fread(tga, TGA_HEADER_SIZE, 1, fp) != 1 )
122     {
123         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
124         return 0 ;
125     }
126     id_len = (unsigned char)tga[0];
127     /*cmap_type = (unsigned char)tga[1];*/
128     image_type = (unsigned char)tga[2];
129     /*cmap_index = get_ushort(*(unsigned short*)(&tga[3]));*/
130     cmap_len = get_ushort(*(unsigned short*)(&tga[5]));
131     cmap_entry_size = (unsigned char)tga[7];
132
133
134 #if 0
135     x_origin = get_ushort(*(unsigned short*)(&tga[8]));
136     y_origin = get_ushort(*(unsigned short*)(&tga[10]));
137 #endif
138     image_w = get_ushort(*(unsigned short*)(&tga[12]));
139     image_h = get_ushort(*(unsigned short*)(&tga[14]));
140     pixel_depth = (unsigned char)tga[16];
141     image_desc  = (unsigned char)tga[17];
142
143     free(tga);
144
145     *bits_per_pixel = (unsigned int)pixel_depth;
146     *width  = (unsigned int)image_w;
147     *height = (unsigned int)image_h;
148
149     /* Ignore tga identifier, if present ... */
150     if (id_len)
151     {
152         unsigned char *id = (unsigned char *) malloc(id_len);
153         if ( !fread(id, id_len, 1, fp) )
154         {
155             fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
156             free(id);
157             return 0 ;
158         }
159         free(id);
160     }
161
162     /* Test for compressed formats ... not yet supported ...
163     // Note :-  9 - RLE encoded palettized.
164     //             10 - RLE encoded RGB. */
165     if (image_type > 8)
166     {
167         fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
168         return 0 ;
169     }
170
171     *flip_image = !(image_desc & 32);
172
173     /* Palettized formats are not yet supported, skip over the palette, if present ... */
174     palette_size = cmap_len * (cmap_entry_size/8);
175
176     if (palette_size>0)
177     {
178         fprintf(stderr, "File contains a palette - not yet supported.");
179         fseek(fp, palette_size, SEEK_CUR);
180     }
181     return 1;
182 }
183
184 #if WORDS_BIGENDIAN == 1
185
186 static inline int16_t swap16(int16_t x)
187 {
188     return((((u_int16_t)x & 0x00ffU) <<  8) |
189            (((u_int16_t)x & 0xff00U) >>  8));
190 }
191
192 #endif
193
194 static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height, 
195                            OPJ_BOOL flip_image)
196 {
197     unsigned short image_w, image_h, us0;
198     unsigned char uc0, image_type;
199     unsigned char pixel_depth, image_desc;
200
201     if (!bits_per_pixel || !width || !height)
202         return 0;
203
204     pixel_depth = 0;
205
206     if ( bits_per_pixel < 256 )
207         pixel_depth = (unsigned char)bits_per_pixel;
208     else{
209         fprintf(stderr,"ERROR: Wrong bits per pixel inside tga_header");
210         return 0;
211     }
212     uc0 = 0;
213
214     if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* id_length */
215     if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_type */
216
217     image_type = 2; /* Uncompressed. */
218     if(fwrite(&image_type, 1, 1, fp) != 1) goto fails;
219
220     us0 = 0;
221     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_index */
222     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* colour_map_length */
223     if(fwrite(&uc0, 1, 1, fp) != 1) goto fails; /* colour_map_entry_size */
224
225     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* x_origin */
226     if(fwrite(&us0, 2, 1, fp) != 1) goto fails; /* y_origin */
227
228     image_w = (unsigned short)width;
229     image_h = (unsigned short) height;
230
231 #if WORDS_BIGENDIAN == 0
232     if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
233     if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
234 #else
235     image_w = swap16(image_w);
236     image_h = swap16(image_h);
237     if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
238     if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
239 #endif
240
241     if(fwrite(&pixel_depth, 1, 1, fp) != 1) goto fails;
242
243     image_desc = 8; /* 8 bits per component. */
244
245     if (flip_image)
246         image_desc |= 32;
247     if(fwrite(&image_desc, 1, 1, fp) != 1) goto fails;
248
249     return 1;
250
251 fails:
252     fputs("\nwrite_tgaheader: write ERROR\n", stderr);
253     return 0;
254 }
255
256 opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
257     FILE *f;
258     opj_image_t *image;
259     unsigned int image_width, image_height, pixel_bit_depth;
260     unsigned int x, y;
261     int flip_image=0;
262     opj_image_cmptparm_t cmptparm[4];   /* maximum 4 components */
263     int numcomps;
264     OPJ_COLOR_SPACE color_space;
265     OPJ_BOOL mono ;
266     OPJ_BOOL save_alpha;
267     int subsampling_dx, subsampling_dy;
268     int i;
269
270     f = fopen(filename, "rb");
271     if (!f) {
272         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
273         return 0;
274     }
275
276     if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image))
277         return NULL;
278
279     /* We currently only support 24 & 32 bit tga's ... */
280     if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32)))
281         return NULL;
282
283     /* initialize image components */
284     memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
285
286     mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16);  /* Mono with & without alpha. */
287     save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
288
289     if (mono) {
290         color_space = OPJ_CLRSPC_GRAY;
291         numcomps = save_alpha ? 2 : 1;
292     }
293     else {
294         numcomps = save_alpha ? 4 : 3;
295         color_space = OPJ_CLRSPC_SRGB;
296     }
297
298     subsampling_dx = parameters->subsampling_dx;
299     subsampling_dy = parameters->subsampling_dy;
300
301     for (i = 0; i < numcomps; i++) {
302         cmptparm[i].prec = 8;
303         cmptparm[i].bpp = 8;
304         cmptparm[i].sgnd = 0;
305         cmptparm[i].dx = subsampling_dx;
306         cmptparm[i].dy = subsampling_dy;
307         cmptparm[i].w = image_width;
308         cmptparm[i].h = image_height;
309     }
310
311     /* create the image */
312     image = opj_image_create(numcomps, &cmptparm[0], color_space);
313
314     if (!image)
315         return NULL;
316
317     /* set image offset and reference grid */
318     image->x0 = parameters->image_offset_x0;
319     image->y0 = parameters->image_offset_y0;
320     image->x1 = !image->x0 ? (image_width - 1) * subsampling_dx + 1 : image->x0 + (image_width - 1) * subsampling_dx + 1;
321     image->y1 = !image->y0 ? (image_height - 1) * subsampling_dy + 1 : image->y0 + (image_height - 1) * subsampling_dy + 1;
322
323     /* set image data */
324     for (y=0; y < image_height; y++)
325     {
326         int index;
327
328         if (flip_image)
329             index = (image_height-y-1)*image_width;
330         else
331             index = y*image_width;
332
333         if (numcomps==3)
334         {
335             for (x=0;x<image_width;x++)
336             {
337                 unsigned char r,g,b;
338
339                 if( !fread(&b, 1, 1, f) )
340                 {
341                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
342                     opj_image_destroy(image);
343                     return NULL;
344                 }
345                 if ( !fread(&g, 1, 1, f) )
346                 {
347                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
348                     opj_image_destroy(image);
349                     return NULL;
350                 }
351                 if ( !fread(&r, 1, 1, f) )
352                 {
353                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
354                     opj_image_destroy(image);
355                     return NULL;
356                 }
357
358                 image->comps[0].data[index]=r;
359                 image->comps[1].data[index]=g;
360                 image->comps[2].data[index]=b;
361                 index++;
362             }
363         }
364         else if (numcomps==4)
365         {
366             for (x=0;x<image_width;x++)
367             {
368                 unsigned char r,g,b,a;
369                 if ( !fread(&b, 1, 1, f) )
370                 {
371                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
372                     opj_image_destroy(image);
373                     return NULL;
374                 }
375                 if ( !fread(&g, 1, 1, f) )
376                 {
377                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
378                     opj_image_destroy(image);
379                     return NULL;
380                 }
381                 if ( !fread(&r, 1, 1, f) )
382                 {
383                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
384                     opj_image_destroy(image);
385                     return NULL;
386                 }
387                 if ( !fread(&a, 1, 1, f) )
388                 {
389                     fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
390                     opj_image_destroy(image);
391                     return NULL;
392                 }
393
394                 image->comps[0].data[index]=r;
395                 image->comps[1].data[index]=g;
396                 image->comps[2].data[index]=b;
397                 image->comps[3].data[index]=a;
398                 index++;
399             }
400         }
401         else {
402             fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
403         }
404     }
405     return image;
406 }
407
408 int imagetotga(opj_image_t * image, const char *outfile) {
409     int width, height, bpp, x, y;
410     OPJ_BOOL write_alpha;
411     int i, adjustR, adjustG, adjustB, fails;
412     unsigned int alpha_channel;
413     float r,g,b,a;
414     unsigned char value;
415     float scale;
416     FILE *fdest;
417     size_t res;
418
419     fdest = fopen(outfile, "wb");
420     if (!fdest) {
421         fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
422         return 1;
423     }
424
425     for (i = 0; i < image->numcomps-1; i++)     {
426         if ((image->comps[0].dx != image->comps[i+1].dx)
427                 ||(image->comps[0].dy != image->comps[i+1].dy)
428                 ||(image->comps[0].prec != image->comps[i+1].prec))     {
429             fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
430             return 1;
431         }
432     }
433
434     width = image->comps[0].w;
435     height = image->comps[0].h;
436
437     /* Mono with alpha, or RGB with alpha. */
438     write_alpha = (image->numcomps==2) || (image->numcomps==4);
439
440     /* Write TGA header  */
441     bpp = write_alpha ? 32 : 24;
442
443     if (!tga_writeheader(fdest, bpp, width , height, OPJ_TRUE))
444                 goto fin;
445
446     alpha_channel = image->numcomps-1;
447
448     scale = 255.0f / (float)((1<<image->comps[0].prec)-1);
449
450     adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
451     adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
452     adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
453
454         for (y=0; y < height; y++) 
455    {
456         unsigned int index=y*width;
457
458         for (x=0; x < width; x++, index++)      
459   {
460         r = (float)(image->comps[0].data[index] + adjustR);
461
462         if (image->numcomps > 2) 
463  {
464         g = (float)(image->comps[1].data[index] + adjustG);
465         b = (float)(image->comps[2].data[index] + adjustB);
466  }
467         else  
468  {/* Greyscale ... */
469         g = r;
470         b = r;
471  }
472
473 /* TGA format writes BGR ... */
474         if(b > 255.) b = 255.; else if(b < 0.) b = 0.;
475         value = (unsigned char)(b*scale);
476         res = fwrite(&value,1,1,fdest);
477
478         if( res < 1 ) 
479  {
480         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
481         goto fin;
482  }
483         if(g > 255.) g = 255.; else if(g < 0.) g = 0.;
484         value = (unsigned char)(g*scale);
485         res = fwrite(&value,1,1,fdest);
486
487         if( res < 1 ) 
488  {
489         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
490         goto fin;
491  }
492         if(r > 255.) r = 255.; else if(r < 0.) r = 0.;
493         value = (unsigned char)(r*scale);
494         res = fwrite(&value,1,1,fdest);
495
496         if( res < 1 ) 
497  {
498         fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
499         goto fin;
500  }
501
502         if (write_alpha) 
503  {
504         a = (float)(image->comps[alpha_channel].data[index]);
505         if(a > 255.) a = 255.; else if(a < 0.) a = 0.;
506         value = (unsigned char)(a*scale);
507         res = fwrite(&value,1,1,fdest);
508
509                 if( res < 1 ) 
510            {
511                 fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
512                 goto fin;
513            }
514  }
515   }
516    }
517         fails = 0;
518 fin:
519         fclose(fdest);
520
521         return fails;
522 }
523
524 /* -->> -->> -->> -->>
525
526   BMP IMAGE FORMAT
527
528  <<-- <<-- <<-- <<-- */
529
530 /* WORD defines a two byte word */
531 typedef unsigned short int WORD;
532
533 /* DWORD defines a four byte word */
534 typedef unsigned int DWORD;
535
536 typedef struct {
537     WORD bfType;                        /* 'BM' for Bitmap (19776) */
538     DWORD bfSize;                       /* Size of the file        */
539     WORD bfReserved1;           /* Reserved : 0            */
540     WORD bfReserved2;           /* Reserved : 0            */
541     DWORD bfOffBits;            /* Offset                  */
542 } BITMAPFILEHEADER_t;
543
544 typedef struct {
545     DWORD biSize;                       /* Size of the structure in bytes */
546     DWORD biWidth;              /* Width of the image in pixels */
547     DWORD biHeight;             /* Heigth of the image in pixels */
548     WORD biPlanes;              /* 1 */
549     WORD biBitCount;            /* Number of color bits by pixels */
550     DWORD biCompression;                /* Type of encoding 0: none 1: RLE8 2: RLE4 */
551     DWORD biSizeImage;          /* Size of the image in bytes */
552     DWORD biXpelsPerMeter;      /* Horizontal (X) resolution in pixels/meter */
553     DWORD biYpelsPerMeter;      /* Vertical (Y) resolution in pixels/meter */
554     DWORD biClrUsed;            /* Number of color used in the image (0: ALL) */
555     DWORD biClrImportant;               /* Number of important color (0: ALL) */
556 } BITMAPINFOHEADER_t;
557
558 opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters) 
559 {
560     int subsampling_dx = parameters->subsampling_dx;
561     int subsampling_dy = parameters->subsampling_dy;
562
563     int i, numcomps, w, h;
564     OPJ_COLOR_SPACE color_space;
565     opj_image_cmptparm_t cmptparm[3];   /* maximum of 3 components */
566     opj_image_t * image = NULL;
567
568     FILE *IN;
569     BITMAPFILEHEADER_t File_h;
570     BITMAPINFOHEADER_t Info_h;
571     unsigned char *RGB;
572     unsigned char *table_R, *table_G, *table_B;
573     unsigned int j, PAD = 0;
574
575     int x, y, index;
576     int gray_scale = 1;
577     int has_color;
578     DWORD W, H;
579
580     IN = fopen(filename, "rb");
581     if (!IN)
582     {
583         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
584         return NULL;
585     }
586
587     File_h.bfType = getc(IN);
588     File_h.bfType = (getc(IN) << 8) + File_h.bfType;
589
590     if (File_h.bfType != 19778)
591     {
592         fprintf(stderr,"Error, not a BMP file!\n");
593         fclose(IN);
594         return NULL;
595     }
596     /* FILE HEADER */
597     /* ------------- */
598     File_h.bfSize = getc(IN);
599     File_h.bfSize = (getc(IN) << 8) + File_h.bfSize;
600     File_h.bfSize = (getc(IN) << 16) + File_h.bfSize;
601     File_h.bfSize = (getc(IN) << 24) + File_h.bfSize;
602
603     File_h.bfReserved1 = getc(IN);
604     File_h.bfReserved1 = (getc(IN) << 8) + File_h.bfReserved1;
605
606     File_h.bfReserved2 = getc(IN);
607     File_h.bfReserved2 = (getc(IN) << 8) + File_h.bfReserved2;
608
609     File_h.bfOffBits = getc(IN);
610     File_h.bfOffBits = (getc(IN) << 8) + File_h.bfOffBits;
611     File_h.bfOffBits = (getc(IN) << 16) + File_h.bfOffBits;
612     File_h.bfOffBits = (getc(IN) << 24) + File_h.bfOffBits;
613
614     /* INFO HEADER */
615     /* ------------- */
616
617     Info_h.biSize = getc(IN);
618     Info_h.biSize = (getc(IN) << 8) + Info_h.biSize;
619     Info_h.biSize = (getc(IN) << 16) + Info_h.biSize;
620     Info_h.biSize = (getc(IN) << 24) + Info_h.biSize;
621
622     if(Info_h.biSize != 40)
623     {
624         fprintf(stderr,"Error, unknown BMP header size %d\n", Info_h.biSize);
625         fclose(IN);
626         return NULL;
627     }
628     Info_h.biWidth = getc(IN);
629     Info_h.biWidth = (getc(IN) << 8) + Info_h.biWidth;
630     Info_h.biWidth = (getc(IN) << 16) + Info_h.biWidth;
631     Info_h.biWidth = (getc(IN) << 24) + Info_h.biWidth;
632     w = Info_h.biWidth;
633
634     Info_h.biHeight = getc(IN);
635     Info_h.biHeight = (getc(IN) << 8) + Info_h.biHeight;
636     Info_h.biHeight = (getc(IN) << 16) + Info_h.biHeight;
637     Info_h.biHeight = (getc(IN) << 24) + Info_h.biHeight;
638     h = Info_h.biHeight;
639
640     Info_h.biPlanes = getc(IN);
641     Info_h.biPlanes = (getc(IN) << 8) + Info_h.biPlanes;
642
643     Info_h.biBitCount = getc(IN);
644     Info_h.biBitCount = (getc(IN) << 8) + Info_h.biBitCount;
645
646     Info_h.biCompression = getc(IN);
647     Info_h.biCompression = (getc(IN) << 8) + Info_h.biCompression;
648     Info_h.biCompression = (getc(IN) << 16) + Info_h.biCompression;
649     Info_h.biCompression = (getc(IN) << 24) + Info_h.biCompression;
650
651     Info_h.biSizeImage = getc(IN);
652     Info_h.biSizeImage = (getc(IN) << 8) + Info_h.biSizeImage;
653     Info_h.biSizeImage = (getc(IN) << 16) + Info_h.biSizeImage;
654     Info_h.biSizeImage = (getc(IN) << 24) + Info_h.biSizeImage;
655
656     Info_h.biXpelsPerMeter = getc(IN);
657     Info_h.biXpelsPerMeter = (getc(IN) << 8) + Info_h.biXpelsPerMeter;
658     Info_h.biXpelsPerMeter = (getc(IN) << 16) + Info_h.biXpelsPerMeter;
659     Info_h.biXpelsPerMeter = (getc(IN) << 24) + Info_h.biXpelsPerMeter;
660
661     Info_h.biYpelsPerMeter = getc(IN);
662     Info_h.biYpelsPerMeter = (getc(IN) << 8) + Info_h.biYpelsPerMeter;
663     Info_h.biYpelsPerMeter = (getc(IN) << 16) + Info_h.biYpelsPerMeter;
664     Info_h.biYpelsPerMeter = (getc(IN) << 24) + Info_h.biYpelsPerMeter;
665
666     Info_h.biClrUsed = getc(IN);
667     Info_h.biClrUsed = (getc(IN) << 8) + Info_h.biClrUsed;
668     Info_h.biClrUsed = (getc(IN) << 16) + Info_h.biClrUsed;
669     Info_h.biClrUsed = (getc(IN) << 24) + Info_h.biClrUsed;
670
671     Info_h.biClrImportant = getc(IN);
672     Info_h.biClrImportant = (getc(IN) << 8) + Info_h.biClrImportant;
673     Info_h.biClrImportant = (getc(IN) << 16) + Info_h.biClrImportant;
674     Info_h.biClrImportant = (getc(IN) << 24) + Info_h.biClrImportant;
675
676     /* Read the data and store them in the OUT file */
677
678     if (Info_h.biBitCount == 24)
679     {
680         numcomps = 3;
681         color_space = OPJ_CLRSPC_SRGB;
682         /* initialize image components */
683         memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
684         for(i = 0; i < numcomps; i++)
685         {
686             cmptparm[i].prec = 8;
687             cmptparm[i].bpp = 8;
688             cmptparm[i].sgnd = 0;
689             cmptparm[i].dx = subsampling_dx;
690             cmptparm[i].dy = subsampling_dy;
691             cmptparm[i].w = w;
692             cmptparm[i].h = h;
693         }
694         /* create the image */
695         image = opj_image_create(numcomps, &cmptparm[0], color_space);
696         if(!image)
697         {
698             fclose(IN);
699             return NULL;
700         }
701
702         /* set image offset and reference grid */
703         image->x0 = parameters->image_offset_x0;
704         image->y0 = parameters->image_offset_y0;
705         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
706         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
707
708         /* set image data */
709
710         /* Place the cursor at the beginning of the image information */
711         fseek(IN, 0, SEEK_SET);
712         fseek(IN, File_h.bfOffBits, SEEK_SET);
713
714         W = Info_h.biWidth;
715         H = Info_h.biHeight;
716
717         /* PAD = 4 - (3 * W) % 4; */
718         /* PAD = (PAD == 4) ? 0 : PAD; */
719         PAD = (3 * W) % 4 ? 4 - (3 * W) % 4 : 0;
720
721         RGB = (unsigned char *)
722                 malloc((3 * W + PAD) * H * sizeof(unsigned char));
723
724         if ( fread(RGB, sizeof(unsigned char), (3 * W + PAD) * H, IN) != (3 * W + PAD) * H )
725         {
726             free(RGB);
727             opj_image_destroy(image);
728             fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
729             return NULL;
730         }
731
732         index = 0;
733
734         for(y = 0; y < (int)H; y++)
735         {
736             unsigned char *scanline = RGB + (3 * W + PAD) * (H - 1 - y);
737             for(x = 0; x < (int)W; x++)
738             {
739                 unsigned char *pixel = &scanline[3 * x];
740                 image->comps[0].data[index] = pixel[2]; /* R */
741                 image->comps[1].data[index] = pixel[1]; /* G */
742                 image->comps[2].data[index] = pixel[0]; /* B */
743                 index++;
744             }
745         }
746         free(RGB);
747     }/* if (Info_h.biBitCount == 24) */
748     else
749         if (Info_h.biBitCount == 8 && Info_h.biCompression == 0)/*RGB */
750         {
751             if(Info_h.biClrUsed == 0) Info_h.biClrUsed = 256;
752             else
753                 if(Info_h.biClrUsed > 256) Info_h.biClrUsed = 256;
754
755             table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
756             table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
757             table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
758
759             has_color = 0;
760             for (j = 0; j < Info_h.biClrUsed; j++)
761             {
762                 table_B[j] = (unsigned char)getc(IN);
763                 table_G[j] = (unsigned char)getc(IN);
764                 table_R[j] = (unsigned char)getc(IN);
765                 getc(IN);
766                 has_color +=
767                         !(table_R[j] == table_G[j] && table_R[j] == table_B[j]);
768             }
769             if(has_color) gray_scale = 0;
770
771             /* Place the cursor at the beginning of the image information */
772             fseek(IN, 0, SEEK_SET);
773             fseek(IN, File_h.bfOffBits, SEEK_SET);
774
775             W = Info_h.biWidth;
776             H = Info_h.biHeight;
777             if (Info_h.biWidth % 2)
778                 W++;
779
780             numcomps = gray_scale ? 1 : 3;
781             color_space = gray_scale ? OPJ_CLRSPC_GRAY : OPJ_CLRSPC_SRGB;
782             /* initialize image components */
783             memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
784             for(i = 0; i < numcomps; i++)
785             {
786                 cmptparm[i].prec = 8;
787                 cmptparm[i].bpp = 8;
788                 cmptparm[i].sgnd = 0;
789                 cmptparm[i].dx = subsampling_dx;
790                 cmptparm[i].dy = subsampling_dy;
791                 cmptparm[i].w = w;
792                 cmptparm[i].h = h;
793             }
794             /* create the image */
795             image = opj_image_create(numcomps, &cmptparm[0], color_space);
796             if(!image)
797             {
798                 fclose(IN);
799                 free(table_R); free(table_G); free(table_B);
800                 return NULL;
801             }
802
803             /* set image offset and reference grid */
804             image->x0 = parameters->image_offset_x0;
805             image->y0 = parameters->image_offset_y0;
806             image->x1 = !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
807             image->y1 = !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
808
809             /* set image data */
810
811             RGB = (unsigned char *) malloc(W * H * sizeof(unsigned char));
812
813             if ( fread(RGB, sizeof(unsigned char), W * H, IN) != W * H )
814             {
815                 free(table_R);
816                 free(table_G);
817                 free(table_B);
818                 free(RGB);
819                 opj_image_destroy(image);
820                 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
821                 return NULL;
822             }
823             if (gray_scale)
824             {
825                 index = 0;
826                 for (j = 0; j < W * H; j++)
827                 {
828                     if ((j % W < W - 1 && Info_h.biWidth % 2) || !(Info_h.biWidth % 2))
829                     {
830                         image->comps[0].data[index] =
831                                 table_R[RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)]];
832                         index++;
833                     }
834                 }
835
836             }
837             else
838             {
839                 index = 0;
840                 for (j = 0; j < W * H; j++)
841                 {
842                     if ((j % W < W - 1 && Info_h.biWidth % 2)
843                             || !(Info_h.biWidth % 2))
844                     {
845                         unsigned char pixel_index =
846                                 RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)];
847                         image->comps[0].data[index] = table_R[pixel_index];
848                         image->comps[1].data[index] = table_G[pixel_index];
849                         image->comps[2].data[index] = table_B[pixel_index];
850                         index++;
851                     }
852                 }
853             }
854             free(RGB);
855             free(table_R);
856             free(table_G);
857             free(table_B);
858         }/* RGB8 */
859         else
860             if (Info_h.biBitCount == 8 && Info_h.biCompression == 1)/*RLE8*/
861             {
862                 unsigned char *pix, *beyond;
863                 int *gray, *red, *green, *blue;
864                 unsigned int x, y, max;
865                 int i, c, c1;
866                 unsigned char uc;
867
868                 if (Info_h.biClrUsed == 0)
869                     Info_h.biClrUsed = 256;
870                 else if (Info_h.biClrUsed > 256)
871                     Info_h.biClrUsed = 256;
872
873                 table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
874                 table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
875                 table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
876
877                 has_color = 0;
878                 for (j = 0; j < Info_h.biClrUsed; j++)
879                 {
880                     table_B[j] = (unsigned char)getc(IN);
881                     table_G[j] = (unsigned char)getc(IN);
882                     table_R[j] = (unsigned char)getc(IN);
883                     getc(IN);
884                     has_color += !(table_R[j] == table_G[j] && table_R[j] == table_B[j]);
885                 }
886
887                 if (has_color)
888                     gray_scale = 0;
889
890                 numcomps = gray_scale ? 1 : 3;
891                 color_space = gray_scale ? OPJ_CLRSPC_GRAY : OPJ_CLRSPC_SRGB;
892                 /* initialize image components */
893                 memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
894                 for (i = 0; i < numcomps; i++)
895                 {
896                     cmptparm[i].prec = 8;
897                     cmptparm[i].bpp = 8;
898                     cmptparm[i].sgnd = 0;
899                     cmptparm[i].dx = subsampling_dx;
900                     cmptparm[i].dy = subsampling_dy;
901                     cmptparm[i].w = w;
902                     cmptparm[i].h = h;
903                 }
904                 /* create the image */
905                 image = opj_image_create(numcomps, &cmptparm[0], color_space);
906                 if (!image)
907                 {
908                     fclose(IN);
909                     free(table_R);
910                     free(table_G);
911                     free(table_B);
912                     return NULL;
913                 }
914
915                 /* set image offset and reference grid */
916                 image->x0 = parameters->image_offset_x0;
917                 image->y0 = parameters->image_offset_y0;
918                 image->x1 = !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w
919                                                                                      - 1) * subsampling_dx + 1;
920                 image->y1 = !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h
921                                                                                      - 1) * subsampling_dy + 1;
922
923                 /* set image data */
924
925                 /* Place the cursor at the beginning of the image information */
926                 fseek(IN, 0, SEEK_SET);
927                 fseek(IN, File_h.bfOffBits, SEEK_SET);
928
929                 W = Info_h.biWidth;
930                 H = Info_h.biHeight;
931                 RGB = (unsigned char *) calloc(1, W * H * sizeof(unsigned char));
932                 beyond = RGB + W * H;
933                 pix = beyond - W;
934                 x = y = 0;
935
936                 while (y < H)
937                 {
938                     c = getc(IN);
939
940                     if (c)
941                     {
942                         c1 = getc(IN);
943
944                         for (i = 0; i < c && x < W && pix < beyond; i++, x++, pix++)
945                             *pix = (unsigned char)c1;
946                     }
947                     else
948                     {
949                         c = getc(IN);
950
951                         if (c == 0x00) /* EOL */
952                         {
953                             x = 0;
954                             ++y;
955                             pix = RGB + x + (H - y - 1) * W;
956                         }
957                         else if (c == 0x01) /* EOP */
958                             break;
959                         else if (c == 0x02) /* MOVE by dxdy */
960                         {
961                             c = getc(IN);
962                             x += c;
963                             c = getc(IN);
964                             y += c;
965                             pix = RGB + (H - y - 1) * W + x;
966                         }
967                         else /* 03 .. 255 */
968                         {
969                             i = 0;
970                             for (; i < c && x < W && pix < beyond; i++, x++, pix++)
971                             {
972                                 c1 = getc(IN);
973                                 *pix = (unsigned char)c1;
974                             }
975                             if (c & 1) /* skip padding byte */
976                                 getc(IN);
977                         }
978                     }
979                 }/* while() */
980
981                 if (gray_scale)
982                 {
983                     gray = image->comps[0].data;
984                     pix = RGB;
985                     max = W * H;
986
987                     while (max--)
988                     {
989                         uc = *pix++;
990
991                         *gray++ = table_R[uc];
992                     }
993                 }
994                 else
995                 {
996                     /*int *red, *green, *blue;*/
997
998                     red = image->comps[0].data;
999                     green = image->comps[1].data;
1000                     blue = image->comps[2].data;
1001                     pix = RGB;
1002                     max = W * H;
1003
1004                     while (max--)
1005                     {
1006                         uc = *pix++;
1007
1008                         *red++ = table_R[uc];
1009                         *green++ = table_G[uc];
1010                         *blue++ = table_B[uc];
1011                     }
1012                 }
1013                 free(RGB);
1014                 free(table_R);
1015                 free(table_G);
1016                 free(table_B);
1017             }/* RLE8 */
1018             else
1019             {
1020                 fprintf(stderr,
1021                         "Other system than 24 bits/pixels or 8 bits (no RLE coding) "
1022                         "is not yet implemented [%d]\n", Info_h.biBitCount);
1023             }
1024     fclose(IN);
1025     return image;
1026 }
1027
1028 int imagetobmp(opj_image_t * image, const char *outfile) {
1029     int w, h;
1030     int i, pad;
1031     FILE *fdest = NULL;
1032     int adjustR, adjustG, adjustB;
1033
1034     if (image->comps[0].prec < 8) {
1035         fprintf(stderr, "Unsupported number of components: %d\n", image->comps[0].prec);
1036         return 1;
1037     }
1038     if (image->numcomps >= 3 && image->comps[0].dx == image->comps[1].dx
1039             && image->comps[1].dx == image->comps[2].dx
1040             && image->comps[0].dy == image->comps[1].dy
1041             && image->comps[1].dy == image->comps[2].dy
1042             && image->comps[0].prec == image->comps[1].prec
1043             && image->comps[1].prec == image->comps[2].prec) {
1044
1045         /* -->> -->> -->> -->>
1046         24 bits color
1047         <<-- <<-- <<-- <<-- */
1048
1049         fdest = fopen(outfile, "wb");
1050         if (!fdest) {
1051             fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1052             return 1;
1053         }
1054
1055         w = image->comps[0].w;
1056         h = image->comps[0].h;
1057
1058         fprintf(fdest, "BM");
1059
1060         /* FILE HEADER */
1061         /* ------------- */
1062         fprintf(fdest, "%c%c%c%c",
1063                 (unsigned char) (h * w * 3 + 3 * h * (w % 2) + 54) & 0xff,
1064                 (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 8) & 0xff,
1065                 (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 16) & 0xff,
1066                 (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 24) & 0xff);
1067         fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1068         fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,((54) >> 16) & 0xff, ((54) >> 24) & 0xff);
1069
1070         /* INFO HEADER   */
1071         /* ------------- */
1072         fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
1073         fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
1074                 (unsigned char) ((w) >> 8) & 0xff,
1075                 (unsigned char) ((w) >> 16) & 0xff,
1076                 (unsigned char) ((w) >> 24) & 0xff);
1077         fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
1078                 (unsigned char) ((h) >> 8) & 0xff,
1079                 (unsigned char) ((h) >> 16) & 0xff,
1080                 (unsigned char) ((h) >> 24) & 0xff);
1081         fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
1082         fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff);
1083         fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1084         fprintf(fdest, "%c%c%c%c", (unsigned char) (3 * h * w + 3 * h * (w % 2)) & 0xff,
1085                 (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 8) & 0xff,
1086                 (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 16) & 0xff,
1087                 (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 24) & 0xff);
1088         fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
1089         fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
1090         fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1091         fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1092
1093         if (image->comps[0].prec > 8) {
1094             adjustR = image->comps[0].prec - 8;
1095             printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
1096         }
1097         else
1098             adjustR = 0;
1099         if (image->comps[1].prec > 8) {
1100             adjustG = image->comps[1].prec - 8;
1101             printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
1102         }
1103         else
1104             adjustG = 0;
1105         if (image->comps[2].prec > 8) {
1106             adjustB = image->comps[2].prec - 8;
1107             printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec);
1108         }
1109         else
1110             adjustB = 0;
1111
1112         for (i = 0; i < w * h; i++) {
1113             unsigned char rc, gc, bc;
1114             int r, g, b;
1115
1116             r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
1117             r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1118             r = ((r >> adjustR)+((r >> (adjustR-1))%2));
1119             if(r > 255) r = 255; else if(r < 0) r = 0;
1120             rc = (unsigned char)r;
1121
1122             g = image->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
1123             g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
1124             g = ((g >> adjustG)+((g >> (adjustG-1))%2));
1125             if(g > 255) g = 255; else if(g < 0) g = 0;
1126             gc = (unsigned char)g;
1127
1128             b = image->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
1129             b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
1130             b = ((b >> adjustB)+((b >> (adjustB-1))%2));
1131             if(b > 255) b = 255; else if(b < 0) b = 0;
1132             bc = (unsigned char)b;
1133
1134             fprintf(fdest, "%c%c%c", bc, gc, rc);
1135
1136             if ((i + 1) % w == 0) {
1137                 for (pad = (3 * w) % 4 ? 4 - (3 * w) % 4 : 0; pad > 0; pad--)   /* ADD */
1138                     fprintf(fdest, "%c", 0);
1139             }
1140         }
1141         fclose(fdest);
1142     } else {                    /* Gray-scale */
1143
1144         /* -->> -->> -->> -->>
1145         8 bits non code (Gray scale)
1146         <<-- <<-- <<-- <<-- */
1147
1148         fdest = fopen(outfile, "wb");
1149         w = image->comps[0].w;
1150         h = image->comps[0].h;
1151
1152         fprintf(fdest, "BM");
1153
1154         /* FILE HEADER */
1155         /* ------------- */
1156         fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + 54 + 1024 + h * (w % 2)) & 0xff,
1157                 (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 8) & 0xff,
1158                 (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 16) & 0xff,
1159                 (unsigned char) ((h * w + 54 + 1024 + w * (w % 2)) >> 24) & 0xff);
1160         fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1161         fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff,
1162                 ((54 + 1024) >> 16) & 0xff,
1163                 ((54 + 1024) >> 24) & 0xff);
1164
1165         /* INFO HEADER */
1166         /* ------------- */
1167         fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
1168         fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
1169                 (unsigned char) ((w) >> 8) & 0xff,
1170                 (unsigned char) ((w) >> 16) & 0xff,
1171                 (unsigned char) ((w) >> 24) & 0xff);
1172         fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
1173                 (unsigned char) ((h) >> 8) & 0xff,
1174                 (unsigned char) ((h) >> 16) & 0xff,
1175                 (unsigned char) ((h) >> 24) & 0xff);
1176         fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
1177         fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff);
1178         fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
1179         fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + h * (w % 2)) & 0xff,
1180                 (unsigned char) ((h * w + h * (w % 2)) >> 8) &  0xff,
1181                 (unsigned char) ((h * w + h * (w % 2)) >> 16) & 0xff,
1182                 (unsigned char) ((h * w + h * (w % 2)) >> 24) & 0xff);
1183         fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
1184         fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
1185         fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
1186         fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
1187
1188         if (image->comps[0].prec > 8) {
1189             adjustR = image->comps[0].prec - 8;
1190             printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
1191         }else
1192             adjustR = 0;
1193
1194         for (i = 0; i < 256; i++) {
1195             fprintf(fdest, "%c%c%c%c", i, i, i, 0);
1196         }
1197
1198         for (i = 0; i < w * h; i++) {
1199             int r;
1200
1201             r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
1202             r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
1203             r = ((r >> adjustR)+((r >> (adjustR-1))%2));
1204             if(r > 255) r = 255; else if(r < 0) r = 0;
1205
1206             fprintf(fdest, "%c", (unsigned char)r);
1207
1208             if ((i + 1) % w == 0) {
1209                 for (pad = w % 4 ? 4 - w % 4 : 0; pad > 0; pad--)       /* ADD */
1210                     fprintf(fdest, "%c", 0);
1211             }
1212         }
1213         fclose(fdest);
1214     }
1215
1216     return 0;
1217 }
1218
1219 /* -->> -->> -->> -->>
1220
1221 PGX IMAGE FORMAT
1222
1223 <<-- <<-- <<-- <<-- */
1224
1225
1226 static unsigned char readuchar(FILE * f)
1227 {
1228     unsigned char c1;
1229     if ( !fread(&c1, 1, 1, f) )
1230     {
1231         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1232         return 0;
1233     }
1234     return c1;
1235 }
1236
1237 static unsigned short readushort(FILE * f, int bigendian)
1238 {
1239     unsigned char c1, c2;
1240     if ( !fread(&c1, 1, 1, f) )
1241     {
1242         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1243         return 0;
1244     }
1245     if ( !fread(&c2, 1, 1, f) )
1246     {
1247         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1248         return 0;
1249     }
1250     if (bigendian)
1251         return (c1 << 8) + c2;
1252     else
1253         return (c2 << 8) + c1;
1254 }
1255
1256 static unsigned int readuint(FILE * f, int bigendian)
1257 {
1258     unsigned char c1, c2, c3, c4;
1259     if ( !fread(&c1, 1, 1, f) )
1260     {
1261         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1262         return 0;
1263     }
1264     if ( !fread(&c2, 1, 1, f) )
1265     {
1266         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1267         return 0;
1268     }
1269     if ( !fread(&c3, 1, 1, f) )
1270     {
1271         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1272         return 0;
1273     }
1274     if ( !fread(&c4, 1, 1, f) )
1275     {
1276         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1277         return 0;
1278     }
1279     if (bigendian)
1280         return (c1 << 24) + (c2 << 16) + (c3 << 8) + c4;
1281     else
1282         return (c4 << 24) + (c3 << 16) + (c2 << 8) + c1;
1283 }
1284
1285 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
1286     FILE *f = NULL;
1287     int w, h, prec;
1288     int i, numcomps, max;
1289     OPJ_COLOR_SPACE color_space;
1290     opj_image_cmptparm_t cmptparm;      /* maximum of 1 component  */
1291     opj_image_t * image = NULL;
1292     int adjustS, ushift, dshift, force8;
1293
1294     char endian1,endian2,sign;
1295     char signtmp[32];
1296
1297     char temp[32];
1298     int bigendian;
1299     opj_image_comp_t *comp = NULL;
1300
1301     numcomps = 1;
1302     color_space = OPJ_CLRSPC_GRAY;
1303
1304     memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
1305
1306     max = 0;
1307
1308     f = fopen(filename, "rb");
1309     if (!f) {
1310         fprintf(stderr, "Failed to open %s for reading !\n", filename);
1311         return NULL;
1312     }
1313
1314     fseek(f, 0, SEEK_SET);
1315     if( fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h) != 9){
1316         fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n");
1317         return NULL;
1318     }
1319
1320     i=0;
1321     sign='+';
1322     while (signtmp[i]!='\0') {
1323         if (signtmp[i]=='-') sign='-';
1324         i++;
1325     }
1326
1327     fgetc(f);
1328     if (endian1=='M' && endian2=='L') {
1329         bigendian = 1;
1330     } else if (endian2=='M' && endian1=='L') {
1331         bigendian = 0;
1332     } else {
1333         fprintf(stderr, "Bad pgx header, please check input file\n");
1334         return NULL;
1335     }
1336
1337     /* initialize image component */
1338
1339     cmptparm.x0 = parameters->image_offset_x0;
1340     cmptparm.y0 = parameters->image_offset_y0;
1341     cmptparm.w = !cmptparm.x0 ? (w - 1) * parameters->subsampling_dx + 1 : cmptparm.x0 + (w - 1) * parameters->subsampling_dx + 1;
1342     cmptparm.h = !cmptparm.y0 ? (h - 1) * parameters->subsampling_dy + 1 : cmptparm.y0 + (h - 1) * parameters->subsampling_dy + 1;
1343
1344     if (sign == '-') {
1345         cmptparm.sgnd = 1;
1346     } else {
1347         cmptparm.sgnd = 0;
1348     }
1349     if(prec < 8)
1350     {
1351         force8 = 1;
1352         ushift = 8 - prec; dshift = prec - ushift;
1353         if(cmptparm.sgnd) adjustS = (1<<(prec - 1)); else adjustS = 0;
1354         cmptparm.sgnd = 0;
1355         prec = 8;
1356     }
1357     else ushift = dshift = force8 = adjustS = 0;
1358
1359     cmptparm.prec = prec;
1360     cmptparm.bpp = prec;
1361     cmptparm.dx = parameters->subsampling_dx;
1362     cmptparm.dy = parameters->subsampling_dy;
1363
1364     /* create the image */
1365     image = opj_image_create(numcomps, &cmptparm, color_space);
1366     if(!image) {
1367         fclose(f);
1368         return NULL;
1369     }
1370     /* set image offset and reference grid */
1371     image->x0 = cmptparm.x0;
1372     image->y0 = cmptparm.x0;
1373     image->x1 = cmptparm.w;
1374     image->y1 = cmptparm.h;
1375
1376     /* set image data */
1377
1378     comp = &image->comps[0];
1379
1380     for (i = 0; i < w * h; i++) {
1381         int v;
1382         if(force8)
1383         {
1384             v = readuchar(f) + adjustS;
1385             v = (v<<ushift) + (v>>dshift);
1386             comp->data[i] = (unsigned char)v;
1387
1388             if(v > max) max = v;
1389
1390             continue;
1391         }
1392         if (comp->prec == 8) {
1393             if (!comp->sgnd) {
1394                 v = readuchar(f);
1395             } else {
1396                 v = (char) readuchar(f);
1397             }
1398         } else if (comp->prec <= 16) {
1399             if (!comp->sgnd) {
1400                 v = readushort(f, bigendian);
1401             } else {
1402                 v = (short) readushort(f, bigendian);
1403             }
1404         } else {
1405             if (!comp->sgnd) {
1406                 v = readuint(f, bigendian);
1407             } else {
1408                 v = (int) readuint(f, bigendian);
1409             }
1410         }
1411         if (v > max)
1412             max = v;
1413         comp->data[i] = v;
1414     }
1415     fclose(f);
1416     comp->bpp = int_floorlog2(max) + 1;
1417
1418     return image;
1419 }
1420
1421 #define CLAMP(x,a,b) x < a ? a : (x > b ? b : x)
1422
1423 static inline int clamp( const int value, const int prec, const int sgnd )
1424 {
1425   if( sgnd )
1426     {
1427     if (prec <= 8)       return CLAMP(value,-128,127);
1428     else if (prec <= 16) return CLAMP(value,-32768,32767);
1429     else                 return CLAMP(value,-2147483647-1,2147483647);
1430     }
1431   else
1432     {
1433     if (prec <= 8)       return CLAMP(value,0,255);
1434     else if (prec <= 16) return CLAMP(value,0,65535);
1435     else                 return CLAMP(value,0,4294967295);
1436     }
1437 }
1438
1439 int imagetopgx(opj_image_t * image, const char *outfile) 
1440 {
1441   int w, h;
1442   int i, j, compno, fails = 1;
1443   FILE *fdest = NULL;
1444
1445   for (compno = 0; compno < image->numcomps; compno++) 
1446     {
1447     opj_image_comp_t *comp = &image->comps[compno];
1448     char bname[256]; /* buffer for name */
1449     char *name = bname; /* pointer */
1450     int nbytes = 0;
1451     size_t res;
1452     const size_t olen = strlen(outfile);
1453     const size_t dotpos = olen - 4;
1454     const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
1455
1456     if( outfile[dotpos] != '.' ) 
1457       {
1458       /* `pgx` was recognized but there is no dot at expected position */
1459       fprintf(stderr, "ERROR -> Impossible happen." );
1460       goto fin;
1461       }
1462     if( total > 256 ) 
1463       {
1464       name = (char*)malloc(total+1);
1465       }
1466     strncpy(name, outfile, dotpos);
1467     sprintf(name+dotpos, "_%d.pgx", compno);
1468     fdest = fopen(name, "wb");
1469     /* dont need name anymore */
1470     if( total > 256 ) free(name);
1471     if (!fdest) 
1472       {
1473       fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
1474       goto fin;
1475       }
1476
1477     w = image->comps[compno].w;
1478     h = image->comps[compno].h;
1479
1480     fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
1481       w, h);
1482
1483     if (comp->prec <= 8) 
1484       nbytes = 1;
1485     else if (comp->prec <= 16)
1486       nbytes = 2;
1487     else
1488       nbytes = 4;
1489
1490     for (i = 0; i < w * h; i++) 
1491       {
1492       /* FIXME: clamp func is being called within a loop */
1493       const int val = clamp(image->comps[compno].data[i],
1494         comp->prec, comp->sgnd);
1495
1496       for (j = nbytes - 1; j >= 0; j--) 
1497         {
1498         int v = (int)(val >> (j * 8));
1499         unsigned char byte = (unsigned char)v;
1500         res = fwrite(&byte, 1, 1, fdest);
1501
1502         if( res < 1 ) 
1503           {
1504           fprintf(stderr, "failed to write 1 byte for %s\n", name);
1505           goto fin;
1506           }
1507         }
1508       }
1509     fclose(fdest); fdest = NULL;
1510     }
1511   fails = 0;
1512 fin:
1513   if(fdest) fclose(fdest);
1514
1515   return fails;
1516 }
1517
1518 /* -->> -->> -->> -->>
1519
1520 PNM IMAGE FORMAT
1521
1522 <<-- <<-- <<-- <<-- */
1523
1524 struct pnm_header
1525 {
1526     int width, height, maxval, depth, format;
1527     char rgb, rgba, gray, graya, bw;
1528     char ok;
1529 };
1530
1531 static char *skip_white(char *s)
1532 {
1533     while(*s)
1534     {
1535         if(*s == '\n' || *s == '\r') return NULL;
1536         if(isspace(*s)) { ++s; continue; }
1537         return s;
1538     }
1539     return NULL;
1540 }
1541
1542 static char *skip_int(char *start, int *out_n)
1543 {
1544     char *s;
1545     char c;
1546
1547     *out_n = 0; s = start;
1548
1549     s = skip_white(start);
1550     if(s == NULL) return NULL;
1551     start = s;
1552
1553     while(*s)
1554     {
1555         if( !isdigit(*s)) break;
1556         ++s;
1557     }
1558     c = *s; *s = 0; *out_n = atoi(start); *s = c;
1559     return s;
1560 }
1561
1562 static char *skip_idf(char *start, char out_idf[256])
1563 {
1564     char *s;
1565     char c;
1566
1567     s = skip_white(start);
1568     if(s == NULL) return NULL;
1569     start = s;
1570
1571     while(*s)
1572     {
1573         if(isalpha(*s) || *s == '_') { ++s; continue; }
1574         break;
1575     }
1576     c = *s; *s = 0; strncpy(out_idf, start, 255); *s = c;
1577     return s;
1578 }
1579
1580 static void read_pnm_header(FILE *reader, struct pnm_header *ph)
1581 {
1582     char *s;
1583     int format, have_wh, end, ttype;
1584     char idf[256], type[256];
1585     char line[256];
1586
1587     if (fgets(line, 250, reader) == NULL)
1588     {
1589         fprintf(stderr,"\nWARNING: fgets return a NULL value");
1590         return;
1591     }
1592
1593     if(line[0] != 'P')
1594     {
1595         fprintf(stderr,"read_pnm_header:PNM:magic P missing\n"); return;
1596     }
1597     format = atoi(line + 1);
1598     if(format < 1 || format > 7)
1599     {
1600         fprintf(stderr,"read_pnm_header:magic format %d invalid\n", format);
1601         return;
1602     }
1603     ph->format = format;
1604     ttype = end = have_wh = 0;
1605
1606     while(fgets(line, 250, reader))
1607     {
1608         if(*line == '#') continue;
1609
1610         s = line;
1611
1612         if(format == 7)
1613         {
1614             s = skip_idf(s, idf);
1615
1616             if(s == NULL || *s == 0) return;
1617
1618             if(strcmp(idf, "ENDHDR") == 0)
1619             {
1620                 end = 1; break;
1621             }
1622             if(strcmp(idf, "WIDTH") == 0)
1623             {
1624                 s = skip_int(s, &ph->width);
1625                 if(s == NULL || *s == 0) return;
1626
1627                 continue;
1628             }
1629             if(strcmp(idf, "HEIGHT") == 0)
1630             {
1631                 s = skip_int(s, &ph->height);
1632                 if(s == NULL || *s == 0) return;
1633
1634                 continue;
1635             }
1636             if(strcmp(idf, "DEPTH") == 0)
1637             {
1638                 s = skip_int(s, &ph->depth);
1639                 if(s == NULL || *s == 0) return;
1640
1641                 continue;
1642             }
1643             if(strcmp(idf, "MAXVAL") == 0)
1644             {
1645                 s = skip_int(s, &ph->maxval);
1646                 if(s == NULL || *s == 0) return;
1647
1648                 continue;
1649             }
1650             if(strcmp(idf, "TUPLTYPE") == 0)
1651             {
1652                 s = skip_idf(s, type);
1653                 if(s == NULL || *s == 0) return;
1654
1655                 if(strcmp(type, "BLACKANDWHITE") == 0)
1656                 {
1657                     ph->bw = 1; ttype = 1; continue;
1658                 }
1659                 if(strcmp(type, "GRAYSCALE") == 0)
1660                 {
1661                     ph->gray = 1; ttype = 1; continue;
1662                 }
1663                 if(strcmp(type, "GRAYSCALE_ALPHA") == 0)
1664                 {
1665                     ph->graya = 1; ttype = 1; continue;
1666                 }
1667                 if(strcmp(type, "RGB") == 0)
1668                 {
1669                     ph->rgb = 1; ttype = 1; continue;
1670                 }
1671                 if(strcmp(type, "RGB_ALPHA") == 0)
1672                 {
1673                     ph->rgba = 1; ttype = 1; continue;
1674                 }
1675                 fprintf(stderr,"read_pnm_header:unknown P7 TUPLTYPE %s\n",type);
1676                 return;
1677             }
1678             fprintf(stderr,"read_pnm_header:unknown P7 idf %s\n",idf);
1679             return;
1680         } /* if(format == 7) */
1681
1682         if( !have_wh)
1683         {
1684             s = skip_int(s, &ph->width);
1685
1686             s = skip_int(s, &ph->height);
1687
1688             have_wh = 1;
1689
1690             if(format == 1 || format == 4) break;
1691
1692             continue;
1693         }
1694         if(format == 2 || format == 3 || format == 5 || format == 6)
1695         {
1696             /* P2, P3, P5, P6: */
1697             s = skip_int(s, &ph->maxval);
1698
1699             if(ph->maxval > 65535) return;
1700         }
1701         break;
1702     }/* while(fgets( ) */
1703     if(format == 2 || format == 3 || format > 4)
1704     {
1705         if(ph->maxval < 1 || ph->maxval > 65535) return;
1706     }
1707     if(ph->width < 1 || ph->height < 1) return;
1708
1709     if(format == 7)
1710     {
1711         if(!end)
1712         {
1713             fprintf(stderr,"read_pnm_header:P7 without ENDHDR\n"); return;
1714         }
1715         if(ph->depth < 1 || ph->depth > 4) return;
1716
1717         if(ph->width && ph->height && ph->depth & ph->maxval && ttype)
1718             ph->ok = 1;
1719     }
1720     else
1721     {
1722         if(format != 1 && format != 4)
1723         {
1724             if(ph->width && ph->height && ph->maxval) ph->ok = 1;
1725         }
1726         else
1727         {
1728             if(ph->width && ph->height) ph->ok = 1;
1729             ph->maxval = 255;
1730         }
1731     }
1732 }
1733
1734 static int has_prec(int val)
1735 {
1736     if(val < 2) return 1;
1737     if(val < 4) return 2;
1738     if(val < 8) return 3;
1739     if(val < 16) return 4;
1740     if(val < 32) return 5;
1741     if(val < 64) return 6;
1742     if(val < 128) return 7;
1743     if(val < 256) return 8;
1744     if(val < 512) return 9;
1745     if(val < 1024) return 10;
1746     if(val < 2048) return 11;
1747     if(val < 4096) return 12;
1748     if(val < 8192) return 13;
1749     if(val < 16384) return 14;
1750     if(val < 32768) return 15;
1751     return 16;
1752 }
1753
1754 opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
1755     int subsampling_dx = parameters->subsampling_dx;
1756     int subsampling_dy = parameters->subsampling_dy;
1757
1758     FILE *fp = NULL;
1759     int i, compno, numcomps, w, h, prec, format;
1760     OPJ_COLOR_SPACE color_space;
1761     opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
1762     opj_image_t * image = NULL;
1763     struct pnm_header header_info;
1764
1765     if((fp = fopen(filename, "rb")) == NULL)
1766     {
1767         fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n",filename);
1768         return NULL;
1769     }
1770     memset(&header_info, 0, sizeof(struct pnm_header));
1771
1772     read_pnm_header(fp, &header_info);
1773
1774     if(!header_info.ok) { fclose(fp); return NULL; }
1775
1776     format = header_info.format;
1777
1778     switch(format)
1779     {
1780     case 1: /* ascii bitmap */
1781     case 4: /* raw bitmap */
1782         numcomps = 1;
1783         break;
1784
1785     case 2: /* ascii greymap */
1786     case 5: /* raw greymap */
1787         numcomps = 1;
1788         break;
1789
1790     case 3: /* ascii pixmap */
1791     case 6: /* raw pixmap */
1792         numcomps = 3;
1793         break;
1794
1795     case 7: /* arbitrary map */
1796         numcomps = header_info.depth;
1797         break;
1798
1799     default: fclose(fp); return NULL;
1800     }
1801     if(numcomps < 3)
1802         color_space = OPJ_CLRSPC_GRAY;/* GRAY, GRAYA */
1803     else
1804         color_space = OPJ_CLRSPC_SRGB;/* RGB, RGBA */
1805
1806     prec = has_prec(header_info.maxval);
1807
1808     if(prec < 8) prec = 8;
1809
1810     w = header_info.width;
1811     h = header_info.height;
1812     subsampling_dx = parameters->subsampling_dx;
1813     subsampling_dy = parameters->subsampling_dy;
1814
1815     memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
1816
1817     for(i = 0; i < numcomps; i++)
1818     {
1819         cmptparm[i].prec = prec;
1820         cmptparm[i].bpp = prec;
1821         cmptparm[i].sgnd = 0;
1822         cmptparm[i].dx = subsampling_dx;
1823         cmptparm[i].dy = subsampling_dy;
1824         cmptparm[i].w = w;
1825         cmptparm[i].h = h;
1826     }
1827     image = opj_image_create(numcomps, &cmptparm[0], color_space);
1828
1829     if(!image) { fclose(fp); return NULL; }
1830
1831     /* set image offset and reference grid */
1832     image->x0 = parameters->image_offset_x0;
1833     image->y0 = parameters->image_offset_y0;
1834     image->x1 = parameters->image_offset_x0 + (w - 1) * subsampling_dx + 1;
1835     image->y1 = parameters->image_offset_y0 + (h - 1) * subsampling_dy + 1;
1836
1837     if((format == 2) || (format == 3)) /* ascii pixmap */
1838     {
1839         unsigned int index;
1840
1841         for (i = 0; i < w * h; i++)
1842         {
1843             for(compno = 0; compno < numcomps; compno++)
1844             {
1845                 index = 0;
1846                 if (fscanf(fp, "%u", &index) != 1)
1847                     fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1848
1849                 image->comps[compno].data[i] = (index * 255)/header_info.maxval;
1850             }
1851         }
1852     }
1853     else
1854         if((format == 5)
1855                 || (format == 6)
1856                 ||((format == 7)
1857                    && (   header_info.gray || header_info.graya
1858                           || header_info.rgb || header_info.rgba)))/* binary pixmap */
1859         {
1860             unsigned char c0, c1, one;
1861
1862             one = (prec < 9);
1863
1864             for (i = 0; i < w * h; i++)
1865             {
1866                 for(compno = 0; compno < numcomps; compno++)
1867                 {
1868                     if ( !fread(&c0, 1, 1, fp) )
1869                         fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1870                     if(one)
1871                     {
1872                         image->comps[compno].data[i] = c0;
1873                     }
1874                     else
1875                     {
1876                         if ( !fread(&c1, 1, 1, fp) )
1877                             fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1878                         /* netpbm: */
1879                         image->comps[compno].data[i] = ((c0<<8) | c1);
1880                     }
1881                 }
1882             }
1883         }
1884         else
1885             if(format == 1) /* ascii bitmap */
1886             {
1887                 for (i = 0; i < w * h; i++)
1888                 {
1889                     unsigned int index;
1890
1891                     if ( fscanf(fp, "%u", &index) != 1)
1892                         fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
1893
1894                     image->comps[0].data[i] = (index?0:255);
1895                 }
1896             }
1897             else
1898                 if(format == 4)
1899                 {
1900                     int x, y, bit;
1901                     unsigned char uc;
1902
1903                     i = 0;
1904                     for(y = 0; y < h; ++y)
1905                     {
1906                         bit = -1; uc = 0;
1907
1908                         for(x = 0; x < w; ++x)
1909                         {
1910                             if(bit == -1)
1911                             {
1912                                 bit = 7;
1913                                 uc = (unsigned char)getc(fp);
1914                             }
1915                             image->comps[0].data[i] = (((uc>>bit) & 1)?0:255);
1916                             --bit; ++i;
1917                         }
1918                     }
1919                 }
1920                 else
1921                     if((format == 7 && header_info.bw)) /*MONO*/
1922                     {
1923                         unsigned char uc;
1924
1925                         for(i = 0; i < w * h; ++i)
1926                         {
1927                             if ( !fread(&uc, 1, 1, fp) )
1928                                 fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
1929                             image->comps[0].data[i] = (uc & 1)?0:255;
1930                         }
1931                     }
1932     fclose(fp);
1933
1934     return image;
1935 }/* pnmtoimage() */
1936
1937 int imagetopnm(opj_image_t * image, const char *outfile) 
1938 {
1939     int *red, *green, *blue, *alpha;
1940     int wr, hr, max;
1941     int i, compno, ncomp;
1942     int adjustR, adjustG, adjustB, adjustA;
1943     int fails, two, want_gray, has_alpha, triple;
1944     int prec, v;
1945     FILE *fdest = NULL;
1946     const char *tmp = outfile;
1947     char *destname;
1948
1949         alpha = NULL;
1950
1951     if((prec = image->comps[0].prec) > 16)
1952     {
1953         fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
1954                 "\n\t: refused.\n",__FILE__,__LINE__,prec);
1955         return 1;
1956     }
1957     two = has_alpha = 0; fails = 1;
1958     ncomp = image->numcomps;
1959
1960     while (*tmp) ++tmp; tmp -= 2;
1961     want_gray = (*tmp == 'g' || *tmp == 'G');
1962     ncomp = image->numcomps;
1963
1964     if(want_gray) ncomp = 1;
1965
1966     if (ncomp == 2 /* GRAYA */
1967             || (ncomp > 2 /* RGB, RGBA */
1968                 && image->comps[0].dx == image->comps[1].dx
1969                 && image->comps[1].dx == image->comps[2].dx
1970                 && image->comps[0].dy == image->comps[1].dy
1971                 && image->comps[1].dy == image->comps[2].dy
1972                 && image->comps[0].prec == image->comps[1].prec
1973                 && image->comps[1].prec == image->comps[2].prec
1974                 ))
1975     {
1976         fdest = fopen(outfile, "wb");
1977
1978         if (!fdest)
1979         {
1980             fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
1981             return fails;
1982         }
1983         two = (prec > 8);
1984         triple = (ncomp > 2);
1985         wr = image->comps[0].w; hr = image->comps[0].h;
1986         max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);
1987
1988         red = image->comps[0].data;
1989
1990         if(triple)
1991         {
1992             green = image->comps[1].data;
1993             blue = image->comps[2].data;
1994         }
1995         else green = blue = NULL;
1996
1997         if(has_alpha)
1998         {
1999             const char *tt = (triple?"RGB_ALPHA":"GRAYSCALE_ALPHA");
2000
2001             fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %d\n"
2002                     "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
2003                     wr, hr, ncomp, max, tt);
2004             alpha = image->comps[ncomp - 1].data;
2005             adjustA = (image->comps[ncomp - 1].sgnd ?
2006                         1 << (image->comps[ncomp - 1].prec - 1) : 0);
2007         }
2008         else
2009         {
2010             fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
2011                     opj_version(), wr, hr, max);
2012             adjustA = 0;
2013         }
2014         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
2015
2016         if(triple)
2017         {
2018             adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
2019             adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
2020         }
2021         else adjustG = adjustB = 0;
2022
2023         for(i = 0; i < wr * hr; ++i)
2024         {
2025             if(two)
2026             {
2027                 v = *red + adjustR; ++red;
2028 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2029
2030                 /* netpbm: */
2031                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
2032
2033                 if(triple)
2034                 {
2035                     v = *green + adjustG; ++green;
2036 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2037
2038                     /* netpbm: */
2039                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
2040
2041                     v =  *blue + adjustB; ++blue;
2042 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2043
2044                     /* netpbm: */
2045                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
2046
2047                 }/* if(triple) */
2048
2049                 if(has_alpha)
2050                 {
2051                     v = *alpha + adjustA; ++alpha;
2052                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2053
2054                     /* netpbm: */
2055                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
2056                 }
2057                 continue;
2058
2059             }   /* if(two) */
2060
2061             /* prec <= 8: */
2062         v = *red++;
2063         if(v > 255) v = 255; else if(v < 0) v = 0;
2064
2065         fprintf(fdest, "%c", (unsigned char)v);
2066             if(triple)
2067  {
2068         v = *green++;
2069         if(v > 255) v = 255; else if(v < 0) v = 0;
2070
2071         fprintf(fdest, "%c", (unsigned char)v);
2072         v = *blue++;
2073         if(v > 255) v = 255; else if(v < 0) v = 0;
2074
2075         fprintf(fdest, "%c", (unsigned char)v);
2076  }
2077             if(has_alpha)
2078  {
2079         v = *alpha++;
2080         if(v > 255) v = 255; else if(v < 0) v = 0;
2081
2082         fprintf(fdest, "%c", (unsigned char)v);
2083  }
2084         }       /* for(i */
2085
2086         fclose(fdest); return 0;
2087     }
2088
2089     /* YUV or MONO: */
2090
2091     if (image->numcomps > ncomp)
2092     {
2093         fprintf(stderr,"WARNING -> [PGM file] Only the first component\n");
2094         fprintf(stderr,"           is written to the file\n");
2095     }
2096     destname = (char*)malloc(strlen(outfile) + 8);
2097
2098     for (compno = 0; compno < ncomp; compno++)
2099     {
2100         if (ncomp > 1)
2101             sprintf(destname, "%d.%s", compno, outfile);
2102         else
2103             sprintf(destname, "%s", outfile);
2104
2105         fdest = fopen(destname, "wb");
2106         if (!fdest)
2107         {
2108             fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
2109             free(destname);
2110             return 1;
2111         }
2112         wr = image->comps[compno].w; hr = image->comps[compno].h;
2113         prec = image->comps[compno].prec;
2114         max = (1<<prec) - 1;
2115
2116         fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
2117                 opj_version(), wr, hr, max);
2118
2119         red = image->comps[compno].data;
2120         adjustR =
2121                 (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
2122
2123         if(prec > 8)
2124         {
2125             for (i = 0; i < wr * hr; i++)
2126             {
2127                 v = *red + adjustR; ++red;
2128 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2129
2130                 /* netpbm: */
2131                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
2132
2133                 if(has_alpha)
2134                 {
2135                     v = *alpha++;
2136 if(v > 65535) v = 65535; else if(v < 0) v = 0;
2137
2138                     /* netpbm: */
2139                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
2140                 }
2141             }/* for(i */
2142         }
2143         else /* prec <= 8 */
2144         {
2145             for(i = 0; i < wr * hr; ++i)
2146             {
2147         v = *red + adjustR; ++red;
2148         if(v > 255) v = 255; else if(v < 0) v = 0;
2149
2150          fprintf(fdest, "%c", (unsigned char)v);
2151             }
2152         }
2153         fclose(fdest);
2154     } /* for (compno */
2155     free(destname);
2156
2157     return 0;
2158 }/* imagetopnm() */
2159
2160 #ifdef OPJ_HAVE_LIBTIFF
2161 /* -->> -->> -->> -->>
2162
2163     TIFF IMAGE FORMAT
2164
2165  <<-- <<-- <<-- <<-- */
2166
2167 int imagetotif(opj_image_t * image, const char *outfile) 
2168 {
2169     int width, height, imgsize;
2170     int bps,index,adjust, sgnd;
2171     int ushift, dshift, has_alpha, force16;
2172     TIFF *tif;
2173     tdata_t buf;
2174     tstrip_t strip;
2175     tsize_t strip_size;
2176
2177     ushift = dshift = force16 = has_alpha = 0;
2178     bps = image->comps[0].prec;
2179
2180     if(bps > 8 && bps < 16)
2181     {
2182         ushift = 16 - bps; dshift = bps - ushift;
2183         bps = 16; force16 = 1;
2184     }
2185
2186     if(bps != 8 && bps != 16)
2187     {
2188         fprintf(stderr,"imagetotif: Bits=%d, Only 8 and 16 bits implemented\n",
2189                 bps);
2190         fprintf(stderr,"\tAborting\n");
2191         return 1;
2192     }
2193     tif = TIFFOpen(outfile, "wb");
2194
2195     if (!tif)
2196     {
2197         fprintf(stderr, "imagetotif:failed to open %s for writing\n", outfile);
2198         return 1;
2199     }
2200     sgnd = image->comps[0].sgnd;
2201     adjust = sgnd ? 1 << (image->comps[0].prec - 1) : 0;
2202
2203     if(image->numcomps >= 3
2204             && image->comps[0].dx == image->comps[1].dx
2205             && image->comps[1].dx == image->comps[2].dx
2206             && image->comps[0].dy == image->comps[1].dy
2207             && image->comps[1].dy == image->comps[2].dy
2208             && image->comps[0].prec == image->comps[1].prec
2209             && image->comps[1].prec == image->comps[2].prec)
2210     {
2211         has_alpha = (image->numcomps == 4);
2212
2213         width   = image->comps[0].w;
2214         height  = image->comps[0].h;
2215         imgsize = width * height ;
2216
2217         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
2218         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
2219         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3 + has_alpha);
2220         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
2221         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
2222         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
2223         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
2224         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
2225         strip_size = TIFFStripSize(tif);
2226         buf = _TIFFmalloc(strip_size);
2227         index=0;
2228
2229         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
2230         {
2231             unsigned char *dat8;
2232             tsize_t i, ssize, last_i = 0;
2233             int step, restx;
2234             ssize = TIFFStripSize(tif);
2235             dat8 = (unsigned char*)buf;
2236
2237             if(bps == 8)
2238             {
2239                 step = 3 + has_alpha;
2240                 restx = step - 1;
2241
2242                 for(i=0; i < ssize - restx; i += step)
2243                 {
2244                     int r, g, b, a = 0;
2245
2246                     if(index < imgsize)
2247                     {
2248                         r = image->comps[0].data[index];
2249                         g = image->comps[1].data[index];
2250                         b = image->comps[2].data[index];
2251                         if(has_alpha) a = image->comps[3].data[index];
2252
2253                         if(sgnd)
2254                         {
2255                             r += adjust;
2256                             g += adjust;
2257                             b += adjust;
2258                             if(has_alpha) a += adjust;
2259                         }
2260                 if(r > 255) r = 255; else if(r < 0) r = 0;
2261                         dat8[i+0] = r ;
2262                 if(g > 255) g = 255; else if(g < 0) g = 0;
2263                         dat8[i+1] = g ;
2264                 if(b > 255) b = 255; else if(b < 0) b = 0;
2265                         dat8[i+2] = b ;
2266                 if(has_alpha) 
2267          {
2268                 if(a > 255) a = 255; else if(a < 0) a = 0;
2269                 dat8[i+3] = a;
2270          }
2271
2272                         index++;
2273                         last_i = i + step;
2274                     }
2275                     else
2276                         break;
2277                 }/*for(i = 0;)*/
2278
2279                 if(last_i < ssize)
2280                 {
2281                     for(i = last_i; i < ssize; i += step)
2282                     {
2283                         int r, g, b, a = 0;
2284
2285                         if(index < imgsize)
2286                         {
2287                             r = image->comps[0].data[index];
2288                             g = image->comps[1].data[index];
2289                             b = image->comps[2].data[index];
2290                             if(has_alpha) a = image->comps[3].data[index];
2291
2292                             if(sgnd)
2293                             {
2294                                 r += adjust;
2295                                 g += adjust;
2296                                 b += adjust;
2297                                 if(has_alpha) a += adjust;
2298                             }
2299                 if(r > 255) r = 255; else if(r < 0) r = 0;
2300                 if(g > 255) g = 255; else if(g < 0) g = 0;
2301                 if(b > 255) b = 255; else if(b < 0) b = 0;
2302
2303                             dat8[i+0] = r ;
2304                             if(i+1 < ssize) dat8[i+1] = g ;  else break;
2305                             if(i+2 < ssize) dat8[i+2] = b ;  else break;
2306                             if(has_alpha)
2307                             {
2308                 if(a > 255) a = 255; else if(a < 0) a = 0;
2309
2310                                 if(i+3 < ssize) dat8[i+3] = a ;  else break;
2311                             }
2312                             index++;
2313                         }
2314                         else
2315                             break;
2316                     }/*for(i)*/
2317                 }/*if(last_i < ssize)*/
2318
2319             }   /*if(bps == 8)*/
2320             else
2321                 if(bps == 16)
2322                 {
2323                     step = 6 + has_alpha + has_alpha;
2324                     restx = step - 1;
2325
2326                     for(i = 0; i < ssize - restx ; i += step)
2327                     {
2328                         int r, g, b, a = 0;
2329
2330                         if(index < imgsize)
2331                         {
2332                             r = image->comps[0].data[index];
2333                             g = image->comps[1].data[index];
2334                             b = image->comps[2].data[index];
2335                             if(has_alpha) a = image->comps[3].data[index];
2336
2337                             if(sgnd)
2338                             {
2339                                 r += adjust;
2340                                 g += adjust;
2341                                 b += adjust;
2342                                 if(has_alpha) a += adjust;
2343                             }
2344                             if(force16)
2345                             {
2346                                 r = (r<<ushift) + (r>>dshift);
2347                                 g = (g<<ushift) + (g>>dshift);
2348                                 b = (b<<ushift) + (b>>dshift);
2349                                 if(has_alpha) a = (a<<ushift) + (a>>dshift);
2350                             }
2351                 if(r > 65535) r = 65535; else if(r < 0) r = 0;
2352                 if(g > 65535) g = 65535; else if(g < 0) g = 0;
2353                 if(b > 65535) b = 65535; else if(b < 0) b = 0;
2354
2355                             dat8[i+0] =  r;/*LSB*/
2356                             dat8[i+1] = (r >> 8);/*MSB*/
2357                             dat8[i+2] =  g;
2358                             dat8[i+3] = (g >> 8);
2359                             dat8[i+4] =  b;
2360                             dat8[i+5] = (b >> 8);
2361                             if(has_alpha)
2362                             {
2363                 if(a > 65535) a = 65535; else if(a < 0) a = 0;
2364                                 dat8[i+6] =  a;
2365                                 dat8[i+7] = (a >> 8);
2366                             }
2367                             index++;
2368                             last_i = i + step;
2369                         }
2370                         else
2371                             break;
2372                     }/*for(i = 0;)*/
2373
2374                     if(last_i < ssize)
2375                     {
2376                         for(i = last_i ; i < ssize ; i += step)
2377                         {
2378                             int r, g, b, a = 0;
2379
2380                             if(index < imgsize)
2381                             {
2382                                 r = image->comps[0].data[index];
2383                                 g = image->comps[1].data[index];
2384                                 b = image->comps[2].data[index];
2385                                 if(has_alpha) a = image->comps[3].data[index];
2386
2387                                 if(sgnd)
2388                                 {
2389                                     r += adjust;
2390                                     g += adjust;
2391                                     b += adjust;
2392                                     if(has_alpha) a += adjust;
2393                                 }
2394                                 if(force16)
2395                                 {
2396                                     r = (r<<ushift) + (r>>dshift);
2397                                     g = (g<<ushift) + (g>>dshift);
2398                                     b = (b<<ushift) + (b>>dshift);
2399                                     if(has_alpha) a = (a<<ushift) + (a>>dshift);
2400                                 }
2401                 if(r > 65535) r = 65535; else if(r < 0) r = 0;
2402                 if(g > 65535) g = 65535; else if(g < 0) g = 0;
2403                 if(b > 65535) b = 65535; else if(b < 0) b = 0;
2404
2405                                 dat8[i+0] =  r;/*LSB*/
2406                                 if(i+1 < ssize) dat8[i+1] = (r >> 8);else break;/*MSB*/
2407                                 if(i+2 < ssize) dat8[i+2] =  g;      else break;
2408                                 if(i+3 < ssize) dat8[i+3] = (g >> 8);else break;
2409                                 if(i+4 < ssize) dat8[i+4] =  b;      else break;
2410                                 if(i+5 < ssize) dat8[i+5] = (b >> 8);else break;
2411
2412                                 if(has_alpha)
2413                                 {
2414                 if(a > 65535) a = 65535; else if(a < 0) a = 0;
2415                                     if(i+6 < ssize) dat8[i+6] = a; else break;
2416                                     if(i+7 < ssize) dat8[i+7] = (a >> 8); else break;
2417                                 }
2418                                 index++;
2419                             }
2420                             else
2421                                 break;
2422                         }/*for(i)*/
2423                     }/*if(last_i < ssize)*/
2424
2425                 }/*if(bps == 16)*/
2426             (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
2427         }/*for(strip = 0; )*/
2428
2429         _TIFFfree((void*)buf);
2430         TIFFClose(tif);
2431
2432         return 0;
2433     }/*RGB(A)*/
2434
2435     if(image->numcomps == 1 /* GRAY */
2436             || (   image->numcomps == 2 /* GRAY_ALPHA */
2437                    && image->comps[0].dx == image->comps[1].dx
2438                    && image->comps[0].dy == image->comps[1].dy
2439                    && image->comps[0].prec == image->comps[1].prec))
2440     {
2441         int step;
2442
2443         has_alpha = (image->numcomps == 2);
2444
2445         width   = image->comps[0].w;
2446         height  = image->comps[0].h;
2447         imgsize = width * height;
2448
2449         /* Set tags */
2450         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
2451         TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
2452         TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1 + has_alpha);
2453         TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
2454         TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
2455         TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
2456         TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
2457         TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
2458
2459         /* Get a buffer for the data */
2460         strip_size = TIFFStripSize(tif);
2461         buf = _TIFFmalloc(strip_size);
2462         index = 0;
2463
2464         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
2465         {
2466             unsigned char *dat8;
2467             tsize_t i, ssize = TIFFStripSize(tif);
2468             dat8 = (unsigned char*)buf;
2469
2470             if(bps == 8)
2471             {
2472                 step = 1 + has_alpha;
2473
2474                 for(i=0; i < ssize; i += step)
2475                 {
2476                     if(index < imgsize)
2477                     {
2478                         int r, a = 0;
2479
2480                         r = image->comps[0].data[index];
2481                         if(has_alpha) a = image->comps[1].data[index];
2482
2483                         if(sgnd)
2484                         {
2485                             r += adjust;
2486                             if(has_alpha) a += adjust;
2487                         }
2488                 if(r > 255) r = 255; else if(r < 0) r = 0;
2489                         dat8[i+0] = r;
2490
2491                 if(has_alpha) 
2492          {
2493                 if(a > 255) a = 255; else if(a < 0) a = 0;
2494                 dat8[i+1] = a;
2495                     }
2496                 index++;
2497           }
2498                     else
2499                         break;
2500            }/*for(i )*/
2501             }/*if(bps == 8*/
2502             else
2503                 if(bps == 16)
2504                 {
2505                     step = 2 + has_alpha + has_alpha;
2506
2507                     for(i=0; i < ssize; i += step)
2508                     {
2509                         if(index < imgsize)
2510                         {
2511                             int r, a = 0;
2512
2513                             r = image->comps[0].data[index];
2514                             if(has_alpha) a = image->comps[1].data[index];
2515
2516                             if(sgnd)
2517                             {
2518                                 r += adjust;
2519                                 if(has_alpha) a += adjust;
2520                             }
2521                             if(force16)
2522                             {
2523                                 r = (r<<ushift) + (r>>dshift);
2524                                 if(has_alpha) a = (a<<ushift) + (a>>dshift);
2525                             }
2526                 if(r > 65535) r = 65535; else if(r < 0) r = 0;
2527                             dat8[i+0] = r;/*LSB*/
2528                             dat8[i+1] = r >> 8;/*MSB*/
2529                             if(has_alpha)
2530                             {
2531                 if(a > 65535) a = 65535; else if(a < 0) a = 0;
2532                                 dat8[i+2] = a;
2533                                 dat8[i+3] = a >> 8;
2534                             }
2535                             index++;
2536                         }/*if(index < imgsize)*/
2537                         else
2538                             break;
2539                     }/*for(i )*/
2540                 }
2541             (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
2542         }/*for(strip*/
2543
2544         _TIFFfree(buf);
2545         TIFFClose(tif);
2546
2547         return 0;
2548     }
2549
2550     TIFFClose(tif);
2551
2552     fprintf(stderr,"imagetotif: Bad color format.\n"
2553             "\tOnly RGB(A) and GRAY(A) has been implemented\n");
2554     fprintf(stderr,"\tFOUND: numcomps(%d)\n\tAborting\n",
2555             image->numcomps);
2556
2557     return 1;
2558 }/* imagetotif() */
2559
2560 /*
2561  * libtiff/tif_getimage.c : 1,2,4,8,16 bitspersample accepted
2562  * CINEMA                 : 12 bit precision
2563 */
2564 opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
2565 {
2566     int subsampling_dx = parameters->subsampling_dx;
2567     int subsampling_dy = parameters->subsampling_dy;
2568     TIFF *tif;
2569     tdata_t buf;
2570     tstrip_t strip;
2571     tsize_t strip_size;
2572     int j, numcomps, w, h,index;
2573     OPJ_COLOR_SPACE color_space;
2574     opj_image_cmptparm_t cmptparm[4]; /* RGBA */
2575     opj_image_t *image = NULL;
2576     int imgsize = 0;
2577     int has_alpha = 0;
2578     unsigned short tiBps, tiPhoto, tiSf, tiSpp, tiPC;
2579     unsigned int tiWidth, tiHeight;
2580
2581     tif = TIFFOpen(filename, "r");
2582
2583     if(!tif)
2584     {
2585         fprintf(stderr, "tiftoimage:Failed to open %s for reading\n", filename);
2586         return 0;
2587     }
2588     tiBps = tiPhoto = tiSf = tiSpp = tiPC = 0;
2589     tiWidth = tiHeight = 0;
2590
2591     TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &tiWidth);
2592     TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &tiHeight);
2593     TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &tiBps);
2594     TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &tiSf);
2595     TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &tiSpp);
2596     TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &tiPhoto);
2597     TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &tiPC);
2598     w= tiWidth;
2599     h= tiHeight;
2600
2601     if(tiBps != 8 && tiBps != 16 && tiBps != 12) tiBps = 0;
2602     if(tiPhoto != 1 && tiPhoto != 2) tiPhoto = 0;
2603
2604     if( !tiBps || !tiPhoto)
2605     {
2606         if( !tiBps)
2607      fprintf(stderr,"tiftoimage: Bits=%d, Only 8 and 16 bits"
2608                     " implemented\n",tiBps);
2609         else
2610             if( !tiPhoto)
2611                 fprintf(stderr,"tiftoimage: Bad color format %d.\n\tOnly RGB(A)"
2612                         " and GRAY(A) has been implemented\n",(int) tiPhoto);
2613
2614         fprintf(stderr,"\tAborting\n");
2615         TIFFClose(tif);
2616
2617         return NULL;
2618     }
2619
2620     {/* From: tiff-4.0.x/libtiff/tif_getimage.c : */
2621         uint16* sampleinfo;
2622         uint16 extrasamples;
2623
2624         TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
2625                               &extrasamples, &sampleinfo);
2626
2627         if(extrasamples >= 1)
2628         {
2629             switch(sampleinfo[0])
2630             {
2631             case EXTRASAMPLE_UNSPECIFIED:
2632                 /* Workaround for some images without correct info about alpha channel
2633 */
2634                 if(tiSpp > 3)
2635                     has_alpha = 1;
2636                 break;
2637
2638             case EXTRASAMPLE_ASSOCALPHA: /* data pre-multiplied */
2639             case EXTRASAMPLE_UNASSALPHA: /* data not pre-multiplied */
2640                 has_alpha = 1;
2641                 break;
2642             }
2643         }
2644         else /* extrasamples == 0 */
2645             if(tiSpp == 4 || tiSpp == 2) has_alpha = 1;
2646     }
2647
2648     /* initialize image components
2649 */ 
2650     memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
2651
2652     if ((tiPhoto == PHOTOMETRIC_RGB) && (parameters->cp_cinema)) {
2653         fprintf(stdout,"WARNING:\n"
2654                 "Input image bitdepth is %d bits\n"
2655                 "TIF conversion has automatically rescaled to 12-bits\n"
2656                 "to comply with cinema profiles.\n",
2657                 tiBps);
2658     }
2659
2660     if(tiPhoto == PHOTOMETRIC_RGB) /* RGB(A) */
2661     {
2662         numcomps = 3 + has_alpha;
2663         color_space = OPJ_CLRSPC_SRGB;
2664
2665         /*#define USETILEMODE*/
2666         for(j = 0; j < numcomps; j++)
2667         {
2668             if(parameters->cp_cinema)
2669             {
2670                 cmptparm[j].prec = 12;
2671                 cmptparm[j].bpp = 12;
2672             }
2673             else
2674             {
2675                 cmptparm[j].prec = tiBps;
2676                 cmptparm[j].bpp = tiBps;
2677             }
2678             cmptparm[j].dx = subsampling_dx;
2679             cmptparm[j].dy = subsampling_dy;
2680             cmptparm[j].w = w;
2681             cmptparm[j].h = h;
2682 #ifdef USETILEMODE
2683             cmptparm[j].x0 = 0;
2684             cmptparm[j].y0 = 0;
2685 #endif
2686         }
2687
2688 #ifdef USETILEMODE
2689         image = opj_image_tile_create(numcomps,&cmptparm[0],color_space);
2690 #else
2691         image = opj_image_create(numcomps, &cmptparm[0], color_space);
2692 #endif
2693
2694         if(!image)
2695         {
2696             TIFFClose(tif);
2697             return NULL;
2698         }
2699         /* set image offset and reference grid
2700 */
2701         image->x0 = parameters->image_offset_x0;
2702         image->y0 = parameters->image_offset_y0;
2703         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 :
2704                                  image->x0 + (w - 1) * subsampling_dx + 1;
2705         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 :
2706                                  image->y0 + (h - 1) * subsampling_dy + 1;
2707
2708         buf = _TIFFmalloc(TIFFStripSize(tif));
2709
2710         strip_size=TIFFStripSize(tif);
2711         index = 0;
2712         imgsize = image->comps[0].w * image->comps[0].h ;
2713         /* Read the Image components
2714 */
2715         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
2716         {
2717             unsigned char *dat8;
2718             int step;
2719             tsize_t i, ssize;
2720             ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2721             dat8 = (unsigned char*)buf;
2722
2723             if(tiBps == 16)
2724             {
2725                 step = 6 + has_alpha + has_alpha;
2726
2727                 for(i = 0; i < ssize; i += step)
2728                 {
2729                     if(index < imgsize)
2730                     {
2731                         image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0]; /* R */
2732                         image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2]; /* G */
2733                         image->comps[2].data[index] = ( dat8[i+5] << 8 ) | dat8[i+4]; /* B */
2734                         if(has_alpha)
2735                             image->comps[3].data[index] = ( dat8[i+7] << 8 ) | dat8[i+6];
2736
2737                         if(parameters->cp_cinema)
2738                         {
2739                             /* Rounding 16 to 12 bits
2740 */
2741                             image->comps[0].data[index] =
2742                                     (image->comps[0].data[index] + 0x08) >> 4 ;
2743                             image->comps[1].data[index] =
2744                                     (image->comps[1].data[index] + 0x08) >> 4 ;
2745                             image->comps[2].data[index] =
2746                                     (image->comps[2].data[index] + 0x08) >> 4 ;
2747                             if(has_alpha)
2748                                 image->comps[3].data[index] =
2749                                         (image->comps[3].data[index] + 0x08) >> 4 ;
2750                         }
2751                         index++;
2752                     }
2753                     else
2754                         break;
2755                 }/*for(i = 0)*/
2756             }/*if(tiBps == 16)*/
2757             else
2758                 if(tiBps == 8)
2759                 {
2760                     step = 3 + has_alpha;
2761
2762                     for(i = 0; i < ssize; i += step)
2763                     {
2764                         if(index < imgsize)
2765                         {
2766 #ifndef USETILEMODE
2767                             image->comps[0].data[index] = dat8[i+0];/* R */
2768                             image->comps[1].data[index] = dat8[i+1];/* G */
2769                             image->comps[2].data[index] = dat8[i+2];/* B */
2770                             if(has_alpha)
2771                                 image->comps[3].data[index] = dat8[i+3];
2772 #endif
2773
2774                             if(parameters->cp_cinema)
2775                             {
2776                                 /* Rounding 8 to 12 bits
2777 */
2778 #ifndef USETILEMODE
2779                                 image->comps[0].data[index] = image->comps[0].data[index] << 4 ;
2780                                 image->comps[1].data[index] = image->comps[1].data[index] << 4 ;
2781                                 image->comps[2].data[index] = image->comps[2].data[index] << 4 ;
2782                                 if(has_alpha)
2783                                     image->comps[3].data[index] = image->comps[3].data[index] << 4 ;
2784 #endif
2785                             }
2786                             index++;
2787                         }/*if(index*/
2788                         else
2789                             break;
2790                     }/*for(i )*/
2791                 }/*if( tiBps == 8)*/
2792                 else
2793                     if(tiBps == 12)/* CINEMA file */
2794                     {
2795                         step = 9;
2796
2797                         for(i = 0; i < ssize; i += step)
2798                         {
2799                             if((index < imgsize)&(index+1 < imgsize))
2800                             {
2801                                 image->comps[0].data[index]   = ( dat8[i+0]<<4 )        |(dat8[i+1]>>4);
2802                                 image->comps[1].data[index]   = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
2803
2804                                 image->comps[2].data[index]   = ( dat8[i+3]<<4)         |(dat8[i+4]>>4);
2805                                 image->comps[0].data[index+1] = ((dat8[i+4]& 0x0f)<< 8) | dat8[i+5];
2806
2807                                 image->comps[1].data[index+1] = ( dat8[i+6] <<4)        |(dat8[i+7]>>4);
2808                                 image->comps[2].data[index+1] = ((dat8[i+7]& 0x0f)<< 8) | dat8[i+8];
2809
2810                                 index += 2;
2811                             }
2812                             else
2813                                 break;
2814                         }/*for(i )*/
2815                     }
2816         }/*for(strip = 0; )*/
2817
2818         _TIFFfree(buf);
2819         TIFFClose(tif);
2820
2821         return image;
2822     }/*RGB(A)*/
2823
2824     if(tiPhoto == PHOTOMETRIC_MINISBLACK) /* GRAY(A) */
2825     {
2826         numcomps = 1 + has_alpha;
2827         color_space = OPJ_CLRSPC_GRAY;
2828
2829         for(j = 0; j < numcomps; ++j)
2830         {
2831             cmptparm[j].prec = tiBps;
2832             cmptparm[j].bpp = tiBps;
2833             cmptparm[j].dx = subsampling_dx;
2834             cmptparm[j].dy = subsampling_dy;
2835             cmptparm[j].w = w;
2836             cmptparm[j].h = h;
2837         }
2838 #ifdef USETILEMODE
2839         image = opj_image_tile_create(numcomps,&cmptparm[0],color_space);
2840 #else
2841         image = opj_image_create(numcomps, &cmptparm[0], color_space);
2842 #endif
2843
2844         if(!image)
2845         {
2846             TIFFClose(tif);
2847             return NULL;
2848         }
2849         /* set image offset and reference grid
2850 */
2851         image->x0 = parameters->image_offset_x0;
2852         image->y0 = parameters->image_offset_y0;
2853         image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 :
2854                                  image->x0 + (w - 1) * subsampling_dx + 1;
2855         image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 :
2856                                  image->y0 + (h - 1) * subsampling_dy + 1;
2857
2858         buf = _TIFFmalloc(TIFFStripSize(tif));
2859
2860         strip_size = TIFFStripSize(tif);
2861         index = 0;
2862         imgsize = image->comps[0].w * image->comps[0].h ;
2863         /* Read the Image components
2864 */
2865         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
2866         {
2867             unsigned char *dat8;
2868             tsize_t i, ssize;
2869             int step;
2870
2871             ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
2872             dat8 = (unsigned char*)buf;
2873
2874             if(tiBps == 16)
2875             {
2876                 step = 2 + has_alpha + has_alpha;
2877
2878                 for(i = 0; i < ssize; i += step)
2879                 {
2880                     if(index < imgsize)
2881                     {
2882                         image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0];
2883                         if(has_alpha)
2884                             image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2];
2885                         index++;
2886                     }
2887                     else
2888                         break;
2889                 }/*for(i )*/
2890             }
2891             else
2892                 if(tiBps == 8)
2893                 {
2894                     step = 1 + has_alpha;
2895
2896                     for(i = 0; i < ssize; i += step)
2897                     {
2898                         if(index < imgsize)
2899                         {
2900                             image->comps[0].data[index] = dat8[i+0];
2901                             if(has_alpha)
2902                                 image->comps[1].data[index] = dat8[i+1];
2903                             index++;
2904                         }
2905                         else
2906                             break;
2907                     }/*for(i )*/
2908                 }
2909         }/*for(strip = 0;*/
2910
2911         _TIFFfree(buf);
2912         TIFFClose(tif);
2913
2914     }/*GRAY(A)*/
2915
2916     return image;
2917
2918 }/* tiftoimage() */
2919
2920 #endif /* OPJ_HAVE_LIBTIFF */
2921
2922 /* -->> -->> -->> -->>
2923
2924     RAW IMAGE FORMAT
2925
2926  <<-- <<-- <<-- <<-- */
2927 static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian) {
2928     int subsampling_dx = parameters->subsampling_dx;
2929     int subsampling_dy = parameters->subsampling_dy;
2930
2931     FILE *f = NULL;
2932     int i, compno, numcomps, w, h;
2933     OPJ_COLOR_SPACE color_space;
2934     opj_image_cmptparm_t *cmptparm;
2935     opj_image_t * image = NULL;
2936     unsigned short ch;
2937
2938     if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
2939     {
2940         fprintf(stderr,"\nError: invalid raw image parameters\n");
2941         fprintf(stderr,"Please use the Format option -F:\n");
2942         fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
2943         fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
2944         fprintf(stderr,"Aborting\n");
2945         return NULL;
2946     }
2947
2948     f = fopen(filename, "rb");
2949     if (!f) {
2950         fprintf(stderr, "Failed to open %s for reading !!\n", filename);
2951         fprintf(stderr,"Aborting\n");
2952         return NULL;
2953     }
2954     numcomps = raw_cp->rawComp;
2955     color_space = OPJ_CLRSPC_SRGB;
2956     w = raw_cp->rawWidth;
2957     h = raw_cp->rawHeight;
2958     cmptparm = (opj_image_cmptparm_t*) malloc(numcomps * sizeof(opj_image_cmptparm_t));
2959
2960     /* initialize image components */
2961     memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
2962     for(i = 0; i < numcomps; i++) {
2963         cmptparm[i].prec = raw_cp->rawBitDepth;
2964         cmptparm[i].bpp = raw_cp->rawBitDepth;
2965         cmptparm[i].sgnd = raw_cp->rawSigned;
2966         cmptparm[i].dx = subsampling_dx;
2967         cmptparm[i].dy = subsampling_dy;
2968         cmptparm[i].w = w;
2969         cmptparm[i].h = h;
2970     }
2971     /* create the image */
2972     image = opj_image_create(numcomps, &cmptparm[0], color_space);
2973     free(cmptparm);
2974     if(!image) {
2975         fclose(f);
2976         return NULL;
2977     }
2978     /* set image offset and reference grid */
2979     image->x0 = parameters->image_offset_x0;
2980     image->y0 = parameters->image_offset_y0;
2981     image->x1 = parameters->image_offset_x0 + (w - 1) * subsampling_dx + 1;
2982     image->y1 = parameters->image_offset_y0 + (h - 1) * subsampling_dy + 1;
2983
2984     if(raw_cp->rawBitDepth <= 8)
2985     {
2986         unsigned char value = 0;
2987         for(compno = 0; compno < numcomps; compno++) {
2988             for (i = 0; i < w * h; i++) {
2989                 if (!fread(&value, 1, 1, f)) {
2990                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
2991                     return NULL;
2992                 }
2993                 image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
2994             }
2995         }
2996     }
2997     else if(raw_cp->rawBitDepth <= 16)
2998     {
2999         unsigned short value;
3000         for(compno = 0; compno < numcomps; compno++) {
3001             for (i = 0; i < w * h; i++) {
3002                 unsigned char temp1;
3003                 unsigned char temp2;
3004                 if (!fread(&temp1, 1, 1, f)) {
3005                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
3006                     return NULL;
3007                 }
3008                 if (!fread(&temp2, 1, 1, f)) {
3009                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
3010                     return NULL;
3011                 }
3012                 if( big_endian )
3013                 {
3014                     value = temp1 << 8;
3015                     value += temp2;
3016                 }
3017                 else
3018                 {
3019                     value = temp2 << 8;
3020                     value += temp1;
3021                 }
3022                 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
3023             }
3024         }
3025     }
3026     else {
3027         fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
3028         return NULL;
3029     }
3030
3031     if (fread(&ch, 1, 1, f)) {
3032         fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
3033     }
3034     fclose(f);
3035
3036     return image;
3037 }
3038
3039 opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
3040     return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE);
3041 }
3042
3043 opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
3044     return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE);
3045 }
3046
3047 static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL big_endian)
3048 {
3049     FILE *rawFile = NULL;
3050     size_t res;
3051     int compno;
3052     int w, h, fails;
3053     int line, row, curr, mask;
3054     int *ptr;
3055     unsigned char uc;
3056     (void)big_endian;
3057
3058     if((image->numcomps * image->x1 * image->y1) == 0)
3059     {
3060         fprintf(stderr,"\nError: invalid raw image parameters\n");
3061         return 1;
3062     }
3063
3064     rawFile = fopen(outfile, "wb");
3065     if (!rawFile) {
3066         fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
3067         return 1;
3068     }
3069
3070     fails = 1;
3071     fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
3072
3073     for(compno = 0; compno < image->numcomps; compno++)
3074     {
3075         fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
3076                 image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
3077
3078         w = image->comps[compno].w;
3079         h = image->comps[compno].h;
3080
3081         if(image->comps[compno].prec <= 8)
3082         {
3083             if(image->comps[compno].sgnd == 1)
3084             {
3085                 mask = (1 << image->comps[compno].prec) - 1;
3086                 ptr = image->comps[compno].data;
3087                 for (line = 0; line < h; line++) {
3088                     for(row = 0; row < w; row++)        {
3089                         curr = *ptr;
3090                         if(curr > 127) curr = 127; else if(curr < -128) curr = -128;
3091                         uc = (unsigned char) (curr & mask);
3092                         res = fwrite(&uc, 1, 1, rawFile);
3093                         if( res < 1 ) {
3094                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
3095                             goto fin;
3096                         }
3097                         ptr++;
3098                     }
3099                 }
3100             }
3101             else if(image->comps[compno].sgnd == 0)
3102             {
3103                 mask = (1 << image->comps[compno].prec) - 1;
3104                 ptr = image->comps[compno].data;
3105                 for (line = 0; line < h; line++) {
3106                     for(row = 0; row < w; row++)        {
3107                         curr = *ptr;
3108                         if(curr > 255) curr = 255; else if(curr < 0) curr = 0;
3109                         uc = (unsigned char) (curr & mask);
3110                         res = fwrite(&uc, 1, 1, rawFile);
3111                         if( res < 1 ) {
3112                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
3113                             goto fin;
3114                         }
3115                         ptr++;
3116                     }
3117                 }
3118             }
3119         }
3120         else if(image->comps[compno].prec <= 16)
3121         {
3122             if(image->comps[compno].sgnd == 1)
3123             {
3124                 union { signed short val; signed char vals[2]; } uc;
3125                 mask = (1 << image->comps[compno].prec) - 1;
3126                 ptr = image->comps[compno].data;
3127                 for (line = 0; line < h; line++) {
3128                     for(row = 0; row < w; row++)        {
3129                         curr = *ptr;
3130                         if(curr > 32767 ) curr = 32767; else if( curr < -32768) curr = -32768;
3131                         uc.val = (signed short)(curr & mask);
3132                         res = fwrite(uc.vals, 1, 2, rawFile);
3133                         if( res < 2 ) {
3134                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
3135                             goto fin;
3136                         }
3137                         ptr++;
3138                     }
3139                 }
3140             }
3141             else if(image->comps[compno].sgnd == 0)
3142             {
3143                 union { unsigned short val; unsigned char vals[2]; } uc;
3144                 mask = (1 << image->comps[compno].prec) - 1;
3145                 ptr = image->comps[compno].data;
3146                 for (line = 0; line < h; line++) {
3147                     for(row = 0; row < w; row++)        {
3148                         curr = *ptr;
3149                         if(curr > 65536 ) curr = 65536; else if( curr < 0) curr = 0;
3150                         uc.val = (unsigned short)(curr & mask);
3151                         res = fwrite(uc.vals, 1, 2, rawFile);
3152                         if( res < 2 ) {
3153                             fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
3154                             goto fin;
3155                         }
3156                         ptr++;
3157                     }
3158                 }
3159             }
3160         }
3161         else if (image->comps[compno].prec <= 32)
3162         {
3163             fprintf(stderr,"More than 16 bits per component no handled yet\n");
3164             goto fin;
3165         }
3166         else
3167         {
3168             fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
3169             goto fin;
3170         }
3171     }
3172   fails = 0;
3173 fin:
3174     fclose(rawFile);
3175     return fails;
3176 }
3177
3178 int imagetoraw(opj_image_t * image, const char *outfile)
3179 {
3180     return imagetoraw_common(image, outfile, OPJ_TRUE);
3181 }
3182
3183 int imagetorawl(opj_image_t * image, const char *outfile)
3184 {
3185     return imagetoraw_common(image, outfile, OPJ_FALSE);
3186 }
3187
3188 #ifdef OPJ_HAVE_LIBPNG
3189
3190 #define PNG_MAGIC "\x89PNG\x0d\x0a\x1a\x0a"
3191 #define MAGIC_SIZE 8
3192 /* PNG allows bits per sample: 1, 2, 4, 8, 16 */
3193
3194 opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
3195 {
3196     png_structp  png;
3197     png_infop    info;
3198     double gamma, display_exponent;
3199     int bit_depth, interlace_type,compression_type, filter_type;
3200     int unit;
3201     png_uint_32 resx, resy;
3202     unsigned int i, j;
3203     png_uint_32  width, height;
3204     int color_type, has_alpha, is16;
3205     unsigned char *s;
3206     FILE *reader;
3207     unsigned char **rows;
3208     /* j2k: */
3209     opj_image_t *image;
3210     opj_image_cmptparm_t cmptparm[4];
3211     int sub_dx, sub_dy;
3212     unsigned int nr_comp;
3213     int *r, *g, *b, *a;
3214     unsigned char sigbuf[8];
3215
3216     if((reader = fopen(read_idf, "rb")) == NULL)
3217     {
3218         fprintf(stderr,"pngtoimage: can not open %s\n",read_idf);
3219         return NULL;
3220     }
3221     image = NULL; png = NULL; rows = NULL;
3222
3223     if(fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE
3224             || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0)
3225     {
3226         fprintf(stderr,"pngtoimage: %s is no valid PNG file\n",read_idf);
3227         goto fin;
3228     }
3229     /* libpng-VERSION/example.c:
3230  * PC : screen_gamma = 2.2;
3231  * Mac: screen_gamma = 1.7 or 1.0;
3232 */
3233     display_exponent = 2.2;
3234
3235     if((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,
3236                                      NULL, NULL, NULL)) == NULL)
3237         goto fin;
3238     if((info = png_create_info_struct(png)) == NULL)
3239         goto fin;
3240
3241     if(setjmp(png_jmpbuf(png)))
3242         goto fin;
3243
3244     png_init_io(png, reader);
3245     png_set_sig_bytes(png, MAGIC_SIZE);
3246
3247     png_read_info(png, info);
3248
3249     if(png_get_IHDR(png, info, &width, &height,
3250                     &bit_depth, &color_type, &interlace_type,
3251                     &compression_type, &filter_type) == 0)
3252         goto fin;
3253
3254     /* png_set_expand():
3255  * expand paletted images to RGB, expand grayscale images of
3256  * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
3257  * to alpha channels.
3258 */
3259     if(color_type == PNG_COLOR_TYPE_PALETTE)
3260         png_set_expand(png);
3261     else
3262         if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
3263             png_set_expand(png);
3264
3265     if(png_get_valid(png, info, PNG_INFO_tRNS))
3266         png_set_expand(png);
3267
3268     is16 = (bit_depth == 16);
3269
3270     /* GRAY => RGB; GRAY_ALPHA => RGBA
3271 */
3272     if(color_type == PNG_COLOR_TYPE_GRAY
3273             || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
3274     {
3275         png_set_gray_to_rgb(png);
3276         color_type =
3277                 (color_type == PNG_COLOR_TYPE_GRAY? PNG_COLOR_TYPE_RGB:
3278                                                     PNG_COLOR_TYPE_RGB_ALPHA);
3279     }
3280     if( !png_get_gAMA(png, info, &gamma))
3281         gamma = 0.45455;
3282
3283     png_set_gamma(png, display_exponent, gamma);
3284
3285     png_read_update_info(png, info);
3286
3287     png_get_pHYs(png, info, &resx, &resy, &unit);
3288
3289     color_type = png_get_color_type(png, info);
3290
3291     has_alpha = (color_type == PNG_COLOR_TYPE_RGB_ALPHA);
3292
3293     nr_comp = 3 + has_alpha;
3294
3295     bit_depth = png_get_bit_depth(png, info);
3296
3297     rows = (unsigned char**)calloc(height+1, sizeof(unsigned char*));
3298     for(i = 0; i < height; ++i)
3299         rows[i] = (unsigned char*)malloc(png_get_rowbytes(png,info));
3300
3301     png_read_image(png, rows);
3302
3303     memset(&cmptparm, 0, 4 * sizeof(opj_image_cmptparm_t));
3304
3305     sub_dx = params->subsampling_dx; sub_dy = params->subsampling_dy;
3306
3307     for(i = 0; i < nr_comp; ++i)
3308     {
3309         cmptparm[i].prec = bit_depth;
3310         /* bits_per_pixel: 8 or 16 */
3311         cmptparm[i].bpp = bit_depth;
3312         cmptparm[i].sgnd = 0;
3313         cmptparm[i].dx = sub_dx;
3314         cmptparm[i].dy = sub_dy;
3315         cmptparm[i].w = width;
3316         cmptparm[i].h = height;
3317     }
3318
3319     image = opj_image_create(nr_comp, &cmptparm[0], OPJ_CLRSPC_SRGB);
3320
3321     if(image == NULL) goto fin;
3322
3323     image->x0 = params->image_offset_x0;
3324     image->y0 = params->image_offset_y0;
3325     image->x1 = image->x0 + (width  - 1) * sub_dx + 1 + image->x0;
3326     image->y1 = image->y0 + (height - 1) * sub_dy + 1 + image->y0;
3327
3328     r = image->comps[0].data;
3329     g = image->comps[1].data;
3330     b = image->comps[2].data;
3331     a = image->comps[3].data;
3332
3333     for(i = 0; i < height; ++i)
3334     {
3335         s = rows[i];
3336
3337         for(j = 0; j < width; ++j)
3338         {
3339             if(is16)
3340             {
3341                 *r++ = s[0]<<8|s[1]; s += 2;
3342
3343                 *g++ = s[0]<<8|s[1]; s += 2;
3344
3345                 *b++ = s[0]<<8|s[1]; s += 2;
3346
3347                 if(has_alpha) { *a++ = s[0]<<8|s[1]; s += 2; }
3348
3349                 continue;
3350             }
3351             *r++ = *s++; *g++ = *s++; *b++ = *s++;
3352
3353             if(has_alpha) *a++ = *s++;
3354         }
3355     }
3356 fin:
3357     if(rows)
3358     {
3359         for(i = 0; i < height; ++i)
3360             free(rows[i]);
3361         free(rows);
3362     }
3363     if(png)
3364         png_destroy_read_struct(&png, &info, NULL);
3365
3366     fclose(reader);
3367
3368     return image;
3369
3370 }/* pngtoimage() */
3371
3372 int imagetopng(opj_image_t * image, const char *write_idf)
3373 {
3374     FILE *writer;
3375     png_structp png;
3376     png_infop info;
3377     int *red, *green, *blue, *alpha;
3378     unsigned char *row_buf, *d;
3379     int has_alpha, width, height, nr_comp, color_type;
3380     int adjustR, adjustG, adjustB, adjustA, x, y, fails;
3381     int prec, ushift, dshift, is16, force16, force8;
3382     unsigned short mask = 0xffff;
3383     png_color_8 sig_bit;
3384
3385     is16 = force16 = force8 = ushift = dshift = 0; fails = 1;
3386     prec = image->comps[0].prec;
3387     nr_comp = image->numcomps;
3388
3389     if(prec > 8 && prec < 16)
3390     {
3391         ushift = 16 - prec; dshift = prec - ushift;
3392         prec = 16; force16 = 1;
3393     }
3394     else
3395         if(prec < 8 && nr_comp > 1)/* GRAY_ALPHA, RGB, RGB_ALPHA */
3396         {
3397             ushift = 8 - prec; dshift = 8 - ushift;
3398             prec = 8; force8 = 1;
3399         }
3400
3401     if(prec != 1 && prec != 2 && prec != 4 && prec != 8 && prec != 16)
3402     {
3403         fprintf(stderr,"imagetopng: can not create %s"
3404                 "\n\twrong bit_depth %d\n", write_idf, prec);
3405         return fails;
3406     }
3407     writer = fopen(write_idf, "wb");
3408
3409     if(writer == NULL) return fails;
3410
3411     info = NULL; has_alpha = 0;
3412
3413     /* Create and initialize the png_struct with the desired error handler
3414  * functions.  If you want to use the default stderr and longjump method,
3415  * you can supply NULL for the last three parameters.  We also check that
3416  * the library version is compatible with the one used at compile time,
3417  * in case we are using dynamically linked libraries.  REQUIRED.
3418 */
3419     png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
3420                                   NULL, NULL, NULL);
3421     /*png_voidp user_error_ptr, user_error_fn, user_warning_fn); */
3422
3423     if(png == NULL) goto fin;
3424
3425     /* Allocate/initialize the image information data.  REQUIRED
3426 */
3427     info = png_create_info_struct(png);
3428
3429     if(info == NULL) goto fin;
3430
3431     /* Set error handling.  REQUIRED if you are not supplying your own
3432  * error handling functions in the png_create_write_struct() call.
3433 */
3434     if(setjmp(png_jmpbuf(png))) goto fin;
3435
3436     /* I/O initialization functions is REQUIRED
3437 */
3438     png_init_io(png, writer);
3439
3440     /* Set the image information here.  Width and height are up to 2^31,
3441  * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
3442  * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
3443  * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
3444  * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
3445  * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
3446  * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE.
3447  * REQUIRED
3448  *
3449  * ERRORS:
3450  *
3451  * color_type == PNG_COLOR_TYPE_PALETTE && bit_depth > 8
3452  * color_type == PNG_COLOR_TYPE_RGB && bit_depth < 8
3453  * color_type == PNG_COLOR_TYPE_GRAY_ALPHA && bit_depth < 8
3454  * color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8
3455  *
3456 */
3457     png_set_compression_level(png, Z_BEST_COMPRESSION);
3458
3459     if(prec == 16) mask = 0xffff;
3460     else
3461         if(prec == 8) mask = 0x00ff;
3462         else
3463             if(prec == 4) mask = 0x000f;
3464             else
3465                 if(prec == 2) mask = 0x0003;
3466                 else
3467                     if(prec == 1) mask = 0x0001;
3468
3469     if(nr_comp >= 3
3470             && image->comps[0].dx == image->comps[1].dx
3471             && image->comps[1].dx == image->comps[2].dx
3472             && image->comps[0].dy == image->comps[1].dy
3473             && image->comps[1].dy == image->comps[2].dy
3474             && image->comps[0].prec == image->comps[1].prec
3475             && image->comps[1].prec == image->comps[2].prec)
3476     {
3477         int v;
3478
3479         has_alpha = (nr_comp > 3);
3480
3481         is16 = (prec == 16);
3482
3483         width = image->comps[0].w;
3484         height = image->comps[0].h;
3485
3486         red = image->comps[0].data;
3487         green = image->comps[1].data;
3488         blue = image->comps[2].data;
3489
3490         sig_bit.red = sig_bit.green = sig_bit.blue = prec;
3491
3492         if(has_alpha)
3493         {
3494             sig_bit.alpha = prec;
3495             alpha = image->comps[3].data;
3496             color_type = PNG_COLOR_TYPE_RGB_ALPHA;
3497             adjustA = (image->comps[3].sgnd ? 1 << (image->comps[3].prec - 1) : 0);
3498         }
3499         else
3500         {
3501             sig_bit.alpha = 0; alpha = NULL;
3502             color_type = PNG_COLOR_TYPE_RGB;
3503             adjustA = 0;
3504         }
3505         png_set_sBIT(png, info, &sig_bit);
3506
3507         png_set_IHDR(png, info, width, height, prec,
3508                      color_type,
3509                      PNG_INTERLACE_NONE,
3510                      PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
3511
3512         png_set_gamma(png, 2.2, 1./2.2);
3513         png_set_sRGB(png, info, PNG_sRGB_INTENT_PERCEPTUAL);
3514         /*=============================*/
3515         png_write_info(png, info);
3516         /*=============================*/
3517         if(prec < 8)
3518         {
3519             png_set_packing(png);
3520         }
3521 printf("%s:%d:sgnd(%d,%d,%d) w(%d) h(%d) alpha(%d)\n",__FILE__,__LINE__,
3522 image->comps[0].sgnd,
3523 image->comps[1].sgnd,image->comps[2].sgnd,width,height,has_alpha);
3524
3525         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
3526         adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
3527         adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
3528
3529         row_buf = (unsigned char*)malloc(width * nr_comp * 2);
3530
3531         for(y = 0; y < height; ++y)
3532         {
3533             d = row_buf;
3534
3535             for(x = 0; x < width; ++x)
3536             {
3537                 if(is16)
3538                 {
3539                     v = *red + adjustR; ++red;
3540                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3541
3542                     if(force16) { v = (v<<ushift) + (v>>dshift); }
3543
3544                     *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3545
3546                     v = *green + adjustG; ++green;
3547                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3548
3549                     if(force16) { v = (v<<ushift) + (v>>dshift); }
3550
3551                     *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3552
3553                     v =  *blue + adjustB; ++blue;
3554                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3555
3556                     if(force16) { v = (v<<ushift) + (v>>dshift); }
3557
3558                     *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3559
3560                     if(has_alpha)
3561                     {
3562                         v = *alpha + adjustA; ++alpha;
3563                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3564
3565                         if(force16) { v = (v<<ushift) + (v>>dshift); }
3566
3567                         *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3568                     }
3569                     continue;
3570                 }/* if(is16) */
3571
3572                 v = *red + adjustR; ++red;
3573                 if(v > 255) v = 255; else if(v < 0) v = 0;
3574
3575                 if(force8) { v = (v<<ushift) + (v>>dshift); }
3576
3577                 *d++ = (unsigned char)(v & mask);
3578
3579                 v = *green + adjustG; ++green;
3580                 if(v > 255) v = 255; else if(v < 0) v = 0;
3581
3582                 if(force8) { v = (v<<ushift) + (v>>dshift); }
3583
3584                 *d++ = (unsigned char)(v & mask);
3585
3586                 v = *blue + adjustB; ++blue;
3587                 if(v > 255) v = 255; else if(v < 0) v = 0;
3588
3589                 if(force8) { v = (v<<ushift) + (v>>dshift); }
3590
3591                 *d++ = (unsigned char)(v & mask);
3592
3593                 if(has_alpha)
3594                 {
3595                     v = *alpha + adjustA; ++alpha;
3596                 if(v > 255) v = 255; else if(v < 0) v = 0;
3597
3598                     if(force8) { v = (v<<ushift) + (v>>dshift); }
3599
3600                     *d++ = (unsigned char)(v & mask);
3601                 }
3602             }   /* for(x) */
3603
3604             png_write_row(png, row_buf);
3605
3606         }       /* for(y) */
3607         free(row_buf);
3608
3609     }/* nr_comp >= 3 */
3610     else
3611         if(nr_comp == 1 /* GRAY */
3612                 || (   nr_comp == 2 /* GRAY_ALPHA */
3613                        && image->comps[0].dx == image->comps[1].dx
3614                        && image->comps[0].dy == image->comps[1].dy
3615                        && image->comps[0].prec == image->comps[1].prec))
3616         {
3617             int v;
3618
3619             red = image->comps[0].data;
3620
3621             sig_bit.gray = prec;
3622             sig_bit.red = sig_bit.green = sig_bit.blue = sig_bit.alpha = 0;
3623             alpha = NULL; adjustA = 0;
3624             color_type = PNG_COLOR_TYPE_GRAY;
3625
3626             if(nr_comp == 2)
3627             {
3628                 has_alpha = 1; sig_bit.alpha = prec;
3629                 alpha = image->comps[1].data;
3630                 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
3631                 adjustA = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
3632             }
3633             width = image->comps[0].w;
3634             height = image->comps[0].h;
3635
3636             png_set_IHDR(png, info, width, height, sig_bit.gray,
3637                          color_type,
3638                          PNG_INTERLACE_NONE,
3639                          PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
3640
3641             png_set_sBIT(png, info, &sig_bit);
3642
3643             png_set_gamma(png, 2.2, 1./2.2);
3644             png_set_sRGB(png, info, PNG_sRGB_INTENT_PERCEPTUAL);
3645             /*=============================*/
3646             png_write_info(png, info);
3647             /*=============================*/
3648             adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
3649
3650             if(prec < 8)
3651             {
3652                 png_set_packing(png);
3653             }
3654
3655             if(prec > 8)
3656             {
3657                 row_buf = (unsigned char*)
3658                         malloc(width * nr_comp * sizeof(unsigned short));
3659
3660                 for(y = 0; y < height; ++y)
3661                 {
3662                     d = row_buf;
3663
3664                     for(x = 0; x < width; ++x)
3665                     {
3666                         v = *red + adjustR; ++red;
3667                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3668
3669                         if(force16) { v = (v<<ushift) + (v>>dshift); }
3670
3671                         *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3672
3673                         if(has_alpha)
3674                         {
3675                             v = *alpha++;
3676                 if(v > 65535) v = 65535; else if(v < 0) v = 0;
3677
3678                             if(force16) { v = (v<<ushift) + (v>>dshift); }
3679
3680                             *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
3681                         }
3682                     }/* for(x) */
3683                     png_write_row(png, row_buf);
3684
3685                 }       /* for(y) */
3686                 free(row_buf);
3687             }
3688             else /* prec <= 8 */
3689             {
3690                 row_buf = (unsigned char*)calloc(width, nr_comp * 2);
3691
3692                 for(y = 0; y < height; ++y)
3693                 {
3694                     d = row_buf;
3695
3696                     for(x = 0; x < width; ++x)
3697                     {
3698                         v = *red + adjustR; ++red;
3699                 if(v > 255) v = 255; else if(v < 0) v = 0;
3700
3701                         if(force8) { v = (v<<ushift) + (v>>dshift); }
3702
3703                         *d++ = (unsigned char)(v & mask);
3704
3705                         if(has_alpha)
3706                         {
3707                             v = *alpha + adjustA; ++alpha;
3708                 if(v > 255) v = 255; else if(v < 0) v = 0;
3709
3710                             if(force8) { v = (v<<ushift) + (v>>dshift); }
3711
3712                             *d++ = (unsigned char)(v & mask);
3713                         }
3714                     }/* for(x) */
3715
3716                     png_write_row(png, row_buf);
3717
3718                 }       /* for(y) */
3719                 free(row_buf);
3720             }
3721         }
3722         else
3723         {
3724             fprintf(stderr,"imagetopng: can not create %s\n",write_idf);
3725             goto fin;
3726         }
3727     png_write_end(png, info);
3728
3729     fails = 0;
3730
3731 fin:
3732
3733     if(png)
3734     {
3735         png_destroy_write_struct(&png, &info);
3736     }
3737     fclose(writer);
3738
3739     if(fails) remove(write_idf);
3740
3741     return fails;
3742 }/* imagetopng() */
3743 #endif /* OPJ_HAVE_LIBPNG */