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