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