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