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