bd76dcacb7cbe55f9b87888750af5e4d41f31474
[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         OPJ_BOOL force_rgb;
143 }opj_decompress_parameters;
144
145 /* -------------------------------------------------------------------------- */
146 /* Declarations                                                               */
147 int get_num_images(char *imgdirpath);
148 int load_images(dircnt_t *dirptr, char *imgdirpath);
149 int get_file_format(const char *filename);
150 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_decompress_parameters *parameters);
151 static int infile_format(const char *fname);
152
153 int parse_cmdline_decoder(int argc, char **argv, opj_decompress_parameters *parameters,img_fol_t *img_fol, char *indexfilename);
154 int parse_DA_values( char* inArg, unsigned int *DA_x0, unsigned int *DA_y0, unsigned int *DA_x1, unsigned int *DA_y1);
155
156 static opj_image_t* convert_gray_to_rgb(opj_image_t* original);
157
158 /* -------------------------------------------------------------------------- */
159 static void decode_help_display(void) {
160         fprintf(stdout,"\nThis is the opj_decompress utility from the OpenJPEG project.\n"
161                        "It decompresses JPEG 2000 codestreams to various image formats.\n"
162                        "It has been compiled against openjp2 library v%s.\n\n",opj_version());
163
164         fprintf(stdout,"Parameters:\n"
165                        "-----------\n"
166                        "\n"
167                        "  -ImgDir <directory> \n"
168                        "        Image file Directory path \n"
169                        "  -OutFor <PBM|PGM|PPM|PNM|PAM|PGX|PNG|BMP|TIF|RAW|RAWL|TGA>\n"
170                        "    REQUIRED only if -ImgDir is used\n"
171                        "        Output format for decompressed images.\n"
172                        "  -i <compressed file>\n"
173                        "    REQUIRED only if an Input image directory is not specified\n"
174                        "    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n"
175                        "    is identified based on its suffix.\n"
176                        "  -o <decompressed file>\n"
177                        "    REQUIRED\n"
178                        "    Currently accepts formats specified above (see OutFor option)\n"
179                        "    Binary data is written to the file (not ascii). If a PGX\n"
180                        "    filename is given, there will be as many output files as there are\n"
181                        "    components: an indice starting from 0 will then be appended to the\n"
182                        "    output filename, just before the \"pgx\" extension. If a PGM filename\n"
183                        "    is given and there are more than one component, only the first component\n"
184                        "    will be written to the file.\n"
185                        "  -r <reduce factor>\n"
186                        "    Set the number of highest resolution levels to be discarded. The\n"
187                        "    image resolution is effectively divided by 2 to the power of the\n"
188                        "    number of discarded levels. The reduce factor is limited by the\n"
189                        "    smallest total number of decomposition levels among tiles.\n"
190                        "  -l <number of quality layers to decode>\n"
191                        "    Set the maximum number of quality layers to decode. If there are\n"
192                        "    less quality layers than the specified number, all the quality layers\n"
193                        "    are decoded.\n"
194                        "  -x  \n" 
195                        "    Create an index file *.Idx (-x index_name.Idx) \n"
196                        "  -d <x0,y0,x1,y1>\n"
197                        "    OPTIONAL\n"
198                        "    Decoding area\n"
199                        "    By default all the image is decoded.\n"
200                        "  -t <tile_number>\n"
201                        "    OPTIONAL\n"
202                        "    Set the tile number of the decoded tile. Follow the JPEG2000 convention from left-up to bottom-up\n"
203                        "    By default all tiles are decoded.\n"
204                        "  -p <comp 0 precision>[C|S][,<comp 1 precision>[C|S][,...]]\n"
205                        "    OPTIONAL\n"
206                        "    Force the precision (bit depth) of components.\n"
207                        "    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"
208                        "    If there are less values than components, the last value is used for remaining components.\n"
209                        "    If 'C' is specified (default), values are clipped.\n"
210                        "    If 'S' is specified, values are scaled.\n"
211                        "    A 0 value can be specified (meaning original bit depth).\n"
212                        "  -force-rgb\n"
213                        "    Force output image colorspace to RGB\n"
214                        "\n");
215 /* UniPG>> */
216 #ifdef USE_JPWL
217         fprintf(stdout,"  -W <options>\n"
218                        "    Activates the JPWL correction capability, if the codestream complies.\n"
219                        "    Options can be a comma separated list of <param=val> tokens:\n"
220                        "    c, c=numcomps\n"
221                        "       numcomps is the number of expected components in the codestream\n"
222                        "       (search of first EPB rely upon this, default is %d)\n", JPWL_EXPECTED_COMPONENTS);
223 #endif /* USE_JPWL */
224 /* <<UniPG */
225         fprintf(stdout,"\n");
226 }
227
228 /* -------------------------------------------------------------------------- */
229
230 static OPJ_BOOL parse_precision(const char* option, opj_decompress_parameters* parameters)
231 {
232         const char* l_remaining = option;
233         OPJ_BOOL l_result = OPJ_TRUE;
234         
235         /* reset */
236         if (parameters->precision) {
237                 free(parameters->precision);
238                 parameters->precision = NULL;
239         }
240         parameters->nb_precision = 0U;
241         
242         for(;;)
243         {
244                 OPJ_UINT32 prec;
245                 char mode;
246                 char comma;
247                 int count;
248                 
249                 count = sscanf(l_remaining, "%d%c%c", &prec, &mode, &comma);
250                 if (count == 1) {
251                         mode = 'C';
252                         count++;
253                 }
254                 if ((count == 2) || (mode==',')) {
255                         if (mode==',') {
256                                 mode = 'C';
257                         }
258                         comma=',';
259                         count = 3;
260                 }
261                 if (count == 3) {
262                         if (prec > 32U) {
263                                 fprintf(stderr,"Invalid precision %d in precision option %s\n", prec, option);
264                                 l_result = OPJ_FALSE;
265                                 break;
266                         }
267                         if ((mode != 'C') && (mode != 'S')) {
268                                 fprintf(stderr,"Invalid precision mode %c in precision option %s\n", mode, option);
269                                 l_result = OPJ_FALSE;
270                                 break;
271                         }
272                         if (comma != ',') {
273                                 fprintf(stderr,"Invalid character %c in precision option %s\n", comma, option);
274                                 l_result = OPJ_FALSE;
275                                 break;
276                         }
277                         
278                         if (parameters->precision == NULL) {
279                                 /* first one */
280                                 parameters->precision = malloc(sizeof(opj_precision));
281                                 if (parameters->precision == NULL) {
282                                         fprintf(stderr,"Could not allocate memory for precision option\n");
283                                         l_result = OPJ_FALSE;
284                                         break;
285                                 }
286                         } else {
287                                 OPJ_UINT32 l_new_size = parameters->nb_precision + 1U;
288                                 opj_precision* l_new;
289                                 
290                                 if (l_new_size == 0U) {
291                                         fprintf(stderr,"Could not allocate memory for precision option\n");
292                                         l_result = OPJ_FALSE;
293                                         break;
294                                 }
295                                 
296                                 l_new = realloc(parameters->precision, l_new_size * sizeof(opj_precision));
297                                 if (l_new == NULL) {
298                                         fprintf(stderr,"Could not allocate memory for precision option\n");
299                                         l_result = OPJ_FALSE;
300                                         break;
301                                 }
302                                 parameters->precision = l_new;
303                         }
304                         
305                         parameters->precision[parameters->nb_precision].prec = prec;
306                         switch (mode) {
307                                 case 'C':
308                                         parameters->precision[parameters->nb_precision].mode = OPJ_PREC_MODE_CLIP;
309                                         break;
310                                 case 'S':
311                                         parameters->precision[parameters->nb_precision].mode = OPJ_PREC_MODE_SCALE;
312                                         break;
313                                 default:
314                                         break;
315                         }
316                         parameters->nb_precision++;
317                         
318                         l_remaining = strchr(l_remaining, ',');
319                         if (l_remaining == NULL) {
320                                 break;
321                         }
322                         l_remaining += 1;
323                 } else {
324                         fprintf(stderr,"Could not parse precision option %s\n", option);
325                         l_result = OPJ_FALSE;
326                         break;
327                 }
328         }
329         
330         return l_result;
331 }
332
333 /* -------------------------------------------------------------------------- */
334
335 int get_num_images(char *imgdirpath){
336         DIR *dir;
337         struct dirent* content; 
338         int num_images = 0;
339
340         /*Reading the input images from given input directory*/
341
342         dir= opendir(imgdirpath);
343         if(!dir){
344                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
345                 return 0;
346         }
347         
348         while((content=readdir(dir))!=NULL){
349                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
350                         continue;
351                 num_images++;
352         }
353         return num_images;
354 }
355
356 /* -------------------------------------------------------------------------- */
357 int load_images(dircnt_t *dirptr, char *imgdirpath){
358         DIR *dir;
359         struct dirent* content; 
360         int i = 0;
361
362         /*Reading the input images from given input directory*/
363
364         dir= opendir(imgdirpath);
365         if(!dir){
366                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
367                 return 1;
368         }else   {
369                 fprintf(stderr,"Folder opened successfully\n");
370         }
371         
372         while((content=readdir(dir))!=NULL){
373                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
374                         continue;
375
376                 strcpy(dirptr->filename[i],content->d_name);
377                 i++;
378         }
379         return 0;       
380 }
381
382 /* -------------------------------------------------------------------------- */
383 int get_file_format(const char *filename) {
384         unsigned int i;
385         static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "rawl", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc" };
386         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 };
387         char * ext = strrchr(filename, '.');
388         if (ext == NULL)
389                 return -1;
390         ext++;
391         if(*ext) {
392                 for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
393                         if(strcasecmp(ext, extension[i]) == 0) {
394                                 return format[i];
395                         }
396                 }
397         }
398
399         return -1;
400 }
401
402 /* -------------------------------------------------------------------------- */
403 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_decompress_parameters *parameters){
404         char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
405         char *temp_p, temp1[OPJ_PATH_LEN]="";
406
407         strcpy(image_filename,dirptr->filename[imageno]);
408         fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
409         parameters->decod_format = infile_format(image_filename);
410         if (parameters->decod_format == -1)
411                 return 1;
412         sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
413         strncpy(parameters->infile, infilename, sizeof(infilename));
414
415         /*Set output file*/
416         strcpy(temp_ofname,strtok(image_filename,"."));
417         while((temp_p = strtok(NULL,".")) != NULL){
418                 strcat(temp_ofname,temp1);
419                 sprintf(temp1,".%s",temp_p);
420         }
421         if(img_fol->set_out_format==1){
422                 sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
423                 strncpy(parameters->outfile, outfilename, sizeof(outfilename));
424         }
425         return 0;
426 }
427
428 /* -------------------------------------------------------------------------- */
429 #define JP2_RFC3745_MAGIC "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a"
430 #define JP2_MAGIC "\x0d\x0a\x87\x0a"
431 /* position 45: "\xff\x52" */
432 #define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51"
433
434 static int infile_format(const char *fname)
435 {
436         FILE *reader;
437         const char *s, *magic_s;
438         int ext_format, magic_format;
439         unsigned char buf[12];
440         OPJ_SIZE_T l_nb_read;
441
442         reader = fopen(fname, "rb");
443
444         if (reader == NULL)
445                 return -2;
446
447         memset(buf, 0, 12);
448         l_nb_read = fread(buf, 1, 12, reader);
449         fclose(reader);
450         if (l_nb_read != 12)
451                 return -1;
452
453
454
455         ext_format = get_file_format(fname);
456
457         if (ext_format == JPT_CFMT)
458                 return JPT_CFMT;
459
460         if (memcmp(buf, JP2_RFC3745_MAGIC, 12) == 0 || memcmp(buf, JP2_MAGIC, 4) == 0) {
461                 magic_format = JP2_CFMT;
462                 magic_s = ".jp2";
463         }
464         else if (memcmp(buf, J2K_CODESTREAM_MAGIC, 4) == 0) {
465                 magic_format = J2K_CFMT;
466                 magic_s = ".j2k or .jpc or .j2c";
467         }
468         else
469                 return -1;
470
471         if (magic_format == ext_format)
472                 return ext_format;
473
474         s = fname + strlen(fname) - 4;
475
476         fputs("\n===========================================\n", stderr);
477         fprintf(stderr, "The extension of this file is incorrect.\n"
478                                         "FOUND %s. SHOULD BE %s\n", s, magic_s);
479         fputs("===========================================\n", stderr);
480
481         return magic_format;
482 }
483
484 /* -------------------------------------------------------------------------- */
485 /**
486  * Parse the command line
487  */
488 /* -------------------------------------------------------------------------- */
489 int parse_cmdline_decoder(int argc, char **argv, opj_decompress_parameters *parameters,img_fol_t *img_fol, char *indexfilename) {
490         /* parse the command line */
491         int totlen, c;
492         opj_option_t long_option[]={
493                 {"ImgDir",    REQ_ARG, NULL ,'y'},
494                 {"OutFor",    REQ_ARG, NULL ,'O'},
495                 {"force-rgb", NO_ARG,  NULL ,'FRGB'}
496         };
497
498         const char optlist[] = "i:o:r:l:x:d:t:p:"
499
500 /* UniPG>> */
501 #ifdef USE_JPWL
502                                         "W:"
503 #endif /* USE_JPWL */
504 /* <<UniPG */
505             "h"         ;
506         totlen=sizeof(long_option);
507         opj_reset_options_reading();
508         img_fol->set_out_format = 0;
509         do {
510                 c = opj_getopt_long(argc, argv,optlist,long_option,totlen);
511                 if (c == -1)
512                         break;
513                 switch (c) {
514                         case 'i':                       /* input file */
515                         {
516                                 char *infile = opj_optarg;
517                                 parameters->decod_format = infile_format(infile);
518                                 switch(parameters->decod_format) {
519                                         case J2K_CFMT:
520                                                 break;
521                                         case JP2_CFMT:
522                                                 break;
523                                         case JPT_CFMT:
524                                                 break;
525                                         case -2:
526                                                 fprintf(stderr, 
527                                                         "!! infile cannot be read: %s !!\n\n", 
528                                                         infile);
529                                                 return 1;
530                                         default:
531                                                 fprintf(stderr, 
532                             "[ERROR] Unknown input file format: %s \n"
533                             "        Known file formats are *.j2k, *.jp2, *.jpc or *.jpt\n",
534                                                         infile);
535                                                 return 1;
536                                 }
537                                 strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
538                         }
539                         break;
540                                 
541                                 /* ----------------------------------------------------- */
542
543                         case 'o':                       /* output file */
544                         {
545                                 char *outfile = opj_optarg;
546                                 parameters->cod_format = get_file_format(outfile);
547                                 switch(parameters->cod_format) {
548                                         case PGX_DFMT:
549                                                 break;
550                                         case PXM_DFMT:
551                                                 break;
552                                         case BMP_DFMT:
553                                                 break;
554                                         case TIF_DFMT:
555                                                 break;
556                                         case RAW_DFMT:
557                                                 break;
558                                         case RAWL_DFMT:
559                                                 break;
560                                         case TGA_DFMT:
561                                                 break;
562                                         case PNG_DFMT:
563                                                 break;
564                                         default:
565                                                 fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outfile);
566                                                 return 1;
567                                 }
568                                 strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);
569                         }
570                         break;
571                         
572                                 /* ----------------------------------------------------- */
573
574                         case 'O':                       /* output format */
575                         {
576                                 char outformat[50];
577                                 char *of = opj_optarg;
578                                 sprintf(outformat,".%s",of);
579                                 img_fol->set_out_format = 1;
580                                 parameters->cod_format = get_file_format(outformat);
581                                 switch(parameters->cod_format) {
582                                         case PGX_DFMT:
583                                                 img_fol->out_format = "pgx";
584                                                 break;
585                                         case PXM_DFMT:
586                                                 img_fol->out_format = "ppm";
587                                                 break;
588                                         case BMP_DFMT:
589                                                 img_fol->out_format = "bmp";
590                                                 break;
591                                         case TIF_DFMT:
592                                                 img_fol->out_format = "tif";
593                                                 break;
594                                         case RAW_DFMT:
595                                                 img_fol->out_format = "raw";
596                                                 break;
597                                         case RAWL_DFMT:
598                                                 img_fol->out_format = "rawl";
599                                                 break;
600                                         case TGA_DFMT:
601                                                 img_fol->out_format = "raw";
602                                                 break;
603                                         case PNG_DFMT:
604                                                 img_fol->out_format = "png";
605                                                 break;
606                                         default:
607                                                 fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outformat);
608                                                 return 1;
609                                                 break;
610                                 }
611                         }
612                         break;
613
614                                 /* ----------------------------------------------------- */
615
616
617                         case 'r':               /* reduce option */
618                         {
619                                 sscanf(opj_optarg, "%ud", &(parameters->core.cp_reduce));
620                         }
621                         break;
622                         
623                                 /* ----------------------------------------------------- */
624       
625
626                         case 'l':               /* layering option */
627                         {
628                                 sscanf(opj_optarg, "%ud", &(parameters->core.cp_layer));
629                         }
630                         break;
631                         
632                                 /* ----------------------------------------------------- */
633
634                         case 'h':                       /* display an help description */
635                                 decode_help_display();
636                                 return 1;                               
637
638             /* ----------------------------------------------------- */
639
640                         case 'y':                       /* Image Directory path */
641                 {
642                                         img_fol->imgdirpath = (char*)malloc(strlen(opj_optarg) + 1);
643                                         strcpy(img_fol->imgdirpath,opj_optarg);
644                                         img_fol->set_imgdir=1;
645                                 }
646                                 break;
647
648                                 /* ----------------------------------------------------- */
649
650                         case 'd':               /* Input decode ROI */
651                         {
652                                 int size_optarg = (int)strlen(opj_optarg) + 1;
653                                 char *ROI_values = (char*) malloc((size_t)size_optarg);
654                                 ROI_values[0] = '\0';
655                                 strncpy(ROI_values, opj_optarg, strlen(opj_optarg));
656                                 ROI_values[strlen(opj_optarg)] = '\0';
657                                 /*printf("ROI_values = %s [%d / %d]\n", ROI_values, strlen(ROI_values), size_optarg ); */
658                                 parse_DA_values( ROI_values, &parameters->DA_x0, &parameters->DA_y0, &parameters->DA_x1, &parameters->DA_y1);
659
660                                 free(ROI_values);
661                         }
662                         break;
663
664                         /* ----------------------------------------------------- */
665
666                         case 't':               /* Input tile index */
667                         {
668                                 sscanf(opj_optarg, "%ud", &parameters->tile_index);
669                                 parameters->nb_tile_to_decode = 1;
670                         }
671                         break;
672
673                                 /* ----------------------------------------------------- */                                                             
674
675                         case 'x':                       /* Creation of index file */
676                                 {
677                                         char *index = opj_optarg;
678                                         strncpy(indexfilename, index, OPJ_PATH_LEN);
679                                 }
680                                 break;
681                                 
682                                 /* ----------------------------------------------------- */
683                         case 'p': /* Force precision */
684                                 {
685                                         if (!parse_precision(opj_optarg, parameters))
686                                         {
687                                                 return 1;
688                                         }
689                                 }
690                                 break;
691                                 /* ----------------------------------------------------- */
692                         case 'FRGB': /* Force RGB output */
693                                 {
694                                         parameters->force_rgb = OPJ_TRUE;
695                                 }
696                                 break;
697                                 /* ----------------------------------------------------- */
698                                 
699                                 /* UniPG>> */
700 #ifdef USE_JPWL
701                         
702                         case 'W':                       /* activate JPWL correction */
703                         {
704                                 char *token = NULL;
705
706                                 token = strtok(opj_optarg, ",");
707                                 while(token != NULL) {
708
709                                         /* search expected number of components */
710                                         if (*token == 'c') {
711
712                                                 static int compno;
713
714                                                 compno = JPWL_EXPECTED_COMPONENTS; /* predefined no. of components */
715
716                                                 if(sscanf(token, "c=%d", &compno) == 1) {
717                                                         /* Specified */
718                                                         if ((compno < 1) || (compno > 256)) {
719                                                                 fprintf(stderr, "ERROR -> invalid number of components c = %d\n", compno);
720                                                                 return 1;
721                                                         }
722                                                         parameters->jpwl_exp_comps = compno;
723
724                                                 } else if (!strcmp(token, "c")) {
725                                                         /* default */
726                                                         parameters->jpwl_exp_comps = compno; /* auto for default size */
727
728                                                 } else {
729                                                         fprintf(stderr, "ERROR -> invalid components specified = %s\n", token);
730                                                         return 1;
731                                                 };
732                                         }
733
734                                         /* search maximum number of tiles */
735                                         if (*token == 't') {
736
737                                                 static int tileno;
738
739                                                 tileno = JPWL_MAXIMUM_TILES; /* maximum no. of tiles */
740
741                                                 if(sscanf(token, "t=%d", &tileno) == 1) {
742                                                         /* Specified */
743                                                         if ((tileno < 1) || (tileno > JPWL_MAXIMUM_TILES)) {
744                                                                 fprintf(stderr, "ERROR -> invalid number of tiles t = %d\n", tileno);
745                                                                 return 1;
746                                                         }
747                                                         parameters->jpwl_max_tiles = tileno;
748
749                                                 } else if (!strcmp(token, "t")) {
750                                                         /* default */
751                                                         parameters->jpwl_max_tiles = tileno; /* auto for default size */
752
753                                                 } else {
754                                                         fprintf(stderr, "ERROR -> invalid tiles specified = %s\n", token);
755                                                         return 1;
756                                                 };
757                                         }
758
759                                         /* next token or bust */
760                                         token = strtok(NULL, ",");
761                                 };
762                                 parameters->jpwl_correct = OPJ_TRUE;
763                                 fprintf(stdout, "JPWL correction capability activated\n");
764                                 fprintf(stdout, "- expecting %d components\n", parameters->jpwl_exp_comps);
765                         }
766                         break;  
767 #endif /* USE_JPWL */
768 /* <<UniPG */            
769
770                                 /* ----------------------------------------------------- */
771                         
772         default:
773             fprintf(stderr, "[WARNING] An invalid option has been ignored.\n");
774             break;
775                 }
776         }while(c != -1);
777
778         /* check for possible errors */
779         if(img_fol->set_imgdir==1){
780                 if(!(parameters->infile[0]==0)){
781             fprintf(stderr, "[ERROR] options -ImgDir and -i cannot be used together.\n");
782                         return 1;
783                 }
784                 if(img_fol->set_out_format == 0){
785             fprintf(stderr, "[ERROR] When -ImgDir is used, -OutFor <FORMAT> must be used.\n");
786             fprintf(stderr, "Only one format allowed.\n"
787                             "Valid format are PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA.\n");
788                         return 1;
789                 }
790                 if(!((parameters->outfile[0] == 0))){
791             fprintf(stderr, "[ERROR] options -ImgDir and -o cannot be used together.\n");
792                         return 1;
793                 }
794         }else{
795                 if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
796             fprintf(stderr, "[ERROR] Required parameters are missing\n"
797                             "Example: %s -i image.j2k -o image.pgm\n",argv[0]);
798             fprintf(stderr, "   Help: %s -h\n",argv[0]);
799                         return 1;
800                 }
801         }
802
803         return 0;
804 }
805
806 /* -------------------------------------------------------------------------- */
807 /**
808  * Parse decoding area input values
809  * separator = ","
810  */
811 /* -------------------------------------------------------------------------- */
812 int parse_DA_values( char* inArg, unsigned int *DA_x0, unsigned int *DA_y0, unsigned int *DA_x1, unsigned int *DA_y1)
813 {
814         int it = 0;
815         int values[4];
816         char delims[] = ",";
817         char *result = NULL;
818         result = strtok( inArg, delims );
819
820         while( (result != NULL) && (it < 4 ) ) {
821                 values[it] = atoi(result);
822                 result = strtok( NULL, delims );
823                 it++;
824         }
825
826         if (it != 4) {
827                 return EXIT_FAILURE;
828         }
829         else{
830                 *DA_x0 = (OPJ_UINT32)values[0]; *DA_y0 = (OPJ_UINT32)values[1];
831                 *DA_x1 = (OPJ_UINT32)values[2]; *DA_y1 = (OPJ_UINT32)values[3];
832                 return EXIT_SUCCESS;
833         }
834 }
835
836 /* -------------------------------------------------------------------------- */
837
838 /**
839 sample error callback expecting a FILE* client object
840 */
841 static void error_callback(const char *msg, void *client_data) {
842         (void)client_data;
843         fprintf(stdout, "[ERROR] %s", msg);
844 }
845 /**
846 sample warning callback expecting a FILE* client object
847 */
848 static void warning_callback(const char *msg, void *client_data) {
849         (void)client_data;
850         fprintf(stdout, "[WARNING] %s", msg);
851 }
852 /**
853 sample debug callback expecting no client object
854 */
855 static void info_callback(const char *msg, void *client_data) {
856         (void)client_data;
857         fprintf(stdout, "[INFO] %s", msg);
858 }
859
860 static void set_default_parameters(opj_decompress_parameters* parameters)
861 {
862         if (parameters) {
863                 memset(parameters, 0, sizeof(opj_decompress_parameters));
864                 
865                 /* default decoding parameters (command line specific) */
866                 parameters->decod_format = -1;
867                 parameters->cod_format = -1;
868                 
869                 /* default decoding parameters (core) */
870                 opj_set_default_decoder_parameters(&(parameters->core));
871         }
872 }
873
874 static void destroy_parameters(opj_decompress_parameters* parameters)
875 {
876         if (parameters) {
877                 if (parameters->precision) {
878                         free(parameters->precision);
879                         parameters->precision = NULL;
880                 }
881         }
882 }
883
884 /* -------------------------------------------------------------------------- */
885
886 static opj_image_t* convert_gray_to_rgb(opj_image_t* original)
887 {
888         OPJ_UINT32 compno;
889         opj_image_t* l_new_image = NULL;
890         opj_image_cmptparm_t* l_new_components = NULL;
891         
892         l_new_components = (opj_image_cmptparm_t*)malloc((original->numcomps + 2U) * sizeof(opj_image_cmptparm_t));
893         if (l_new_components == NULL) {
894                 fprintf(stderr, "ERROR -> opj_decompress: failed to allocate memory for RGB image!\n");
895                 opj_image_destroy(original);
896                 return NULL;
897         }
898         
899         l_new_components[0].bpp  = l_new_components[1].bpp  = l_new_components[2].bpp  = original->comps[0].bpp;
900         l_new_components[0].dx   = l_new_components[1].dx   = l_new_components[2].dx   = original->comps[0].dx;
901         l_new_components[0].dy   = l_new_components[1].dy   = l_new_components[2].dy   = original->comps[0].dy;
902         l_new_components[0].h    = l_new_components[1].h    = l_new_components[2].h    = original->comps[0].h;
903         l_new_components[0].w    = l_new_components[1].w    = l_new_components[2].w    = original->comps[0].w;
904         l_new_components[0].prec = l_new_components[1].prec = l_new_components[2].prec = original->comps[0].prec;
905         l_new_components[0].sgnd = l_new_components[1].sgnd = l_new_components[2].sgnd = original->comps[0].sgnd;
906         l_new_components[0].x0   = l_new_components[1].x0   = l_new_components[2].x0   = original->comps[0].x0;
907         l_new_components[0].y0   = l_new_components[1].y0   = l_new_components[2].y0   = original->comps[0].y0;
908         
909         for(compno = 1U; compno < original->numcomps; ++compno) {
910                 l_new_components[compno+2U].bpp  = original->comps[compno].bpp;
911                 l_new_components[compno+2U].dx   = original->comps[compno].dx;
912                 l_new_components[compno+2U].dy   = original->comps[compno].dy;
913                 l_new_components[compno+2U].h    = original->comps[compno].h;
914                 l_new_components[compno+2U].w    = original->comps[compno].w;
915                 l_new_components[compno+2U].prec = original->comps[compno].prec;
916                 l_new_components[compno+2U].sgnd = original->comps[compno].sgnd;
917                 l_new_components[compno+2U].x0   = original->comps[compno].x0;
918                 l_new_components[compno+2U].y0   = original->comps[compno].y0;
919         }
920         
921         l_new_image = opj_image_create(original->numcomps + 2U, l_new_components, OPJ_CLRSPC_SRGB);
922         free(l_new_components);
923         if (l_new_image == NULL) {
924                 fprintf(stderr, "ERROR -> opj_decompress: failed to allocate memory for RGB image!\n");
925                 opj_image_destroy(original);
926                 return NULL;
927         }
928         
929         l_new_image->x0 = original->x0;
930         l_new_image->x1 = original->x1;
931         l_new_image->y0 = original->y0;
932         l_new_image->y1 = original->y1;
933         
934         l_new_image->comps[0].factor        = l_new_image->comps[1].factor        = l_new_image->comps[2].factor        = original->comps[0].factor;
935         l_new_image->comps[0].alpha         = l_new_image->comps[1].alpha         = l_new_image->comps[2].alpha         = original->comps[0].alpha;
936         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;
937         
938         memcpy(l_new_image->comps[0].data, original->comps[0].data, original->comps[0].w * original->comps[0].h * sizeof(OPJ_INT32));
939         memcpy(l_new_image->comps[1].data, original->comps[0].data, original->comps[0].w * original->comps[0].h * sizeof(OPJ_INT32));
940         memcpy(l_new_image->comps[2].data, original->comps[0].data, original->comps[0].w * original->comps[0].h * sizeof(OPJ_INT32));
941         
942         for(compno = 1U; compno < original->numcomps; ++compno) {
943                 l_new_image->comps[compno+2U].factor        = original->comps[compno].factor;
944                 l_new_image->comps[compno+2U].alpha         = original->comps[compno].alpha;
945                 l_new_image->comps[compno+2U].resno_decoded = original->comps[compno].resno_decoded;
946                 memcpy(l_new_image->comps[compno+2U].data, original->comps[compno].data, original->comps[compno].w * original->comps[compno].h * sizeof(OPJ_INT32));
947         }
948         opj_image_destroy(original);
949         return l_new_image;
950 }
951
952 /* -------------------------------------------------------------------------- */
953 /**
954  * OPJ_DECOMPRESS MAIN
955  */
956 /* -------------------------------------------------------------------------- */
957 int main(int argc, char **argv)
958 {
959         opj_decompress_parameters parameters;                   /* decompression parameters */
960         opj_image_t* image = NULL;
961         opj_stream_t *l_stream = NULL;                          /* Stream */
962         opj_codec_t* l_codec = NULL;                            /* Handle to a decompressor */
963         opj_codestream_index_t* cstr_index = NULL;
964
965         char indexfilename[OPJ_PATH_LEN];       /* index file name */
966
967         OPJ_INT32 num_images, imageno;
968         img_fol_t img_fol;
969         dircnt_t *dirptr = NULL;
970   int failed = 0;
971
972         /* set decoding parameters to default values */
973         set_default_parameters(&parameters);
974
975         /* FIXME Initialize indexfilename and img_fol */
976         *indexfilename = 0;
977
978         /* Initialize img_fol */
979         memset(&img_fol,0,sizeof(img_fol_t));
980
981         /* parse input and get user encoding parameters */
982         if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {
983                 destroy_parameters(&parameters);
984                 return EXIT_FAILURE;
985         }
986
987         /* Initialize reading of directory */
988         if(img_fol.set_imgdir==1){      
989                 int it_image;
990                 num_images=get_num_images(img_fol.imgdirpath);
991
992                 dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
993                 if(dirptr){
994                         dirptr->filename_buf = (char*)malloc((size_t)num_images*OPJ_PATH_LEN*sizeof(char));     /* Stores at max 10 image file names*/
995                         dirptr->filename = (char**) malloc((size_t)num_images*sizeof(char*));
996
997                         if(!dirptr->filename_buf){
998                                 destroy_parameters(&parameters);
999                                 return EXIT_FAILURE;
1000                         }
1001                         for(it_image=0;it_image<num_images;it_image++){
1002                                 dirptr->filename[it_image] = dirptr->filename_buf + it_image*OPJ_PATH_LEN;
1003                         }
1004                 }
1005                 if(load_images(dirptr,img_fol.imgdirpath)==1){
1006                         destroy_parameters(&parameters);
1007                         return EXIT_FAILURE;
1008                 }
1009                 if (num_images==0){
1010                         fprintf(stdout,"Folder is empty\n");
1011                         destroy_parameters(&parameters);
1012                         return EXIT_FAILURE;
1013                 }
1014         }else{
1015                 num_images=1;
1016         }
1017
1018         /*Decoding image one by one*/
1019         for(imageno = 0; imageno < num_images ; imageno++)      {
1020
1021                 fprintf(stderr,"\n");
1022
1023                 if(img_fol.set_imgdir==1){
1024                         if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
1025                                 fprintf(stderr,"skipping file...\n");
1026                                 destroy_parameters(&parameters);
1027                                 continue;
1028                         }
1029                 }
1030
1031                 /* read the input file and put it in memory */
1032                 /* ---------------------------------------- */
1033
1034                 l_stream = opj_stream_create_default_file_stream(parameters.infile,1);
1035                 if (!l_stream){
1036                         fprintf(stderr, "ERROR -> failed to create the stream from the file %s\n", parameters.infile);
1037                         destroy_parameters(&parameters);
1038                         return EXIT_FAILURE;
1039                 }
1040
1041                 /* decode the JPEG2000 stream */
1042                 /* ---------------------- */
1043
1044                 switch(parameters.decod_format) {
1045                         case J2K_CFMT:  /* JPEG-2000 codestream */
1046                         {
1047                                 /* Get a decoder handle */
1048                                 l_codec = opj_create_decompress(OPJ_CODEC_J2K);
1049                                 break;
1050                         }
1051                         case JP2_CFMT:  /* JPEG 2000 compressed image data */
1052                         {
1053                                 /* Get a decoder handle */
1054                                 l_codec = opj_create_decompress(OPJ_CODEC_JP2);
1055                                 break;
1056                         }
1057                         case JPT_CFMT:  /* JPEG 2000, JPIP */
1058                         {
1059                                 /* Get a decoder handle */
1060                                 l_codec = opj_create_decompress(OPJ_CODEC_JPT);
1061                                 break;
1062                         }
1063                         default:
1064                                 fprintf(stderr, "skipping file..\n");
1065                                 destroy_parameters(&parameters);
1066                                 opj_stream_destroy(l_stream);
1067                                 continue;
1068                 }
1069
1070                 /* catch events using our callbacks and give a local context */         
1071                 opj_set_info_handler(l_codec, info_callback,00);
1072                 opj_set_warning_handler(l_codec, warning_callback,00);
1073                 opj_set_error_handler(l_codec, error_callback,00);
1074
1075                 /* Setup the decoder decoding parameters using user parameters */
1076                 if ( !opj_setup_decoder(l_codec, &(parameters.core)) ){
1077                         fprintf(stderr, "ERROR -> opj_compress: failed to setup the decoder\n");
1078                         destroy_parameters(&parameters);
1079                         opj_stream_destroy(l_stream);
1080                         opj_destroy_codec(l_codec);
1081                         return EXIT_FAILURE;
1082                 }
1083
1084
1085                 /* Read the main header of the codestream and if necessary the JP2 boxes*/
1086                 if(! opj_read_header(l_stream, l_codec, &image)){
1087                         fprintf(stderr, "ERROR -> opj_decompress: failed to read the header\n");
1088                         destroy_parameters(&parameters);
1089                         opj_stream_destroy(l_stream);
1090                         opj_destroy_codec(l_codec);
1091                         opj_image_destroy(image);
1092                         return EXIT_FAILURE;
1093                 }
1094
1095                 if (!parameters.nb_tile_to_decode) {
1096                         /* Optional if you want decode the entire image */
1097                         if (!opj_set_decode_area(l_codec, image, (OPJ_INT32)parameters.DA_x0,
1098                                         (OPJ_INT32)parameters.DA_y0, (OPJ_INT32)parameters.DA_x1, (OPJ_INT32)parameters.DA_y1)){
1099                                 fprintf(stderr, "ERROR -> opj_decompress: failed to set the decoded area\n");
1100                                 destroy_parameters(&parameters);
1101                                 opj_stream_destroy(l_stream);
1102                                 opj_destroy_codec(l_codec);
1103                                 opj_image_destroy(image);
1104                                 return EXIT_FAILURE;
1105                         }
1106
1107                         /* Get the decoded image */
1108                         if (!(opj_decode(l_codec, l_stream, image) && opj_end_decompress(l_codec,       l_stream))) {
1109                                 fprintf(stderr,"ERROR -> opj_decompress: failed to decode image!\n");
1110                                 destroy_parameters(&parameters);
1111                                 opj_destroy_codec(l_codec);
1112                                 opj_stream_destroy(l_stream);
1113                                 opj_image_destroy(image);
1114                                 return EXIT_FAILURE;
1115                         }
1116                 }
1117                 else {
1118
1119                         /* It is just here to illustrate how to use the resolution after set parameters */
1120                         /*if (!opj_set_decoded_resolution_factor(l_codec, 5)) {
1121                                 fprintf(stderr, "ERROR -> opj_decompress: failed to set the resolution factor tile!\n");
1122                                 opj_destroy_codec(l_codec);
1123                                 opj_stream_destroy(l_stream);
1124                                 opj_image_destroy(image);
1125                                 return EXIT_FAILURE;
1126                         }*/
1127
1128                         if (!opj_get_decoded_tile(l_codec, l_stream, image, parameters.tile_index)) {
1129                                 fprintf(stderr, "ERROR -> opj_decompress: failed to decode tile!\n");
1130                                 destroy_parameters(&parameters);
1131                                 opj_destroy_codec(l_codec);
1132                                 opj_stream_destroy(l_stream);
1133                                 opj_image_destroy(image);
1134                                 return EXIT_FAILURE;
1135                         }
1136                         fprintf(stdout, "tile %d is decoded!\n\n", parameters.tile_index);
1137                 }
1138
1139                 /* Close the byte stream */
1140                 opj_stream_destroy(l_stream);
1141
1142                 if(image->color_space == OPJ_CLRSPC_SYCC){
1143                         color_sycc_to_rgb(image); /* FIXME */
1144                 }
1145                 
1146                 if( image->color_space != OPJ_CLRSPC_SYCC 
1147                         && image->numcomps == 3 && image->comps[0].dx == image->comps[0].dy
1148                         && image->comps[1].dx != 1 )
1149                         image->color_space = OPJ_CLRSPC_SYCC;
1150                 else if (image->numcomps <= 2)
1151                         image->color_space = OPJ_CLRSPC_GRAY;
1152
1153                 if(image->icc_profile_buf) {
1154 #if defined(OPJ_HAVE_LIBLCMS1) || defined(OPJ_HAVE_LIBLCMS2)
1155                         color_apply_icc_profile(image); /* FIXME */
1156 #endif
1157                         free(image->icc_profile_buf);
1158                         image->icc_profile_buf = NULL; image->icc_profile_len = 0;
1159                 }
1160                 
1161                 /* Force output precision */
1162                 /* ---------------------- */
1163                 if (parameters.precision != NULL)
1164                 {
1165                         OPJ_UINT32 compno;
1166                         for (compno = 0; compno < image->numcomps; ++compno)
1167                         {
1168                                 OPJ_UINT32 precno = compno;
1169                                 OPJ_UINT32 prec;
1170                                 
1171                                 if (precno >= parameters.nb_precision) {
1172                                         precno = parameters.nb_precision - 1U;
1173                                 }
1174                                 
1175                                 prec = parameters.precision[precno].prec;
1176                                 if (prec == 0) {
1177                                         prec = image->comps[compno].prec;
1178                                 }
1179                                 
1180                                 switch (parameters.precision[precno].mode) {
1181                                         case OPJ_PREC_MODE_CLIP:
1182                                                 clip_component(&(image->comps[compno]), prec);
1183                                                 break;
1184                                         case OPJ_PREC_MODE_SCALE:
1185                                                 scale_component(&(image->comps[compno]), prec);
1186                                                 break;
1187                                         default:
1188                                                 break;
1189                                 }
1190                                 
1191                         }
1192                 }
1193                 
1194                 /* Force RGB output */
1195                 /* ---------------- */
1196                 if (parameters.force_rgb)
1197                 {
1198                         switch (image->color_space) {
1199                                 case OPJ_CLRSPC_SRGB:
1200                                         break;
1201                                 case OPJ_CLRSPC_GRAY:
1202                                         image = convert_gray_to_rgb(image);
1203                                         break;
1204                                 default:
1205                                         fprintf(stderr, "ERROR -> opj_decompress: don't know how to convert image to RGB colorspace!\n");
1206                                         opj_image_destroy(image);
1207                                         image = NULL;
1208                                         break;
1209                         }
1210                         if (image == NULL) {
1211                                 fprintf(stderr, "ERROR -> opj_decompress: failed to convert to RGB image!\n");
1212                                 destroy_parameters(&parameters);
1213                                 opj_destroy_codec(l_codec);
1214                                 opj_stream_destroy(l_stream);
1215                                 return EXIT_FAILURE;
1216                         }
1217                 }
1218
1219                 /* create output image */
1220                 /* ------------------- */
1221                 switch (parameters.cod_format) {
1222                 case PXM_DFMT:                  /* PNM PGM PPM */
1223                         if (imagetopnm(image, parameters.outfile)) {
1224                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1225         failed = 1;
1226                         }
1227                         else {
1228                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1229                         }
1230                         break;
1231
1232                 case PGX_DFMT:                  /* PGX */
1233                         if(imagetopgx(image, parameters.outfile)){
1234                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1235         failed = 1;
1236                         }
1237                         else {
1238                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1239                         }
1240                         break;
1241
1242                 case BMP_DFMT:                  /* BMP */
1243                         if(imagetobmp(image, parameters.outfile)){
1244                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1245         failed = 1;
1246                         }
1247                         else {
1248                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1249                         }
1250                         break;
1251 #ifdef OPJ_HAVE_LIBTIFF
1252                 case TIF_DFMT:                  /* TIFF */
1253                         if(imagetotif(image, parameters.outfile)){
1254                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1255         failed = 1;
1256                         }
1257                         else {
1258                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1259                         }
1260                         break;
1261 #endif /* OPJ_HAVE_LIBTIFF */
1262                 case RAW_DFMT:                  /* RAW */
1263                         if(imagetoraw(image, parameters.outfile)){
1264                 fprintf(stderr,"[ERROR] Error generating raw file. Outfile %s not generated\n",parameters.outfile);
1265         failed = 1;
1266                         }
1267                         else {
1268                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1269                         }
1270                         break;
1271
1272                 case RAWL_DFMT:                 /* RAWL */
1273                         if(imagetorawl(image, parameters.outfile)){
1274                 fprintf(stderr,"[ERROR] Error generating rawl file. Outfile %s not generated\n",parameters.outfile);
1275         failed = 1;
1276                         }
1277                         else {
1278                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1279                         }
1280                         break;
1281
1282                 case TGA_DFMT:                  /* TGA */
1283                         if(imagetotga(image, parameters.outfile)){
1284                 fprintf(stderr,"[ERROR] Error generating tga file. Outfile %s not generated\n",parameters.outfile);
1285         failed = 1;
1286                         }
1287                         else {
1288                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1289                         }
1290                         break;
1291 #ifdef OPJ_HAVE_LIBPNG
1292                 case PNG_DFMT:                  /* PNG */
1293                         if(imagetopng(image, parameters.outfile)){
1294                 fprintf(stderr,"[ERROR] Error generating png file. Outfile %s not generated\n",parameters.outfile);
1295         failed = 1;
1296                         }
1297                         else {
1298                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1299                         }
1300                         break;
1301 #endif /* OPJ_HAVE_LIBPNG */
1302 /* Can happen if output file is TIFF or PNG
1303  * and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined
1304 */
1305                         default:
1306                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1307         failed = 1;
1308                 }
1309
1310                 /* free remaining structures */
1311                 if (l_codec) {
1312                         opj_destroy_codec(l_codec);
1313                 }
1314
1315
1316                 /* free image data structure */
1317                 opj_image_destroy(image);
1318
1319                 /* destroy the codestream index */
1320                 opj_destroy_cstr_index(&cstr_index);
1321
1322                 if(failed) remove(parameters.outfile);
1323         }
1324         destroy_parameters(&parameters);
1325         return failed ? EXIT_FAILURE : EXIT_SUCCESS;
1326 }
1327 /*end main*/