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