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