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