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