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