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