Refactor build of both types of linkage
[openjpeg.git] / wrapping / java / openjp2 / JavaOpenJPEGDecoder.c
1 /*\r
2  * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium\r
3  * Copyright (c) 2002-2014, Professor Benoit Macq\r
4  * Copyright (c) 2001-2003, David Janssens\r
5  * Copyright (c) 2002-2003, Yannick Verschueren\r
6  * Copyright (c) 2003-2007, Francois-Olivier Devaux 
7  * Copyright (c) 2003-2014, Antonin Descampe\r
8  * Copyright (c) 2005, Herve Drolon, FreeImage Team\r
9  * Copyright (c) 2006-2007, Parvatha Elangovan\r
10  * Copyright (c) 2007, Patrick Piscaglia (Telemis)\r
11  * All rights reserved.\r
12  *\r
13  * Redistribution and use in source and binary forms, with or without\r
14  * modification, are permitted provided that the following conditions\r
15  * are met:\r
16  * 1. Redistributions of source code must retain the above copyright\r
17  *    notice, this list of conditions and the following disclaimer.\r
18  * 2. Redistributions in binary form must reproduce the above copyright\r
19  *    notice, this list of conditions and the following disclaimer in the\r
20  *    documentation and/or other materials provided with the distribution.\r
21  *\r
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
23  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
26  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
32  * POSSIBILITY OF SUCH DAMAGE.\r
33  */\r
34 #include <stdio.h>\r
35 #include <string.h>\r
36 #include <stdlib.h>\r
37 #include <jni.h>\r
38 #include <math.h>\r
39 \r
40 #include "openjpeg.h"\r
41 #include "opj_includes.h"\r
42 #include "opj_getopt.h"\r
43 #include "convert.h"\r
44 #include "dirent.h"\r
45 #include "org_openJpeg_OpenJPEGJavaDecoder.h"\r
46 \r
47 #ifndef _WIN32\r
48 #define stricmp strcasecmp\r
49 #define strnicmp strncasecmp\r
50 #endif\r
51 \r
52 #include "format_defs.h"\r
53 \r
54 typedef struct callback_variables {\r
55         JNIEnv *env;\r
56         /** 'jclass' object used to call a Java method from the C */\r
57         jobject *jobj;\r
58         /** 'jclass' object used to call a Java method from the C */\r
59         jmethodID message_mid;\r
60         jmethodID error_mid;\r
61 } callback_variables_t;\r
62 \r
63 typedef struct dircnt{\r
64         /** Buffer for holding images read from Directory*/\r
65         char *filename_buf;\r
66         /** Pointer to the buffer*/\r
67         char **filename;\r
68 }dircnt_t;\r
69 \r
70 \r
71 typedef struct img_folder{\r
72         /** The directory path of the folder containing input images*/\r
73         char *imgdirpath;\r
74         /** Output format*/\r
75         char *out_format;\r
76         /** Enable option*/\r
77         char set_imgdir;\r
78         /** Enable Cod Format for output*/\r
79         char set_out_format;\r
80 \r
81 }img_fol_t;\r
82 \r
83 \r
84 void decode_help_display() {\r
85         fprintf(stdout,"HELP\n----\n\n");\r
86         fprintf(stdout,"- the -h option displays this help information on screen\n\n");\r
87 \r
88 /* UniPG>> */\r
89         fprintf(stdout,"List of parameters for the JPEG 2000 "\r
90 #ifdef USE_JPWL\r
91                 "+ JPWL "\r
92 #endif /* USE_JPWL */\r
93                 "decoder:\n");\r
94 /* <<UniPG */\r
95         fprintf(stdout,"\n");\r
96         fprintf(stdout,"\n");\r
97         fprintf(stdout,"  -ImgDir \n");\r
98         fprintf(stdout,"        Image file Directory path \n");\r
99         fprintf(stdout,"  -OutFor \n");\r
100         fprintf(stdout,"    REQUIRED only if -ImgDir is used\n");\r
101         fprintf(stdout,"          Need to specify only format without filename <BMP>  \n");\r
102         fprintf(stdout,"    Currently accepts PGM, PPM, PNM, PGX, BMP format\n");\r
103         fprintf(stdout,"  -i <compressed file>\n");\r
104         fprintf(stdout,"    REQUIRED only if an Input image directory not specified\n");\r
105         fprintf(stdout,"    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n");\r
106         fprintf(stdout,"    is identified based on its suffix.\n");\r
107         fprintf(stdout,"  -o <decompressed file>\n");\r
108         fprintf(stdout,"    REQUIRED\n");\r
109         fprintf(stdout,"    Currently accepts PGM-files, PPM-files, PNM-files, PGX-files and\n");\r
110         fprintf(stdout,"    BMP-files. Binary data is written to the file (not ascii). If a PGX\n");\r
111         fprintf(stdout,"    filename is given, there will be as many output files as there are\n");\r
112         fprintf(stdout,"    components: an indice starting from 0 will then be appended to the\n");\r
113         fprintf(stdout,"    output filename, just before the \"pgx\" extension. If a PGM filename\n");\r
114         fprintf(stdout,"    is given and there are more than one component, only the first component\n");\r
115         fprintf(stdout,"    will be written to the file.\n");\r
116         fprintf(stdout,"  -r <reduce factor>\n");\r
117         fprintf(stdout,"    Set the number of highest resolution levels to be discarded. The\n");\r
118         fprintf(stdout,"    image resolution is effectively divided by 2 to the power of the\n");\r
119         fprintf(stdout,"    number of discarded levels. The reduce factor is limited by the\n");\r
120         fprintf(stdout,"    smallest total number of decomposition levels among tiles.\n");\r
121         fprintf(stdout,"  -l <number of quality layers to decode>\n");\r
122         fprintf(stdout,"    Set the maximum number of quality layers to decode. If there are\n");\r
123         fprintf(stdout,"    less quality layers than the specified number, all the quality layers\n");\r
124         fprintf(stdout,"    are decoded.\n");\r
125 /* UniPG>> */\r
126 #ifdef USE_JPWL\r
127         fprintf(stdout,"  -W <options>\n");\r
128         fprintf(stdout,"    Activates the JPWL correction capability, if the codestream complies.\n");\r
129         fprintf(stdout,"    Options can be a comma separated list of <param=val> tokens:\n");\r
130         fprintf(stdout,"    c, c=numcomps\n");\r
131         fprintf(stdout,"       numcomps is the number of expected components in the codestream\n");\r
132         fprintf(stdout,"       (search of first EPB rely upon this, default is %d)\n", JPWL_EXPECTED_COMPONENTS);\r
133 #endif /* USE_JPWL */\r
134 /* <<UniPG */\r
135         fprintf(stdout,"\n");\r
136 }\r
137 \r
138 /* -------------------------------------------------------------------------- */\r
139 \r
140 int get_num_images(char *imgdirpath){\r
141         DIR *dir;\r
142         struct dirent* content; \r
143         int num_images = 0;\r
144 \r
145         /*Reading the input images from given input directory*/\r
146 \r
147         dir= opendir(imgdirpath);\r
148         if(!dir){\r
149                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);\r
150                 return 0;\r
151         }\r
152         \r
153         while((content=readdir(dir))!=NULL){\r
154                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )\r
155                         continue;\r
156                 num_images++;\r
157         }\r
158         return num_images;\r
159 }\r
160 \r
161 int load_images(dircnt_t *dirptr, char *imgdirpath){\r
162         DIR *dir;\r
163         struct dirent* content; \r
164         int i = 0;\r
165 \r
166         /*Reading the input images from given input directory*/\r
167 \r
168         dir= opendir(imgdirpath);\r
169         if(!dir){\r
170                 fprintf(stderr,"Could not open Folder %s\n",imgdirpath);\r
171                 return 1;\r
172         }else   {\r
173                 fprintf(stderr,"Folder opened successfully\n");\r
174         }\r
175         \r
176         while((content=readdir(dir))!=NULL){\r
177                 if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )\r
178                         continue;\r
179 \r
180                 strcpy(dirptr->filename[i],content->d_name);\r
181                 i++;\r
182         }\r
183         return 0;       \r
184 }\r
185 \r
186 int get_file_format(char *filename) {\r
187         unsigned int i;\r
188         static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "tga", "j2k", "jp2", "jpt", "j2c" };\r
189         static const int format[] = { PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, TGA_DFMT, J2K_CFMT, JP2_CFMT, JPT_CFMT, J2K_CFMT };\r
190         char * ext = strrchr(filename, '.');\r
191         if (ext == NULL)\r
192                 return -1;\r
193         ext++;\r
194         if(ext) {\r
195                 for(i = 0; i < sizeof(format)/sizeof(*format); i++) {\r
196                         if(strnicmp(ext, extension[i], 3) == 0) {\r
197                                 return format[i];\r
198                         }\r
199                 }\r
200         }\r
201 \r
202         return -1;\r
203 }\r
204 \r
205 \r
206 /* -------------------------------------------------------------------------- */\r
207 \r
208 int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol) {\r
209         /* parse the command line */\r
210         int totlen;\r
211         opj_option_t long_option[]={\r
212                 {"ImgDir",REQ_ARG, NULL ,'y'},\r
213                 {"OutFor",REQ_ARG, NULL ,'O'},\r
214         };\r
215 \r
216 /* UniPG>> */\r
217         const char optlist[] = "i:o:r:l:hx:"\r
218 \r
219 #ifdef USE_JPWL\r
220                                         "W:"\r
221 #endif /* USE_JPWL */\r
222                                         ;\r
223         /*for (i=0; i<argc; i++) {\r
224                 printf("[%s]",argv[i]);\r
225         }\r
226         printf("\n");*/\r
227 \r
228 /* <<UniPG */\r
229         totlen=sizeof(long_option);\r
230         img_fol->set_out_format = 0;\r
231         reset_options_reading();\r
232 \r
233         while (1) {\r
234                 int c = opj_getopt_long(argc, argv,optlist,long_option,totlen);\r
235                 if (c == -1)\r
236                         break;\r
237                 switch (c) {\r
238                         case 'i':                       /* input file */\r
239                         {\r
240                                 char *infile = opj_optarg;\r
241                                 parameters->decod_format = get_file_format(infile);\r
242                                 switch(parameters->decod_format) {\r
243                                         case J2K_CFMT:\r
244                                         case JP2_CFMT:\r
245                                         case JPT_CFMT:\r
246                                                 break;\r
247                                         default:\r
248                                                 fprintf(stderr, \r
249                                                         "!! Unrecognized format for infile : %s [accept only *.j2k, *.jp2, *.jpc or *.jpt] !!\n\n", \r
250                                                         infile);\r
251                                                 return 1;\r
252                                 }\r
253                                 strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);\r
254                         }\r
255                         break;\r
256                                 \r
257                                 /* ----------------------------------------------------- */\r
258 \r
259                         case 'o':                       /* output file */\r
260                         {\r
261                                 char *outfile = opj_optarg;\r
262                                 parameters->cod_format = get_file_format(outfile);\r
263                                 switch(parameters->cod_format) {\r
264                                         case PGX_DFMT:\r
265                                         case PXM_DFMT:\r
266                                         case BMP_DFMT:\r
267                                         case TIF_DFMT:\r
268                                         case RAW_DFMT:\r
269                                         case TGA_DFMT:\r
270                                                 break;\r
271                                         default:\r
272                                                 fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outfile);\r
273                                                 return 1;\r
274                                 }\r
275                                 strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);\r
276                         }\r
277                         break;\r
278                         \r
279                                 /* ----------------------------------------------------- */\r
280 \r
281                         case 'O':                       /* output format */\r
282                         {\r
283                                 char outformat[50];\r
284                                 char *of = opj_optarg;\r
285                                 sprintf(outformat,".%s",of);\r
286                                 img_fol->set_out_format = 1;\r
287                                 parameters->cod_format = get_file_format(outformat);\r
288                                 switch(parameters->cod_format) {\r
289                                         case PGX_DFMT:\r
290                                                 img_fol->out_format = "pgx";\r
291                                                 break;\r
292                                         case PXM_DFMT:\r
293                                                 img_fol->out_format = "ppm";\r
294                                                 break;\r
295                                         case BMP_DFMT:\r
296                                                 img_fol->out_format = "bmp";\r
297                                                 break;\r
298                                         case TIF_DFMT:\r
299                                                 img_fol->out_format = "tif";\r
300                                                 break;\r
301                                         case RAW_DFMT:\r
302                                                 img_fol->out_format = "raw";\r
303                                                 break;\r
304                                         case TGA_DFMT:\r
305                                                 img_fol->out_format = "raw";\r
306                                                 break;\r
307                                         default:\r
308                                                 fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outformat);\r
309                                                 return 1;\r
310                                                 break;\r
311                                 }\r
312                         }\r
313                         break;\r
314 \r
315                                 /* ----------------------------------------------------- */\r
316 \r
317 \r
318                         case 'r':               /* reduce option */\r
319                         {\r
320                                 sscanf(opj_optarg, "%d", &parameters->cp_reduce);\r
321                         }\r
322                         break;\r
323                         \r
324                                 /* ----------------------------------------------------- */\r
325       \r
326 \r
327                         case 'l':               /* layering option */\r
328                         {\r
329                                 sscanf(opj_optarg, "%d", &parameters->cp_layer);\r
330                         }\r
331                         break;\r
332                         \r
333                                 /* ----------------------------------------------------- */\r
334 \r
335                         case 'h':                       /* display an help description */\r
336                                 decode_help_display();\r
337                                 return 1;                               \r
338 \r
339                                 /* ------------------------------------------------------ */\r
340 \r
341                         case 'y':                       /* Image Directory path */\r
342                                 {\r
343                                         img_fol->imgdirpath = (char*)opj_malloc(strlen(opj_optarg) + 1);\r
344                                         strcpy(img_fol->imgdirpath,opj_optarg);\r
345                                         img_fol->set_imgdir=1;\r
346                                 }\r
347                                 break;\r
348                                 /* ----------------------------------------------------- */\r
349 /* UniPG>> */\r
350 #ifdef USE_JPWL\r
351                         \r
352                         case 'W':                       /* activate JPWL correction */\r
353                         {\r
354                                 char *token = NULL;\r
355 \r
356                                 token = strtok(opj_optarg, ",");\r
357                                 while(token != NULL) {\r
358 \r
359                                         /* search expected number of components */\r
360                                         if (*token == 'c') {\r
361 \r
362                                                 static int compno;\r
363 \r
364                                                 compno = JPWL_EXPECTED_COMPONENTS; /* predefined no. of components */\r
365 \r
366                                                 if(sscanf(token, "c=%d", &compno) == 1) {\r
367                                                         /* Specified */\r
368                                                         if ((compno < 1) || (compno > 256)) {\r
369                                                                 fprintf(stderr, "ERROR -> invalid number of components c = %d\n", compno);\r
370                                                                 return 1;\r
371                                                         }\r
372                                                         parameters->jpwl_exp_comps = compno;\r
373 \r
374                                                 } else if (!strcmp(token, "c")) {\r
375                                                         /* default */\r
376                                                         parameters->jpwl_exp_comps = compno; /* auto for default size */\r
377 \r
378                                                 } else {\r
379                                                         fprintf(stderr, "ERROR -> invalid components specified = %s\n", token);\r
380                                                         return 1;\r
381                                                 };\r
382                                         }\r
383 \r
384                                         /* search maximum number of tiles */\r
385                                         if (*token == 't') {\r
386 \r
387                                                 static int tileno;\r
388 \r
389                                                 tileno = JPWL_MAXIMUM_TILES; /* maximum no. of tiles */\r
390 \r
391                                                 if(sscanf(token, "t=%d", &tileno) == 1) {\r
392                                                         /* Specified */\r
393                                                         if ((tileno < 1) || (tileno > JPWL_MAXIMUM_TILES)) {\r
394                                                                 fprintf(stderr, "ERROR -> invalid number of tiles t = %d\n", tileno);\r
395                                                                 return 1;\r
396                                                         }\r
397                                                         parameters->jpwl_max_tiles = tileno;\r
398 \r
399                                                 } else if (!strcmp(token, "t")) {\r
400                                                         /* default */\r
401                                                         parameters->jpwl_max_tiles = tileno; /* auto for default size */\r
402 \r
403                                                 } else {\r
404                                                         fprintf(stderr, "ERROR -> invalid tiles specified = %s\n", token);\r
405                                                         return 1;\r
406                                                 };\r
407                                         }\r
408 \r
409                                         /* next token or bust */\r
410                                         token = strtok(NULL, ",");\r
411                                 };\r
412                                 parameters->jpwl_correct = true;\r
413                                 fprintf(stdout, "JPWL correction capability activated\n");\r
414                                 fprintf(stdout, "- expecting %d components\n", parameters->jpwl_exp_comps);\r
415                         }\r
416                         break;  \r
417 #endif /* USE_JPWL */\r
418 /* <<UniPG */            \r
419 \r
420                                 /* ----------------------------------------------------- */\r
421                         \r
422                         default:\r
423                                 fprintf(stderr,"WARNING -> this option is not valid \"-%c %s\"\n",c, opj_optarg);\r
424                                 break;\r
425                 }\r
426         }\r
427 \r
428         /* No check for possible errors before the -i and -o options are of course not mandatory*/\r
429 \r
430         return 0;\r
431 }\r
432 \r
433 /* -------------------------------------------------------------------------- */\r
434 \r
435 /**\r
436 error callback returning the message to Java andexpecting a callback_variables_t client object\r
437 */\r
438 void error_callback(const char *msg, void *client_data) {\r
439         callback_variables_t* vars = (callback_variables_t*) client_data;\r
440         JNIEnv *env = vars->env;\r
441         jstring jbuffer;\r
442 \r
443         jbuffer = (*env)->NewStringUTF(env, msg);\r
444         (*env)->ExceptionClear(env);\r
445         (*env)->CallVoidMethod(env, *(vars->jobj), vars->error_mid, jbuffer);\r
446 \r
447         if ((*env)->ExceptionOccurred(env)) {\r
448                 fprintf(stderr,"C: Exception during call back method\n");\r
449                 (*env)->ExceptionDescribe(env);\r
450                 (*env)->ExceptionClear(env);\r
451         }\r
452         (*env)->DeleteLocalRef(env, jbuffer);\r
453 }\r
454 /**\r
455 warning callback returning the message to Java andexpecting a callback_variables_t client object\r
456 */\r
457 void warning_callback(const char *msg, void *client_data) {\r
458         callback_variables_t* vars = (callback_variables_t*) client_data;\r
459         JNIEnv *env = vars->env;\r
460         jstring jbuffer;\r
461 \r
462         jbuffer = (*env)->NewStringUTF(env, msg);\r
463         (*env)->ExceptionClear(env);\r
464         (*env)->CallVoidMethod(env, *(vars->jobj), vars->message_mid, jbuffer);\r
465         \r
466         if ((*env)->ExceptionOccurred(env)) {\r
467                 fprintf(stderr,"C: Exception during call back method\n");\r
468                 (*env)->ExceptionDescribe(env);\r
469                 (*env)->ExceptionClear(env);\r
470         }\r
471         (*env)->DeleteLocalRef(env, jbuffer);\r
472 }\r
473 /**\r
474 information callback returning the message to Java andexpecting a callback_variables_t client object\r
475 */\r
476 void info_callback(const char *msg, void *client_data) {\r
477         callback_variables_t* vars = (callback_variables_t*) client_data;\r
478         JNIEnv *env = vars->env;\r
479         jstring jbuffer;\r
480 \r
481         jbuffer = (*env)->NewStringUTF(env, msg);\r
482         (*env)->ExceptionClear(env);\r
483         (*env)->CallVoidMethod(env, *(vars->jobj), vars->message_mid, jbuffer);\r
484 \r
485         if ((*env)->ExceptionOccurred(env)) {\r
486                 fprintf(stderr,"C: Exception during call back method\n");\r
487                 (*env)->ExceptionDescribe(env);\r
488                 (*env)->ExceptionClear(env);\r
489         }\r
490         (*env)->DeleteLocalRef(env, jbuffer);\r
491 }\r
492 \r
493 \r
494 /* --------------------------------------------------------------------------\r
495    --------------------   MAIN METHOD, CALLED BY JAVA -----------------------*/\r
496 JNIEXPORT jint JNICALL Java_org_openJpeg_OpenJPEGJavaDecoder_internalDecodeJ2KtoImage(JNIEnv *env, jobject obj, jobjectArray javaParameters) {\r
497         int argc;               /* To simulate the command line parameters (taken from the javaParameters variable) and be able to re-use the */\r
498         char **argv;    /*  'parse_cmdline_decoder' method taken from the j2k_to_image project */\r
499         opj_dparameters_t parameters;   /* decompression parameters */\r
500         img_fol_t img_fol;\r
501         opj_event_mgr_t event_mgr;              /* event manager */\r
502         opj_image_t *image = NULL;\r
503         FILE *fsrc = NULL;\r
504         unsigned char *src = NULL;\r
505         int file_length;\r
506         int num_images;\r
507         int i,j,imageno;\r
508         opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */\r
509         opj_cio_t *cio = NULL;\r
510         int w,h;\r
511         long min_value, max_value;\r
512         short tempS; unsigned char tempUC, tempUC1, tempUC2;\r
513         /* ==> Access variables to the Java member variables*/\r
514         jsize           arraySize;\r
515         jclass          cls;\r
516         jobject         object;\r
517         jboolean        isCopy;\r
518         jfieldID        fid;\r
519         jbyteArray      jba;\r
520         jshortArray jsa;\r
521         jintArray       jia;\r
522         jbyte           *jbBody, *ptrBBody;\r
523         jshort          *jsBody, *ptrSBody;\r
524         jint            *jiBody, *ptrIBody;\r
525         callback_variables_t msgErrorCallback_vars;\r
526         /* <=== access variable to Java member variables */\r
527         int *ptr, *ptr1, *ptr2;                         /* <== To transfer the decoded image to Java*/\r
528 \r
529         /* configure the event callbacks */\r
530         memset(&event_mgr, 0, sizeof(opj_event_mgr_t)); \r
531         event_mgr.error_handler = error_callback;\r
532         event_mgr.warning_handler = warning_callback;\r
533         event_mgr.info_handler = info_callback;\r
534 \r
535         /* JNI reference to the calling class*/\r
536         cls = (*env)->GetObjectClass(env, obj);\r
537 \r
538         /* Pointers to be able to call a Java method for all the info and error messages*/\r
539         msgErrorCallback_vars.env = env;\r
540         msgErrorCallback_vars.jobj = &obj;\r
541         msgErrorCallback_vars.message_mid = (*env)->GetMethodID(env, cls, "logMessage", "(Ljava/lang/String;)V");\r
542         msgErrorCallback_vars.error_mid = (*env)->GetMethodID(env, cls, "logError", "(Ljava/lang/String;)V");\r
543 \r
544         /* Get the String[] containing the parameters, and converts it into a char** to simulate command line arguments.*/\r
545         arraySize = (*env)->GetArrayLength(env, javaParameters);\r
546         argc = (int) arraySize +1;\r
547         argv = opj_malloc(argc*sizeof(char*));\r
548         argv[0] = "ProgramName.exe";    /* The program name: useless*/\r
549         j=0;\r
550         for (i=1; i<argc; i++) {\r
551                 object = (*env)->GetObjectArrayElement(env, javaParameters, i-1);\r
552                 argv[i] = (char*)(*env)->GetStringUTFChars(env, object, &isCopy);\r
553         }\r
554 \r
555         /*printf("C: decoder params = ");\r
556         for (i=0; i<argc; i++) {\r
557                 printf("[%s]",argv[i]);\r
558         }\r
559         printf("\n");*/\r
560 \r
561         /* set decoding parameters to default values */\r
562         opj_set_default_decoder_parameters(&parameters);\r
563         parameters.decod_format = J2K_CFMT;\r
564 \r
565         /* parse input and get user encoding parameters */\r
566         if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol) == 1) {\r
567                 /* Release the Java arguments array*/\r
568                 for (i=1; i<argc; i++)\r
569                         (*env)->ReleaseStringUTFChars(env, (*env)->GetObjectArrayElement(env, javaParameters, i-1), argv[i]);\r
570                 return -1;\r
571         }\r
572         /* Release the Java arguments array*/\r
573         for (i=1; i<argc; i++)\r
574                 (*env)->ReleaseStringUTFChars(env, (*env)->GetObjectArrayElement(env, javaParameters, i-1), argv[i]);\r
575 \r
576         num_images=1;\r
577 \r
578         /* Get additional information from the Java object variables*/\r
579         fid = (*env)->GetFieldID(env, cls,"skippedResolutions", "I");\r
580         parameters.cp_reduce = (short) (*env)->GetIntField(env, obj, fid);\r
581 \r
582         /*Decoding image one by one*/\r
583         for(imageno = 0; imageno < num_images ; imageno++)\r
584         {\r
585                 image = NULL;\r
586                 fprintf(stderr,"\n");\r
587 \r
588                 /* read the input file and put it in memory into the 'src' object, if the -i option is given in JavaParameters.\r
589                    Implemented for debug purpose. */\r
590                 /* -------------------------------------------------------------- */\r
591                 if (parameters.infile && parameters.infile[0]!='\0') {\r
592                         /*printf("C: opening [%s]\n", parameters.infile);*/\r
593                         fsrc = fopen(parameters.infile, "rb");\r
594                         if (!fsrc) {\r
595                                 fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);\r
596                                 return 1;\r
597                         }\r
598                         fseek(fsrc, 0, SEEK_END);\r
599                         file_length = ftell(fsrc);\r
600                         fseek(fsrc, 0, SEEK_SET);\r
601                         src = (unsigned char *) opj_malloc(file_length);\r
602                         fread(src, 1, file_length, fsrc);\r
603                         fclose(fsrc);\r
604                         /*printf("C: %d bytes read from file\n",file_length);*/\r
605                 } else {\r
606                         /* Preparing the transfer of the codestream from Java to C*/\r
607                         /*printf("C: before transferring codestream\n");*/\r
608                         fid = (*env)->GetFieldID(env, cls,"compressedStream", "[B");\r
609                         jba = (*env)->GetObjectField(env, obj, fid);\r
610                         file_length = (*env)->GetArrayLength(env, jba);\r
611                         jbBody = (*env)->GetByteArrayElements(env, jba, &isCopy);\r
612                         src = (unsigned char*)jbBody;\r
613                 }\r
614 \r
615                 /* decode the code-stream */\r
616                 /* ---------------------- */\r
617 \r
618                 switch(parameters.decod_format) {\r
619                 case J2K_CFMT:\r
620                 {\r
621                         /* JPEG-2000 codestream */\r
622 \r
623                         /* get a decoder handle */\r
624                         dinfo = opj_create_decompress(CODEC_J2K);\r
625 \r
626                         /* catch events using our callbacks and give a local context */\r
627                         opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, &msgErrorCallback_vars);\r
628 \r
629                         /* setup the decoder decoding parameters using user parameters */\r
630                         opj_setup_decoder(dinfo, &parameters);\r
631 \r
632                         /* open a byte stream */\r
633                         cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);\r
634 \r
635                         /* decode the stream and fill the image structure */\r
636                         image = opj_decode(dinfo, cio);\r
637                         if(!image) {\r
638                                 fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");\r
639                                 opj_destroy_decompress(dinfo);\r
640                                 opj_cio_close(cio);\r
641                                 return 1;\r
642                         }\r
643 \r
644                         /* close the byte stream */\r
645                         opj_cio_close(cio);\r
646                 }\r
647                 break;\r
648 \r
649                 case JP2_CFMT:\r
650                 {\r
651                         /* JPEG 2000 compressed image data */\r
652 \r
653                         /* get a decoder handle */\r
654                         dinfo = opj_create_decompress(CODEC_JP2);\r
655 \r
656                         /* catch events using our callbacks and give a local context */\r
657                         opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, &msgErrorCallback_vars);\r
658 \r
659                         /* setup the decoder decoding parameters using the current image and user parameters */\r
660                         opj_setup_decoder(dinfo, &parameters);\r
661 \r
662                         /* open a byte stream */\r
663                         cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);\r
664 \r
665                         /* decode the stream and fill the image structure */\r
666                         image = opj_decode(dinfo, cio);\r
667                         if(!image) {\r
668                                 fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");\r
669                                 opj_destroy_decompress(dinfo);\r
670                                 opj_cio_close(cio);\r
671                                 return 1;\r
672                         }\r
673 \r
674                         /* close the byte stream */\r
675                         opj_cio_close(cio);\r
676 \r
677                 }\r
678                 break;\r
679 \r
680                 case JPT_CFMT:\r
681                 {\r
682                         /* JPEG 2000, JPIP */\r
683 \r
684                         /* get a decoder handle */\r
685                         dinfo = opj_create_decompress(CODEC_JPT);\r
686 \r
687                         /* catch events using our callbacks and give a local context */\r
688                         opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, &msgErrorCallback_vars);\r
689 \r
690                         /* setup the decoder decoding parameters using user parameters */\r
691                         opj_setup_decoder(dinfo, &parameters);\r
692 \r
693                         /* open a byte stream */\r
694                         cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);\r
695 \r
696                         /* decode the stream and fill the image structure */\r
697                         image = opj_decode(dinfo, cio);\r
698                         if(!image) {\r
699                                 fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");\r
700                                 opj_destroy_decompress(dinfo);\r
701                                 opj_cio_close(cio);\r
702                                 return 1;\r
703                         }\r
704 \r
705                         /* close the byte stream */\r
706                         opj_cio_close(cio);\r
707                 }\r
708                 break;\r
709 \r
710                 default:\r
711                         fprintf(stderr, "skipping file..\n");\r
712                         continue;\r
713         }\r
714 \r
715                 /* free the memory containing the code-stream */\r
716                 if (parameters.infile && parameters.infile[0]!='\0') {\r
717                         opj_free(src);\r
718                 } else {\r
719                         (*env)->ReleaseByteArrayElements(env, jba, jbBody, 0);\r
720                 }\r
721                 src = NULL;\r
722 \r
723                 /* create output image.\r
724                         If the -o parameter is given in the JavaParameters, write the decoded version into a file.\r
725                         Implemented for debug purpose. */\r
726                 /* ---------------------------------- */\r
727                 switch (parameters.cod_format) {\r
728                 case PXM_DFMT:                  /* PNM PGM PPM */\r
729                         if (imagetopnm(image, parameters.outfile)) {\r
730                                 fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);\r
731                         }\r
732                         else {\r
733                                 fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);\r
734                         }\r
735                         break;\r
736 \r
737                 case PGX_DFMT:                  /* PGX */\r
738                         if(imagetopgx(image, parameters.outfile)){\r
739                                 fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);\r
740                         }\r
741                         else {\r
742                                 fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);\r
743                         }\r
744                         break;\r
745 \r
746                 case BMP_DFMT:                  /* BMP */\r
747                         if(imagetobmp(image, parameters.outfile)){\r
748                                 fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);\r
749                         }\r
750                         else {\r
751                                 fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);\r
752                         }\r
753                         break;\r
754 \r
755                 }\r
756 \r
757                 /* ========= Return the image to the Java structure ===============*/\r
758 #ifdef CHECK_THRESHOLDS\r
759                 printf("C: checking thresholds\n");\r
760 #endif\r
761                 /* First compute the real with and height, in function of the resolutions decoded.*/\r
762                 /*wr = (image->comps[0].w + (1 << image->comps[0].factor) -1) >> image->comps[0].factor;*/\r
763                 /*hr = (image->comps[0].h + (1 << image->comps[0].factor) -1) >> image->comps[0].factor;*/\r
764                 w = image->comps[0].w;\r
765                 h = image->comps[0].h;\r
766 \r
767                 if (image->numcomps==3) {       /* 3 components color image*/\r
768                         ptr = image->comps[0].data;\r
769                         ptr1 = image->comps[1].data;\r
770                         ptr2 = image->comps[2].data;\r
771 #ifdef CHECK_THRESHOLDS \r
772                         if (image->comps[0].sgnd) {\r
773                                 min_value = -128;\r
774                                 max_value = 127;\r
775                         } else {\r
776                                 min_value = 0;\r
777                                 max_value = 255;\r
778                         }\r
779 #endif                  \r
780                         /* Get the pointer to the Java structure where the data must be copied*/\r
781                         fid = (*env)->GetFieldID(env, cls,"image24", "[I");\r
782                         jia = (*env)->GetObjectField(env, obj, fid);\r
783                         jiBody = (*env)->GetIntArrayElements(env, jia, 0);\r
784                         ptrIBody = jiBody;\r
785                         printf("C: transferring image24: %d int to Java pointer=%d\n",image->numcomps*w*h, ptrIBody);\r
786 \r
787                         for (i=0; i<w*h; i++) {\r
788                                 tempUC = (unsigned char)(ptr[i]);\r
789                                 tempUC1 = (unsigned char)(ptr1[i]);\r
790                                 tempUC2 = (unsigned char)(ptr2[i]);\r
791 #ifdef CHECK_THRESHOLDS\r
792                                 if (tempUC < min_value)\r
793                                         tempUC=min_value;\r
794                                 else if (tempUC > max_value)\r
795                                         tempUC=max_value;\r
796                                 if (tempUC1 < min_value)\r
797                                         tempUC1=min_value;\r
798                                 else if (tempUC1 > max_value)\r
799                                         tempUC1=max_value;\r
800                                 if (tempUC2 < min_value)\r
801                                         tempUC2=min_value;\r
802                                 else if (tempUC2 > max_value)\r
803                                         tempUC2=max_value;\r
804 #endif\r
805                                 *(ptrIBody++)  = (int) ( (tempUC2<<16) + (tempUC1<<8) + tempUC );\r
806                         }\r
807                         (*env)->ReleaseIntArrayElements(env, jia, jiBody, 0);\r
808 \r
809                 } else {        /* 1 component 8 or 16 bpp image*/\r
810                         ptr = image->comps[0].data;\r
811                         printf("C: before transferring a %d bpp image to java (length = %d)\n",image->comps[0].prec ,w*h);\r
812                         if (image->comps[0].prec<=8) {\r
813                                 fid = (*env)->GetFieldID(env, cls,"image8", "[B");\r
814                                 jba = (*env)->GetObjectField(env, obj, fid);\r
815                                 jbBody = (*env)->GetByteArrayElements(env, jba, 0);\r
816                                 ptrBBody = jbBody;\r
817 #ifdef CHECK_THRESHOLDS \r
818                                 if (image->comps[0].sgnd) {\r
819                                         min_value = -128;\r
820                                         max_value = 127;\r
821                                 } else {\r
822                                         min_value = 0;\r
823                                         max_value = 255;\r
824                                 }\r
825 #endif                                                          \r
826                                 /*printf("C: transferring %d shorts to Java image8 pointer = %d\n", wr*hr,ptrSBody);*/\r
827                                 for (i=0; i<w*h; i++) {\r
828                                         tempUC = (unsigned char) (ptr[i]);\r
829 #ifdef CHECK_THRESHOLDS\r
830                                         if (tempUC<min_value)\r
831                                                 tempUC = min_value;\r
832                                         else if (tempUC > max_value)\r
833                                                 tempUC = max_value;\r
834 #endif\r
835                                         *(ptrBBody++) = tempUC;\r
836                                 }\r
837                                 (*env)->ReleaseByteArrayElements(env, jba, jbBody, 0);\r
838                                 printf("C: image8 transferred to Java\n");\r
839                         } else {\r
840                                 fid = (*env)->GetFieldID(env, cls,"image16", "[S");\r
841                                 jsa = (*env)->GetObjectField(env, obj, fid);\r
842                                 jsBody = (*env)->GetShortArrayElements(env, jsa, 0);\r
843                                 ptrSBody = jsBody;\r
844 #ifdef CHECK_THRESHOLDS \r
845                                 if (image->comps[0].sgnd) {\r
846                                         min_value = -32768;\r
847                                         max_value = 32767;\r
848                                 } else {\r
849                                         min_value = 0;\r
850                                         max_value = 65535;\r
851                                 }\r
852                                 printf("C: minValue = %d, maxValue = %d\n", min_value, max_value);\r
853 #endif                          \r
854                                 printf("C: transferring %d shorts to Java image16 pointer = %d\n", w*h,ptrSBody);\r
855                                 for (i=0; i<w*h; i++) {\r
856                                         tempS = (short) (ptr[i]);\r
857 #ifdef CHECK_THRESHOLDS\r
858                                         if (tempS<min_value) {\r
859                                                 printf("C: value %d truncated to %d\n", tempS, min_value);\r
860                                                 tempS = min_value;\r
861                                         } else if (tempS > max_value) {\r
862                                                 printf("C: value %d truncated to %d\n", tempS, max_value);\r
863                                                 tempS = max_value;\r
864                                         }\r
865 #endif\r
866                                         *(ptrSBody++) = tempS;\r
867                                 }\r
868                                 (*env)->ReleaseShortArrayElements(env, jsa, jsBody, 0);\r
869                                 printf("C: image16 completely filled\n");\r
870                         }\r
871                 }       \r
872 \r
873 \r
874                 /* free remaining structures */\r
875                 if(dinfo) {\r
876                         opj_destroy_decompress(dinfo);\r
877                 }\r
878                 /* free image data structure */\r
879                 opj_image_destroy(image);\r
880 \r
881         }\r
882         return 1; /* OK */\r
883 }\r
884 /*end main*/\r
885 \r