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