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