136cc9c10ffc2b93e6cbb4f4547537975e599a9e
[openjpeg.git] / src / bin / jp2 / opj_decompress.c
1 /*
2  * The copyright in this software is being made available under the 2-clauses 
3  * BSD License, included below. This software may be subject to other third 
4  * party and contributor rights, including patent rights, and no such rights
5  * are granted under this license.
6  *
7  * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
8  * Copyright (c) 2002-2014, Professor Benoit Macq
9  * Copyright (c) 2001-2003, David Janssens
10  * Copyright (c) 2002-2003, Yannick Verschueren
11  * Copyright (c) 2003-2007, Francois-Olivier Devaux 
12  * Copyright (c) 2003-2014, Antonin Descampe
13  * Copyright (c) 2005, Herve Drolon, FreeImage Team
14  * Copyright (c) 2006-2007, Parvatha Elangovan
15  * Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR 
16  * Copyright (c) 2012, CS Systemes d'Information, France
17  * All rights reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
29  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
32  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGE.
39  */
40 #include "opj_apps_config.h"
41
42 #include <stdio.h>
43 #include <string.h>
44 #include <stdlib.h>
45 #include <math.h>
46
47 #ifdef _WIN32
48 #include "windirent.h"
49 #else
50 #include <dirent.h>
51 #endif /* _WIN32 */
52
53 #ifdef _WIN32
54 #include <windows.h>
55 #define strcasecmp _stricmp
56 #define strncasecmp _strnicmp
57 #else
58 #include <strings.h>
59 #endif /* _WIN32 */
60
61 #include "openjpeg.h"
62 #include "opj_getopt.h"
63 #include "convert.h"
64 #include "index.h"
65
66 #ifdef OPJ_HAVE_LIBLCMS2
67 #include <lcms2.h>
68 #endif
69 #ifdef OPJ_HAVE_LIBLCMS1
70 #include <lcms.h>
71 #endif
72 #include "color.h"
73
74 #include "format_defs.h"
75
76 typedef struct dircnt{
77         /** Buffer for holding images read from Directory*/
78         char *filename_buf;
79         /** Pointer to the buffer*/
80         char **filename;
81 }dircnt_t;
82
83
84 typedef struct img_folder{
85         /** The directory path of the folder containing input images*/
86         char *imgdirpath;
87         /** Output format*/
88         const char *out_format;
89         /** Enable option*/
90         char set_imgdir;
91         /** Enable Cod Format for output*/
92         char set_out_format;
93
94 }img_fol_t;
95
96 typedef enum opj_prec_mode
97 {
98         OPJ_PREC_MODE_CLIP,
99         OPJ_PREC_MODE_SCALE
100 } opj_precision_mode;
101
102 typedef struct opj_prec
103 {
104         OPJ_UINT32         prec;
105         opj_precision_mode mode;
106 }opj_precision;
107
108 typedef struct opj_decompress_params
109 {
110         /** core library parameters */
111         opj_dparameters_t core;
112         
113         /** input file name */
114         char infile[OPJ_PATH_LEN];
115         /** output file name */
116         char outfile[OPJ_PATH_LEN];
117         /** input file format 0: J2K, 1: JP2, 2: JPT */
118         int decod_format;
119         /** output file format 0: PGX, 1: PxM, 2: BMP */
120         int cod_format;
121         
122         /** Decoding area left boundary */
123         OPJ_UINT32 DA_x0;
124         /** Decoding area right boundary */
125         OPJ_UINT32 DA_x1;
126         /** Decoding area up boundary */
127         OPJ_UINT32 DA_y0;
128         /** Decoding area bottom boundary */
129         OPJ_UINT32 DA_y1;
130         /** Verbose mode */
131         OPJ_BOOL m_verbose;
132         
133         /** tile number ot the decoded tile*/
134         OPJ_UINT32 tile_index;
135         /** Nb of tile to decode */
136         OPJ_UINT32 nb_tile_to_decode;
137         
138         opj_precision* precision;
139         OPJ_UINT32     nb_precision;
140         
141         /* force output colorspace to RGB */
142         int force_rgb;
143         /* upsample components according to their dx/dy values */
144         int upsample;
145 }opj_decompress_parameters;
146
147 /* -------------------------------------------------------------------------- */
148 /* Declarations                                                               */
149 int get_num_images(char *imgdirpath);
150 int load_images(dircnt_t *dirptr, char *imgdirpath);
151 int get_file_format(const char *filename);
152 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_decompress_parameters *parameters);
153 static int infile_format(const char *fname);
154
155 int parse_cmdline_decoder(int argc, char **argv, opj_decompress_parameters *parameters,img_fol_t *img_fol, char *indexfilename);
156 int parse_DA_values( char* inArg, unsigned int *DA_x0, unsigned int *DA_y0, unsigned int *DA_x1, unsigned int *DA_y1);
157
158 static opj_image_t* convert_gray_to_rgb(opj_image_t* original);
159
160 /* -------------------------------------------------------------------------- */
161 static void decode_help_display(void) {
162         fprintf(stdout,"\nThis is the opj_decompress utility from the OpenJPEG project.\n"
163                        "It decompresses JPEG 2000 codestreams to various image formats.\n"
164                        "It has been compiled against openjp2 library v%s.\n\n",opj_version());
165
166         fprintf(stdout,"Parameters:\n"
167                        "-----------\n"
168                        "\n"
169                        "  -ImgDir <directory> \n"
170                        "        Image file Directory path \n"
171                        "  -OutFor <PBM|PGM|PPM|PNM|PAM|PGX|PNG|BMP|TIF|RAW|RAWL|TGA>\n"
172                        "    REQUIRED only if -ImgDir is used\n"
173                        "        Output format for decompressed images.\n"
174                        "  -i <compressed file>\n"
175                        "    REQUIRED only if an Input image directory is not specified\n"
176                        "    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n"
177                        "    is identified based on its suffix.\n"
178                        "  -o <decompressed file>\n"
179                        "    REQUIRED\n"
180                        "    Currently accepts formats specified above (see OutFor option)\n"
181                        "    Binary data is written to the file (not ascii). If a PGX\n"
182                        "    filename is given, there will be as many output files as there are\n"
183                        "    components: an indice starting from 0 will then be appended to the\n"
184                        "    output filename, just before the \"pgx\" extension. If a PGM filename\n"
185                        "    is given and there are more than one component, only the first component\n"
186                        "    will be written to the file.\n"
187                        "  -r <reduce factor>\n"
188                        "    Set the number of highest resolution levels to be discarded. The\n"
189                        "    image resolution is effectively divided by 2 to the power of the\n"
190                        "    number of discarded levels. The reduce factor is limited by the\n"
191                        "    smallest total number of decomposition levels among tiles.\n"
192                        "  -l <number of quality layers to decode>\n"
193                        "    Set the maximum number of quality layers to decode. If there are\n"
194                        "    less quality layers than the specified number, all the quality layers\n"
195                        "    are decoded.\n"
196                        "  -x  \n" 
197                        "    Create an index file *.Idx (-x index_name.Idx) \n"
198                        "  -d <x0,y0,x1,y1>\n"
199                        "    OPTIONAL\n"
200                        "    Decoding area\n"
201                        "    By default all the image is decoded.\n"
202                        "  -t <tile_number>\n"
203                        "    OPTIONAL\n"
204                        "    Set the tile number of the decoded tile. Follow the JPEG2000 convention from left-up to bottom-up\n"
205                        "    By default all tiles are decoded.\n"
206                        "  -p <comp 0 precision>[C|S][,<comp 1 precision>[C|S][,...]]\n"
207                        "    OPTIONAL\n"
208                        "    Force the precision (bit depth) of components.\n"
209                        "    There shall be at least 1 value. Theres no limit on the number of values (comma separated, last values ignored if too much values).\n"
210                        "    If there are less values than components, the last value is used for remaining components.\n"
211                        "    If 'C' is specified (default), values are clipped.\n"
212                        "    If 'S' is specified, values are scaled.\n"
213                        "    A 0 value can be specified (meaning original bit depth).\n"
214                        "  -force-rgb\n"
215                        "    Force output image colorspace to RGB\n"
216                        "  -upsample\n"
217                        "    Downsampled components will be upsampled to image size\n"
218                        "\n");
219 /* UniPG>> */
220 #ifdef USE_JPWL
221         fprintf(stdout,"  -W <options>\n"
222                        "    Activates the JPWL correction capability, if the codestream complies.\n"
223                        "    Options can be a comma separated list of <param=val> tokens:\n"
224                        "    c, c=numcomps\n"
225                        "       numcomps is the number of expected components in the codestream\n"
226                        "       (search of first EPB rely upon this, default is %d)\n", JPWL_EXPECTED_COMPONENTS);
227 #endif /* USE_JPWL */
228 /* <<UniPG */
229         fprintf(stdout,"\n");
230 }
231
232 /* -------------------------------------------------------------------------- */
233
234 static OPJ_BOOL parse_precision(const char* option, opj_decompress_parameters* parameters)
235 {
236         const char* l_remaining = option;
237         OPJ_BOOL l_result = OPJ_TRUE;
238         
239         /* reset */
240         if (parameters->precision) {
241                 free(parameters->precision);
242                 parameters->precision = NULL;
243         }
244         parameters->nb_precision = 0U;
245         
246         for(;;)
247         {
248                 OPJ_UINT32 prec;
249                 char mode;
250                 char comma;
251                 int count;
252                 
253                 count = sscanf(l_remaining, "%d%c%c", &prec, &mode, &comma);
254                 if (count == 1) {
255                         mode = 'C';
256                         count++;
257                 }
258                 if ((count == 2) || (mode==',')) {
259                         if (mode==',') {
260                                 mode = 'C';
261                         }
262                         comma=',';
263                         count = 3;
264                 }
265                 if (count == 3) {
266                         if (prec > 32U) {
267                                 fprintf(stderr,"Invalid precision %d in precision option %s\n", prec, option);
268                                 l_result = OPJ_FALSE;
269                                 break;
270                         }
271                         if ((mode != 'C') && (mode != 'S')) {
272                                 fprintf(stderr,"Invalid precision mode %c in precision option %s\n", mode, option);
273                                 l_result = OPJ_FALSE;
274                                 break;
275                         }
276                         if (comma != ',') {
277                                 fprintf(stderr,"Invalid character %c in precision option %s\n", comma, option);
278                                 l_result = OPJ_FALSE;
279                                 break;
280                         }
281                         
282                         if (parameters->precision == NULL) {
283                                 /* first one */
284                                 parameters->precision = malloc(sizeof(opj_precision));
285                                 if (parameters->precision == NULL) {
286                                         fprintf(stderr,"Could not allocate memory for precision option\n");
287                                         l_result = OPJ_FALSE;
288                                         break;
289                                 }
290                         } else {
291                                 OPJ_UINT32 l_new_size = parameters->nb_precision + 1U;
292                                 opj_precision* l_new;
293                                 
294                                 if (l_new_size == 0U) {
295                                         fprintf(stderr,"Could not allocate memory for precision option\n");
296                                         l_result = OPJ_FALSE;
297                                         break;
298                                 }
299                                 
300                                 l_new = realloc(parameters->precision, l_new_size * sizeof(opj_precision));
301                                 if (l_new == NULL) {
302                                         fprintf(stderr,"Could not allocate memory for precision option\n");
303                                         l_result = OPJ_FALSE;
304                                         break;
305                                 }
306                                 parameters->precision = l_new;
307                         }
308                         
309                         parameters->precision[parameters->nb_precision].prec = prec;
310                         switch (mode) {
311                                 case 'C':
312                                         parameters->precision[parameters->nb_precision].mode = OPJ_PREC_MODE_CLIP;
313                                         break;
314                                 case 'S':
315                                         parameters->precision[parameters->nb_precision].mode = OPJ_PREC_MODE_SCALE;
316                                         break;
317                                 default:
318                                         break;
319                         }
320                         parameters->nb_precision++;
321                         
322                         l_remaining = strchr(l_remaining, ',');
323                         if (l_remaining == NULL) {
324                                 break;
325                         }
326                         l_remaining += 1;
327                 } else {
328                         fprintf(stderr,"Could not parse precision option %s\n", option);
329                         l_result = OPJ_FALSE;
330                         break;
331                 }
332         }
333         
334         return l_result;
335 }
336
337 /* -------------------------------------------------------------------------- */
338
339 int get_num_images(char *imgdirpath){
340         DIR *dir;
341         struct dirent* content; 
342         int num_images = 0;
343
344         /*Reading the input images from given input directory*/
345
346         dir= opendir(imgdirpath);
347         if(!dir){
348                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
349                 return 0;
350         }
351         
352         while((content=readdir(dir))!=NULL){
353                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
354                         continue;
355                 num_images++;
356         }
357         return num_images;
358 }
359
360 /* -------------------------------------------------------------------------- */
361 int load_images(dircnt_t *dirptr, char *imgdirpath){
362         DIR *dir;
363         struct dirent* content; 
364         int i = 0;
365
366         /*Reading the input images from given input directory*/
367
368         dir= opendir(imgdirpath);
369         if(!dir){
370                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
371                 return 1;
372         }else   {
373                 fprintf(stderr,"Folder opened successfully\n");
374         }
375         
376         while((content=readdir(dir))!=NULL){
377                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
378                         continue;
379
380                 strcpy(dirptr->filename[i],content->d_name);
381                 i++;
382         }
383         return 0;       
384 }
385
386 /* -------------------------------------------------------------------------- */
387 int get_file_format(const char *filename) {
388         unsigned int i;
389         static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "rawl", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc" };
390         static const int format[] = { PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, RAWL_DFMT, TGA_DFMT, PNG_DFMT, J2K_CFMT, JP2_CFMT, JPT_CFMT, J2K_CFMT, J2K_CFMT };
391         char * ext = strrchr(filename, '.');
392         if (ext == NULL)
393                 return -1;
394         ext++;
395         if(*ext) {
396                 for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
397                         if(strcasecmp(ext, extension[i]) == 0) {
398                                 return format[i];
399                         }
400                 }
401         }
402
403         return -1;
404 }
405
406 #ifdef _WIN32
407 const char* path_separator = "\\";
408 #else
409 const char* path_separator = "/";
410 #endif
411
412 /* -------------------------------------------------------------------------- */
413 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_decompress_parameters *parameters){
414         char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
415         char *temp_p, temp1[OPJ_PATH_LEN]="";
416
417         strcpy(image_filename,dirptr->filename[imageno]);
418         fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
419         sprintf(infilename, "%s%s%s", img_fol->imgdirpath, path_separator, image_filename);
420         parameters->decod_format = infile_format(infilename);
421         if (parameters->decod_format == -1)
422                 return 1;
423         strncpy(parameters->infile, infilename, sizeof(infilename));
424
425         /*Set output file*/
426         strcpy(temp_ofname,strtok(image_filename,"."));
427         while((temp_p = strtok(NULL,".")) != NULL){
428                 strcat(temp_ofname,temp1);
429                 sprintf(temp1,".%s",temp_p);
430         }
431         if(img_fol->set_out_format==1){
432                 sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
433                 strncpy(parameters->outfile, outfilename, sizeof(outfilename));
434         }
435         return 0;
436 }
437
438 /* -------------------------------------------------------------------------- */
439 #define JP2_RFC3745_MAGIC "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a"
440 #define JP2_MAGIC "\x0d\x0a\x87\x0a"
441 /* position 45: "\xff\x52" */
442 #define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51"
443
444 static int infile_format(const char *fname)
445 {
446         FILE *reader;
447         const char *s, *magic_s;
448         int ext_format, magic_format;
449         unsigned char buf[12];
450         OPJ_SIZE_T l_nb_read;
451
452         reader = fopen(fname, "rb");
453
454         if (reader == NULL)
455                 return -2;
456
457         memset(buf, 0, 12);
458         l_nb_read = fread(buf, 1, 12, reader);
459         fclose(reader);
460         if (l_nb_read != 12)
461                 return -1;
462
463
464
465         ext_format = get_file_format(fname);
466
467         if (ext_format == JPT_CFMT)
468                 return JPT_CFMT;
469
470         if (memcmp(buf, JP2_RFC3745_MAGIC, 12) == 0 || memcmp(buf, JP2_MAGIC, 4) == 0) {
471                 magic_format = JP2_CFMT;
472                 magic_s = ".jp2";
473         }
474         else if (memcmp(buf, J2K_CODESTREAM_MAGIC, 4) == 0) {
475                 magic_format = J2K_CFMT;
476                 magic_s = ".j2k or .jpc or .j2c";
477         }
478         else
479                 return -1;
480
481         if (magic_format == ext_format)
482                 return ext_format;
483
484         s = fname + strlen(fname) - 4;
485
486         fputs("\n===========================================\n", stderr);
487         fprintf(stderr, "The extension of this file is incorrect.\n"
488                                         "FOUND %s. SHOULD BE %s\n", s, magic_s);
489         fputs("===========================================\n", stderr);
490
491         return magic_format;
492 }
493
494 /* -------------------------------------------------------------------------- */
495 /**
496  * Parse the command line
497  */
498 /* -------------------------------------------------------------------------- */
499 int parse_cmdline_decoder(int argc, char **argv, opj_decompress_parameters *parameters,img_fol_t *img_fol, char *indexfilename) {
500         /* parse the command line */
501         int totlen, c;
502         opj_option_t long_option[]={
503                 {"ImgDir",    REQ_ARG, NULL ,'y'},
504                 {"OutFor",    REQ_ARG, NULL ,'O'},
505                 {"force-rgb", NO_ARG,  &(parameters->force_rgb), 1},
506                 {"upsample",  NO_ARG,  &(parameters->upsample),  1}
507         };
508
509         const char optlist[] = "i:o:r:l:x:d:t:p:"
510
511 /* UniPG>> */
512 #ifdef USE_JPWL
513                                         "W:"
514 #endif /* USE_JPWL */
515 /* <<UniPG */
516             "h"         ;
517         totlen=sizeof(long_option);
518         opj_reset_options_reading();
519         img_fol->set_out_format = 0;
520         do {
521                 c = opj_getopt_long(argc, argv,optlist,long_option,totlen);
522                 if (c == -1)
523                         break;
524                 switch (c) {
525                         case 0: /* long opt with flag */
526                                 break;
527                         case 'i':                       /* input file */
528                         {
529                                 char *infile = opj_optarg;
530                                 parameters->decod_format = infile_format(infile);
531                                 switch(parameters->decod_format) {
532                                         case J2K_CFMT:
533                                                 break;
534                                         case JP2_CFMT:
535                                                 break;
536                                         case JPT_CFMT:
537                                                 break;
538                                         case -2:
539                                                 fprintf(stderr, 
540                                                         "!! infile cannot be read: %s !!\n\n", 
541                                                         infile);
542                                                 return 1;
543                                         default:
544                                                 fprintf(stderr, 
545                             "[ERROR] Unknown input file format: %s \n"
546                             "        Known file formats are *.j2k, *.jp2, *.jpc or *.jpt\n",
547                                                         infile);
548                                                 return 1;
549                                 }
550                                 strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
551                         }
552                         break;
553                                 
554                                 /* ----------------------------------------------------- */
555
556                         case 'o':                       /* output file */
557                         {
558                                 char *outfile = opj_optarg;
559                                 parameters->cod_format = get_file_format(outfile);
560                                 switch(parameters->cod_format) {
561                                         case PGX_DFMT:
562                                                 break;
563                                         case PXM_DFMT:
564                                                 break;
565                                         case BMP_DFMT:
566                                                 break;
567                                         case TIF_DFMT:
568                                                 break;
569                                         case RAW_DFMT:
570                                                 break;
571                                         case RAWL_DFMT:
572                                                 break;
573                                         case TGA_DFMT:
574                                                 break;
575                                         case PNG_DFMT:
576                                                 break;
577                                         default:
578                                                 fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outfile);
579                                                 return 1;
580                                 }
581                                 strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);
582                         }
583                         break;
584                         
585                                 /* ----------------------------------------------------- */
586
587                         case 'O':                       /* output format */
588                         {
589                                 char outformat[50];
590                                 char *of = opj_optarg;
591                                 sprintf(outformat,".%s",of);
592                                 img_fol->set_out_format = 1;
593                                 parameters->cod_format = get_file_format(outformat);
594                                 switch(parameters->cod_format) {
595                                         case PGX_DFMT:
596                                                 img_fol->out_format = "pgx";
597                                                 break;
598                                         case PXM_DFMT:
599                                                 img_fol->out_format = "ppm";
600                                                 break;
601                                         case BMP_DFMT:
602                                                 img_fol->out_format = "bmp";
603                                                 break;
604                                         case TIF_DFMT:
605                                                 img_fol->out_format = "tif";
606                                                 break;
607                                         case RAW_DFMT:
608                                                 img_fol->out_format = "raw";
609                                                 break;
610                                         case RAWL_DFMT:
611                                                 img_fol->out_format = "rawl";
612                                                 break;
613                                         case TGA_DFMT:
614                                                 img_fol->out_format = "raw";
615                                                 break;
616                                         case PNG_DFMT:
617                                                 img_fol->out_format = "png";
618                                                 break;
619                                         default:
620                                                 fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outformat);
621                                                 return 1;
622                                                 break;
623                                 }
624                         }
625                         break;
626
627                                 /* ----------------------------------------------------- */
628
629
630                         case 'r':               /* reduce option */
631                         {
632                                 sscanf(opj_optarg, "%u", &(parameters->core.cp_reduce));
633                         }
634                         break;
635                         
636                                 /* ----------------------------------------------------- */
637       
638
639                         case 'l':               /* layering option */
640                         {
641                                 sscanf(opj_optarg, "%u", &(parameters->core.cp_layer));
642                         }
643                         break;
644                         
645                                 /* ----------------------------------------------------- */
646
647                         case 'h':                       /* display an help description */
648                                 decode_help_display();
649                                 return 1;                               
650
651             /* ----------------------------------------------------- */
652
653                         case 'y':                       /* Image Directory path */
654                 {
655                                         img_fol->imgdirpath = (char*)malloc(strlen(opj_optarg) + 1);
656                                         strcpy(img_fol->imgdirpath,opj_optarg);
657                                         img_fol->set_imgdir=1;
658                                 }
659                                 break;
660
661                                 /* ----------------------------------------------------- */
662
663                         case 'd':               /* Input decode ROI */
664                         {
665                                 int size_optarg = (int)strlen(opj_optarg) + 1;
666                                 char *ROI_values = (char*) malloc((size_t)size_optarg);
667                                 ROI_values[0] = '\0';
668                                 strncpy(ROI_values, opj_optarg, strlen(opj_optarg));
669                                 ROI_values[strlen(opj_optarg)] = '\0';
670                                 /*printf("ROI_values = %s [%d / %d]\n", ROI_values, strlen(ROI_values), size_optarg ); */
671                                 parse_DA_values( ROI_values, &parameters->DA_x0, &parameters->DA_y0, &parameters->DA_x1, &parameters->DA_y1);
672
673                                 free(ROI_values);
674                         }
675                         break;
676
677                         /* ----------------------------------------------------- */
678
679                         case 't':               /* Input tile index */
680                         {
681                                 sscanf(opj_optarg, "%u", &parameters->tile_index);
682                                 parameters->nb_tile_to_decode = 1;
683                         }
684                         break;
685
686                                 /* ----------------------------------------------------- */                                                             
687
688                         case 'x':                       /* Creation of index file */
689                                 {
690                                         char *index = opj_optarg;
691                                         strncpy(indexfilename, index, OPJ_PATH_LEN);
692                                 }
693                                 break;
694                                 
695                                 /* ----------------------------------------------------- */
696                         case 'p': /* Force precision */
697                                 {
698                                         if (!parse_precision(opj_optarg, parameters))
699                                         {
700                                                 return 1;
701                                         }
702                                 }
703                                 break;
704                                 /* ----------------------------------------------------- */
705                                 
706                                 /* UniPG>> */
707 #ifdef USE_JPWL
708                         
709                         case 'W':                       /* activate JPWL correction */
710                         {
711                                 char *token = NULL;
712
713                                 token = strtok(opj_optarg, ",");
714                                 while(token != NULL) {
715
716                                         /* search expected number of components */
717                                         if (*token == 'c') {
718
719                                                 static int compno;
720
721                                                 compno = JPWL_EXPECTED_COMPONENTS; /* predefined no. of components */
722
723                                                 if(sscanf(token, "c=%d", &compno) == 1) {
724                                                         /* Specified */
725                                                         if ((compno < 1) || (compno > 256)) {
726                                                                 fprintf(stderr, "ERROR -> invalid number of components c = %d\n", compno);
727                                                                 return 1;
728                                                         }
729                                                         parameters->jpwl_exp_comps = compno;
730
731                                                 } else if (!strcmp(token, "c")) {
732                                                         /* default */
733                                                         parameters->jpwl_exp_comps = compno; /* auto for default size */
734
735                                                 } else {
736                                                         fprintf(stderr, "ERROR -> invalid components specified = %s\n", token);
737                                                         return 1;
738                                                 };
739                                         }
740
741                                         /* search maximum number of tiles */
742                                         if (*token == 't') {
743
744                                                 static int tileno;
745
746                                                 tileno = JPWL_MAXIMUM_TILES; /* maximum no. of tiles */
747
748                                                 if(sscanf(token, "t=%d", &tileno) == 1) {
749                                                         /* Specified */
750                                                         if ((tileno < 1) || (tileno > JPWL_MAXIMUM_TILES)) {
751                                                                 fprintf(stderr, "ERROR -> invalid number of tiles t = %d\n", tileno);
752                                                                 return 1;
753                                                         }
754                                                         parameters->jpwl_max_tiles = tileno;
755
756                                                 } else if (!strcmp(token, "t")) {
757                                                         /* default */
758                                                         parameters->jpwl_max_tiles = tileno; /* auto for default size */
759
760                                                 } else {
761                                                         fprintf(stderr, "ERROR -> invalid tiles specified = %s\n", token);
762                                                         return 1;
763                                                 };
764                                         }
765
766                                         /* next token or bust */
767                                         token = strtok(NULL, ",");
768                                 };
769                                 parameters->jpwl_correct = OPJ_TRUE;
770                                 fprintf(stdout, "JPWL correction capability activated\n");
771                                 fprintf(stdout, "- expecting %d components\n", parameters->jpwl_exp_comps);
772                         }
773                         break;  
774 #endif /* USE_JPWL */
775 /* <<UniPG */            
776
777                                 /* ----------------------------------------------------- */
778                         
779         default:
780             fprintf(stderr, "[WARNING] An invalid option has been ignored.\n");
781             break;
782                 }
783         }while(c != -1);
784
785         /* check for possible errors */
786         if(img_fol->set_imgdir==1){
787                 if(!(parameters->infile[0]==0)){
788             fprintf(stderr, "[ERROR] options -ImgDir and -i cannot be used together.\n");
789                         return 1;
790                 }
791                 if(img_fol->set_out_format == 0){
792             fprintf(stderr, "[ERROR] When -ImgDir is used, -OutFor <FORMAT> must be used.\n");
793             fprintf(stderr, "Only one format allowed.\n"
794                             "Valid format are PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA.\n");
795                         return 1;
796                 }
797                 if(!((parameters->outfile[0] == 0))){
798             fprintf(stderr, "[ERROR] options -ImgDir and -o cannot be used together.\n");
799                         return 1;
800                 }
801         }else{
802                 if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
803             fprintf(stderr, "[ERROR] Required parameters are missing\n"
804                             "Example: %s -i image.j2k -o image.pgm\n",argv[0]);
805             fprintf(stderr, "   Help: %s -h\n",argv[0]);
806                         return 1;
807                 }
808         }
809
810         return 0;
811 }
812
813 /* -------------------------------------------------------------------------- */
814 /**
815  * Parse decoding area input values
816  * separator = ","
817  */
818 /* -------------------------------------------------------------------------- */
819 int parse_DA_values( char* inArg, unsigned int *DA_x0, unsigned int *DA_y0, unsigned int *DA_x1, unsigned int *DA_y1)
820 {
821         int it = 0;
822         int values[4];
823         char delims[] = ",";
824         char *result = NULL;
825         result = strtok( inArg, delims );
826
827         while( (result != NULL) && (it < 4 ) ) {
828                 values[it] = atoi(result);
829                 result = strtok( NULL, delims );
830                 it++;
831         }
832
833         if (it != 4) {
834                 return EXIT_FAILURE;
835         }
836         else{
837                 *DA_x0 = (OPJ_UINT32)values[0]; *DA_y0 = (OPJ_UINT32)values[1];
838                 *DA_x1 = (OPJ_UINT32)values[2]; *DA_y1 = (OPJ_UINT32)values[3];
839                 return EXIT_SUCCESS;
840         }
841 }
842
843 /* -------------------------------------------------------------------------- */
844
845 /**
846 sample error callback expecting a FILE* client object
847 */
848 static void error_callback(const char *msg, void *client_data) {
849         (void)client_data;
850         fprintf(stdout, "[ERROR] %s", msg);
851 }
852 /**
853 sample warning callback expecting a FILE* client object
854 */
855 static void warning_callback(const char *msg, void *client_data) {
856         (void)client_data;
857         fprintf(stdout, "[WARNING] %s", msg);
858 }
859 /**
860 sample debug callback expecting no client object
861 */
862 static void info_callback(const char *msg, void *client_data) {
863         (void)client_data;
864         fprintf(stdout, "[INFO] %s", msg);
865 }
866
867 static void set_default_parameters(opj_decompress_parameters* parameters)
868 {
869         if (parameters) {
870                 memset(parameters, 0, sizeof(opj_decompress_parameters));
871                 
872                 /* default decoding parameters (command line specific) */
873                 parameters->decod_format = -1;
874                 parameters->cod_format = -1;
875                 
876                 /* default decoding parameters (core) */
877                 opj_set_default_decoder_parameters(&(parameters->core));
878         }
879 }
880
881 static void destroy_parameters(opj_decompress_parameters* parameters)
882 {
883         if (parameters) {
884                 if (parameters->precision) {
885                         free(parameters->precision);
886                         parameters->precision = NULL;
887                 }
888         }
889 }
890
891 /* -------------------------------------------------------------------------- */
892
893 static opj_image_t* convert_gray_to_rgb(opj_image_t* original)
894 {
895         OPJ_UINT32 compno;
896         opj_image_t* l_new_image = NULL;
897         opj_image_cmptparm_t* l_new_components = NULL;
898         
899         l_new_components = (opj_image_cmptparm_t*)malloc((original->numcomps + 2U) * sizeof(opj_image_cmptparm_t));
900         if (l_new_components == NULL) {
901                 fprintf(stderr, "ERROR -> opj_decompress: failed to allocate memory for RGB image!\n");
902                 opj_image_destroy(original);
903                 return NULL;
904         }
905         
906         l_new_components[0].bpp  = l_new_components[1].bpp  = l_new_components[2].bpp  = original->comps[0].bpp;
907         l_new_components[0].dx   = l_new_components[1].dx   = l_new_components[2].dx   = original->comps[0].dx;
908         l_new_components[0].dy   = l_new_components[1].dy   = l_new_components[2].dy   = original->comps[0].dy;
909         l_new_components[0].h    = l_new_components[1].h    = l_new_components[2].h    = original->comps[0].h;
910         l_new_components[0].w    = l_new_components[1].w    = l_new_components[2].w    = original->comps[0].w;
911         l_new_components[0].prec = l_new_components[1].prec = l_new_components[2].prec = original->comps[0].prec;
912         l_new_components[0].sgnd = l_new_components[1].sgnd = l_new_components[2].sgnd = original->comps[0].sgnd;
913         l_new_components[0].x0   = l_new_components[1].x0   = l_new_components[2].x0   = original->comps[0].x0;
914         l_new_components[0].y0   = l_new_components[1].y0   = l_new_components[2].y0   = original->comps[0].y0;
915         
916         for(compno = 1U; compno < original->numcomps; ++compno) {
917                 l_new_components[compno+2U].bpp  = original->comps[compno].bpp;
918                 l_new_components[compno+2U].dx   = original->comps[compno].dx;
919                 l_new_components[compno+2U].dy   = original->comps[compno].dy;
920                 l_new_components[compno+2U].h    = original->comps[compno].h;
921                 l_new_components[compno+2U].w    = original->comps[compno].w;
922                 l_new_components[compno+2U].prec = original->comps[compno].prec;
923                 l_new_components[compno+2U].sgnd = original->comps[compno].sgnd;
924                 l_new_components[compno+2U].x0   = original->comps[compno].x0;
925                 l_new_components[compno+2U].y0   = original->comps[compno].y0;
926         }
927         
928         l_new_image = opj_image_create(original->numcomps + 2U, l_new_components, OPJ_CLRSPC_SRGB);
929         free(l_new_components);
930         if (l_new_image == NULL) {
931                 fprintf(stderr, "ERROR -> opj_decompress: failed to allocate memory for RGB image!\n");
932                 opj_image_destroy(original);
933                 return NULL;
934         }
935         
936         l_new_image->x0 = original->x0;
937         l_new_image->x1 = original->x1;
938         l_new_image->y0 = original->y0;
939         l_new_image->y1 = original->y1;
940         
941         l_new_image->comps[0].factor        = l_new_image->comps[1].factor        = l_new_image->comps[2].factor        = original->comps[0].factor;
942         l_new_image->comps[0].alpha         = l_new_image->comps[1].alpha         = l_new_image->comps[2].alpha         = original->comps[0].alpha;
943         l_new_image->comps[0].resno_decoded = l_new_image->comps[1].resno_decoded = l_new_image->comps[2].resno_decoded = original->comps[0].resno_decoded;
944         
945         memcpy(l_new_image->comps[0].data, original->comps[0].data, original->comps[0].w * original->comps[0].h * sizeof(OPJ_INT32));
946         memcpy(l_new_image->comps[1].data, original->comps[0].data, original->comps[0].w * original->comps[0].h * sizeof(OPJ_INT32));
947         memcpy(l_new_image->comps[2].data, original->comps[0].data, original->comps[0].w * original->comps[0].h * sizeof(OPJ_INT32));
948         
949         for(compno = 1U; compno < original->numcomps; ++compno) {
950                 l_new_image->comps[compno+2U].factor        = original->comps[compno].factor;
951                 l_new_image->comps[compno+2U].alpha         = original->comps[compno].alpha;
952                 l_new_image->comps[compno+2U].resno_decoded = original->comps[compno].resno_decoded;
953                 memcpy(l_new_image->comps[compno+2U].data, original->comps[compno].data, original->comps[compno].w * original->comps[compno].h * sizeof(OPJ_INT32));
954         }
955         opj_image_destroy(original);
956         return l_new_image;
957 }
958
959 /* -------------------------------------------------------------------------- */
960
961 static opj_image_t* upsample_image_components(opj_image_t* original)
962 {
963         opj_image_t* l_new_image = NULL;
964         opj_image_cmptparm_t* l_new_components = NULL;
965         OPJ_BOOL l_upsample_need = OPJ_FALSE;
966         OPJ_UINT32 compno;
967
968         for (compno = 0U; compno < original->numcomps; ++compno) {
969                 if (original->comps[compno].factor > 0U) {
970                         fprintf(stderr, "ERROR -> opj_decompress: -upsample not supported with reduction\n");
971                         opj_image_destroy(original);
972                         return NULL;
973                 }
974                 if ((original->comps[compno].dx > 1U) || (original->comps[compno].dy > 1U)) {
975                         l_upsample_need = OPJ_TRUE;
976                         break;
977                 }
978         }
979         if (!l_upsample_need) {
980                 return original;
981         }
982         /* Upsample is needed */
983         l_new_components = (opj_image_cmptparm_t*)malloc(original->numcomps * sizeof(opj_image_cmptparm_t));
984         if (l_new_components == NULL) {
985                 fprintf(stderr, "ERROR -> opj_decompress: failed to allocate memory for upsampled components!\n");
986                 opj_image_destroy(original);
987                 return NULL;
988         }
989         
990         for (compno = 0U; compno < original->numcomps; ++compno) {
991                 opj_image_cmptparm_t* l_new_cmp = &(l_new_components[compno]);
992                 opj_image_comp_t*     l_org_cmp = &(original->comps[compno]);
993                 
994                 l_new_cmp->bpp  = l_org_cmp->bpp;
995                 l_new_cmp->prec = l_org_cmp->prec;
996                 l_new_cmp->sgnd = l_org_cmp->sgnd;
997                 l_new_cmp->x0   = original->x0;
998                 l_new_cmp->y0   = original->y0;
999                 l_new_cmp->dx   = 1;
1000                 l_new_cmp->dy   = 1;
1001                 l_new_cmp->w    = l_org_cmp->w; /* should be original->x1 - original->x0 for dx==1 */
1002                 l_new_cmp->h    = l_org_cmp->h; /* should be original->y1 - original->y0 for dy==0 */
1003                 
1004                 if (l_org_cmp->dx > 1U) {
1005                         l_new_cmp->w = original->x1 - original->x0;
1006                 }
1007                 
1008                 if (l_org_cmp->dy > 1U) {
1009                         l_new_cmp->h = original->y1 - original->y0;
1010                 }
1011         }
1012         
1013         l_new_image = opj_image_create(original->numcomps, l_new_components, original->color_space);
1014         free(l_new_components);
1015         if (l_new_image == NULL) {
1016                 fprintf(stderr, "ERROR -> opj_decompress: failed to allocate memory for upsampled components!\n");
1017                 opj_image_destroy(original);
1018                 return NULL;
1019         }
1020         
1021         l_new_image->x0 = original->x0;
1022         l_new_image->x1 = original->x1;
1023         l_new_image->y0 = original->y0;
1024         l_new_image->y1 = original->y1;
1025         
1026         for (compno = 0U; compno < original->numcomps; ++compno) {
1027                 opj_image_comp_t* l_new_cmp = &(l_new_image->comps[compno]);
1028                 opj_image_comp_t* l_org_cmp = &(original->comps[compno]);
1029                 
1030                 l_new_cmp->factor        = l_org_cmp->factor;
1031                 l_new_cmp->alpha         = l_org_cmp->alpha;
1032                 l_new_cmp->resno_decoded = l_org_cmp->resno_decoded;
1033                 
1034                 if ((l_org_cmp->dx > 1U) || (l_org_cmp->dy > 1U)) {
1035                         const OPJ_INT32* l_src = l_org_cmp->data;
1036                         OPJ_INT32*       l_dst = l_new_cmp->data;
1037                         OPJ_UINT32 y;
1038                         OPJ_UINT32 xoff, yoff;
1039                         
1040                         /* need to take into account dx & dy */
1041                         xoff = l_org_cmp->dx * l_org_cmp->x0 -  original->x0;
1042                         yoff = l_org_cmp->dy * l_org_cmp->y0 -  original->y0;
1043                         if ((xoff >= l_org_cmp->dx) || (yoff >= l_org_cmp->dy)) {
1044                                 fprintf(stderr, "ERROR -> opj_decompress: Invalid image/component parameters found when upsampling\n");
1045                                 opj_image_destroy(original);
1046                                 opj_image_destroy(l_new_image);
1047                                 return NULL;
1048                         }
1049                         
1050                         for (y = 0U; y < yoff; ++y) {
1051                                 memset(l_dst, 0U, l_new_cmp->w * sizeof(OPJ_INT32));
1052                                 l_dst += l_new_cmp->w;
1053                         }
1054                         
1055                         if(l_new_cmp->h > (l_org_cmp->dy - 1U)) { /* check substraction overflow for really small images */
1056                                 for (; y < l_new_cmp->h - (l_org_cmp->dy - 1U); y += l_org_cmp->dy) {
1057                                         OPJ_UINT32 x, dy;
1058                                         OPJ_UINT32 xorg;
1059                                         
1060                                         xorg = 0U;
1061                                         for (x = 0U; x < xoff; ++x) {
1062                                                 l_dst[x] = 0;
1063                                         }
1064                                         if (l_new_cmp->w > (l_org_cmp->dx - 1U)) { /* check substraction overflow for really small images */
1065                                                 for (; x < l_new_cmp->w - (l_org_cmp->dx - 1U); x += l_org_cmp->dx, ++xorg) {
1066                                                         OPJ_UINT32 dx;
1067                                                         for (dx = 0U; dx < l_org_cmp->dx; ++dx) {
1068                                                                 l_dst[x + dx] = l_src[xorg];
1069                                                         }
1070                                                 }
1071                                         }
1072                                         for (; x < l_new_cmp->w; ++x) {
1073                                                 l_dst[x] = l_src[xorg];
1074                                         }
1075                                         l_dst += l_new_cmp->w;
1076                                                 
1077                                         for (dy = 1U; dy < l_org_cmp->dy; ++dy) {
1078                                                 memcpy(l_dst, l_dst - l_new_cmp->w, l_new_cmp->w * sizeof(OPJ_INT32));
1079                                                 l_dst += l_new_cmp->w;
1080                                         }
1081                                         l_src += l_org_cmp->w;
1082                                 }
1083                         }
1084                         if (y < l_new_cmp->h) {
1085                                 OPJ_UINT32 x;
1086                                 OPJ_UINT32 xorg;
1087                                 
1088                                 xorg = 0U;
1089                                 for (x = 0U; x < xoff; ++x) {
1090                                         l_dst[x] = 0;
1091                                 }
1092                                 if (l_new_cmp->w > (l_org_cmp->dx - 1U)) { /* check substraction overflow for really small images */
1093                                         for (; x < l_new_cmp->w - (l_org_cmp->dx - 1U); x += l_org_cmp->dx, ++xorg) {
1094                                                 OPJ_UINT32 dx;
1095                                                 for (dx = 0U; dx < l_org_cmp->dx; ++dx) {
1096                                                         l_dst[x + dx] = l_src[xorg];
1097                                                 }
1098                                         }
1099                                 }
1100                                 for (; x < l_new_cmp->w; ++x) {
1101                                         l_dst[x] = l_src[xorg];
1102                                 }
1103                                 l_dst += l_new_cmp->w;
1104                                 ++y;
1105                                 for (; y < l_new_cmp->h; ++y) {
1106                                         memcpy(l_dst, l_dst - l_new_cmp->w, l_new_cmp->w * sizeof(OPJ_INT32));
1107                                         l_dst += l_new_cmp->w;
1108                                 }
1109                         }
1110                 }
1111                 else {
1112                         memcpy(l_new_cmp->data, l_org_cmp->data, l_org_cmp->w * l_org_cmp->h * sizeof(OPJ_INT32));
1113                 }
1114         }
1115         opj_image_destroy(original);
1116         return l_new_image;
1117 }
1118
1119 /* -------------------------------------------------------------------------- */
1120 /**
1121  * OPJ_DECOMPRESS MAIN
1122  */
1123 /* -------------------------------------------------------------------------- */
1124 int main(int argc, char **argv)
1125 {
1126         opj_decompress_parameters parameters;                   /* decompression parameters */
1127         opj_image_t* image = NULL;
1128         opj_stream_t *l_stream = NULL;                          /* Stream */
1129         opj_codec_t* l_codec = NULL;                            /* Handle to a decompressor */
1130         opj_codestream_index_t* cstr_index = NULL;
1131
1132         char indexfilename[OPJ_PATH_LEN];       /* index file name */
1133
1134         OPJ_INT32 num_images, imageno;
1135         img_fol_t img_fol;
1136         dircnt_t *dirptr = NULL;
1137   int failed = 0;
1138
1139         /* set decoding parameters to default values */
1140         set_default_parameters(&parameters);
1141
1142         /* FIXME Initialize indexfilename and img_fol */
1143         *indexfilename = 0;
1144
1145         /* Initialize img_fol */
1146         memset(&img_fol,0,sizeof(img_fol_t));
1147
1148         /* parse input and get user encoding parameters */
1149         if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {
1150                 destroy_parameters(&parameters);
1151                 return EXIT_FAILURE;
1152         }
1153
1154         /* Initialize reading of directory */
1155         if(img_fol.set_imgdir==1){      
1156                 int it_image;
1157                 num_images=get_num_images(img_fol.imgdirpath);
1158
1159                 dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
1160                 if(dirptr){
1161                         dirptr->filename_buf = (char*)malloc((size_t)num_images*OPJ_PATH_LEN*sizeof(char));     /* Stores at max 10 image file names*/
1162                         dirptr->filename = (char**) malloc((size_t)num_images*sizeof(char*));
1163
1164                         if(!dirptr->filename_buf){
1165                                 destroy_parameters(&parameters);
1166                                 return EXIT_FAILURE;
1167                         }
1168                         for(it_image=0;it_image<num_images;it_image++){
1169                                 dirptr->filename[it_image] = dirptr->filename_buf + it_image*OPJ_PATH_LEN;
1170                         }
1171                 }
1172                 if(load_images(dirptr,img_fol.imgdirpath)==1){
1173                         destroy_parameters(&parameters);
1174                         return EXIT_FAILURE;
1175                 }
1176                 if (num_images==0){
1177                         fprintf(stdout,"Folder is empty\n");
1178                         destroy_parameters(&parameters);
1179                         return EXIT_FAILURE;
1180                 }
1181         }else{
1182                 num_images=1;
1183         }
1184
1185         /*Decoding image one by one*/
1186         for(imageno = 0; imageno < num_images ; imageno++)      {
1187
1188                 fprintf(stderr,"\n");
1189
1190                 if(img_fol.set_imgdir==1){
1191                         if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
1192                                 fprintf(stderr,"skipping file...\n");
1193                                 destroy_parameters(&parameters);
1194                                 continue;
1195                         }
1196                 }
1197
1198                 /* read the input file and put it in memory */
1199                 /* ---------------------------------------- */
1200
1201                 l_stream = opj_stream_create_default_file_stream(parameters.infile,1);
1202                 if (!l_stream){
1203                         fprintf(stderr, "ERROR -> failed to create the stream from the file %s\n", parameters.infile);
1204                         destroy_parameters(&parameters);
1205                         return EXIT_FAILURE;
1206                 }
1207
1208                 /* decode the JPEG2000 stream */
1209                 /* ---------------------- */
1210
1211                 switch(parameters.decod_format) {
1212                         case J2K_CFMT:  /* JPEG-2000 codestream */
1213                         {
1214                                 /* Get a decoder handle */
1215                                 l_codec = opj_create_decompress(OPJ_CODEC_J2K);
1216                                 break;
1217                         }
1218                         case JP2_CFMT:  /* JPEG 2000 compressed image data */
1219                         {
1220                                 /* Get a decoder handle */
1221                                 l_codec = opj_create_decompress(OPJ_CODEC_JP2);
1222                                 break;
1223                         }
1224                         case JPT_CFMT:  /* JPEG 2000, JPIP */
1225                         {
1226                                 /* Get a decoder handle */
1227                                 l_codec = opj_create_decompress(OPJ_CODEC_JPT);
1228                                 break;
1229                         }
1230                         default:
1231                                 fprintf(stderr, "skipping file..\n");
1232                                 destroy_parameters(&parameters);
1233                                 opj_stream_destroy(l_stream);
1234                                 continue;
1235                 }
1236
1237                 /* catch events using our callbacks and give a local context */         
1238                 opj_set_info_handler(l_codec, info_callback,00);
1239                 opj_set_warning_handler(l_codec, warning_callback,00);
1240                 opj_set_error_handler(l_codec, error_callback,00);
1241
1242                 /* Setup the decoder decoding parameters using user parameters */
1243                 if ( !opj_setup_decoder(l_codec, &(parameters.core)) ){
1244                         fprintf(stderr, "ERROR -> opj_decompress: failed to setup the decoder\n");
1245                         destroy_parameters(&parameters);
1246                         opj_stream_destroy(l_stream);
1247                         opj_destroy_codec(l_codec);
1248                         return EXIT_FAILURE;
1249                 }
1250
1251
1252                 /* Read the main header of the codestream and if necessary the JP2 boxes*/
1253                 if(! opj_read_header(l_stream, l_codec, &image)){
1254                         fprintf(stderr, "ERROR -> opj_decompress: failed to read the header\n");
1255                         destroy_parameters(&parameters);
1256                         opj_stream_destroy(l_stream);
1257                         opj_destroy_codec(l_codec);
1258                         opj_image_destroy(image);
1259                         return EXIT_FAILURE;
1260                 }
1261
1262                 if (!parameters.nb_tile_to_decode) {
1263                         /* Optional if you want decode the entire image */
1264                         if (!opj_set_decode_area(l_codec, image, (OPJ_INT32)parameters.DA_x0,
1265                                         (OPJ_INT32)parameters.DA_y0, (OPJ_INT32)parameters.DA_x1, (OPJ_INT32)parameters.DA_y1)){
1266                                 fprintf(stderr, "ERROR -> opj_decompress: failed to set the decoded area\n");
1267                                 destroy_parameters(&parameters);
1268                                 opj_stream_destroy(l_stream);
1269                                 opj_destroy_codec(l_codec);
1270                                 opj_image_destroy(image);
1271                                 return EXIT_FAILURE;
1272                         }
1273
1274                         /* Get the decoded image */
1275                         if (!(opj_decode(l_codec, l_stream, image) && opj_end_decompress(l_codec,       l_stream))) {
1276                                 fprintf(stderr,"ERROR -> opj_decompress: failed to decode image!\n");
1277                                 destroy_parameters(&parameters);
1278                                 opj_destroy_codec(l_codec);
1279                                 opj_stream_destroy(l_stream);
1280                                 opj_image_destroy(image);
1281                                 return EXIT_FAILURE;
1282                         }
1283                 }
1284                 else {
1285
1286                         /* It is just here to illustrate how to use the resolution after set parameters */
1287                         /*if (!opj_set_decoded_resolution_factor(l_codec, 5)) {
1288                                 fprintf(stderr, "ERROR -> opj_decompress: failed to set the resolution factor tile!\n");
1289                                 opj_destroy_codec(l_codec);
1290                                 opj_stream_destroy(l_stream);
1291                                 opj_image_destroy(image);
1292                                 return EXIT_FAILURE;
1293                         }*/
1294
1295                         if (!opj_get_decoded_tile(l_codec, l_stream, image, parameters.tile_index)) {
1296                                 fprintf(stderr, "ERROR -> opj_decompress: failed to decode tile!\n");
1297                                 destroy_parameters(&parameters);
1298                                 opj_destroy_codec(l_codec);
1299                                 opj_stream_destroy(l_stream);
1300                                 opj_image_destroy(image);
1301                                 return EXIT_FAILURE;
1302                         }
1303                         fprintf(stdout, "tile %d is decoded!\n\n", parameters.tile_index);
1304                 }
1305
1306                 /* Close the byte stream */
1307                 opj_stream_destroy(l_stream);
1308
1309                 if(image->color_space == OPJ_CLRSPC_SYCC){
1310                         color_sycc_to_rgb(image); /* FIXME */
1311                 }
1312                 
1313                 if( image->color_space != OPJ_CLRSPC_SYCC 
1314                         && image->numcomps == 3 && image->comps[0].dx == image->comps[0].dy
1315                         && image->comps[1].dx != 1 )
1316                         image->color_space = OPJ_CLRSPC_SYCC;
1317                 else if (image->numcomps <= 2)
1318                         image->color_space = OPJ_CLRSPC_GRAY;
1319
1320                 if(image->icc_profile_buf) {
1321 #if defined(OPJ_HAVE_LIBLCMS1) || defined(OPJ_HAVE_LIBLCMS2)
1322                         color_apply_icc_profile(image); /* FIXME */
1323 #endif
1324                         free(image->icc_profile_buf);
1325                         image->icc_profile_buf = NULL; image->icc_profile_len = 0;
1326                 }
1327                 
1328                 /* Force output precision */
1329                 /* ---------------------- */
1330                 if (parameters.precision != NULL)
1331                 {
1332                         OPJ_UINT32 compno;
1333                         for (compno = 0; compno < image->numcomps; ++compno)
1334                         {
1335                                 OPJ_UINT32 precno = compno;
1336                                 OPJ_UINT32 prec;
1337                                 
1338                                 if (precno >= parameters.nb_precision) {
1339                                         precno = parameters.nb_precision - 1U;
1340                                 }
1341                                 
1342                                 prec = parameters.precision[precno].prec;
1343                                 if (prec == 0) {
1344                                         prec = image->comps[compno].prec;
1345                                 }
1346                                 
1347                                 switch (parameters.precision[precno].mode) {
1348                                         case OPJ_PREC_MODE_CLIP:
1349                                                 clip_component(&(image->comps[compno]), prec);
1350                                                 break;
1351                                         case OPJ_PREC_MODE_SCALE:
1352                                                 scale_component(&(image->comps[compno]), prec);
1353                                                 break;
1354                                         default:
1355                                                 break;
1356                                 }
1357                                 
1358                         }
1359                 }
1360                 
1361                 /* Upsample components */
1362                 /* ------------------- */
1363                 if (parameters.upsample)
1364                 {
1365                         image = upsample_image_components(image);
1366                         if (image == NULL) {
1367                                 fprintf(stderr, "ERROR -> opj_decompress: failed to upsample image components!\n");
1368                                 destroy_parameters(&parameters);
1369                                 opj_destroy_codec(l_codec);
1370                                 return EXIT_FAILURE;
1371                         }
1372                 }
1373                 
1374                 /* Force RGB output */
1375                 /* ---------------- */
1376                 if (parameters.force_rgb)
1377                 {
1378                         switch (image->color_space) {
1379                                 case OPJ_CLRSPC_SRGB:
1380                                         break;
1381                                 case OPJ_CLRSPC_GRAY:
1382                                         image = convert_gray_to_rgb(image);
1383                                         break;
1384                                 default:
1385                                         fprintf(stderr, "ERROR -> opj_decompress: don't know how to convert image to RGB colorspace!\n");
1386                                         opj_image_destroy(image);
1387                                         image = NULL;
1388                                         break;
1389                         }
1390                         if (image == NULL) {
1391                                 fprintf(stderr, "ERROR -> opj_decompress: failed to convert to RGB image!\n");
1392                                 destroy_parameters(&parameters);
1393                                 opj_destroy_codec(l_codec);
1394                                 return EXIT_FAILURE;
1395                         }
1396                 }
1397
1398                 /* create output image */
1399                 /* ------------------- */
1400                 switch (parameters.cod_format) {
1401                 case PXM_DFMT:                  /* PNM PGM PPM */
1402                         if (imagetopnm(image, parameters.outfile)) {
1403                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1404         failed = 1;
1405                         }
1406                         else {
1407                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1408                         }
1409                         break;
1410
1411                 case PGX_DFMT:                  /* PGX */
1412                         if(imagetopgx(image, parameters.outfile)){
1413                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1414         failed = 1;
1415                         }
1416                         else {
1417                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1418                         }
1419                         break;
1420
1421                 case BMP_DFMT:                  /* BMP */
1422                         if(imagetobmp(image, parameters.outfile)){
1423                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1424         failed = 1;
1425                         }
1426                         else {
1427                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1428                         }
1429                         break;
1430 #ifdef OPJ_HAVE_LIBTIFF
1431                 case TIF_DFMT:                  /* TIFF */
1432                         if(imagetotif(image, parameters.outfile)){
1433                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1434         failed = 1;
1435                         }
1436                         else {
1437                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1438                         }
1439                         break;
1440 #endif /* OPJ_HAVE_LIBTIFF */
1441                 case RAW_DFMT:                  /* RAW */
1442                         if(imagetoraw(image, parameters.outfile)){
1443                 fprintf(stderr,"[ERROR] Error generating raw file. Outfile %s not generated\n",parameters.outfile);
1444         failed = 1;
1445                         }
1446                         else {
1447                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1448                         }
1449                         break;
1450
1451                 case RAWL_DFMT:                 /* RAWL */
1452                         if(imagetorawl(image, parameters.outfile)){
1453                 fprintf(stderr,"[ERROR] Error generating rawl file. Outfile %s not generated\n",parameters.outfile);
1454         failed = 1;
1455                         }
1456                         else {
1457                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1458                         }
1459                         break;
1460
1461                 case TGA_DFMT:                  /* TGA */
1462                         if(imagetotga(image, parameters.outfile)){
1463                 fprintf(stderr,"[ERROR] Error generating tga file. Outfile %s not generated\n",parameters.outfile);
1464         failed = 1;
1465                         }
1466                         else {
1467                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1468                         }
1469                         break;
1470 #ifdef OPJ_HAVE_LIBPNG
1471                 case PNG_DFMT:                  /* PNG */
1472                         if(imagetopng(image, parameters.outfile)){
1473                 fprintf(stderr,"[ERROR] Error generating png file. Outfile %s not generated\n",parameters.outfile);
1474         failed = 1;
1475                         }
1476                         else {
1477                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1478                         }
1479                         break;
1480 #endif /* OPJ_HAVE_LIBPNG */
1481 /* Can happen if output file is TIFF or PNG
1482  * and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined
1483 */
1484                         default:
1485                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1486         failed = 1;
1487                 }
1488
1489                 /* free remaining structures */
1490                 if (l_codec) {
1491                         opj_destroy_codec(l_codec);
1492                 }
1493
1494
1495                 /* free image data structure */
1496                 opj_image_destroy(image);
1497
1498                 /* destroy the codestream index */
1499                 opj_destroy_cstr_index(&cstr_index);
1500
1501                 if(failed) remove(parameters.outfile);
1502         }
1503         destroy_parameters(&parameters);
1504         return failed ? EXIT_FAILURE : EXIT_SUCCESS;
1505 }
1506 /*end main*/