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