[trunk] Properly handle failure to compress (remove file)
[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 /* -------------------------------------------------------------------------- */
97 /* Declarations                                                               */
98 int get_num_images(char *imgdirpath);
99 int load_images(dircnt_t *dirptr, char *imgdirpath);
100 int get_file_format(const char *filename);
101 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters);
102 static int infile_format(const char *fname);
103
104 int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol, char *indexfilename);
105 int parse_DA_values( char* inArg, unsigned int *DA_x0, unsigned int *DA_y0, unsigned int *DA_x1, unsigned int *DA_y1);
106
107 /* -------------------------------------------------------------------------- */
108 static void decode_help_display(void) {
109     fprintf(stdout,"\nThis is the opj_decompress utility from the OpenJPEG project.\n"
110             "It decompresses JPEG 2000 codestreams to various image formats.\n"
111             "It has been compiled against openjp2 library v%s.\n\n",opj_version());
112
113     fprintf(stdout,"Parameters:\n");
114     fprintf(stdout,"-----------\n");
115         fprintf(stdout,"\n");
116     fprintf(stdout,"  -ImgDir <directory> \n");
117         fprintf(stdout,"        Image file Directory path \n");
118     fprintf(stdout,"  -OutFor <PBM|PGM|PPM|PNM|PAM|PGX|PNG|BMP|TIF|RAW|RAWL|TGA>\n");
119         fprintf(stdout,"    REQUIRED only if -ImgDir is used\n");
120     fprintf(stdout,"    Output format for decompressed images.\n");
121         fprintf(stdout,"  -i <compressed file>\n");
122     fprintf(stdout,"    REQUIRED only if an Input image directory is not specified\n");
123         fprintf(stdout,"    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n");
124         fprintf(stdout,"    is identified based on its suffix.\n");
125         fprintf(stdout,"  -o <decompressed file>\n");
126         fprintf(stdout,"    REQUIRED\n");
127     fprintf(stdout,"    Currently accepts formats specified above (see OutFor option)\n");
128         fprintf(stdout,"    Binary data is written to the file (not ascii). If a PGX\n");
129         fprintf(stdout,"    filename is given, there will be as many output files as there are\n");
130         fprintf(stdout,"    components: an indice starting from 0 will then be appended to the\n");
131         fprintf(stdout,"    output filename, just before the \"pgx\" extension. If a PGM filename\n");
132         fprintf(stdout,"    is given and there are more than one component, only the first component\n");
133         fprintf(stdout,"    will be written to the file.\n");
134         fprintf(stdout,"  -r <reduce factor>\n");
135         fprintf(stdout,"    Set the number of highest resolution levels to be discarded. The\n");
136         fprintf(stdout,"    image resolution is effectively divided by 2 to the power of the\n");
137         fprintf(stdout,"    number of discarded levels. The reduce factor is limited by the\n");
138         fprintf(stdout,"    smallest total number of decomposition levels among tiles.\n");
139         fprintf(stdout,"  -l <number of quality layers to decode>\n");
140         fprintf(stdout,"    Set the maximum number of quality layers to decode. If there are\n");
141         fprintf(stdout,"    less quality layers than the specified number, all the quality layers\n");
142         fprintf(stdout,"    are decoded.\n");
143         fprintf(stdout,"  -x  \n"); 
144         fprintf(stdout,"    Create an index file *.Idx (-x index_name.Idx) \n");
145         fprintf(stdout,"  -d <x0,y0,x1,y1>\n");
146         fprintf(stdout,"    OPTIONAL\n");
147         fprintf(stdout,"    Decoding area\n");
148         fprintf(stdout,"    By default all the image is decoded.\n");
149         fprintf(stdout,"  -t <tile_number>\n");
150         fprintf(stdout,"    OPTIONAL\n");
151         fprintf(stdout,"    Set the tile number of the decoded tile. Follow the JPEG2000 convention from left-up to bottom-up\n");
152         fprintf(stdout,"    By default all tiles are decoded.\n");
153         fprintf(stdout,"\n");
154 /* UniPG>> */
155 #ifdef USE_JPWL
156         fprintf(stdout,"  -W <options>\n");
157         fprintf(stdout,"    Activates the JPWL correction capability, if the codestream complies.\n");
158         fprintf(stdout,"    Options can be a comma separated list of <param=val> tokens:\n");
159         fprintf(stdout,"    c, c=numcomps\n");
160         fprintf(stdout,"       numcomps is the number of expected components in the codestream\n");
161         fprintf(stdout,"       (search of first EPB rely upon this, default is %d)\n", JPWL_EXPECTED_COMPONENTS);
162 #endif /* USE_JPWL */
163 /* <<UniPG */
164         fprintf(stdout,"\n");
165 }
166
167 /* -------------------------------------------------------------------------- */
168
169 int get_num_images(char *imgdirpath){
170         DIR *dir;
171         struct dirent* content; 
172         int num_images = 0;
173
174         /*Reading the input images from given input directory*/
175
176         dir= opendir(imgdirpath);
177         if(!dir){
178                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
179                 return 0;
180         }
181         
182         while((content=readdir(dir))!=NULL){
183                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
184                         continue;
185                 num_images++;
186         }
187         return num_images;
188 }
189
190 /* -------------------------------------------------------------------------- */
191 int load_images(dircnt_t *dirptr, char *imgdirpath){
192         DIR *dir;
193         struct dirent* content; 
194         int i = 0;
195
196         /*Reading the input images from given input directory*/
197
198         dir= opendir(imgdirpath);
199         if(!dir){
200                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
201                 return 1;
202         }else   {
203                 fprintf(stderr,"Folder opened successfully\n");
204         }
205         
206         while((content=readdir(dir))!=NULL){
207                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
208                         continue;
209
210                 strcpy(dirptr->filename[i],content->d_name);
211                 i++;
212         }
213         return 0;       
214 }
215
216 /* -------------------------------------------------------------------------- */
217 int get_file_format(const char *filename) {
218         unsigned int i;
219         static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "rawl", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc" };
220         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 };
221         char * ext = strrchr(filename, '.');
222         if (ext == NULL)
223                 return -1;
224         ext++;
225         if(*ext) {
226                 for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
227                         if(strcasecmp(ext, extension[i]) == 0) {
228                                 return format[i];
229                         }
230                 }
231         }
232
233         return -1;
234 }
235
236 /* -------------------------------------------------------------------------- */
237 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters){
238         char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
239         char *temp_p, temp1[OPJ_PATH_LEN]="";
240
241         strcpy(image_filename,dirptr->filename[imageno]);
242         fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
243         parameters->decod_format = infile_format(image_filename);
244         if (parameters->decod_format == -1)
245                 return 1;
246         sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
247         strncpy(parameters->infile, infilename, sizeof(infilename));
248
249         /*Set output file*/
250         strcpy(temp_ofname,strtok(image_filename,"."));
251         while((temp_p = strtok(NULL,".")) != NULL){
252                 strcat(temp_ofname,temp1);
253                 sprintf(temp1,".%s",temp_p);
254         }
255         if(img_fol->set_out_format==1){
256                 sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
257                 strncpy(parameters->outfile, outfilename, sizeof(outfilename));
258         }
259         return 0;
260 }
261
262 /* -------------------------------------------------------------------------- */
263 #define JP2_RFC3745_MAGIC "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a"
264 #define JP2_MAGIC "\x0d\x0a\x87\x0a"
265 /* position 45: "\xff\x52" */
266 #define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51"
267
268 static int infile_format(const char *fname)
269 {
270         FILE *reader;
271         const char *s, *magic_s;
272         int ext_format, magic_format;
273         unsigned char buf[12];
274         OPJ_SIZE_T l_nb_read;
275
276         reader = fopen(fname, "rb");
277
278         if (reader == NULL)
279                 return -2;
280
281         memset(buf, 0, 12);
282         l_nb_read = fread(buf, 1, 12, reader);
283         fclose(reader);
284         if (l_nb_read != 12)
285                 return -1;
286
287
288
289         ext_format = get_file_format(fname);
290
291         if (ext_format == JPT_CFMT)
292                 return JPT_CFMT;
293
294         if (memcmp(buf, JP2_RFC3745_MAGIC, 12) == 0 || memcmp(buf, JP2_MAGIC, 4) == 0) {
295                 magic_format = JP2_CFMT;
296                 magic_s = ".jp2";
297         }
298         else if (memcmp(buf, J2K_CODESTREAM_MAGIC, 4) == 0) {
299                 magic_format = J2K_CFMT;
300                 magic_s = ".j2k or .jpc or .j2c";
301         }
302         else
303                 return -1;
304
305         if (magic_format == ext_format)
306                 return ext_format;
307
308         s = fname + strlen(fname) - 4;
309
310         fputs("\n===========================================\n", stderr);
311         fprintf(stderr, "The extension of this file is incorrect.\n"
312                                         "FOUND %s. SHOULD BE %s\n", s, magic_s);
313         fputs("===========================================\n", stderr);
314
315         return magic_format;
316 }
317
318 /* -------------------------------------------------------------------------- */
319 /**
320  * Parse the command line
321  */
322 /* -------------------------------------------------------------------------- */
323 int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol, char *indexfilename) {
324         /* parse the command line */
325         int totlen, c;
326         opj_option_t long_option[]={
327                 {"ImgDir",REQ_ARG, NULL ,'y'},
328         {"OutFor",REQ_ARG, NULL ,'O'}
329         };
330
331         const char optlist[] = "i:o:r:l:x:d:t:"
332
333 /* UniPG>> */
334 #ifdef USE_JPWL
335                                         "W:"
336 #endif /* USE_JPWL */
337 /* <<UniPG */
338             "h"         ;
339         totlen=sizeof(long_option);
340         img_fol->set_out_format = 0;
341         do {
342                 c = opj_getopt_long(argc, argv,optlist,long_option,totlen);
343                 if (c == -1)
344                         break;
345                 switch (c) {
346                         case 'i':                       /* input file */
347                         {
348                                 char *infile = opj_optarg;
349                                 parameters->decod_format = infile_format(infile);
350                                 switch(parameters->decod_format) {
351                                         case J2K_CFMT:
352                                                 break;
353                                         case JP2_CFMT:
354                                                 break;
355                                         case JPT_CFMT:
356                                                 break;
357                                         case -2:
358                                                 fprintf(stderr, 
359                                                         "!! infile cannot be read: %s !!\n\n", 
360                                                         infile);
361                                                 return 1;
362                                         default:
363                                                 fprintf(stderr, 
364                             "[ERROR] Unknown input file format: %s \n"
365                             "        Known file formats are *.j2k, *.jp2, *.jpc or *.jpt\n",
366                                                         infile);
367                                                 return 1;
368                                 }
369                                 strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
370                         }
371                         break;
372                                 
373                                 /* ----------------------------------------------------- */
374
375                         case 'o':                       /* output file */
376                         {
377                                 char *outfile = opj_optarg;
378                                 parameters->cod_format = get_file_format(outfile);
379                                 switch(parameters->cod_format) {
380                                         case PGX_DFMT:
381                                                 break;
382                                         case PXM_DFMT:
383                                                 break;
384                                         case BMP_DFMT:
385                                                 break;
386                                         case TIF_DFMT:
387                                                 break;
388                                         case RAW_DFMT:
389                                                 break;
390                                         case RAWL_DFMT:
391                                                 break;
392                                         case TGA_DFMT:
393                                                 break;
394                                         case PNG_DFMT:
395                                                 break;
396                                         default:
397                                                 fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outfile);
398                                                 return 1;
399                                 }
400                                 strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);
401                         }
402                         break;
403                         
404                                 /* ----------------------------------------------------- */
405
406                         case 'O':                       /* output format */
407                         {
408                                 char outformat[50];
409                                 char *of = opj_optarg;
410                                 sprintf(outformat,".%s",of);
411                                 img_fol->set_out_format = 1;
412                                 parameters->cod_format = get_file_format(outformat);
413                                 switch(parameters->cod_format) {
414                                         case PGX_DFMT:
415                                                 img_fol->out_format = "pgx";
416                                                 break;
417                                         case PXM_DFMT:
418                                                 img_fol->out_format = "ppm";
419                                                 break;
420                                         case BMP_DFMT:
421                                                 img_fol->out_format = "bmp";
422                                                 break;
423                                         case TIF_DFMT:
424                                                 img_fol->out_format = "tif";
425                                                 break;
426                                         case RAW_DFMT:
427                                                 img_fol->out_format = "raw";
428                                                 break;
429                                         case RAWL_DFMT:
430                                                 img_fol->out_format = "rawl";
431                                                 break;
432                                         case TGA_DFMT:
433                                                 img_fol->out_format = "raw";
434                                                 break;
435                                         case PNG_DFMT:
436                                                 img_fol->out_format = "png";
437                                                 break;
438                                         default:
439                                                 fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outformat);
440                                                 return 1;
441                                                 break;
442                                 }
443                         }
444                         break;
445
446                                 /* ----------------------------------------------------- */
447
448
449                         case 'r':               /* reduce option */
450                         {
451                                 sscanf(opj_optarg, "%ud", &parameters->cp_reduce);
452                         }
453                         break;
454                         
455                                 /* ----------------------------------------------------- */
456       
457
458                         case 'l':               /* layering option */
459                         {
460                                 sscanf(opj_optarg, "%ud", &parameters->cp_layer);
461                         }
462                         break;
463                         
464                                 /* ----------------------------------------------------- */
465
466                         case 'h':                       /* display an help description */
467                                 decode_help_display();
468                                 return 1;                               
469
470             /* ----------------------------------------------------- */
471
472                         case 'y':                       /* Image Directory path */
473                 {
474                                         img_fol->imgdirpath = (char*)malloc(strlen(opj_optarg) + 1);
475                                         strcpy(img_fol->imgdirpath,opj_optarg);
476                                         img_fol->set_imgdir=1;
477                                 }
478                                 break;
479
480                                 /* ----------------------------------------------------- */
481
482                         case 'd':               /* Input decode ROI */
483                         {
484                                 int size_optarg = (int)strlen(opj_optarg) + 1;
485                                 char *ROI_values = (char*) malloc((size_t)size_optarg);
486                                 ROI_values[0] = '\0';
487                                 strncpy(ROI_values, opj_optarg, strlen(opj_optarg));
488                                 ROI_values[strlen(opj_optarg)] = '\0';
489                                 /*printf("ROI_values = %s [%d / %d]\n", ROI_values, strlen(ROI_values), size_optarg ); */
490                                 parse_DA_values( ROI_values, &parameters->DA_x0, &parameters->DA_y0, &parameters->DA_x1, &parameters->DA_y1);
491
492                                 free(ROI_values);
493                         }
494                         break;
495
496                         /* ----------------------------------------------------- */
497
498                         case 't':               /* Input tile index */
499                         {
500                                 sscanf(opj_optarg, "%ud", &parameters->tile_index);
501                                 parameters->nb_tile_to_decode = 1;
502                         }
503                         break;
504
505                                 /* ----------------------------------------------------- */                                                             
506
507                         case 'x':                       /* Creation of index file */
508                                 {
509                                         char *index = opj_optarg;
510                                         strncpy(indexfilename, index, OPJ_PATH_LEN);
511                                 }
512                                 break;
513                                 /* ----------------------------------------------------- */
514                                 /* UniPG>> */
515 #ifdef USE_JPWL
516                         
517                         case 'W':                       /* activate JPWL correction */
518                         {
519                                 char *token = NULL;
520
521                                 token = strtok(opj_optarg, ",");
522                                 while(token != NULL) {
523
524                                         /* search expected number of components */
525                                         if (*token == 'c') {
526
527                                                 static int compno;
528
529                                                 compno = JPWL_EXPECTED_COMPONENTS; /* predefined no. of components */
530
531                                                 if(sscanf(token, "c=%d", &compno) == 1) {
532                                                         /* Specified */
533                                                         if ((compno < 1) || (compno > 256)) {
534                                                                 fprintf(stderr, "ERROR -> invalid number of components c = %d\n", compno);
535                                                                 return 1;
536                                                         }
537                                                         parameters->jpwl_exp_comps = compno;
538
539                                                 } else if (!strcmp(token, "c")) {
540                                                         /* default */
541                                                         parameters->jpwl_exp_comps = compno; /* auto for default size */
542
543                                                 } else {
544                                                         fprintf(stderr, "ERROR -> invalid components specified = %s\n", token);
545                                                         return 1;
546                                                 };
547                                         }
548
549                                         /* search maximum number of tiles */
550                                         if (*token == 't') {
551
552                                                 static int tileno;
553
554                                                 tileno = JPWL_MAXIMUM_TILES; /* maximum no. of tiles */
555
556                                                 if(sscanf(token, "t=%d", &tileno) == 1) {
557                                                         /* Specified */
558                                                         if ((tileno < 1) || (tileno > JPWL_MAXIMUM_TILES)) {
559                                                                 fprintf(stderr, "ERROR -> invalid number of tiles t = %d\n", tileno);
560                                                                 return 1;
561                                                         }
562                                                         parameters->jpwl_max_tiles = tileno;
563
564                                                 } else if (!strcmp(token, "t")) {
565                                                         /* default */
566                                                         parameters->jpwl_max_tiles = tileno; /* auto for default size */
567
568                                                 } else {
569                                                         fprintf(stderr, "ERROR -> invalid tiles specified = %s\n", token);
570                                                         return 1;
571                                                 };
572                                         }
573
574                                         /* next token or bust */
575                                         token = strtok(NULL, ",");
576                                 };
577                                 parameters->jpwl_correct = OPJ_TRUE;
578                                 fprintf(stdout, "JPWL correction capability activated\n");
579                                 fprintf(stdout, "- expecting %d components\n", parameters->jpwl_exp_comps);
580                         }
581                         break;  
582 #endif /* USE_JPWL */
583 /* <<UniPG */            
584
585                                 /* ----------------------------------------------------- */
586                         
587         default:
588             fprintf(stderr, "[WARNING] An invalid option has been ignored.\n");
589             break;
590                 }
591         }while(c != -1);
592
593         /* check for possible errors */
594         if(img_fol->set_imgdir==1){
595                 if(!(parameters->infile[0]==0)){
596             fprintf(stderr, "[ERROR] options -ImgDir and -i cannot be used together.\n");
597                         return 1;
598                 }
599                 if(img_fol->set_out_format == 0){
600             fprintf(stderr, "[ERROR] When -ImgDir is used, -OutFor <FORMAT> must be used.\n");
601             fprintf(stderr, "Only one format allowed.\n"
602                             "Valid format are PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA.\n");
603                         return 1;
604                 }
605                 if(!((parameters->outfile[0] == 0))){
606             fprintf(stderr, "[ERROR] options -ImgDir and -o cannot be used together.\n");
607                         return 1;
608                 }
609         }else{
610                 if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
611             fprintf(stderr, "[ERROR] Required parameters are missing\n"
612                             "Example: %s -i image.j2k -o image.pgm\n",argv[0]);
613             fprintf(stderr, "   Help: %s -h\n",argv[0]);
614                         return 1;
615                 }
616         }
617
618         return 0;
619 }
620
621 /* -------------------------------------------------------------------------- */
622 /**
623  * Parse decoding area input values
624  * separator = ","
625  */
626 /* -------------------------------------------------------------------------- */
627 int parse_DA_values( char* inArg, unsigned int *DA_x0, unsigned int *DA_y0, unsigned int *DA_x1, unsigned int *DA_y1)
628 {
629         int it = 0;
630         int values[4];
631         char delims[] = ",";
632         char *result = NULL;
633         result = strtok( inArg, delims );
634
635         while( (result != NULL) && (it < 4 ) ) {
636                 values[it] = atoi(result);
637                 result = strtok( NULL, delims );
638                 it++;
639         }
640
641         if (it != 4) {
642                 return EXIT_FAILURE;
643         }
644         else{
645                 *DA_x0 = (OPJ_UINT32)values[0]; *DA_y0 = (OPJ_UINT32)values[1];
646                 *DA_x1 = (OPJ_UINT32)values[2]; *DA_y1 = (OPJ_UINT32)values[3];
647                 return EXIT_SUCCESS;
648         }
649 }
650
651 /* -------------------------------------------------------------------------- */
652
653 /**
654 sample error callback expecting a FILE* client object
655 */
656 static void error_callback(const char *msg, void *client_data) {
657         (void)client_data;
658         fprintf(stdout, "[ERROR] %s", msg);
659 }
660 /**
661 sample warning callback expecting a FILE* client object
662 */
663 static void warning_callback(const char *msg, void *client_data) {
664         (void)client_data;
665         fprintf(stdout, "[WARNING] %s", msg);
666 }
667 /**
668 sample debug callback expecting no client object
669 */
670 static void info_callback(const char *msg, void *client_data) {
671         (void)client_data;
672         fprintf(stdout, "[INFO] %s", msg);
673 }
674
675 /* -------------------------------------------------------------------------- */
676 /**
677  * OPJ_DECOMPRESS MAIN
678  */
679 /* -------------------------------------------------------------------------- */
680 int main(int argc, char **argv)
681 {
682         opj_dparameters_t parameters;                   /* decompression parameters */
683         opj_image_t* image = NULL;
684         opj_stream_t *l_stream = NULL;                          /* Stream */
685         opj_codec_t* l_codec = NULL;                            /* Handle to a decompressor */
686         opj_codestream_index_t* cstr_index = NULL;
687
688         char indexfilename[OPJ_PATH_LEN];       /* index file name */
689
690         OPJ_INT32 num_images, imageno;
691         img_fol_t img_fol;
692         dircnt_t *dirptr = NULL;
693   int failed = 0;
694
695         /* set decoding parameters to default values */
696         opj_set_default_decoder_parameters(&parameters);
697
698         /* FIXME Initialize indexfilename and img_fol */
699         *indexfilename = 0;
700
701         /* Initialize img_fol */
702         memset(&img_fol,0,sizeof(img_fol_t));
703
704         /* parse input and get user encoding parameters */
705         if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {
706                 return EXIT_FAILURE;
707         }
708
709         /* Initialize reading of directory */
710         if(img_fol.set_imgdir==1){      
711                 int it_image;
712                 num_images=get_num_images(img_fol.imgdirpath);
713
714                 dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
715                 if(dirptr){
716                         dirptr->filename_buf = (char*)malloc((size_t)num_images*OPJ_PATH_LEN*sizeof(char));     /* Stores at max 10 image file names*/
717                         dirptr->filename = (char**) malloc((size_t)num_images*sizeof(char*));
718
719                         if(!dirptr->filename_buf){
720                                 return EXIT_FAILURE;
721                         }
722                         for(it_image=0;it_image<num_images;it_image++){
723                                 dirptr->filename[it_image] = dirptr->filename_buf + it_image*OPJ_PATH_LEN;
724                         }
725                 }
726                 if(load_images(dirptr,img_fol.imgdirpath)==1){
727                         return EXIT_FAILURE;
728                 }
729                 if (num_images==0){
730                         fprintf(stdout,"Folder is empty\n");
731                         return EXIT_FAILURE;
732                 }
733         }else{
734                 num_images=1;
735         }
736
737         /*Decoding image one by one*/
738         for(imageno = 0; imageno < num_images ; imageno++)      {
739
740                 fprintf(stderr,"\n");
741
742                 if(img_fol.set_imgdir==1){
743                         if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
744                                 fprintf(stderr,"skipping file...\n");
745                                 continue;
746                         }
747                 }
748
749                 /* read the input file and put it in memory */
750                 /* ---------------------------------------- */
751
752                 l_stream = opj_stream_create_default_file_stream(parameters.infile,1);
753                 if (!l_stream){
754                         fprintf(stderr, "ERROR -> failed to create the stream from the file %s\n", parameters.infile);
755                         return EXIT_FAILURE;
756                 }
757
758                 /* decode the JPEG2000 stream */
759                 /* ---------------------- */
760
761                 switch(parameters.decod_format) {
762                         case J2K_CFMT:  /* JPEG-2000 codestream */
763                         {
764                                 /* Get a decoder handle */
765                                 l_codec = opj_create_decompress(OPJ_CODEC_J2K);
766                                 break;
767                         }
768                         case JP2_CFMT:  /* JPEG 2000 compressed image data */
769                         {
770                                 /* Get a decoder handle */
771                                 l_codec = opj_create_decompress(OPJ_CODEC_JP2);
772                                 break;
773                         }
774                         case JPT_CFMT:  /* JPEG 2000, JPIP */
775                         {
776                                 /* Get a decoder handle */
777                                 l_codec = opj_create_decompress(OPJ_CODEC_JPT);
778                                 break;
779                         }
780                         default:
781                                 fprintf(stderr, "skipping file..\n");
782                                 opj_stream_destroy(l_stream);
783                                 continue;
784                 }
785
786                 /* catch events using our callbacks and give a local context */         
787                 opj_set_info_handler(l_codec, info_callback,00);
788                 opj_set_warning_handler(l_codec, warning_callback,00);
789                 opj_set_error_handler(l_codec, error_callback,00);
790
791                 /* Setup the decoder decoding parameters using user parameters */
792                 if ( !opj_setup_decoder(l_codec, &parameters) ){
793                         fprintf(stderr, "ERROR -> opj_compress: failed to setup the decoder\n");
794                         opj_stream_destroy(l_stream);
795                         opj_destroy_codec(l_codec);
796                         return EXIT_FAILURE;
797                 }
798
799
800                 /* Read the main header of the codestream and if necessary the JP2 boxes*/
801                 if(! opj_read_header(l_stream, l_codec, &image)){
802                         fprintf(stderr, "ERROR -> opj_decompress: failed to read the header\n");
803                         opj_stream_destroy(l_stream);
804                         opj_destroy_codec(l_codec);
805                         opj_image_destroy(image);
806                         return EXIT_FAILURE;
807                 }
808
809                 if (!parameters.nb_tile_to_decode) {
810                         /* Optional if you want decode the entire image */
811                         if (!opj_set_decode_area(l_codec, image, (OPJ_INT32)parameters.DA_x0,
812                                         (OPJ_INT32)parameters.DA_y0, (OPJ_INT32)parameters.DA_x1, (OPJ_INT32)parameters.DA_y1)){
813                                 fprintf(stderr, "ERROR -> opj_decompress: failed to set the decoded area\n");
814                                 opj_stream_destroy(l_stream);
815                                 opj_destroy_codec(l_codec);
816                                 opj_image_destroy(image);
817                                 return EXIT_FAILURE;
818                         }
819
820                         /* Get the decoded image */
821                         if (!(opj_decode(l_codec, l_stream, image) && opj_end_decompress(l_codec,       l_stream))) {
822                                 fprintf(stderr,"ERROR -> opj_decompress: failed to decode image!\n");
823                                 opj_destroy_codec(l_codec);
824                                 opj_stream_destroy(l_stream);
825                                 opj_image_destroy(image);
826                                 return EXIT_FAILURE;
827                         }
828                 }
829                 else {
830
831                         /* It is just here to illustrate how to use the resolution after set parameters */
832                         /*if (!opj_set_decoded_resolution_factor(l_codec, 5)) {
833                                 fprintf(stderr, "ERROR -> opj_decompress: failed to set the resolution factor tile!\n");
834                                 opj_destroy_codec(l_codec);
835                                 opj_stream_destroy(l_stream);
836                                 opj_image_destroy(image);
837                                 return EXIT_FAILURE;
838                         }*/
839
840                         if (!opj_get_decoded_tile(l_codec, l_stream, image, parameters.tile_index)) {
841                                 fprintf(stderr, "ERROR -> opj_decompress: failed to decode tile!\n");
842                                 opj_destroy_codec(l_codec);
843                                 opj_stream_destroy(l_stream);
844                                 opj_image_destroy(image);
845                                 return EXIT_FAILURE;
846                         }
847                         fprintf(stdout, "tile %d is decoded!\n\n", parameters.tile_index);
848                 }
849
850                 /* Close the byte stream */
851                 opj_stream_destroy(l_stream);
852
853                 if(image->color_space == OPJ_CLRSPC_SYCC){
854                         color_sycc_to_rgb(image); /* FIXME */
855                 }
856                 
857                 if( image->color_space != OPJ_CLRSPC_SYCC 
858                         && image->numcomps == 3 && image->comps[0].dx == image->comps[0].dy
859                         && image->comps[1].dx != 1 )
860                         image->color_space = OPJ_CLRSPC_SYCC;
861                 else if (image->numcomps <= 2)
862                         image->color_space = OPJ_CLRSPC_GRAY;
863
864                 if(image->icc_profile_buf) {
865 #if defined(OPJ_HAVE_LIBLCMS1) || defined(OPJ_HAVE_LIBLCMS2)
866                         color_apply_icc_profile(image); /* FIXME */
867 #endif
868                         free(image->icc_profile_buf);
869                         image->icc_profile_buf = NULL; image->icc_profile_len = 0;
870                 }
871
872                 /* create output image */
873                 /* ------------------- */
874                 switch (parameters.cod_format) {
875                 case PXM_DFMT:                  /* PNM PGM PPM */
876                         if (imagetopnm(image, parameters.outfile)) {
877                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
878         failed = 1;
879                         }
880                         else {
881                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
882                         }
883                         break;
884
885                 case PGX_DFMT:                  /* PGX */
886                         if(imagetopgx(image, parameters.outfile)){
887                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
888         failed = 1;
889                         }
890                         else {
891                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
892                         }
893                         break;
894
895                 case BMP_DFMT:                  /* BMP */
896                         if(imagetobmp(image, parameters.outfile)){
897                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
898         failed = 1;
899                         }
900                         else {
901                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
902                         }
903                         break;
904 #ifdef OPJ_HAVE_LIBTIFF
905                 case TIF_DFMT:                  /* TIFF */
906                         if(imagetotif(image, parameters.outfile)){
907                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
908         failed = 1;
909                         }
910                         else {
911                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
912                         }
913                         break;
914 #endif /* OPJ_HAVE_LIBTIFF */
915                 case RAW_DFMT:                  /* RAW */
916                         if(imagetoraw(image, parameters.outfile)){
917                 fprintf(stderr,"[ERROR] Error generating raw file. Outfile %s not generated\n",parameters.outfile);
918         failed = 1;
919                         }
920                         else {
921                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
922                         }
923                         break;
924
925                 case RAWL_DFMT:                 /* RAWL */
926                         if(imagetorawl(image, parameters.outfile)){
927                 fprintf(stderr,"[ERROR] Error generating rawl file. Outfile %s not generated\n",parameters.outfile);
928         failed = 1;
929                         }
930                         else {
931                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
932                         }
933                         break;
934
935                 case TGA_DFMT:                  /* TGA */
936                         if(imagetotga(image, parameters.outfile)){
937                 fprintf(stderr,"[ERROR] Error generating tga file. Outfile %s not generated\n",parameters.outfile);
938         failed = 1;
939                         }
940                         else {
941                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
942                         }
943                         break;
944 #ifdef OPJ_HAVE_LIBPNG
945                 case PNG_DFMT:                  /* PNG */
946                         if(imagetopng(image, parameters.outfile)){
947                 fprintf(stderr,"[ERROR] Error generating png file. Outfile %s not generated\n",parameters.outfile);
948         failed = 1;
949                         }
950                         else {
951                 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
952                         }
953                         break;
954 #endif /* OPJ_HAVE_LIBPNG */
955 /* Can happen if output file is TIFF or PNG
956  * and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined
957 */
958                         default:
959                 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
960         failed = 1;
961                 }
962
963                 /* free remaining structures */
964                 if (l_codec) {
965                         opj_destroy_codec(l_codec);
966                 }
967
968
969                 /* free image data structure */
970                 opj_image_destroy(image);
971
972                 /* destroy the codestream index */
973                 opj_destroy_cstr_index(&cstr_index);
974
975                 if(failed) remove(parameters.outfile);
976         }
977         return failed ? EXIT_FAILURE : EXIT_SUCCESS;
978 }
979 /*end main*/
980
981
982
983