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