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.
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.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
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.
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.
40 #include "opj_apps_config.h"
48 #include "windirent.h"
55 #define strcasecmp _stricmp
56 #define strncasecmp _strnicmp
60 #include <sys/resource.h>
61 #include <sys/times.h>
65 #include "opj_getopt.h"
69 #ifdef OPJ_HAVE_LIBLCMS2
72 #ifdef OPJ_HAVE_LIBLCMS1
77 #include "format_defs.h"
79 typedef struct dircnt{
80 /** Buffer for holding images read from Directory*/
82 /** Pointer to the buffer*/
87 typedef struct img_folder{
88 /** The directory path of the folder containing input images*/
91 const char *out_format;
94 /** Enable Cod Format for output*/
99 typedef enum opj_prec_mode
103 } opj_precision_mode;
105 typedef struct opj_prec
108 opj_precision_mode mode;
111 typedef struct opj_decompress_params
113 /** core library parameters */
114 opj_dparameters_t core;
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 */
122 /** output file format 0: PGX, 1: PxM, 2: BMP */
125 /** Decoding area left boundary */
127 /** Decoding area right boundary */
129 /** Decoding area up boundary */
131 /** Decoding area bottom boundary */
136 /** tile number ot the decoded tile*/
137 OPJ_UINT32 tile_index;
138 /** Nb of tile to decode */
139 OPJ_UINT32 nb_tile_to_decode;
141 opj_precision* precision;
142 OPJ_UINT32 nb_precision;
144 /* force output colorspace to RGB */
146 /* upsample components according to their dx/dy values */
148 /* split output components to different files */
150 }opj_decompress_parameters;
152 /* -------------------------------------------------------------------------- */
154 int get_num_images(char *imgdirpath);
155 int load_images(dircnt_t *dirptr, char *imgdirpath);
156 int get_file_format(const char *filename);
157 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_decompress_parameters *parameters);
158 static int infile_format(const char *fname);
160 int parse_cmdline_decoder(int argc, char **argv, opj_decompress_parameters *parameters,img_fol_t *img_fol, char *indexfilename);
161 int parse_DA_values( char* inArg, unsigned int *DA_x0, unsigned int *DA_y0, unsigned int *DA_x1, unsigned int *DA_y1);
163 static opj_image_t* convert_gray_to_rgb(opj_image_t* original);
165 /* -------------------------------------------------------------------------- */
166 static void decode_help_display(void) {
167 fprintf(stdout,"\nThis is the opj_decompress utility from the OpenJPEG project.\n"
168 "It decompresses JPEG 2000 codestreams to various image formats.\n"
169 "It has been compiled against openjp2 library v%s.\n\n",opj_version());
171 fprintf(stdout,"Parameters:\n"
174 " -ImgDir <directory> \n"
175 " Image file Directory path \n"
176 " -OutFor <PBM|PGM|PPM|PNM|PAM|PGX|PNG|BMP|TIF|RAW|RAWL|TGA>\n"
177 " REQUIRED only if -ImgDir is used\n"
178 " Output format for decompressed images.\n"
179 " -i <compressed file>\n"
180 " REQUIRED only if an Input image directory is not specified\n"
181 " Currently accepts J2K-files, JP2-files and JPT-files. The file type\n"
182 " is identified based on its suffix.\n"
183 " -o <decompressed file>\n"
185 " Currently accepts formats specified above (see OutFor option)\n"
186 " Binary data is written to the file (not ascii). If a PGX\n"
187 " filename is given, there will be as many output files as there are\n"
188 " components: an indice starting from 0 will then be appended to the\n"
189 " output filename, just before the \"pgx\" extension. If a PGM filename\n"
190 " is given and there are more than one component, only the first component\n"
191 " will be written to the file.\n"
192 " -r <reduce factor>\n"
193 " Set the number of highest resolution levels to be discarded. The\n"
194 " image resolution is effectively divided by 2 to the power of the\n"
195 " number of discarded levels. The reduce factor is limited by the\n"
196 " smallest total number of decomposition levels among tiles.\n"
197 " -l <number of quality layers to decode>\n"
198 " Set the maximum number of quality layers to decode. If there are\n"
199 " less quality layers than the specified number, all the quality layers\n"
202 " Create an index file *.Idx (-x index_name.Idx) \n"
203 " -d <x0,y0,x1,y1>\n"
206 " By default all the image is decoded.\n"
207 " -t <tile_number>\n"
209 " Set the tile number of the decoded tile. Follow the JPEG2000 convention from left-up to bottom-up\n"
210 " By default all tiles are decoded.\n"
211 " -p <comp 0 precision>[C|S][,<comp 1 precision>[C|S][,...]]\n"
213 " Force the precision (bit depth) of components.\n"
214 " 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"
215 " If there are less values than components, the last value is used for remaining components.\n"
216 " If 'C' is specified (default), values are clipped.\n"
217 " If 'S' is specified, values are scaled.\n"
218 " A 0 value can be specified (meaning original bit depth).\n"
220 " Force output image colorspace to RGB\n"
222 " Downsampled components will be upsampled to image size\n"
224 " Split output components to different files when writing to PNM\n"
228 fprintf(stdout," -W <options>\n"
229 " Activates the JPWL correction capability, if the codestream complies.\n"
230 " Options can be a comma separated list of <param=val> tokens:\n"
232 " numcomps is the number of expected components in the codestream\n"
233 " (search of first EPB rely upon this, default is %d)\n", JPWL_EXPECTED_COMPONENTS);
234 #endif /* USE_JPWL */
236 fprintf(stdout,"\n");
239 /* -------------------------------------------------------------------------- */
241 static OPJ_BOOL parse_precision(const char* option, opj_decompress_parameters* parameters)
243 const char* l_remaining = option;
244 OPJ_BOOL l_result = OPJ_TRUE;
247 if (parameters->precision) {
248 free(parameters->precision);
249 parameters->precision = NULL;
251 parameters->nb_precision = 0U;
260 count = sscanf(l_remaining, "%d%c%c", &prec, &mode, &comma);
265 if ((count == 2) || (mode==',')) {
274 fprintf(stderr,"Invalid precision %d in precision option %s\n", prec, option);
275 l_result = OPJ_FALSE;
278 if ((mode != 'C') && (mode != 'S')) {
279 fprintf(stderr,"Invalid precision mode %c in precision option %s\n", mode, option);
280 l_result = OPJ_FALSE;
284 fprintf(stderr,"Invalid character %c in precision option %s\n", comma, option);
285 l_result = OPJ_FALSE;
289 if (parameters->precision == NULL) {
291 parameters->precision = malloc(sizeof(opj_precision));
292 if (parameters->precision == NULL) {
293 fprintf(stderr,"Could not allocate memory for precision option\n");
294 l_result = OPJ_FALSE;
298 OPJ_UINT32 l_new_size = parameters->nb_precision + 1U;
299 opj_precision* l_new;
301 if (l_new_size == 0U) {
302 fprintf(stderr,"Could not allocate memory for precision option\n");
303 l_result = OPJ_FALSE;
307 l_new = realloc(parameters->precision, l_new_size * sizeof(opj_precision));
309 fprintf(stderr,"Could not allocate memory for precision option\n");
310 l_result = OPJ_FALSE;
313 parameters->precision = l_new;
316 parameters->precision[parameters->nb_precision].prec = prec;
319 parameters->precision[parameters->nb_precision].mode = OPJ_PREC_MODE_CLIP;
322 parameters->precision[parameters->nb_precision].mode = OPJ_PREC_MODE_SCALE;
327 parameters->nb_precision++;
329 l_remaining = strchr(l_remaining, ',');
330 if (l_remaining == NULL) {
335 fprintf(stderr,"Could not parse precision option %s\n", option);
336 l_result = OPJ_FALSE;
344 /* -------------------------------------------------------------------------- */
346 int get_num_images(char *imgdirpath){
348 struct dirent* content;
351 /*Reading the input images from given input directory*/
353 dir= opendir(imgdirpath);
355 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
359 while((content=readdir(dir))!=NULL){
360 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
367 /* -------------------------------------------------------------------------- */
368 int load_images(dircnt_t *dirptr, char *imgdirpath){
370 struct dirent* content;
373 /*Reading the input images from given input directory*/
375 dir= opendir(imgdirpath);
377 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
380 fprintf(stderr,"Folder opened successfully\n");
383 while((content=readdir(dir))!=NULL){
384 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
387 strcpy(dirptr->filename[i],content->d_name);
393 /* -------------------------------------------------------------------------- */
394 int get_file_format(const char *filename) {
396 static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "rawl", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc" };
397 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 };
398 char * ext = strrchr(filename, '.');
403 for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
404 if(strcasecmp(ext, extension[i]) == 0) {
414 const char* path_separator = "\\";
416 const char* path_separator = "/";
419 /* -------------------------------------------------------------------------- */
420 char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_decompress_parameters *parameters){
421 char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
422 char *temp_p, temp1[OPJ_PATH_LEN]="";
424 strcpy(image_filename,dirptr->filename[imageno]);
425 fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
426 sprintf(infilename, "%s%s%s", img_fol->imgdirpath, path_separator, image_filename);
427 parameters->decod_format = infile_format(infilename);
428 if (parameters->decod_format == -1)
430 strncpy(parameters->infile, infilename, sizeof(infilename));
433 strcpy(temp_ofname,strtok(image_filename,"."));
434 while((temp_p = strtok(NULL,".")) != NULL){
435 strcat(temp_ofname,temp1);
436 sprintf(temp1,".%s",temp_p);
438 if(img_fol->set_out_format==1){
439 sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
440 strncpy(parameters->outfile, outfilename, sizeof(outfilename));
445 /* -------------------------------------------------------------------------- */
446 #define JP2_RFC3745_MAGIC "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a"
447 #define JP2_MAGIC "\x0d\x0a\x87\x0a"
448 /* position 45: "\xff\x52" */
449 #define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51"
451 static int infile_format(const char *fname)
454 const char *s, *magic_s;
455 int ext_format, magic_format;
456 unsigned char buf[12];
457 OPJ_SIZE_T l_nb_read;
459 reader = fopen(fname, "rb");
465 l_nb_read = fread(buf, 1, 12, reader);
472 ext_format = get_file_format(fname);
474 if (ext_format == JPT_CFMT)
477 if (memcmp(buf, JP2_RFC3745_MAGIC, 12) == 0 || memcmp(buf, JP2_MAGIC, 4) == 0) {
478 magic_format = JP2_CFMT;
481 else if (memcmp(buf, J2K_CODESTREAM_MAGIC, 4) == 0) {
482 magic_format = J2K_CFMT;
483 magic_s = ".j2k or .jpc or .j2c";
488 if (magic_format == ext_format)
491 s = fname + strlen(fname) - 4;
493 fputs("\n===========================================\n", stderr);
494 fprintf(stderr, "The extension of this file is incorrect.\n"
495 "FOUND %s. SHOULD BE %s\n", s, magic_s);
496 fputs("===========================================\n", stderr);
501 /* -------------------------------------------------------------------------- */
503 * Parse the command line
505 /* -------------------------------------------------------------------------- */
506 int parse_cmdline_decoder(int argc, char **argv, opj_decompress_parameters *parameters,img_fol_t *img_fol, char *indexfilename) {
507 /* parse the command line */
509 opj_option_t long_option[]={
510 {"ImgDir", REQ_ARG, NULL ,'y'},
511 {"OutFor", REQ_ARG, NULL ,'O'},
512 {"force-rgb", NO_ARG, &(parameters->force_rgb), 1},
513 {"upsample", NO_ARG, &(parameters->upsample), 1},
514 {"split-pnm", NO_ARG, &(parameters->split_pnm), 1}
517 const char optlist[] = "i:o:r:l:x:d:t:p:"
522 #endif /* USE_JPWL */
525 totlen=sizeof(long_option);
526 opj_reset_options_reading();
527 img_fol->set_out_format = 0;
529 c = opj_getopt_long(argc, argv,optlist,long_option,totlen);
533 case 0: /* long opt with flag */
535 case 'i': /* input file */
537 char *infile = opj_optarg;
538 parameters->decod_format = infile_format(infile);
539 switch(parameters->decod_format) {
548 "!! infile cannot be read: %s !!\n\n",
553 "[ERROR] Unknown input file format: %s \n"
554 " Known file formats are *.j2k, *.jp2, *.jpc or *.jpt\n",
558 strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
562 /* ----------------------------------------------------- */
564 case 'o': /* output file */
566 char *outfile = opj_optarg;
567 parameters->cod_format = get_file_format(outfile);
568 switch(parameters->cod_format) {
586 fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outfile);
589 strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);
593 /* ----------------------------------------------------- */
595 case 'O': /* output format */
598 char *of = opj_optarg;
599 sprintf(outformat,".%s",of);
600 img_fol->set_out_format = 1;
601 parameters->cod_format = get_file_format(outformat);
602 switch(parameters->cod_format) {
604 img_fol->out_format = "pgx";
607 img_fol->out_format = "ppm";
610 img_fol->out_format = "bmp";
613 img_fol->out_format = "tif";
616 img_fol->out_format = "raw";
619 img_fol->out_format = "rawl";
622 img_fol->out_format = "raw";
625 img_fol->out_format = "png";
628 fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outformat);
635 /* ----------------------------------------------------- */
638 case 'r': /* reduce option */
640 sscanf(opj_optarg, "%u", &(parameters->core.cp_reduce));
644 /* ----------------------------------------------------- */
647 case 'l': /* layering option */
649 sscanf(opj_optarg, "%u", &(parameters->core.cp_layer));
653 /* ----------------------------------------------------- */
655 case 'h': /* display an help description */
656 decode_help_display();
659 /* ----------------------------------------------------- */
661 case 'y': /* Image Directory path */
663 img_fol->imgdirpath = (char*)malloc(strlen(opj_optarg) + 1);
664 strcpy(img_fol->imgdirpath,opj_optarg);
665 img_fol->set_imgdir=1;
669 /* ----------------------------------------------------- */
671 case 'd': /* Input decode ROI */
673 int size_optarg = (int)strlen(opj_optarg) + 1;
674 char *ROI_values = (char*) malloc((size_t)size_optarg);
675 ROI_values[0] = '\0';
676 strncpy(ROI_values, opj_optarg, strlen(opj_optarg));
677 ROI_values[strlen(opj_optarg)] = '\0';
678 /*printf("ROI_values = %s [%d / %d]\n", ROI_values, strlen(ROI_values), size_optarg ); */
679 parse_DA_values( ROI_values, ¶meters->DA_x0, ¶meters->DA_y0, ¶meters->DA_x1, ¶meters->DA_y1);
685 /* ----------------------------------------------------- */
687 case 't': /* Input tile index */
689 sscanf(opj_optarg, "%u", ¶meters->tile_index);
690 parameters->nb_tile_to_decode = 1;
694 /* ----------------------------------------------------- */
696 case 'x': /* Creation of index file */
698 char *index = opj_optarg;
699 strncpy(indexfilename, index, OPJ_PATH_LEN);
703 /* ----------------------------------------------------- */
704 case 'p': /* Force precision */
706 if (!parse_precision(opj_optarg, parameters))
712 /* ----------------------------------------------------- */
717 case 'W': /* activate JPWL correction */
721 token = strtok(opj_optarg, ",");
722 while(token != NULL) {
724 /* search expected number of components */
729 compno = JPWL_EXPECTED_COMPONENTS; /* predefined no. of components */
731 if(sscanf(token, "c=%d", &compno) == 1) {
733 if ((compno < 1) || (compno > 256)) {
734 fprintf(stderr, "ERROR -> invalid number of components c = %d\n", compno);
737 parameters->jpwl_exp_comps = compno;
739 } else if (!strcmp(token, "c")) {
741 parameters->jpwl_exp_comps = compno; /* auto for default size */
744 fprintf(stderr, "ERROR -> invalid components specified = %s\n", token);
749 /* search maximum number of tiles */
754 tileno = JPWL_MAXIMUM_TILES; /* maximum no. of tiles */
756 if(sscanf(token, "t=%d", &tileno) == 1) {
758 if ((tileno < 1) || (tileno > JPWL_MAXIMUM_TILES)) {
759 fprintf(stderr, "ERROR -> invalid number of tiles t = %d\n", tileno);
762 parameters->jpwl_max_tiles = tileno;
764 } else if (!strcmp(token, "t")) {
766 parameters->jpwl_max_tiles = tileno; /* auto for default size */
769 fprintf(stderr, "ERROR -> invalid tiles specified = %s\n", token);
774 /* next token or bust */
775 token = strtok(NULL, ",");
777 parameters->jpwl_correct = OPJ_TRUE;
778 fprintf(stdout, "JPWL correction capability activated\n");
779 fprintf(stdout, "- expecting %d components\n", parameters->jpwl_exp_comps);
782 #endif /* USE_JPWL */
785 /* ----------------------------------------------------- */
788 fprintf(stderr, "[WARNING] An invalid option has been ignored.\n");
793 /* check for possible errors */
794 if(img_fol->set_imgdir==1){
795 if(!(parameters->infile[0]==0)){
796 fprintf(stderr, "[ERROR] options -ImgDir and -i cannot be used together.\n");
799 if(img_fol->set_out_format == 0){
800 fprintf(stderr, "[ERROR] When -ImgDir is used, -OutFor <FORMAT> must be used.\n");
801 fprintf(stderr, "Only one format allowed.\n"
802 "Valid format are PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA.\n");
805 if(!((parameters->outfile[0] == 0))){
806 fprintf(stderr, "[ERROR] options -ImgDir and -o cannot be used together.\n");
810 if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
811 fprintf(stderr, "[ERROR] Required parameters are missing\n"
812 "Example: %s -i image.j2k -o image.pgm\n",argv[0]);
813 fprintf(stderr, " Help: %s -h\n",argv[0]);
821 /* -------------------------------------------------------------------------- */
823 * Parse decoding area input values
826 /* -------------------------------------------------------------------------- */
827 int parse_DA_values( char* inArg, unsigned int *DA_x0, unsigned int *DA_y0, unsigned int *DA_x1, unsigned int *DA_y1)
833 result = strtok( inArg, delims );
835 while( (result != NULL) && (it < 4 ) ) {
836 values[it] = atoi(result);
837 result = strtok( NULL, delims );
845 *DA_x0 = (OPJ_UINT32)values[0]; *DA_y0 = (OPJ_UINT32)values[1];
846 *DA_x1 = (OPJ_UINT32)values[2]; *DA_y1 = (OPJ_UINT32)values[3];
851 OPJ_FLOAT64 opj_clock(void) {
853 /* _WIN32: use QueryPerformance (very accurate) */
854 LARGE_INTEGER freq , t ;
855 /* freq is the clock speed of the CPU */
856 QueryPerformanceFrequency(&freq) ;
857 /* cout << "freq = " << ((double) freq.QuadPart) << endl; */
858 /* t is the high resolution performance counter (see MSDN) */
859 QueryPerformanceCounter ( & t ) ;
860 return freq.QuadPart ? (t.QuadPart / (OPJ_FLOAT64)freq.QuadPart) : 0;
862 /* Unix or Linux: use resource usage */
864 OPJ_FLOAT64 procTime;
865 /* (1) Get the rusage data structure at this moment (man getrusage) */
867 /* (2) What is the elapsed time ? - CPU time = User time + System time */
868 /* (2a) Get the seconds */
869 procTime = (OPJ_FLOAT64)(t.ru_utime.tv_sec + t.ru_stime.tv_sec);
870 /* (2b) More precisely! Get the microseconds part ! */
871 return ( procTime + (OPJ_FLOAT64)(t.ru_utime.tv_usec + t.ru_stime.tv_usec) * 1e-6 ) ;
875 /* -------------------------------------------------------------------------- */
878 sample error callback expecting a FILE* client object
880 static void error_callback(const char *msg, void *client_data) {
882 fprintf(stdout, "[ERROR] %s", msg);
885 sample warning callback expecting a FILE* client object
887 static void warning_callback(const char *msg, void *client_data) {
889 fprintf(stdout, "[WARNING] %s", msg);
892 sample debug callback expecting no client object
894 static void info_callback(const char *msg, void *client_data) {
896 fprintf(stdout, "[INFO] %s", msg);
899 static void set_default_parameters(opj_decompress_parameters* parameters)
902 memset(parameters, 0, sizeof(opj_decompress_parameters));
904 /* default decoding parameters (command line specific) */
905 parameters->decod_format = -1;
906 parameters->cod_format = -1;
908 /* default decoding parameters (core) */
909 opj_set_default_decoder_parameters(&(parameters->core));
913 static void destroy_parameters(opj_decompress_parameters* parameters)
916 if (parameters->precision) {
917 free(parameters->precision);
918 parameters->precision = NULL;
923 /* -------------------------------------------------------------------------- */
925 static opj_image_t* convert_gray_to_rgb(opj_image_t* original)
928 opj_image_t* l_new_image = NULL;
929 opj_image_cmptparm_t* l_new_components = NULL;
931 l_new_components = (opj_image_cmptparm_t*)malloc((original->numcomps + 2U) * sizeof(opj_image_cmptparm_t));
932 if (l_new_components == NULL) {
933 fprintf(stderr, "ERROR -> opj_decompress: failed to allocate memory for RGB image!\n");
934 opj_image_destroy(original);
938 l_new_components[0].bpp = l_new_components[1].bpp = l_new_components[2].bpp = original->comps[0].bpp;
939 l_new_components[0].dx = l_new_components[1].dx = l_new_components[2].dx = original->comps[0].dx;
940 l_new_components[0].dy = l_new_components[1].dy = l_new_components[2].dy = original->comps[0].dy;
941 l_new_components[0].h = l_new_components[1].h = l_new_components[2].h = original->comps[0].h;
942 l_new_components[0].w = l_new_components[1].w = l_new_components[2].w = original->comps[0].w;
943 l_new_components[0].prec = l_new_components[1].prec = l_new_components[2].prec = original->comps[0].prec;
944 l_new_components[0].sgnd = l_new_components[1].sgnd = l_new_components[2].sgnd = original->comps[0].sgnd;
945 l_new_components[0].x0 = l_new_components[1].x0 = l_new_components[2].x0 = original->comps[0].x0;
946 l_new_components[0].y0 = l_new_components[1].y0 = l_new_components[2].y0 = original->comps[0].y0;
948 for(compno = 1U; compno < original->numcomps; ++compno) {
949 l_new_components[compno+2U].bpp = original->comps[compno].bpp;
950 l_new_components[compno+2U].dx = original->comps[compno].dx;
951 l_new_components[compno+2U].dy = original->comps[compno].dy;
952 l_new_components[compno+2U].h = original->comps[compno].h;
953 l_new_components[compno+2U].w = original->comps[compno].w;
954 l_new_components[compno+2U].prec = original->comps[compno].prec;
955 l_new_components[compno+2U].sgnd = original->comps[compno].sgnd;
956 l_new_components[compno+2U].x0 = original->comps[compno].x0;
957 l_new_components[compno+2U].y0 = original->comps[compno].y0;
960 l_new_image = opj_image_create(original->numcomps + 2U, l_new_components, OPJ_CLRSPC_SRGB);
961 free(l_new_components);
962 if (l_new_image == NULL) {
963 fprintf(stderr, "ERROR -> opj_decompress: failed to allocate memory for RGB image!\n");
964 opj_image_destroy(original);
968 l_new_image->x0 = original->x0;
969 l_new_image->x1 = original->x1;
970 l_new_image->y0 = original->y0;
971 l_new_image->y1 = original->y1;
973 l_new_image->comps[0].factor = l_new_image->comps[1].factor = l_new_image->comps[2].factor = original->comps[0].factor;
974 l_new_image->comps[0].alpha = l_new_image->comps[1].alpha = l_new_image->comps[2].alpha = original->comps[0].alpha;
975 l_new_image->comps[0].resno_decoded = l_new_image->comps[1].resno_decoded = l_new_image->comps[2].resno_decoded = original->comps[0].resno_decoded;
977 memcpy(l_new_image->comps[0].data, original->comps[0].data, original->comps[0].w * original->comps[0].h * sizeof(OPJ_INT32));
978 memcpy(l_new_image->comps[1].data, original->comps[0].data, original->comps[0].w * original->comps[0].h * sizeof(OPJ_INT32));
979 memcpy(l_new_image->comps[2].data, original->comps[0].data, original->comps[0].w * original->comps[0].h * sizeof(OPJ_INT32));
981 for(compno = 1U; compno < original->numcomps; ++compno) {
982 l_new_image->comps[compno+2U].factor = original->comps[compno].factor;
983 l_new_image->comps[compno+2U].alpha = original->comps[compno].alpha;
984 l_new_image->comps[compno+2U].resno_decoded = original->comps[compno].resno_decoded;
985 memcpy(l_new_image->comps[compno+2U].data, original->comps[compno].data, original->comps[compno].w * original->comps[compno].h * sizeof(OPJ_INT32));
987 opj_image_destroy(original);
991 /* -------------------------------------------------------------------------- */
993 static opj_image_t* upsample_image_components(opj_image_t* original)
995 opj_image_t* l_new_image = NULL;
996 opj_image_cmptparm_t* l_new_components = NULL;
997 OPJ_BOOL l_upsample_need = OPJ_FALSE;
1000 for (compno = 0U; compno < original->numcomps; ++compno) {
1001 if (original->comps[compno].factor > 0U) {
1002 fprintf(stderr, "ERROR -> opj_decompress: -upsample not supported with reduction\n");
1003 opj_image_destroy(original);
1006 if ((original->comps[compno].dx > 1U) || (original->comps[compno].dy > 1U)) {
1007 l_upsample_need = OPJ_TRUE;
1011 if (!l_upsample_need) {
1014 /* Upsample is needed */
1015 l_new_components = (opj_image_cmptparm_t*)malloc(original->numcomps * sizeof(opj_image_cmptparm_t));
1016 if (l_new_components == NULL) {
1017 fprintf(stderr, "ERROR -> opj_decompress: failed to allocate memory for upsampled components!\n");
1018 opj_image_destroy(original);
1022 for (compno = 0U; compno < original->numcomps; ++compno) {
1023 opj_image_cmptparm_t* l_new_cmp = &(l_new_components[compno]);
1024 opj_image_comp_t* l_org_cmp = &(original->comps[compno]);
1026 l_new_cmp->bpp = l_org_cmp->bpp;
1027 l_new_cmp->prec = l_org_cmp->prec;
1028 l_new_cmp->sgnd = l_org_cmp->sgnd;
1029 l_new_cmp->x0 = original->x0;
1030 l_new_cmp->y0 = original->y0;
1033 l_new_cmp->w = l_org_cmp->w; /* should be original->x1 - original->x0 for dx==1 */
1034 l_new_cmp->h = l_org_cmp->h; /* should be original->y1 - original->y0 for dy==0 */
1036 if (l_org_cmp->dx > 1U) {
1037 l_new_cmp->w = original->x1 - original->x0;
1040 if (l_org_cmp->dy > 1U) {
1041 l_new_cmp->h = original->y1 - original->y0;
1045 l_new_image = opj_image_create(original->numcomps, l_new_components, original->color_space);
1046 free(l_new_components);
1047 if (l_new_image == NULL) {
1048 fprintf(stderr, "ERROR -> opj_decompress: failed to allocate memory for upsampled components!\n");
1049 opj_image_destroy(original);
1053 l_new_image->x0 = original->x0;
1054 l_new_image->x1 = original->x1;
1055 l_new_image->y0 = original->y0;
1056 l_new_image->y1 = original->y1;
1058 for (compno = 0U; compno < original->numcomps; ++compno) {
1059 opj_image_comp_t* l_new_cmp = &(l_new_image->comps[compno]);
1060 opj_image_comp_t* l_org_cmp = &(original->comps[compno]);
1062 l_new_cmp->factor = l_org_cmp->factor;
1063 l_new_cmp->alpha = l_org_cmp->alpha;
1064 l_new_cmp->resno_decoded = l_org_cmp->resno_decoded;
1066 if ((l_org_cmp->dx > 1U) || (l_org_cmp->dy > 1U)) {
1067 const OPJ_INT32* l_src = l_org_cmp->data;
1068 OPJ_INT32* l_dst = l_new_cmp->data;
1070 OPJ_UINT32 xoff, yoff;
1072 /* need to take into account dx & dy */
1073 xoff = l_org_cmp->dx * l_org_cmp->x0 - original->x0;
1074 yoff = l_org_cmp->dy * l_org_cmp->y0 - original->y0;
1075 if ((xoff >= l_org_cmp->dx) || (yoff >= l_org_cmp->dy)) {
1076 fprintf(stderr, "ERROR -> opj_decompress: Invalid image/component parameters found when upsampling\n");
1077 opj_image_destroy(original);
1078 opj_image_destroy(l_new_image);
1082 for (y = 0U; y < yoff; ++y) {
1083 memset(l_dst, 0U, l_new_cmp->w * sizeof(OPJ_INT32));
1084 l_dst += l_new_cmp->w;
1087 if(l_new_cmp->h > (l_org_cmp->dy - 1U)) { /* check substraction overflow for really small images */
1088 for (; y < l_new_cmp->h - (l_org_cmp->dy - 1U); y += l_org_cmp->dy) {
1093 for (x = 0U; x < xoff; ++x) {
1096 if (l_new_cmp->w > (l_org_cmp->dx - 1U)) { /* check substraction overflow for really small images */
1097 for (; x < l_new_cmp->w - (l_org_cmp->dx - 1U); x += l_org_cmp->dx, ++xorg) {
1099 for (dx = 0U; dx < l_org_cmp->dx; ++dx) {
1100 l_dst[x + dx] = l_src[xorg];
1104 for (; x < l_new_cmp->w; ++x) {
1105 l_dst[x] = l_src[xorg];
1107 l_dst += l_new_cmp->w;
1109 for (dy = 1U; dy < l_org_cmp->dy; ++dy) {
1110 memcpy(l_dst, l_dst - l_new_cmp->w, l_new_cmp->w * sizeof(OPJ_INT32));
1111 l_dst += l_new_cmp->w;
1113 l_src += l_org_cmp->w;
1116 if (y < l_new_cmp->h) {
1121 for (x = 0U; x < xoff; ++x) {
1124 if (l_new_cmp->w > (l_org_cmp->dx - 1U)) { /* check substraction overflow for really small images */
1125 for (; x < l_new_cmp->w - (l_org_cmp->dx - 1U); x += l_org_cmp->dx, ++xorg) {
1127 for (dx = 0U; dx < l_org_cmp->dx; ++dx) {
1128 l_dst[x + dx] = l_src[xorg];
1132 for (; x < l_new_cmp->w; ++x) {
1133 l_dst[x] = l_src[xorg];
1135 l_dst += l_new_cmp->w;
1137 for (; y < l_new_cmp->h; ++y) {
1138 memcpy(l_dst, l_dst - l_new_cmp->w, l_new_cmp->w * sizeof(OPJ_INT32));
1139 l_dst += l_new_cmp->w;
1144 memcpy(l_new_cmp->data, l_org_cmp->data, l_org_cmp->w * l_org_cmp->h * sizeof(OPJ_INT32));
1147 opj_image_destroy(original);
1151 /* -------------------------------------------------------------------------- */
1153 * OPJ_DECOMPRESS MAIN
1155 /* -------------------------------------------------------------------------- */
1156 int main(int argc, char **argv)
1158 opj_decompress_parameters parameters; /* decompression parameters */
1159 opj_image_t* image = NULL;
1160 opj_stream_t *l_stream = NULL; /* Stream */
1161 opj_codec_t* l_codec = NULL; /* Handle to a decompressor */
1162 opj_codestream_index_t* cstr_index = NULL;
1164 char indexfilename[OPJ_PATH_LEN]; /* index file name */
1166 OPJ_INT32 num_images, imageno;
1168 dircnt_t *dirptr = NULL;
1170 OPJ_FLOAT64 t, tCumulative = 0;
1171 OPJ_UINT32 numDecompressedImages = 0;
1173 /* set decoding parameters to default values */
1174 set_default_parameters(¶meters);
1176 /* FIXME Initialize indexfilename and img_fol */
1179 /* Initialize img_fol */
1180 memset(&img_fol,0,sizeof(img_fol_t));
1182 /* parse input and get user encoding parameters */
1183 if(parse_cmdline_decoder(argc, argv, ¶meters,&img_fol, indexfilename) == 1) {
1184 destroy_parameters(¶meters);
1185 return EXIT_FAILURE;
1188 /* Initialize reading of directory */
1189 if(img_fol.set_imgdir==1){
1191 num_images=get_num_images(img_fol.imgdirpath);
1193 dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
1195 dirptr->filename_buf = (char*)malloc((size_t)num_images*OPJ_PATH_LEN*sizeof(char)); /* Stores at max 10 image file names*/
1196 dirptr->filename = (char**) malloc((size_t)num_images*sizeof(char*));
1198 if(!dirptr->filename_buf){
1199 destroy_parameters(¶meters);
1200 return EXIT_FAILURE;
1202 for(it_image=0;it_image<num_images;it_image++){
1203 dirptr->filename[it_image] = dirptr->filename_buf + it_image*OPJ_PATH_LEN;
1206 if(load_images(dirptr,img_fol.imgdirpath)==1){
1207 destroy_parameters(¶meters);
1208 return EXIT_FAILURE;
1211 fprintf(stdout,"Folder is empty\n");
1212 destroy_parameters(¶meters);
1213 return EXIT_FAILURE;
1219 /*Decoding image one by one*/
1220 for(imageno = 0; imageno < num_images ; imageno++) {
1222 fprintf(stderr,"\n");
1224 if(img_fol.set_imgdir==1){
1225 if (get_next_file(imageno, dirptr,&img_fol, ¶meters)) {
1226 fprintf(stderr,"skipping file...\n");
1227 destroy_parameters(¶meters);
1232 /* read the input file and put it in memory */
1233 /* ---------------------------------------- */
1235 l_stream = opj_stream_create_default_file_stream(parameters.infile,1);
1237 fprintf(stderr, "ERROR -> failed to create the stream from the file %s\n", parameters.infile);
1238 destroy_parameters(¶meters);
1239 return EXIT_FAILURE;
1242 /* decode the JPEG2000 stream */
1243 /* ---------------------- */
1245 switch(parameters.decod_format) {
1246 case J2K_CFMT: /* JPEG-2000 codestream */
1248 /* Get a decoder handle */
1249 l_codec = opj_create_decompress(OPJ_CODEC_J2K);
1252 case JP2_CFMT: /* JPEG 2000 compressed image data */
1254 /* Get a decoder handle */
1255 l_codec = opj_create_decompress(OPJ_CODEC_JP2);
1258 case JPT_CFMT: /* JPEG 2000, JPIP */
1260 /* Get a decoder handle */
1261 l_codec = opj_create_decompress(OPJ_CODEC_JPT);
1265 fprintf(stderr, "skipping file..\n");
1266 destroy_parameters(¶meters);
1267 opj_stream_destroy(l_stream);
1271 /* catch events using our callbacks and give a local context */
1272 opj_set_info_handler(l_codec, info_callback,00);
1273 opj_set_warning_handler(l_codec, warning_callback,00);
1274 opj_set_error_handler(l_codec, error_callback,00);
1278 /* Setup the decoder decoding parameters using user parameters */
1279 if ( !opj_setup_decoder(l_codec, &(parameters.core)) ){
1280 fprintf(stderr, "ERROR -> opj_decompress: failed to setup the decoder\n");
1281 destroy_parameters(¶meters);
1282 opj_stream_destroy(l_stream);
1283 opj_destroy_codec(l_codec);
1284 return EXIT_FAILURE;
1288 /* Read the main header of the codestream and if necessary the JP2 boxes*/
1289 if(! opj_read_header(l_stream, l_codec, &image)){
1290 fprintf(stderr, "ERROR -> opj_decompress: failed to read the header\n");
1291 destroy_parameters(¶meters);
1292 opj_stream_destroy(l_stream);
1293 opj_destroy_codec(l_codec);
1294 opj_image_destroy(image);
1295 return EXIT_FAILURE;
1298 if (!parameters.nb_tile_to_decode) {
1299 /* Optional if you want decode the entire image */
1300 if (!opj_set_decode_area(l_codec, image, (OPJ_INT32)parameters.DA_x0,
1301 (OPJ_INT32)parameters.DA_y0, (OPJ_INT32)parameters.DA_x1, (OPJ_INT32)parameters.DA_y1)){
1302 fprintf(stderr, "ERROR -> opj_decompress: failed to set the decoded area\n");
1303 destroy_parameters(¶meters);
1304 opj_stream_destroy(l_stream);
1305 opj_destroy_codec(l_codec);
1306 opj_image_destroy(image);
1307 return EXIT_FAILURE;
1310 /* Get the decoded image */
1311 if (!(opj_decode(l_codec, l_stream, image) && opj_end_decompress(l_codec, l_stream))) {
1312 fprintf(stderr,"ERROR -> opj_decompress: failed to decode image!\n");
1313 destroy_parameters(¶meters);
1314 opj_destroy_codec(l_codec);
1315 opj_stream_destroy(l_stream);
1316 opj_image_destroy(image);
1317 return EXIT_FAILURE;
1322 /* It is just here to illustrate how to use the resolution after set parameters */
1323 /*if (!opj_set_decoded_resolution_factor(l_codec, 5)) {
1324 fprintf(stderr, "ERROR -> opj_decompress: failed to set the resolution factor tile!\n");
1325 opj_destroy_codec(l_codec);
1326 opj_stream_destroy(l_stream);
1327 opj_image_destroy(image);
1328 return EXIT_FAILURE;
1331 if (!opj_get_decoded_tile(l_codec, l_stream, image, parameters.tile_index)) {
1332 fprintf(stderr, "ERROR -> opj_decompress: failed to decode tile!\n");
1333 destroy_parameters(¶meters);
1334 opj_destroy_codec(l_codec);
1335 opj_stream_destroy(l_stream);
1336 opj_image_destroy(image);
1337 return EXIT_FAILURE;
1339 fprintf(stdout, "tile %d is decoded!\n\n", parameters.tile_index);
1342 tCumulative += opj_clock() - t;
1343 numDecompressedImages++;
1345 /* Close the byte stream */
1346 opj_stream_destroy(l_stream);
1348 if(image->color_space == OPJ_CLRSPC_SYCC){
1349 color_sycc_to_rgb(image); /* FIXME */
1352 if( image->color_space != OPJ_CLRSPC_SYCC
1353 && image->numcomps == 3 && image->comps[0].dx == image->comps[0].dy
1354 && image->comps[1].dx != 1 )
1355 image->color_space = OPJ_CLRSPC_SYCC;
1356 else if (image->numcomps <= 2)
1357 image->color_space = OPJ_CLRSPC_GRAY;
1359 if(image->icc_profile_buf) {
1360 #if defined(OPJ_HAVE_LIBLCMS1) || defined(OPJ_HAVE_LIBLCMS2)
1361 color_apply_icc_profile(image); /* FIXME */
1363 free(image->icc_profile_buf);
1364 image->icc_profile_buf = NULL; image->icc_profile_len = 0;
1367 /* Force output precision */
1368 /* ---------------------- */
1369 if (parameters.precision != NULL)
1372 for (compno = 0; compno < image->numcomps; ++compno)
1374 OPJ_UINT32 precno = compno;
1377 if (precno >= parameters.nb_precision) {
1378 precno = parameters.nb_precision - 1U;
1381 prec = parameters.precision[precno].prec;
1383 prec = image->comps[compno].prec;
1386 switch (parameters.precision[precno].mode) {
1387 case OPJ_PREC_MODE_CLIP:
1388 clip_component(&(image->comps[compno]), prec);
1390 case OPJ_PREC_MODE_SCALE:
1391 scale_component(&(image->comps[compno]), prec);
1400 /* Upsample components */
1401 /* ------------------- */
1402 if (parameters.upsample)
1404 image = upsample_image_components(image);
1405 if (image == NULL) {
1406 fprintf(stderr, "ERROR -> opj_decompress: failed to upsample image components!\n");
1407 destroy_parameters(¶meters);
1408 opj_destroy_codec(l_codec);
1409 return EXIT_FAILURE;
1413 /* Force RGB output */
1414 /* ---------------- */
1415 if (parameters.force_rgb)
1417 switch (image->color_space) {
1418 case OPJ_CLRSPC_SRGB:
1420 case OPJ_CLRSPC_GRAY:
1421 image = convert_gray_to_rgb(image);
1424 fprintf(stderr, "ERROR -> opj_decompress: don't know how to convert image to RGB colorspace!\n");
1425 opj_image_destroy(image);
1429 if (image == NULL) {
1430 fprintf(stderr, "ERROR -> opj_decompress: failed to convert to RGB image!\n");
1431 destroy_parameters(¶meters);
1432 opj_destroy_codec(l_codec);
1433 return EXIT_FAILURE;
1437 /* create output image */
1438 /* ------------------- */
1439 switch (parameters.cod_format) {
1440 case PXM_DFMT: /* PNM PGM PPM */
1441 if (imagetopnm(image, parameters.outfile, parameters.split_pnm)) {
1442 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1446 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1450 case PGX_DFMT: /* PGX */
1451 if(imagetopgx(image, parameters.outfile)){
1452 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1456 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1460 case BMP_DFMT: /* BMP */
1461 if(imagetobmp(image, parameters.outfile)){
1462 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1466 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1469 #ifdef OPJ_HAVE_LIBTIFF
1470 case TIF_DFMT: /* TIFF */
1471 if(imagetotif(image, parameters.outfile)){
1472 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1476 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1479 #endif /* OPJ_HAVE_LIBTIFF */
1480 case RAW_DFMT: /* RAW */
1481 if(imagetoraw(image, parameters.outfile)){
1482 fprintf(stderr,"[ERROR] Error generating raw file. Outfile %s not generated\n",parameters.outfile);
1486 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1490 case RAWL_DFMT: /* RAWL */
1491 if(imagetorawl(image, parameters.outfile)){
1492 fprintf(stderr,"[ERROR] Error generating rawl file. Outfile %s not generated\n",parameters.outfile);
1496 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1500 case TGA_DFMT: /* TGA */
1501 if(imagetotga(image, parameters.outfile)){
1502 fprintf(stderr,"[ERROR] Error generating tga file. Outfile %s not generated\n",parameters.outfile);
1506 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1509 #ifdef OPJ_HAVE_LIBPNG
1510 case PNG_DFMT: /* PNG */
1511 if(imagetopng(image, parameters.outfile)){
1512 fprintf(stderr,"[ERROR] Error generating png file. Outfile %s not generated\n",parameters.outfile);
1516 fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
1519 #endif /* OPJ_HAVE_LIBPNG */
1520 /* Can happen if output file is TIFF or PNG
1521 * and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined
1524 fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
1528 /* free remaining structures */
1530 opj_destroy_codec(l_codec);
1534 /* free image data structure */
1535 opj_image_destroy(image);
1537 /* destroy the codestream index */
1538 opj_destroy_cstr_index(&cstr_index);
1540 if(failed) remove(parameters.outfile);
1542 destroy_parameters(¶meters);
1543 if (numDecompressedImages)
1544 fprintf(stdout, "decode time: %d ms \n", (int)( (tCumulative * 1000) / numDecompressedImages));
1546 return failed ? EXIT_FAILURE : EXIT_SUCCESS;