Debian Codegraph @

wrapping/java/openjp2/JavaOpenJPEGDecoder.c

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