Subversion Repositories Kolibri OS

Rev

Go to most recent revision | Blame | Last modification | View Log | RSS feed

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