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