re-organization of openjpeg directories hierarchy : step 1
authorAntonin Descampe <antonin@gmail.com>
Wed, 13 Apr 2011 21:01:39 +0000 (21:01 +0000)
committerAntonin Descampe <antonin@gmail.com>
Wed, 13 Apr 2011 21:01:39 +0000 (21:01 +0000)
276 files changed:
JavaOpenJPEG/CMakeLists.txt [deleted file]
JavaOpenJPEG/JavaOpenJPEG.c [deleted file]
JavaOpenJPEG/JavaOpenJPEGDecoder.c [deleted file]
JavaOpenJPEG/Makefile [deleted file]
JavaOpenJPEG/java-jni/include/jawt.h [deleted file]
JavaOpenJPEG/java-jni/include/jdwpTransport.h [deleted file]
JavaOpenJPEG/java-jni/include/jni.h [deleted file]
JavaOpenJPEG/java-jni/include/jvmdi.h [deleted file]
JavaOpenJPEG/java-jni/include/jvmpi.h [deleted file]
JavaOpenJPEG/java-jni/include/jvmti.h [deleted file]
JavaOpenJPEG/java-jni/include/win32/jawt_md.h [deleted file]
JavaOpenJPEG/java-jni/include/win32/jni_md.h [deleted file]
JavaOpenJPEG/java-jni/lib/jvm.lib [deleted file]
JavaOpenJPEG/java-sources/org/openJpeg/OpenJPEGJavaDecoder.java [deleted file]
JavaOpenJPEG/java-sources/org/openJpeg/OpenJPEGJavaEncoder.java [deleted file]
JavaOpenJPEG/org_openJpeg_OpenJPEGJavaDecoder.h [deleted file]
JavaOpenJPEG/org_openJpeg_OpenJPEGJavaEncoder.h [deleted file]
OPJViewer/Makefile [deleted file]
OPJViewer/OPJViewer.dsp [deleted file]
OPJViewer/OPJViewer.dsw [deleted file]
OPJViewer/OPJViewer.iss [deleted file]
OPJViewer/Readme.txt [deleted file]
OPJViewer/about/about.htm [deleted file]
OPJViewer/about/opj_logo.png [deleted file]
OPJViewer/buildupdate.bat [deleted file]
OPJViewer/source/OPJAbout.cpp [deleted file]
OPJViewer/source/OPJChild.ico [deleted file]
OPJViewer/source/OPJChild16.xpm [deleted file]
OPJViewer/source/OPJDialogs.cpp [deleted file]
OPJViewer/source/OPJThreads.cpp [deleted file]
OPJViewer/source/OPJViewer.cpp [deleted file]
OPJViewer/source/OPJViewer.h [deleted file]
OPJViewer/source/OPJViewer.ico [deleted file]
OPJViewer/source/OPJViewer.rc [deleted file]
OPJViewer/source/OPJViewer16.xpm [deleted file]
OPJViewer/source/about_htm.h [deleted file]
OPJViewer/source/build.h [deleted file]
OPJViewer/source/icon1.xpm [deleted file]
OPJViewer/source/icon2.xpm [deleted file]
OPJViewer/source/icon3.xpm [deleted file]
OPJViewer/source/icon4.xpm [deleted file]
OPJViewer/source/icon5.xpm [deleted file]
OPJViewer/source/imagjpeg2000.cpp [deleted file]
OPJViewer/source/imagjpeg2000.h [deleted file]
OPJViewer/source/imagmxf.cpp [deleted file]
OPJViewer/source/imagmxf.h [deleted file]
OPJViewer/source/license.txt [deleted file]
OPJViewer/source/opj_logo.xpm [deleted file]
OPJViewer/source/readmeafter.txt [deleted file]
OPJViewer/source/readmebefore.txt [deleted file]
OPJViewer/source/wxj2kparser.cpp [deleted file]
OPJViewer/source/wxjp2parser.cpp [deleted file]
OPJ_Validate/Makefile [deleted file]
OPJ_Validate/OPJ_Param_File_v0_1.txt [deleted file]
OPJ_Validate/OPJ_Validate.c [deleted file]
OPJ_Validate/OPJ_Validate.dsp [deleted file]
OPJ_Validate/OPJ_Validate.dsw [deleted file]
OPJ_Validate/OPJ_Validate_Candidate_vs_Ref.bat [deleted file]
OPJ_Validate/OPJ_Validate_Candidate_vs_Ref.sh [deleted file]
OPJ_Validate/OPJ_Validate_Create_Ref.bat [deleted file]
OPJ_Validate/OPJ_Validate_Create_Ref.sh [deleted file]
OPJ_Validate/README.txt [deleted file]
OPJ_Validate/linux_OPJ_Param_File_v0_1.txt [deleted file]
OPJ_Validate/md5.c [deleted file]
OPJ_Validate/md5.h [deleted file]
OPJ_Validate/original/README.txt [deleted file]
applications/JavaOpenJPEG/CMakeLists.txt [new file with mode: 0644]
applications/JavaOpenJPEG/JavaOpenJPEG.c [new file with mode: 0644]
applications/JavaOpenJPEG/JavaOpenJPEGDecoder.c [new file with mode: 0644]
applications/JavaOpenJPEG/Makefile [new file with mode: 0644]
applications/JavaOpenJPEG/java-jni/include/jawt.h [new file with mode: 0644]
applications/JavaOpenJPEG/java-jni/include/jdwpTransport.h [new file with mode: 0644]
applications/JavaOpenJPEG/java-jni/include/jni.h [new file with mode: 0644]
applications/JavaOpenJPEG/java-jni/include/jvmdi.h [new file with mode: 0644]
applications/JavaOpenJPEG/java-jni/include/jvmpi.h [new file with mode: 0644]
applications/JavaOpenJPEG/java-jni/include/jvmti.h [new file with mode: 0644]
applications/JavaOpenJPEG/java-jni/include/win32/jawt_md.h [new file with mode: 0644]
applications/JavaOpenJPEG/java-jni/include/win32/jni_md.h [new file with mode: 0644]
applications/JavaOpenJPEG/java-jni/lib/jvm.lib [new file with mode: 0644]
applications/JavaOpenJPEG/java-sources/org/openJpeg/OpenJPEGJavaDecoder.java [new file with mode: 0644]
applications/JavaOpenJPEG/java-sources/org/openJpeg/OpenJPEGJavaEncoder.java [new file with mode: 0644]
applications/JavaOpenJPEG/org_openJpeg_OpenJPEGJavaDecoder.h [new file with mode: 0644]
applications/JavaOpenJPEG/org_openJpeg_OpenJPEGJavaEncoder.h [new file with mode: 0644]
applications/OPJViewer/Makefile [new file with mode: 0644]
applications/OPJViewer/OPJViewer.dsp [new file with mode: 0644]
applications/OPJViewer/OPJViewer.dsw [new file with mode: 0644]
applications/OPJViewer/OPJViewer.iss [new file with mode: 0644]
applications/OPJViewer/Readme.txt [new file with mode: 0644]
applications/OPJViewer/about/about.htm [new file with mode: 0644]
applications/OPJViewer/about/opj_logo.png [new file with mode: 0644]
applications/OPJViewer/buildupdate.bat [new file with mode: 0644]
applications/OPJViewer/source/OPJAbout.cpp [new file with mode: 0644]
applications/OPJViewer/source/OPJChild.ico [new file with mode: 0644]
applications/OPJViewer/source/OPJChild16.xpm [new file with mode: 0644]
applications/OPJViewer/source/OPJDialogs.cpp [new file with mode: 0644]
applications/OPJViewer/source/OPJThreads.cpp [new file with mode: 0644]
applications/OPJViewer/source/OPJViewer.cpp [new file with mode: 0644]
applications/OPJViewer/source/OPJViewer.h [new file with mode: 0644]
applications/OPJViewer/source/OPJViewer.ico [new file with mode: 0644]
applications/OPJViewer/source/OPJViewer.rc [new file with mode: 0644]
applications/OPJViewer/source/OPJViewer16.xpm [new file with mode: 0644]
applications/OPJViewer/source/about_htm.h [new file with mode: 0644]
applications/OPJViewer/source/build.h [new file with mode: 0644]
applications/OPJViewer/source/icon1.xpm [new file with mode: 0644]
applications/OPJViewer/source/icon2.xpm [new file with mode: 0644]
applications/OPJViewer/source/icon3.xpm [new file with mode: 0644]
applications/OPJViewer/source/icon4.xpm [new file with mode: 0644]
applications/OPJViewer/source/icon5.xpm [new file with mode: 0644]
applications/OPJViewer/source/imagjpeg2000.cpp [new file with mode: 0644]
applications/OPJViewer/source/imagjpeg2000.h [new file with mode: 0644]
applications/OPJViewer/source/imagmxf.cpp [new file with mode: 0644]
applications/OPJViewer/source/imagmxf.h [new file with mode: 0644]
applications/OPJViewer/source/license.txt [new file with mode: 0644]
applications/OPJViewer/source/opj_logo.xpm [new file with mode: 0644]
applications/OPJViewer/source/readmeafter.txt [new file with mode: 0644]
applications/OPJViewer/source/readmebefore.txt [new file with mode: 0644]
applications/OPJViewer/source/wxj2kparser.cpp [new file with mode: 0644]
applications/OPJViewer/source/wxjp2parser.cpp [new file with mode: 0644]
applications/codec/CMakeLists.txt [new file with mode: 0644]
applications/codec/Makefile.am [new file with mode: 0644]
applications/codec/Makefile.nix [new file with mode: 0644]
applications/codec/README [new file with mode: 0644]
applications/codec/convert.c [new file with mode: 0644]
applications/codec/convert.h [new file with mode: 0644]
applications/codec/image_to_j2k.c [new file with mode: 0644]
applications/codec/index.c [new file with mode: 0644]
applications/codec/index.h [new file with mode: 0644]
applications/codec/j2k_dump.c [new file with mode: 0644]
applications/codec/j2k_to_image.c [new file with mode: 0644]
applications/codec/windirent.h [new file with mode: 0644]
applications/common/color.c [new file with mode: 0644]
applications/common/color.h [new file with mode: 0644]
applications/common/format_defs.h [new file with mode: 0644]
applications/common/getopt.c [new file with mode: 0644]
applications/common/getopt.h [new file with mode: 0644]
applications/indexer_JPIP/CMakeLists.txt [new file with mode: 0644]
applications/indexer_JPIP/Makefile [new file with mode: 0644]
applications/indexer_JPIP/bio.c [new file with mode: 0644]
applications/indexer_JPIP/bio.h [new file with mode: 0644]
applications/indexer_JPIP/cio.c [new file with mode: 0644]
applications/indexer_JPIP/cio.h [new file with mode: 0644]
applications/indexer_JPIP/fix.c [new file with mode: 0644]
applications/indexer_JPIP/fix.h [new file with mode: 0644]
applications/indexer_JPIP/index_create.c [new file with mode: 0644]
applications/indexer_JPIP/int.c [new file with mode: 0644]
applications/indexer_JPIP/int.h [new file with mode: 0644]
applications/indexer_JPIP/j2k.h [new file with mode: 0644]
applications/indexer_JPIP/jp2.c [new file with mode: 0644]
applications/indexer_JPIP/jp2.h [new file with mode: 0644]
applications/indexer_JPIP/jpip.c [new file with mode: 0644]
applications/indexer_JPIP/jpip.h [new file with mode: 0644]
applications/indexer_JPIP/pi.c [new file with mode: 0644]
applications/indexer_JPIP/pi.h [new file with mode: 0644]
applications/indexer_JPIP/t2.c [new file with mode: 0644]
applications/indexer_JPIP/t2.h [new file with mode: 0644]
applications/indexer_JPIP/tcd.c [new file with mode: 0644]
applications/indexer_JPIP/tcd.h [new file with mode: 0644]
applications/indexer_JPIP/tgt.c [new file with mode: 0644]
applications/indexer_JPIP/tgt.h [new file with mode: 0644]
applications/mj2/CMakeLists.txt [new file with mode: 0644]
applications/mj2/Makefile.am [new file with mode: 0644]
applications/mj2/Makefile.nix [new file with mode: 0644]
applications/mj2/extract_j2k_from_mj2.c [new file with mode: 0644]
applications/mj2/frames_to_mj2.c [new file with mode: 0644]
applications/mj2/meta_out.c [new file with mode: 0644]
applications/mj2/meta_out.h [new file with mode: 0644]
applications/mj2/mj2.c [new file with mode: 0644]
applications/mj2/mj2.h [new file with mode: 0644]
applications/mj2/mj2_convert.c [new file with mode: 0644]
applications/mj2/mj2_convert.h [new file with mode: 0644]
applications/mj2/mj2_to_frames.c [new file with mode: 0644]
applications/mj2/mj2_to_metadata.c [new file with mode: 0644]
applications/mj2/mj2_to_metadata.dtd [new file with mode: 0644]
applications/mj2/mj2_to_metadata.h [new file with mode: 0644]
applications/mj2/mj2_to_metadata.sln [new file with mode: 0644]
applications/mj2/mj2_to_metadata.vcproj [new file with mode: 0644]
applications/mj2/mj2_to_metadata_Notes.doc [new file with mode: 0644]
applications/mj2/readme.txt [new file with mode: 0644]
applications/mj2/wrap_j2k_in_mj2.c [new file with mode: 0644]
codec/CMakeLists.txt [deleted file]
codec/Makefile.am [deleted file]
codec/Makefile.nix [deleted file]
codec/README [deleted file]
codec/convert.c [deleted file]
codec/convert.h [deleted file]
codec/image_to_j2k.c [deleted file]
codec/index.c [deleted file]
codec/index.h [deleted file]
codec/j2k_dump.c [deleted file]
codec/j2k_to_image.c [deleted file]
codec/windirent.h [deleted file]
common/color.c [deleted file]
common/color.h [deleted file]
common/format_defs.h [deleted file]
common/getopt.c [deleted file]
common/getopt.h [deleted file]
indexer_JPIP/CMakeLists.txt [deleted file]
indexer_JPIP/Makefile [deleted file]
indexer_JPIP/bio.c [deleted file]
indexer_JPIP/bio.h [deleted file]
indexer_JPIP/cio.c [deleted file]
indexer_JPIP/cio.h [deleted file]
indexer_JPIP/fix.c [deleted file]
indexer_JPIP/fix.h [deleted file]
indexer_JPIP/index_create.c [deleted file]
indexer_JPIP/int.c [deleted file]
indexer_JPIP/int.h [deleted file]
indexer_JPIP/j2k.h [deleted file]
indexer_JPIP/jp2.c [deleted file]
indexer_JPIP/jp2.h [deleted file]
indexer_JPIP/jpip.c [deleted file]
indexer_JPIP/jpip.h [deleted file]
indexer_JPIP/pi.c [deleted file]
indexer_JPIP/pi.h [deleted file]
indexer_JPIP/t2.c [deleted file]
indexer_JPIP/t2.h [deleted file]
indexer_JPIP/tcd.c [deleted file]
indexer_JPIP/tcd.h [deleted file]
indexer_JPIP/tgt.c [deleted file]
indexer_JPIP/tgt.h [deleted file]
jpwl/CMakeLists.txt [deleted file]
jpwl/Makefile.am [deleted file]
jpwl/Makefile.nix [deleted file]
jpwl/README.txt [deleted file]
jpwl/crc.c [deleted file]
jpwl/crc.h [deleted file]
jpwl/jpwl.c [deleted file]
jpwl/jpwl.h [deleted file]
jpwl/jpwl_lib.c [deleted file]
jpwl/rs.c [deleted file]
jpwl/rs.h [deleted file]
libopenjpeg/jpwl/CMakeLists.txt [new file with mode: 0755]
libopenjpeg/jpwl/Makefile.am [new file with mode: 0644]
libopenjpeg/jpwl/Makefile.nix [new file with mode: 0644]
libopenjpeg/jpwl/README.txt [new file with mode: 0644]
libopenjpeg/jpwl/crc.c [new file with mode: 0644]
libopenjpeg/jpwl/crc.h [new file with mode: 0644]
libopenjpeg/jpwl/jpwl.c [new file with mode: 0644]
libopenjpeg/jpwl/jpwl.h [new file with mode: 0644]
libopenjpeg/jpwl/jpwl_lib.c [new file with mode: 0644]
libopenjpeg/jpwl/rs.c [new file with mode: 0644]
libopenjpeg/jpwl/rs.h [new file with mode: 0644]
mj2/CMakeLists.txt [deleted file]
mj2/Makefile.am [deleted file]
mj2/Makefile.nix [deleted file]
mj2/extract_j2k_from_mj2.c [deleted file]
mj2/frames_to_mj2.c [deleted file]
mj2/meta_out.c [deleted file]
mj2/meta_out.h [deleted file]
mj2/mj2.c [deleted file]
mj2/mj2.h [deleted file]
mj2/mj2_convert.c [deleted file]
mj2/mj2_convert.h [deleted file]
mj2/mj2_to_frames.c [deleted file]
mj2/mj2_to_metadata.c [deleted file]
mj2/mj2_to_metadata.dtd [deleted file]
mj2/mj2_to_metadata.h [deleted file]
mj2/mj2_to_metadata.sln [deleted file]
mj2/mj2_to_metadata.vcproj [deleted file]
mj2/mj2_to_metadata_Notes.doc [deleted file]
mj2/readme.txt [deleted file]
mj2/wrap_j2k_in_mj2.c [deleted file]
testing/Makefile [new file with mode: 0644]
testing/OPJ_Param_File_v0_1.txt [new file with mode: 0644]
testing/OPJ_Validate.c [new file with mode: 0644]
testing/OPJ_Validate.dsp [new file with mode: 0644]
testing/OPJ_Validate.dsw [new file with mode: 0644]
testing/OPJ_Validate_Candidate_vs_Ref.bat [new file with mode: 0644]
testing/OPJ_Validate_Candidate_vs_Ref.sh [new file with mode: 0644]
testing/OPJ_Validate_Create_Ref.bat [new file with mode: 0644]
testing/OPJ_Validate_Create_Ref.sh [new file with mode: 0644]
testing/README.txt [new file with mode: 0644]
testing/linux_OPJ_Param_File_v0_1.txt [new file with mode: 0644]
testing/md5.c [new file with mode: 0644]
testing/md5.h [new file with mode: 0644]
testing/original/README.txt [new file with mode: 0644]

diff --git a/JavaOpenJPEG/CMakeLists.txt b/JavaOpenJPEG/CMakeLists.txt
deleted file mode 100644 (file)
index 6b1720b..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-#JavaOpenJPEG/CMakeLists.txt
-
-# First thing define the common source:
-SET(common_SRCS
-  ../codec/convert.c
-  ../codec/index.c
-  )
-
-# If not getopt was found then add it to the lib:
-IF(DONT_HAVE_GETOPT)
-  SET(common_SRCS
-    ${common_SRCS}
-    ../common/getopt.c
-  )
-ENDIF(DONT_HAVE_GETOPT)
-
-
-# Headers file are located here:
-INCLUDE_DIRECTORIES(
-  ${OPENJPEG_SOURCE_DIR}/libopenjpeg
-  ${LCMS_INCLUDE_DIR}
-  ${PNG_INCLUDE_DIR}
-  ${ZLIB_INCLUDE_DIR}
-  ${TIFF_INCLUDE_DIR}
-  )
-
-# Loop over all executables:
-FOREACH(exe j2k_to_image image_to_j2k)
-  ADD_EXECUTABLE(${exe} ${exe}.c ${common_SRCS})
-  TARGET_LINK_LIBRARIES(${exe} ${OPJ_PREFIX}openjpeg ${TIFF_LIBRARIES}
-       ${PNG_LIBRARIES} ${ZLIB_LIBRARY} ${LCMS_LIB})
-  # On unix you need to link to the math library:
-  IF(UNIX)
-    TARGET_LINK_LIBRARIES(${exe} -lm)
-  ENDIF(UNIX)
-  # Install exe
-  INSTALL_TARGETS(/bin/ ${exe})
-ENDFOREACH(exe)
-
-
diff --git a/JavaOpenJPEG/JavaOpenJPEG.c b/JavaOpenJPEG/JavaOpenJPEG.c
deleted file mode 100644 (file)
index b1f0302..0000000
+++ /dev/null
@@ -1,1976 +0,0 @@
-/*\r
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
- * Copyright (c) 2002-2007, Professor Benoit Macq\r
- * Copyright (c) 2001-2003, David Janssens\r
- * Copyright (c) 2002-2003, Yannick Verschueren\r
- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe\r
- * Copyright (c) 2005, Herve Drolon, FreeImage Team \r
- * Copyright (c) 2006-2007, Parvatha Elangovan\r
- * Copyright (c) 2007, Patrick Piscaglia (Telemis)\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-#include <stdio.h>\r
-#include <string.h>\r
-#include <stdlib.h>\r
-#include <jni.h>\r
-#include <math.h>\r
-\r
-#include "openjpeg.h"\r
-#include "getopt.h"\r
-#include "convert.h"\r
-#include "index.h"\r
-#include "dirent.h"\r
-#include "org_openJpeg_OpenJPEGJavaEncoder.h"\r
-\r
-#ifndef _WIN32\r
-#define stricmp strcasecmp\r
-#define strnicmp strncasecmp\r
-#endif\r
-\r
-#include "format_defs.h"\r
-\r
-#define CINEMA_24_CS 1302083   /*Codestream length for 24fps*/\r
-#define CINEMA_48_CS 651041            /*Codestream length for 48fps*/\r
-#define COMP_24_CS 1041666             /*Maximum size per color component for 2K & 4K @ 24fps*/\r
-#define COMP_48_CS 520833              /*Maximum size per color component for 2K @ 48fps*/\r
-\r
-extern int get_file_format(char *filename);\r
-extern void error_callback(const char *msg, void *client_data);\r
-extern warning_callback(const char *msg, void *client_data);\r
-extern void info_callback(const char *msg, void *client_data);\r
-\r
-typedef struct callback_variables {\r
-       JNIEnv *env;\r
-       /** 'jclass' object used to call a Java method from the C */\r
-       jobject *jobj;\r
-       /** 'jclass' object used to call a Java method from the C */\r
-       jmethodID message_mid;\r
-       jmethodID error_mid;\r
-} callback_variables_t;\r
-\r
-typedef struct dircnt{\r
-       /** Buffer for holding images read from Directory*/\r
-       char *filename_buf;\r
-       /** Pointer to the buffer*/\r
-       char **filename;\r
-}dircnt_t;\r
-\r
-typedef struct img_folder{\r
-       /** The directory path of the folder containing input images*/\r
-       char *imgdirpath;\r
-       /** Output format*/\r
-       char *out_format;\r
-       /** Enable option*/\r
-       char set_imgdir;\r
-       /** Enable Cod Format for output*/\r
-       char set_out_format;\r
-       /** User specified rate stored in case of cinema option*/\r
-       float *rates;\r
-}img_fol_t;\r
-\r
-void encode_help_display() {\r
-       fprintf(stdout,"HELP\n----\n\n");\r
-       fprintf(stdout,"- the -h option displays this help information on screen\n\n");\r
-\r
-/* UniPG>> */\r
-       fprintf(stdout,"List of parameters for the JPEG 2000 "\r
-#ifdef USE_JPWL\r
-               "+ JPWL "\r
-#endif /* USE_JPWL */\r
-               "encoder:\n");\r
-/* <<UniPG */\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"REMARKS:\n");\r
-       fprintf(stdout,"---------\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"The markers written to the main_header are : SOC SIZ COD QCD COM.\n");\r
-       fprintf(stdout,"COD and QCD never appear in the tile_header.\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"- This coder can encode a mega image, a test was made on a 24000x24000 pixels \n");\r
-       fprintf(stdout,"color image.  You need enough disk space memory (twice the original) to encode \n");\r
-       fprintf(stdout,"the image,i.e. for a 1.5 GB image you need a minimum of 3GB of disk memory)\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"By default:\n");\r
-       fprintf(stdout,"------------\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout," * Lossless\n");\r
-       fprintf(stdout," * 1 tile\n");\r
-       fprintf(stdout," * Size of precinct : 2^15 x 2^15 (means 1 precinct)\n");\r
-       fprintf(stdout," * Size of code-block : 64 x 64\n");\r
-       fprintf(stdout," * Number of resolutions: 6\n");\r
-       fprintf(stdout," * No SOP marker in the codestream\n");\r
-       fprintf(stdout," * No EPH marker in the codestream\n");\r
-       fprintf(stdout," * No sub-sampling in x or y direction\n");\r
-       fprintf(stdout," * No mode switch activated\n");\r
-       fprintf(stdout," * Progression order: LRCP\n");\r
-       fprintf(stdout," * No index file\n");\r
-       fprintf(stdout," * No ROI upshifted\n");\r
-       fprintf(stdout," * No offset of the origin of the image\n");\r
-       fprintf(stdout," * No offset of the origin of the tiles\n");\r
-       fprintf(stdout," * Reversible DWT 5-3\n");\r
-/* UniPG>> */\r
-#ifdef USE_JPWL\r
-       fprintf(stdout," * No JPWL protection\n");\r
-#endif /* USE_JPWL */\r
-/* <<UniPG */\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"Parameters:\n");\r
-       fprintf(stdout,"------------\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"Required Parameters (except with -h):\n");\r
-       fprintf(stdout,"One of the two options -ImgDir or -i must be used\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-ImgDir      : Image file Directory path (example ../Images) \n");\r
-       fprintf(stdout,"    When using this option -OutFor must be used\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-OutFor \n");\r
-       fprintf(stdout,"    REQUIRED only if -ImgDir is used\n");\r
-       fprintf(stdout,"          Need to specify only format without filename <BMP>  \n");\r
-       fprintf(stdout,"    Currently accepts PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA formats\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-i           : source file  (-i source.pnm also *.pgm, *.ppm, *.bmp, *.tif, *.raw, *.tga) \n");\r
-       fprintf(stdout,"    When using this option -o must be used\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-o           : destination file (-o dest.j2k or .jp2) \n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"Optional Parameters:\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-h           : display the help information \n ");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-cinema2K    : Digital Cinema 2K profile compliant codestream for 2K resolution.(-cinema2k 24 or 48) \n");\r
-       fprintf(stdout,"          Need to specify the frames per second for a 2K resolution. Only 24 or 48 fps is allowed\n"); \r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-cinema4K    : Digital Cinema 4K profile compliant codestream for 4K resolution \n");\r
-       fprintf(stdout,"          Frames per second not required. Default value is 24fps\n"); \r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-r           : different compression ratios for successive layers (-r 20,10,5)\n ");\r
-       fprintf(stdout,"                 - The rate specified for each quality level is the desired \n");\r
-       fprintf(stdout,"                   compression factor.\n");\r
-       fprintf(stdout,"                   Example: -r 20,10,1 means quality 1: compress 20x, \n");\r
-       fprintf(stdout,"                     quality 2: compress 10x and quality 3: compress lossless\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"               (options -r and -q cannot be used together)\n ");\r
-       fprintf(stdout,"\n");\r
-\r
-       fprintf(stdout,"-q           : different psnr for successive layers (-q 30,40,50) \n ");\r
-\r
-       fprintf(stdout,"               (options -r and -q cannot be used together)\n ");\r
-\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-n           : number of resolutions (-n 3) \n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-b           : size of code block (-b 32,32) \n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-c           : size of precinct (-c 128,128) \n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-t           : size of tile (-t 512,512) \n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-p           : progression order (-p LRCP) [LRCP, RLCP, RPCL, PCRL, CPRL] \n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-s           : subsampling factor (-s 2,2) [-s X,Y] \n");\r
-       fprintf(stdout,"             Remark: subsampling bigger than 2 can produce error\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-POC         : Progression order change (-POC T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL) \n");\r
-       fprintf(stdout,"      Example: T1=0,0,1,5,3,CPRL \n");\r
-       fprintf(stdout,"                         : Ttilenumber=Resolution num start,Component num start,Layer num end,Resolution num end,Component num end,Progression order\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-SOP         : write SOP marker before each packet \n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-EPH         : write EPH marker after each header packet \n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-M           : mode switch (-M 3) [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");\r
-       fprintf(stdout,"                 8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)] \n");\r
-       fprintf(stdout,"                 Indicate multiple modes by adding their values. \n");\r
-       fprintf(stdout,"                 ex: RESTART(4) + RESET(2) + SEGMARK(32) = -M 38\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-x           : create an index file *.Idx (-x index_name.Idx) \n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-ROI         : c=%%d,U=%%d : quantization indices upshifted \n");\r
-       fprintf(stdout,"               for component c=%%d [%%d = 0,1,2]\n");\r
-       fprintf(stdout,"               with a value of U=%%d [0 <= %%d <= 37] (i.e. -ROI c=0,U=25) \n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-d           : offset of the origin of the image (-d 150,300) \n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-T           : offset of the origin of the tiles (-T 100,75) \n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"-I           : use the irreversible DWT 9-7 (-I) \n");\r
-       fprintf(stdout,"\n");\r
-/* UniPG>> */\r
-#ifdef USE_JPWL\r
-       fprintf(stdout,"-W           : adoption of JPWL (Part 11) capabilities (-W params)\n");\r
-       fprintf(stdout,"               The parameters can be written and repeated in any order:\n");\r
-       fprintf(stdout,"               [h<tilepart><=type>,s<tilepart><=method>,a=<addr>,...\n");\r
-       fprintf(stdout,"                ...,z=<size>,g=<range>,p<tilepart:pack><=type>]\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"                 h selects the header error protection (EPB): 'type' can be\n");\r
-       fprintf(stdout,"                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");\r
-       fprintf(stdout,"                   if 'tilepart' is absent, it is for main and tile headers\n");\r
-       fprintf(stdout,"                   if 'tilepart' is present, it applies from that tile\n");\r
-       fprintf(stdout,"                     onwards, up to the next h<> spec, or to the last tilepart\n");\r
-       fprintf(stdout,"                     in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"                 p selects the packet error protection (EEP/UEP with EPBs)\n");\r
-       fprintf(stdout,"                  to be applied to raw data: 'type' can be\n");\r
-       fprintf(stdout,"                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");\r
-       fprintf(stdout,"                   if 'tilepart:pack' is absent, it is from tile 0, packet 0\n");\r
-       fprintf(stdout,"                   if 'tilepart:pack' is present, it applies from that tile\n");\r
-       fprintf(stdout,"                     and that packet onwards, up to the next packet spec\n");\r
-       fprintf(stdout,"                     or to the last packet in the last tilepart in the stream\n");\r
-       fprintf(stdout,"                     (max. %d specs)\n", JPWL_MAX_NO_PACKSPECS);\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"                 s enables sensitivity data insertion (ESD): 'method' can be\n");\r
-       fprintf(stdout,"                   [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR\n");\r
-       fprintf(stdout,"                    4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED]\n");\r
-       fprintf(stdout,"                   if 'tilepart' is absent, it is for main header only\n");\r
-       fprintf(stdout,"                   if 'tilepart' is present, it applies from that tile\n");\r
-       fprintf(stdout,"                     onwards, up to the next s<> spec, or to the last tilepart\n");\r
-       fprintf(stdout,"                     in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"                 g determines the addressing mode: <range> can be\n");\r
-       fprintf(stdout,"                   [0=PACKET 1=BYTE RANGE 2=PACKET RANGE]\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"                 a determines the size of data addressing: <addr> can be\n");\r
-       fprintf(stdout,"                   2/4 bytes (small/large codestreams). If not set, auto-mode\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"                 z determines the size of sensitivity values: <size> can be\n");\r
-       fprintf(stdout,"                   1/2 bytes, for the transformed pseudo-floating point value\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"                 ex.:\n");\r
-       fprintf(stdout,"                   h,h0=64,h3=16,h5=32,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,\n");\r
-       fprintf(stdout,"                     s0=6,s3=-1,a=0,g=1,z=1\n");\r
-       fprintf(stdout,"                 means\n");\r
-       fprintf(stdout,"                   predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2,\n");\r
-       fprintf(stdout,"                   CRC-16 in TPH 3 and TPH 4, CRC-32 in remaining TPHs,\n");\r
-       fprintf(stdout,"                   UEP rs(78,32) for packets 0 to 23 of tile 0,\n");\r
-       fprintf(stdout,"                   UEP rs(56,32) for packs. 24 to the last of tilepart 0,\n");\r
-       fprintf(stdout,"                   UEP rs default for packets of tilepart 1,\n");\r
-       fprintf(stdout,"                   no UEP for packets 0 to 19 of tilepart 3,\n");\r
-       fprintf(stdout,"                   UEP CRC-32 for packs. 20 of tilepart 3 to last tilepart,\n");\r
-       fprintf(stdout,"                   relative sensitivity ESD for MH,\n");\r
-       fprintf(stdout,"                   TSE ESD from TPH 0 to TPH 2, byte range with automatic\n");\r
-       fprintf(stdout,"                   size of addresses and 1 byte for each sensitivity value\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"                 ex.:\n");\r
-       fprintf(stdout,"                       h,s,p\n");\r
-       fprintf(stdout,"                 means\n");\r
-       fprintf(stdout,"                   default protection to headers (MH and TPHs) as well as\n");\r
-       fprintf(stdout,"                   data packets, one ESD in MH\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"                 N.B.: use the following recommendations when specifying\n");\r
-       fprintf(stdout,"                       the JPWL parameters list\n");\r
-       fprintf(stdout,"                   - when you use UEP, always pair the 'p' option with 'h'\n");\r
-       fprintf(stdout,"                 \n");\r
-#endif /* USE_JPWL */\r
-/* <<UniPG */\r
-       fprintf(stdout,"IMPORTANT:\n");\r
-       fprintf(stdout,"-----------\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"The index file has the structure below:\n");\r
-       fprintf(stdout,"---------------------------------------\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"Image_height Image_width\n");\r
-       fprintf(stdout,"progression order\n");\r
-       fprintf(stdout,"Tiles_size_X Tiles_size_Y\n");\r
-       fprintf(stdout,"Tiles_nb_X Tiles_nb_Y\n");\r
-       fprintf(stdout,"Components_nb\n");\r
-       fprintf(stdout,"Layers_nb\n");\r
-       fprintf(stdout,"decomposition_levels\n");\r
-       fprintf(stdout,"[Precincts_size_X_res_Nr Precincts_size_Y_res_Nr]...\n");\r
-       fprintf(stdout,"   [Precincts_size_X_res_0 Precincts_size_Y_res_0]\n");\r
-       fprintf(stdout,"Main_header_start_position\n");\r
-       fprintf(stdout,"Main_header_end_position\n");\r
-       fprintf(stdout,"Codestream_size\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"INFO ON TILES\n");\r
-       fprintf(stdout,"tileno start_pos end_hd end_tile nbparts disto nbpix disto/nbpix\n");\r
-       fprintf(stdout,"Tile_0 start_pos end_Theader end_pos NumParts TotalDisto NumPix MaxMSE\n");\r
-       fprintf(stdout,"Tile_1   ''           ''        ''        ''       ''    ''      ''\n");\r
-       fprintf(stdout,"...\n");\r
-       fprintf(stdout,"Tile_Nt   ''           ''        ''        ''       ''    ''     ''\n");\r
-       fprintf(stdout,"...\n");\r
-       fprintf(stdout,"TILE 0 DETAILS\n");\r
-       fprintf(stdout,"part_nb tileno num_packs start_pos end_tph_pos end_pos\n");\r
-       fprintf(stdout,"...\n");\r
-       fprintf(stdout,"Progression_string\n");\r
-       fprintf(stdout,"pack_nb tileno layno resno compno precno start_pos end_ph_pos end_pos disto\n");\r
-       fprintf(stdout,"Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");\r
-       fprintf(stdout,"...\n");\r
-       fprintf(stdout,"Tpacket_Np ''   ''    ''   ''    ''       ''       ''     ''\n");\r
-\r
-       fprintf(stdout,"MaxDisto\n");\r
-\r
-       fprintf(stdout,"TotalDisto\n\n");\r
-}\r
-\r
-\r
-OPJ_PROG_ORDER give_progression(char progression[4]) {\r
-       if(strncmp(progression, "LRCP", 4) == 0) {\r
-               return LRCP;\r
-       }\r
-       if(strncmp(progression, "RLCP", 4) == 0) {\r
-               return RLCP;\r
-       }\r
-       if(strncmp(progression, "RPCL", 4) == 0) {\r
-               return RPCL;\r
-       }\r
-       if(strncmp(progression, "PCRL", 4) == 0) {\r
-               return PCRL;\r
-       }\r
-       if(strncmp(progression, "CPRL", 4) == 0) {\r
-               return CPRL;\r
-       }\r
-\r
-       return PROG_UNKNOWN;\r
-}\r
-\r
-\r
-/// <summary>\r
-/// Get logarithm of an integer and round downwards.\r
-/// </summary>\r
-int int_floorlog2(int a) {\r
-    int l;\r
-    for (l=0; a>1; l++) {\r
-        a>>=1;\r
-    }\r
-    return l;\r
-}\r
-\r
-static int initialise_4K_poc(opj_poc_t *POC, int numres){\r
-       POC[0].tile  = 1; \r
-       POC[0].resno0  = 0; \r
-       POC[0].compno0 = 0;\r
-       POC[0].layno1  = 1;\r
-       POC[0].resno1  = numres-1;\r
-       POC[0].compno1 = 3;\r
-       POC[0].prg1 = CPRL;\r
-       POC[1].tile  = 1;\r
-       POC[1].resno0  = numres-1; \r
-       POC[1].compno0 = 0;\r
-       POC[1].layno1  = 1;\r
-       POC[1].resno1  = numres;\r
-       POC[1].compno1 = 3;\r
-       POC[1].prg1 = CPRL;\r
-       return 2;\r
-}\r
-\r
-void cinema_parameters(opj_cparameters_t *parameters){\r
-       parameters->tile_size_on = false;\r
-       parameters->cp_tdx=1;\r
-       parameters->cp_tdy=1;\r
-       \r
-       /*Tile part*/\r
-       parameters->tp_flag = 'C';\r
-       parameters->tp_on = 1;\r
-\r
-       /*Tile and Image shall be at (0,0)*/\r
-       parameters->cp_tx0 = 0;\r
-       parameters->cp_ty0 = 0;\r
-       parameters->image_offset_x0 = 0;\r
-       parameters->image_offset_y0 = 0;\r
-\r
-       /*Codeblock size= 32*32*/\r
-       parameters->cblockw_init = 32;  \r
-       parameters->cblockh_init = 32;\r
-       parameters->csty |= 0x01;\r
-\r
-       /*The progression order shall be CPRL*/\r
-       parameters->prog_order = CPRL;\r
-\r
-       /* No ROI */\r
-       parameters->roi_compno = -1;\r
-\r
-       parameters->subsampling_dx = 1;         parameters->subsampling_dy = 1;\r
-\r
-       /* 9-7 transform */\r
-       parameters->irreversible = 1;\r
-\r
-}\r
-\r
-void cinema_setup_encoder(opj_cparameters_t *parameters,opj_image_t *image, img_fol_t *img_fol){\r
-       int i;\r
-       float temp_rate;\r
-       opj_poc_t *POC = NULL;\r
-\r
-       switch (parameters->cp_cinema){\r
-       case CINEMA2K_24:\r
-       case CINEMA2K_48:\r
-               if(parameters->numresolution > 6){\r
-                       parameters->numresolution = 6;\r
-               }\r
-               if (!((image->comps[0].w == 2048) | (image->comps[0].h == 1080))){\r
-                       fprintf(stdout,"Image coordinates %d x %d is not 2K compliant.\nJPEG Digital Cinema Profile-3"\r
-                               "(2K profile) compliance requires that at least one of coordinates match 2048 x 1080\n",\r
-                               image->comps[0].w,image->comps[0].h);\r
-                       parameters->cp_rsiz = STD_RSIZ;\r
-               }\r
-       break;\r
-       \r
-       case CINEMA4K_24:\r
-               if(parameters->numresolution < 1){\r
-                               parameters->numresolution = 1;\r
-                       }else if(parameters->numresolution > 7){\r
-                               parameters->numresolution = 7;\r
-                       }\r
-               if (!((image->comps[0].w == 4096) | (image->comps[0].h == 2160))){\r
-                       fprintf(stdout,"Image coordinates %d x %d is not 4K compliant.\nJPEG Digital Cinema Profile-4" \r
-                               "(4K profile) compliance requires that at least one of coordinates match 4096 x 2160\n",\r
-                               image->comps[0].w,image->comps[0].h);\r
-                       parameters->cp_rsiz = STD_RSIZ;\r
-               }\r
-               parameters->numpocs = initialise_4K_poc(parameters->POC,parameters->numresolution);\r
-               break;\r
-       }\r
-\r
-       switch (parameters->cp_cinema){\r
-               case CINEMA2K_24:\r
-               case CINEMA4K_24:\r
-                       for(i=0 ; i<parameters->tcp_numlayers ; i++){\r
-                               temp_rate = 0 ;\r
-                               if (img_fol->rates[i]== 0){\r
-                                       parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ \r
-                                       (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);\r
-                               }else{\r
-                                       temp_rate =((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ \r
-                                               (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy);\r
-                                       if (temp_rate > CINEMA_24_CS ){\r
-                                               parameters->tcp_rates[i]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ \r
-                                               (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);\r
-                                       }else{\r
-                                               parameters->tcp_rates[i]= img_fol->rates[i];\r
-                                       }\r
-                               }\r
-                       }\r
-                       parameters->max_comp_size = COMP_24_CS;\r
-                       break;\r
-               \r
-               case CINEMA2K_48:\r
-                       for(i=0 ; i<parameters->tcp_numlayers ; i++){\r
-                               temp_rate = 0 ;\r
-                               if (img_fol->rates[i]== 0){\r
-                                       parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ \r
-                                       (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);\r
-                               }else{\r
-                                       temp_rate =((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ \r
-                                               (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy);\r
-                                       if (temp_rate > CINEMA_48_CS ){\r
-                                               parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ \r
-                                               (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);\r
-                                       }else{\r
-                                               parameters->tcp_rates[i]= img_fol->rates[i];\r
-                                       }\r
-                               }\r
-                       }\r
-                       parameters->max_comp_size = COMP_48_CS;\r
-                       break;\r
-       }\r
-       parameters->cp_disto_alloc = 1;\r
-}\r
-\r
-\r
-/* ------------------------------------------------------------------------------------ */\r
-int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *parameters,\r
-                                                                                                       img_fol_t *img_fol, char *indexfilename) {\r
-       int i, j,totlen;\r
-       option_t long_option[]={\r
-               {"cinema2K",REQ_ARG, NULL ,'w'},\r
-               {"cinema4K",NO_ARG, NULL ,'y'},\r
-               {"ImgDir",REQ_ARG, NULL ,'z'},\r
-               {"TP",REQ_ARG, NULL ,'v'},\r
-               {"SOP",NO_ARG, NULL ,'S'},\r
-               {"EPH",NO_ARG, NULL ,'E'},\r
-               {"OutFor",REQ_ARG, NULL ,'O'},\r
-               {"POC",REQ_ARG, NULL ,'P'},\r
-               {"ROI",REQ_ARG, NULL ,'R'},\r
-       };\r
-\r
-       /* parse the command line */\r
-/* UniPG>> */\r
-       const char optlist[] = "i:o:hr:q:n:b:c:t:p:s:SEM:x:R:d:T:If:P:C:F:"\r
-#ifdef USE_JPWL\r
-               "W:"\r
-#endif /* USE_JPWL */\r
-               ;\r
-\r
-       /*printf("C: parse_cmdline_encoder:");\r
-       for (i=0; i<argc; i++) {\r
-               printf("[%s]",argv[i]);\r
-       }\r
-       printf("\n");*/\r
-\r
-       totlen=sizeof(long_option);\r
-       img_fol->set_out_format=0;\r
-       reset_options_reading();\r
-\r
-       while (1) {\r
-    int c = getopt_long(argc, argv, optlist,long_option,totlen);\r
-               if (c == -1)\r
-                       break;\r
-               switch (c) {\r
-\r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 'o':                       /* output file */\r
-                       {\r
-                               char *outfile = optarg;\r
-                               parameters->cod_format = get_file_format(outfile);\r
-                               switch(parameters->cod_format) {\r
-                                       case J2K_CFMT:\r
-                                       case JP2_CFMT:\r
-                                               break;\r
-                                       default:\r
-                                               fprintf(stderr, "Unknown output format image %s [only *.j2k, *.j2c or *.jp2]!! \n", outfile);\r
-                                               return 1;\r
-                               }\r
-                               strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);\r
-                       }\r
-                       break;\r
-\r
-                               /* ----------------------------------------------------- */\r
-                       case 'O':                       /* output format */\r
-                               {\r
-                                       char outformat[50];\r
-                                       char *of = optarg;\r
-                                       sprintf(outformat,".%s",of);\r
-                                       img_fol->set_out_format = 1;\r
-                                       parameters->cod_format = get_file_format(outformat);\r
-                                       switch(parameters->cod_format) {\r
-                                               case J2K_CFMT:\r
-                                               case JP2_CFMT:\r
-                                                       img_fol->out_format = optarg;\r
-                                                       break;\r
-                                               default:\r
-                                                       fprintf(stderr, "Unknown output format image [only j2k, j2c, jp2]!! \n");\r
-                                                       return 1;\r
-                                       }\r
-                               }\r
-                               break;\r
-\r
-\r
-                               /* ----------------------------------------------------- */\r
-\r
-\r
-                       case 'r':                       /* rates rates/distorsion */\r
-                       {\r
-                               char *s = optarg;\r
-                               while (sscanf(s, "%f", &parameters->tcp_rates[parameters->tcp_numlayers]) == 1) {\r
-                                       parameters->tcp_numlayers++;\r
-                                       while (*s && *s != ',') {\r
-                                               s++;\r
-                                       }\r
-                                       if (!*s)\r
-                                               break;\r
-                                       s++;\r
-                               }\r
-                               parameters->cp_disto_alloc = 1;\r
-                       }\r
-                       break;\r
-\r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 'q':                       /* add fixed_quality */\r
-                       {\r
-                               char *s = optarg;\r
-                               while (sscanf(s, "%f", &parameters->tcp_distoratio[parameters->tcp_numlayers]) == 1) {\r
-                                       parameters->tcp_numlayers++;\r
-                                       while (*s && *s != ',') {\r
-                                               s++;\r
-                                       }\r
-                                       if (!*s)\r
-                                               break;\r
-                                       s++;\r
-                               }\r
-                               parameters->cp_fixed_quality = 1;\r
-                       }\r
-                       break;\r
-\r
-                               /* dda */\r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 'f':                       /* mod fixed_quality (before : -q) */\r
-                       {\r
-                               int *row = NULL, *col = NULL;\r
-                               int numlayers = 0, numresolution = 0, matrix_width = 0;\r
-\r
-                               char *s = optarg;\r
-                               sscanf(s, "%d", &numlayers);\r
-                               s++;\r
-                               if (numlayers > 9)\r
-                                       s++;\r
-\r
-                               parameters->tcp_numlayers = numlayers;\r
-                               numresolution = parameters->numresolution;\r
-                               matrix_width = numresolution * 3;\r
-                               parameters->cp_matrice = (int *) malloc(numlayers * matrix_width * sizeof(int));\r
-                               s = s + 2;\r
-\r
-                               for (i = 0; i < numlayers; i++) {\r
-                                       row = &parameters->cp_matrice[i * matrix_width];\r
-                                       col = row;\r
-                                       parameters->tcp_rates[i] = 1;\r
-                                       sscanf(s, "%d,", &col[0]);\r
-                                       s += 2;\r
-                                       if (col[0] > 9)\r
-                                               s++;\r
-                                       col[1] = 0;\r
-                                       col[2] = 0;\r
-                                       for (j = 1; j < numresolution; j++) {\r
-                                               col += 3;\r
-                                               sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);\r
-                                               s += 6;\r
-                                               if (col[0] > 9)\r
-                                                       s++;\r
-                                               if (col[1] > 9)\r
-                                                       s++;\r
-                                               if (col[2] > 9)\r
-                                                       s++;\r
-                                       }\r
-                                       if (i < numlayers - 1)\r
-                                               s++;\r
-                               }\r
-                               parameters->cp_fixed_alloc = 1;\r
-                       }\r
-                       break;\r
-\r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 't':                       /* tiles */\r
-                       {\r
-                               sscanf(optarg, "%d,%d", &parameters->cp_tdx, &parameters->cp_tdy);\r
-                               parameters->tile_size_on = true;\r
-                       }\r
-                       break;\r
-\r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 'n':                       /* resolution */\r
-                       {\r
-                               sscanf(optarg, "%d", &parameters->numresolution);\r
-                       }\r
-                       break;\r
-\r
-                               /* ----------------------------------------------------- */\r
-                       case 'c':                       /* precinct dimension */\r
-                       {\r
-                               char sep;\r
-                               int res_spec = 0;\r
-\r
-                               char *s = optarg;\r
-                               do {\r
-                                       sep = 0;\r
-                                       sscanf(s, "[%d,%d]%c", &parameters->prcw_init[res_spec],\r
-                                 &parameters->prch_init[res_spec], &sep);\r
-                                       parameters->csty |= 0x01;\r
-                                       res_spec++;\r
-                                       s = strpbrk(s, "]") + 2;\r
-                               }\r
-                               while (sep == ',');\r
-                               parameters->res_spec = res_spec;\r
-                       }\r
-                       break;\r
-\r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 'b':                       /* code-block dimension */\r
-                       {\r
-                               int cblockw_init = 0, cblockh_init = 0;\r
-                               sscanf(optarg, "%d,%d", &cblockw_init, &cblockh_init);\r
-                               if (cblockw_init * cblockh_init > 4096 || cblockw_init > 1024\r
-                                       || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {\r
-                                       fprintf(stderr,\r
-                                               "!! Size of code_block error (option -b) !!\n\nRestriction :\n"\r
-            "    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");\r
-                                       return 1;\r
-                               }\r
-                               parameters->cblockw_init = cblockw_init;\r
-                               parameters->cblockh_init = cblockh_init;\r
-                       }\r
-                       break;\r
-\r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 'x':                       /* creation of index file */\r
-                       {\r
-                               char *index = optarg;\r
-                               strncpy(indexfilename, index, OPJ_PATH_LEN);\r
-                       }\r
-                       break;\r
-\r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 'p':                       /* progression order */\r
-                       {\r
-                               char progression[4];\r
-\r
-                               strncpy(progression, optarg, 4);\r
-                               parameters->prog_order = give_progression(progression);\r
-                               if (parameters->prog_order == -1) {\r
-                                       fprintf(stderr, "Unrecognized progression order "\r
-            "[LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");\r
-                                       return 1;\r
-                               }\r
-                       }\r
-                       break;\r
-\r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 's':                       /* subsampling factor */\r
-                       {\r
-                               if (sscanf(optarg, "%d,%d", &parameters->subsampling_dx,\r
-                                    &parameters->subsampling_dy) != 2) {\r
-                                       fprintf(stderr, "'-s' sub-sampling argument error !  [-s dx,dy]\n");\r
-                                       return 1;\r
-                               }\r
-                       }\r
-                       break;\r
-\r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 'd':                       /* coordonnate of the reference grid */\r
-                       {\r
-                               if (sscanf(optarg, "%d,%d", &parameters->image_offset_x0,\r
-                                    &parameters->image_offset_y0) != 2) {\r
-                                       fprintf(stderr, "-d 'coordonnate of the reference grid' argument "\r
-            "error !! [-d x0,y0]\n");\r
-                                       return 1;\r
-                               }\r
-                       }\r
-                       break;\r
-\r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 'h':                       /* display an help description */\r
-                               encode_help_display();\r
-                               return 1;\r
-\r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 'P':                       /* POC */\r
-                       {\r
-                               int numpocs = 0;                /* number of progression order change (POC) default 0 */\r
-                               opj_poc_t *POC = NULL;  /* POC : used in case of Progression order change */\r
-\r
-                               char *s = optarg;\r
-                               POC = parameters->POC;\r
-\r
-                               while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%4s", &POC[numpocs].tile,\r
-                                       &POC[numpocs].resno0, &POC[numpocs].compno0,\r
-                                       &POC[numpocs].layno1, &POC[numpocs].resno1,\r
-                                       &POC[numpocs].compno1, &POC[numpocs].progorder) == 7) {\r
-                                       POC[numpocs].prg1 = give_progression(POC[numpocs].progorder);\r
-                                       numpocs++;\r
-                                       while (*s && *s != '/') {\r
-                                               s++;\r
-                                       }\r
-                                       if (!*s) {\r
-                                               break;\r
-                                       }\r
-                                       s++;\r
-                               }\r
-                               parameters->numpocs = numpocs;\r
-                       }\r
-                       break;\r
-\r
-                               /* ------------------------------------------------------ */\r
-\r
-                       case 'S':                       /* SOP marker */\r
-                       {\r
-                               parameters->csty |= 0x02;\r
-                       }\r
-                       break;\r
-\r
-                               /* ------------------------------------------------------ */\r
-\r
-                       case 'E':                       /* EPH marker */\r
-                       {\r
-                               parameters->csty |= 0x04;\r
-                       }\r
-                       break;\r
-\r
-                               /* ------------------------------------------------------ */\r
-\r
-                       case 'M':                       /* Mode switch pas tous au point !! */\r
-                       {\r
-                               int value = 0;\r
-                               if (sscanf(optarg, "%d", &value) == 1) {\r
-                                       for (i = 0; i <= 5; i++) {\r
-                                               int cache = value & (1 << i);\r
-                                               if (cache)\r
-                                                       parameters->mode |= (1 << i);\r
-                                       }\r
-                               }\r
-                       }\r
-                       break;\r
-\r
-                               /* ------------------------------------------------------ */\r
-\r
-                       case 'R':                       /* ROI */\r
-                       {\r
-                               if (sscanf(optarg, "c=%d,U=%d", &parameters->roi_compno,\r
-                                           &parameters->roi_shift) != 2) {\r
-                                       fprintf(stderr, "ROI error !! [-ROI c='compno',U='shift']\n");\r
-                                       return 1;\r
-                               }\r
-                       }\r
-                       break;\r
-\r
-                               /* ------------------------------------------------------ */\r
-\r
-                       case 'T':                       /* Tile offset */\r
-                       {\r
-                               if (sscanf(optarg, "%d,%d", &parameters->cp_tx0, &parameters->cp_ty0) != 2) {\r
-                                       fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");\r
-                                       return 1;\r
-                               }\r
-                       }\r
-                       break;\r
-\r
-                               /* ------------------------------------------------------ */\r
-\r
-                       case 'C':                       /* add a comment */\r
-                       {\r
-                               parameters->cp_comment = (char*)malloc(strlen(optarg) + 1);\r
-                               if(parameters->cp_comment) {\r
-                                       strcpy(parameters->cp_comment, optarg);\r
-                               }\r
-                       }\r
-                       break;\r
-\r
-\r
-                               /* ------------------------------------------------------ */\r
-\r
-                       case 'I':                       /* reversible or not */\r
-                       {\r
-                               parameters->irreversible = 1;\r
-                       }\r
-                       break;\r
-\r
-                       /* ------------------------------------------------------ */\r
-                       \r
-                       case 'v':                       /* Tile part generation*/\r
-                       {\r
-                               parameters->tp_flag = optarg[0];\r
-                               parameters->tp_on = 1;\r
-                       }\r
-                       break;  \r
-\r
-                               /* ------------------------------------------------------ */\r
-                       \r
-                       case 'z':                       /* Image Directory path */\r
-                       {\r
-                               img_fol->imgdirpath = (char*)malloc(strlen(optarg) + 1);\r
-                               strcpy(img_fol->imgdirpath,optarg);\r
-                               img_fol->set_imgdir=1;\r
-                       }\r
-                       break;\r
-\r
-                               /* ------------------------------------------------------ */\r
-                       \r
-                       case 'w':                       /* Digital Cinema 2K profile compliance*/\r
-                       {\r
-                               int fps=0;\r
-                               sscanf(optarg,"%d",&fps);\r
-                               if(fps == 24){\r
-                                       parameters->cp_cinema = CINEMA2K_24;\r
-                               }else if(fps == 48 ){\r
-                                       parameters->cp_cinema = CINEMA2K_48;\r
-                               }else {\r
-                                       fprintf(stderr,"Incorrect value!! must be 24 or 48\n");\r
-                                       return 1;\r
-                               }\r
-                               fprintf(stdout,"CINEMA 2K compliant codestream\n");\r
-                               parameters->cp_rsiz = CINEMA2K;\r
-                               \r
-                       }\r
-                       break;\r
-                               \r
-                               /* ------------------------------------------------------ */\r
-                       \r
-                       case 'y':                       /* Digital Cinema 4K profile compliance*/\r
-                       {\r
-                               parameters->cp_cinema = CINEMA4K_24;\r
-                               fprintf(stdout,"CINEMA 4K compliant codestream\n");\r
-                               parameters->cp_rsiz = CINEMA4K;\r
-                       }\r
-                       break;\r
-                               \r
-                               /* ------------------------------------------------------ */\r
-\r
-/* UniPG>> */\r
-#ifdef USE_JPWL\r
-                               /* ------------------------------------------------------ */\r
-                       \r
-                       case 'W':                       /* JPWL capabilities switched on */\r
-                       {\r
-                               char *token = NULL;\r
-                               int hprot, pprot, sens, addr, size, range;\r
-\r
-                               /* we need to enable indexing */\r
-                               if (!indexfilename) {\r
-                                       strncpy(indexfilename, JPWL_PRIVATEINDEX_NAME, OPJ_PATH_LEN);\r
-                               }\r
-\r
-                               /* search for different protection methods */\r
-\r
-                               /* break the option in comma points and parse the result */\r
-                               token = strtok(optarg, ",");\r
-                               while(token != NULL) {\r
-\r
-                                       /* search header error protection method */\r
-                                       if (*token == 'h') {\r
-\r
-                                               static int tile = 0, tilespec = 0, lasttileno = 0;\r
-\r
-                                               hprot = 1; /* predefined method */\r
-\r
-                                               if(sscanf(token, "h=%d", &hprot) == 1) {\r
-                                                       /* Main header, specified */\r
-                                                       if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||\r
-                                                               ((hprot >= 37) && (hprot <= 128)))) {\r
-                                                               fprintf(stderr, "ERROR -> invalid main header protection method h = %d\n", hprot);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       parameters->jpwl_hprot_MH = hprot;\r
-\r
-                                               } else if(sscanf(token, "h%d=%d", &tile, &hprot) == 2) {\r
-                                                       /* Tile part header, specified */\r
-                                                       if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||\r
-                                                               ((hprot >= 37) && (hprot <= 128)))) {\r
-                                                               fprintf(stderr, "ERROR -> invalid tile part header protection method h = %d\n", hprot);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (tile < 0) {\r
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method t = %d\n", tile);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {\r
-                                                               parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;\r
-                                                               parameters->jpwl_hprot_TPH[tilespec++] = hprot;\r
-                                                       }\r
-\r
-                                               } else if(sscanf(token, "h%d", &tile) == 1) {\r
-                                                       /* Tile part header, unspecified */\r
-                                                       if (tile < 0) {\r
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method t = %d\n", tile);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {\r
-                                                               parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;\r
-                                                               parameters->jpwl_hprot_TPH[tilespec++] = hprot;\r
-                                                       }\r
-\r
-\r
-                                               } else if (!strcmp(token, "h")) {\r
-                                                       /* Main header, unspecified */\r
-                                                       parameters->jpwl_hprot_MH = hprot;\r
-\r
-                                               } else {\r
-                                                       fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);\r
-                                                       return 1;\r
-                                               };\r
-\r
-                                       }\r
-\r
-                                       /* search packet error protection method */\r
-                                       if (*token == 'p') {\r
-\r
-                                               static int pack = 0, tile = 0, packspec = 0, lastpackno = 0;\r
-\r
-                                               pprot = 1; /* predefined method */\r
-\r
-                                               if (sscanf(token, "p=%d", &pprot) == 1) {\r
-                                                       /* Method for all tiles and all packets */\r
-                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||\r
-                                                               ((pprot >= 37) && (pprot <= 128)))) {\r
-                                                               fprintf(stderr, "ERROR -> invalid default packet protection method p = %d\n", pprot);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       parameters->jpwl_pprot_tileno[0] = 0;\r
-                                                       parameters->jpwl_pprot_packno[0] = 0;\r
-                                                       parameters->jpwl_pprot[0] = pprot;\r
-\r
-                                               } else if (sscanf(token, "p%d=%d", &tile, &pprot) == 2) {\r
-                                                       /* method specified from that tile on */\r
-                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||\r
-                                                               ((pprot >= 37) && (pprot <= 128)))) {\r
-                                                               fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (tile < 0) {\r
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {\r
-                                                               parameters->jpwl_pprot_tileno[packspec] = tile;\r
-                                                               parameters->jpwl_pprot_packno[packspec] = 0;\r
-                                                               parameters->jpwl_pprot[packspec++] = pprot;\r
-                                                       }\r
-\r
-                                               } else if (sscanf(token, "p%d:%d=%d", &tile, &pack, &pprot) == 3) {\r
-                                                       /* method fully specified from that tile and that packet on */\r
-                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||\r
-                                                               ((pprot >= 37) && (pprot <= 128)))) {\r
-                                                               fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (tile < 0) {\r
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (pack < 0) {\r
-                                                               fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n", pack);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {\r
-                                                               parameters->jpwl_pprot_tileno[packspec] = tile;\r
-                                                               parameters->jpwl_pprot_packno[packspec] = pack;\r
-                                                               parameters->jpwl_pprot[packspec++] = pprot;\r
-                                                       }\r
-\r
-                                               } else if (sscanf(token, "p%d:%d", &tile, &pack) == 2) {\r
-                                                       /* default method from that tile and that packet on */\r
-                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||\r
-                                                               ((pprot >= 37) && (pprot <= 128)))) {\r
-                                                               fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (tile < 0) {\r
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (pack < 0) {\r
-                                                               fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n", pack);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {\r
-                                                               parameters->jpwl_pprot_tileno[packspec] = tile;\r
-                                                               parameters->jpwl_pprot_packno[packspec] = pack;\r
-                                                               parameters->jpwl_pprot[packspec++] = pprot;\r
-                                                       }\r
-\r
-                                               } else if (sscanf(token, "p%d", &tile) == 1) {\r
-                                                       /* default from a tile on */\r
-                                                       if (tile < 0) {\r
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {\r
-                                                               parameters->jpwl_pprot_tileno[packspec] = tile;\r
-                                                               parameters->jpwl_pprot_packno[packspec] = 0;\r
-                                                               parameters->jpwl_pprot[packspec++] = pprot;\r
-                                                       }\r
-\r
-\r
-                                               } else if (!strcmp(token, "p")) {\r
-                                                       /* all default */\r
-                                                       parameters->jpwl_pprot_tileno[0] = 0;\r
-                                                       parameters->jpwl_pprot_packno[0] = 0;\r
-                                                       parameters->jpwl_pprot[0] = pprot;\r
-\r
-                                               } else {\r
-                                                       fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);\r
-                                                       return 1;\r
-                                               };\r
-\r
-                                       }\r
-\r
-                                       /* search sensitivity method */\r
-                                       if (*token == 's') {\r
-\r
-                                               static int tile = 0, tilespec = 0, lasttileno = 0;\r
-\r
-                                               sens = 0; /* predefined: relative error */\r
-\r
-                                               if(sscanf(token, "s=%d", &sens) == 1) {\r
-                                                       /* Main header, specified */\r
-                                                       if ((sens < -1) || (sens > 7)) {\r
-                                                               fprintf(stderr, "ERROR -> invalid main header sensitivity method s = %d\n", sens);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       parameters->jpwl_sens_MH = sens;\r
-\r
-                                               } else if(sscanf(token, "s%d=%d", &tile, &sens) == 2) {\r
-                                                       /* Tile part header, specified */\r
-                                                       if ((sens < -1) || (sens > 7)) {\r
-                                                               fprintf(stderr, "ERROR -> invalid tile part header sensitivity method s = %d\n", sens);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (tile < 0) {\r
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {\r
-                                                               parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;\r
-                                                               parameters->jpwl_sens_TPH[tilespec++] = sens;\r
-                                                       }\r
-\r
-                                               } else if(sscanf(token, "s%d", &tile) == 1) {\r
-                                                       /* Tile part header, unspecified */\r
-                                                       if (tile < 0) {\r
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {\r
-                                                               parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;\r
-                                                               parameters->jpwl_sens_TPH[tilespec++] = hprot;\r
-                                                       }\r
-\r
-                                               } else if (!strcmp(token, "s")) {\r
-                                                       /* Main header, unspecified */\r
-                                                       parameters->jpwl_sens_MH = sens;\r
-\r
-                                               } else {\r
-                                                       fprintf(stderr, "ERROR -> invalid sensitivity method selection = %s\n", token);\r
-                                                       return 1;\r
-                                               };\r
-                                               \r
-                                               parameters->jpwl_sens_size = 2; /* 2 bytes for default size */\r
-                                       }\r
-\r
-                                       /* search addressing size */\r
-                                       if (*token == 'a') {\r
-\r
-                                               static int tile = 0, tilespec = 0, lasttileno = 0;\r
-\r
-                                               addr = 0; /* predefined: auto */\r
-\r
-                                               if(sscanf(token, "a=%d", &addr) == 1) {\r
-                                                       /* Specified */\r
-                                                       if ((addr != 0) && (addr != 2) && (addr != 4)) {\r
-                                                               fprintf(stderr, "ERROR -> invalid addressing size a = %d\n", addr);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       parameters->jpwl_sens_addr = addr;\r
-\r
-                                               } else if (!strcmp(token, "a")) {\r
-                                                       /* default */\r
-                                                       parameters->jpwl_sens_addr = addr; /* auto for default size */\r
-\r
-                                               } else {\r
-                                                       fprintf(stderr, "ERROR -> invalid addressing selection = %s\n", token);\r
-                                                       return 1;\r
-                                               };\r
-                                               \r
-                                       }\r
-\r
-                                       /* search sensitivity size */\r
-                                       if (*token == 'z') {\r
-\r
-                                               static int tile = 0, tilespec = 0, lasttileno = 0;\r
-\r
-                                               size = 1; /* predefined: 1 byte */\r
-\r
-                                               if(sscanf(token, "z=%d", &size) == 1) {\r
-                                                       /* Specified */\r
-                                                       if ((size != 0) && (size != 1) && (size != 2)) {\r
-                                                               fprintf(stderr, "ERROR -> invalid sensitivity size z = %d\n", size);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       parameters->jpwl_sens_size = size;\r
-\r
-                                               } else if (!strcmp(token, "a")) {\r
-                                                       /* default */\r
-                                                       parameters->jpwl_sens_size = size; /* 1 for default size */\r
-\r
-                                               } else {\r
-                                                       fprintf(stderr, "ERROR -> invalid size selection = %s\n", token);\r
-                                                       return 1;\r
-                                               };\r
-                                               \r
-                                       }\r
-\r
-                                       /* search range method */\r
-                                       if (*token == 'g') {\r
-\r
-                                               static int tile = 0, tilespec = 0, lasttileno = 0;\r
-\r
-                                               range = 0; /* predefined: 0 (packet) */\r
-\r
-                                               if(sscanf(token, "g=%d", &range) == 1) {\r
-                                                       /* Specified */\r
-                                                       if ((range < 0) || (range > 3)) {\r
-                                                               fprintf(stderr, "ERROR -> invalid sensitivity range method g = %d\n", range);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       parameters->jpwl_sens_range = range;\r
-\r
-                                               } else if (!strcmp(token, "g")) {\r
-                                                       /* default */\r
-                                                       parameters->jpwl_sens_range = range;\r
-\r
-                                               } else {\r
-                                                       fprintf(stderr, "ERROR -> invalid range selection = %s\n", token);\r
-                                                       return 1;\r
-                                               };\r
-                                               \r
-                                       }\r
-\r
-                                       /* next token or bust */\r
-                                       token = strtok(NULL, ",");\r
-                               };\r
-\r
-\r
-                               /* some info */\r
-                               fprintf(stdout, "Info: JPWL capabilities enabled\n");\r
-                               parameters->jpwl_epc_on = true;\r
-\r
-                       }\r
-                       break;\r
-#endif /* USE_JPWL */\r
-/* <<UniPG */\r
-\r
-                               /* ------------------------------------------------------ */\r
-\r
-                       default:\r
-                               fprintf(stderr, "ERROR -> Command line not valid\n");\r
-                               return 1;\r
-               }\r
-       }\r
-\r
-       /* check for possible errors */\r
-       if (parameters->cp_cinema){\r
-               if(parameters->tcp_numlayers > 1){\r
-                       parameters->cp_rsiz = STD_RSIZ;\r
-       fprintf(stdout,"Warning: DC profiles do not allow more than one quality layer. The codestream created will not be compliant with the DC profile\n");\r
-               }\r
-       }\r
-\r
-       if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc || parameters->cp_fixed_quality)\r
-               && (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_alloc ^ parameters->cp_fixed_quality))) {\r
-               fprintf(stderr, "Error: options -r -q and -f cannot be used together !!\n");\r
-               return 1;\r
-       }                               /* mod fixed_quality */\r
-\r
-       /* if no rate entered, lossless by default */\r
-       if (parameters->tcp_numlayers == 0) {\r
-               parameters->tcp_rates[0] = 0;   /* MOD antonin : losslessbug */\r
-               parameters->tcp_numlayers++;\r
-               parameters->cp_disto_alloc = 1;\r
-       }\r
-\r
-       if((parameters->cp_tx0 > parameters->image_offset_x0) || (parameters->cp_ty0 > parameters->image_offset_y0)) {\r
-               fprintf(stderr,\r
-                       "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",\r
-                       parameters->cp_tx0, parameters->image_offset_x0, parameters->cp_ty0, parameters->image_offset_y0);\r
-               return 1;\r
-       }\r
-\r
-       for (i = 0; i < parameters->numpocs; i++) {\r
-               if (parameters->POC[i].prg == -1) {\r
-                       fprintf(stderr,\r
-                               "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",\r
-                               i + 1);\r
-               }\r
-       }\r
-\r
-       return 0;\r
-}\r
-\r
-\r
-/** Create the same index as j2k_create_index does, but in an int[] instead of in a file ==> easy to pass it back to Java, to transfer it etc.\r
-  @param buffer_size, increased by the length of the compressed index, in number of bytes\r
-  @return a pointer to a char[]\r
-  Syntax of the index:\r
-       one char for the version number (1): one byte because no problem with little endian, big endian etc.\r
-       one int for each of the following informations:\r
-                       Image Width     \r
-                       Image Height    \r
-                       progression order       \r
-                       Tile width      \r
-                       Tile height     \r
-                       Nb tiles in X   \r
-                       Nb tiles in Y   \r
-                       Nb of components        \r
-                       Nb of layers    \r
-                       Nb of resolutions       \r
-\r
-                       for each resolution:    \r
-                               Precinct width\r
-                               Precinct height\r
-\r
-                       End main header position        \r
-                       codestream size \r
-\r
-                       For each tile:  \r
-                               tile number\r
-                               tile start pos in codestream\r
-                               tile header end position\r
-                               tile end position in codestream\r
-\r
-                       For each LRCP, RLCP etc.:       \r
-                               packet number\r
-                               tile number\r
-                               layer number\r
-                               resolution number\r
-                               component number\r
-                               precinct number\r
-                               start position in the codestream\r
-                               end position of this packet\r
-  */\r
-char* create_index_into_byte_array(opj_codestream_info_t *cstr_info, int* buffer_size) {\r
-       int tileno, compno, layno, resno, precno, pack_nb, x, y;\r
-       char* buffer = NULL;\r
-       int buffer_pos = 0;\r
-       int prec_max = 0;\r
-       \r
-       prec_max = 0;\r
-       for (tileno = 0; tileno < cstr_info->tw * cstr_info->th; tileno++) {\r
-               for (resno = 0; resno < cstr_info->numdecompos[0] + 1; resno++) {\r
-                       prec_max = max(prec_max,cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno]);\r
-               }\r
-       }\r
-\r
-       // Compute the size of the index buffer, in number of bytes*/\r
-       *buffer_size = \r
-                 1 /* version */\r
-               + (10 /* image_w until decomposition */\r
-               + (cstr_info->numdecompos[0]+1) * 2 /* pdx size for each tile */\r
-               + 2 /* main_head_end + codestream_size */\r
-               + cstr_info->tw * cstr_info->th * 4 /* tile info, without distorsion info */\r
-               + cstr_info->tw*cstr_info->th * cstr_info->numlayers * (cstr_info->numdecompos[0] + 1) * cstr_info->numcomps * prec_max *8\r
-                 ) * sizeof(int);\r
-       //printf("C: index buffer size = %d bytes\n", *buffer_size);\r
-       buffer = (char*) malloc(*buffer_size);\r
-\r
-       if (!buffer) {\r
-               //opj_event_msg(j2k->cinfo, EVT_ERROR, "failed to allocate index buffer for writing %d int\n", *buffer_size);\r
-               fprintf(stderr, "failed to allocate index buffer for writing %d int\n", *buffer_size);\r
-               return 0;\r
-       }\r
-       \r
-       buffer[0] = 1;  // Version stored on a byte\r
-       buffer++;\r
-       // Remaining informations are stored on a int.\r
-       ((int*)buffer)[buffer_pos++] = cstr_info->image_w;\r
-       ((int*)buffer)[buffer_pos++] = cstr_info->image_h;\r
-       ((int*)buffer)[buffer_pos++] = cstr_info->prog;\r
-       ((int*)buffer)[buffer_pos++] = cstr_info->tile_x;\r
-       ((int*)buffer)[buffer_pos++] = cstr_info->tile_y;\r
-       ((int*)buffer)[buffer_pos++] = cstr_info->tw;\r
-       ((int*)buffer)[buffer_pos++] = cstr_info->th;\r
-       ((int*)buffer)[buffer_pos++] = cstr_info->numcomps;\r
-       ((int*)buffer)[buffer_pos++] = cstr_info->numlayers;\r
-       ((int*)buffer)[buffer_pos++] = cstr_info->numdecompos[0];\r
-       \r
-       for (resno = cstr_info->numdecompos[0]; resno >= 0; resno--) {\r
-                       /* based on tile 0 */\r
-               ((int*)buffer)[buffer_pos++] = (1 << cstr_info->tile[0].pdx[resno]);\r
-               ((int*)buffer)[buffer_pos++] = (1 << cstr_info->tile[0].pdx[resno]);\r
-       }\r
-       ((int*)buffer)[buffer_pos++] = cstr_info->main_head_end;\r
-       ((int*)buffer)[buffer_pos++] = cstr_info->codestream_size;\r
-       \r
-       for (tileno = 0; tileno < cstr_info->tw * cstr_info->th; tileno++) {\r
-               ((int*)buffer)[buffer_pos++] = cstr_info->tile[tileno].tileno;\r
-               ((int*)buffer)[buffer_pos++] = cstr_info->tile[tileno].start_pos;\r
-               ((int*)buffer)[buffer_pos++] = cstr_info->tile[tileno].end_header;\r
-               ((int*)buffer)[buffer_pos++] = cstr_info->tile[tileno].end_pos;\r
-       }\r
-       \r
-       for (tileno = 0; tileno < cstr_info->tw * cstr_info->th; tileno++) {\r
-               int start_pos, end_pos;\r
-               int max_numdecompos = 0;\r
-               pack_nb = 0;\r
-               \r
-               for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
-                       if (max_numdecompos < cstr_info->numdecompos[compno])\r
-                               max_numdecompos = cstr_info->numdecompos[compno];\r
-               }       \r
-\r
-               if (cstr_info->prog == LRCP) {  /* LRCP */\r
-\r
-                       for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
-                               for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
-                                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
-                                               int prec_max;\r
-                                               if (resno > cstr_info->numdecompos[compno])\r
-                                                       break;\r
-                                               prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
-                                               for (precno = 0; precno < prec_max; precno++) {\r
-                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
-                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
-                                                       ((int*)buffer)[buffer_pos++] = pack_nb;\r
-                                                       ((int*)buffer)[buffer_pos++] = tileno;\r
-                                                       ((int*)buffer)[buffer_pos++] = layno;\r
-                                                       ((int*)buffer)[buffer_pos++] = resno;\r
-                                                       ((int*)buffer)[buffer_pos++] = compno;\r
-                                                       ((int*)buffer)[buffer_pos++] = precno;\r
-                                                       ((int*)buffer)[buffer_pos++] = start_pos;\r
-                                                       ((int*)buffer)[buffer_pos++] = end_pos;\r
-                                                       pack_nb++;\r
-                                               }\r
-                                       }\r
-                               }\r
-                       }\r
-               } /* LRCP */\r
-               else if (cstr_info->prog == RLCP) {     /* RLCP */\r
-\r
-                       for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
-                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
-                                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
-                                               int prec_max; \r
-                                               if (resno > cstr_info->numdecompos[compno])\r
-                                                       break;\r
-                                               prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
-                                               for (precno = 0; precno < prec_max; precno++) {\r
-                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
-                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
-                                                       ((int*)buffer)[buffer_pos++] = pack_nb;\r
-                                                       ((int*)buffer)[buffer_pos++] = tileno;\r
-                                                       ((int*)buffer)[buffer_pos++] = resno;\r
-                                                       ((int*)buffer)[buffer_pos++] = layno;\r
-                                                       ((int*)buffer)[buffer_pos++] = compno;\r
-                                                       ((int*)buffer)[buffer_pos++] = precno;\r
-                                                       ((int*)buffer)[buffer_pos++] = start_pos;\r
-                                                       ((int*)buffer)[buffer_pos++] = end_pos;\r
-                                                       pack_nb++;\r
-                                               }\r
-                                       }\r
-                               }\r
-                       }\r
-               } /* RLCP */\r
-               else if (cstr_info->prog == RPCL) {     /* RPCL */\r
-\r
-                       for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
-                               /* I suppose components have same XRsiz, YRsiz */\r
-                               int x0 = cstr_info->tile_Ox + tileno - (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tw * cstr_info->tile_x;\r
-                               int y0 = cstr_info->tile_Ox + (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tile_y;\r
-                               int x1 = x0 + cstr_info->tile_x;\r
-                               int y1 = y0 + cstr_info->tile_y;\r
-                               for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
-                                       int prec_max; \r
-                                       if (resno > cstr_info->numdecompos[compno])\r
-                                               break;\r
-                                       prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
-                                       for (precno = 0; precno < prec_max; precno++) {\r
-                                               int pcnx = cstr_info->tile[tileno].pw[resno];\r
-                                               int pcx = (int) pow( 2, cstr_info->tile[tileno].pdx[resno] + cstr_info->numdecompos[compno] - resno );\r
-                                               int pcy = (int) pow( 2, cstr_info->tile[tileno].pdy[resno] + cstr_info->numdecompos[compno] - resno );\r
-                                               int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
-                                               int precno_y = (int) floor( (float)precno/(float)pcnx );\r
-                                               for(y = y0; y < y1; y++) {                                                      \r
-                                                       if (precno_y*pcy == y ) {\r
-                                                               for (x = x0; x < x1; x++) {                                                                     \r
-                                                                       if (precno_x*pcx == x ) {\r
-                                                                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
-                                                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
-                                                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = pack_nb;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = tileno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = resno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = precno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = compno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = layno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = start_pos;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = end_pos;\r
-                                                                                       pack_nb++; \r
-                                                                               }\r
-                                                                       }\r
-                                                               }/* x = x0..x1 */\r
-                                                       } \r
-                                               }  /* y = y0..y1 */\r
-                                       } /* precno */\r
-                               } /* compno */\r
-                       } /* resno */\r
-               } /* RPCL */\r
-               else if (cstr_info->prog == PCRL) {     /* PCRL */\r
-                       /* I suppose components have same XRsiz, YRsiz */\r
-                       int x0 = cstr_info->tile_Ox + tileno - (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tw * cstr_info->tile_x;\r
-                       int y0 = cstr_info->tile_Ox + (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tile_y;\r
-                       int x1 = x0 + cstr_info->tile_x;\r
-                       int y1 = y0 + cstr_info->tile_y;\r
-\r
-                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
-                               for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
-                                       int prec_max; \r
-                                       if (resno > cstr_info->numdecompos[compno])\r
-                                               break;\r
-                                       prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
-                                       for (precno = 0; precno < prec_max; precno++) {\r
-                                               int pcnx = cstr_info->tile[tileno].pw[resno];\r
-                                               int pcx = (int) pow( 2, cstr_info->tile[tileno].pdx[resno] + cstr_info->numdecompos[compno] - resno );\r
-                                               int pcy = (int) pow( 2, cstr_info->tile[tileno].pdy[resno] + cstr_info->numdecompos[compno] - resno );\r
-                                               int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
-                                               int precno_y = (int) floor( (float)precno/(float)pcnx );\r
-                                               for(y = y0; y < y1; y++) {                                                      \r
-                                                       if (precno_y*pcy == y ) {\r
-                                                               for (x = x0; x < x1; x++) {                                                                     \r
-                                                                       if (precno_x*pcx == x ) {\r
-                                                                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
-                                                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
-                                                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = pack_nb;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = tileno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = precno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = compno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = resno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = layno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = start_pos;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = end_pos;\r
-                                                                                       pack_nb++; \r
-                                                                               }\r
-                                                                       }\r
-                                                               }/* x = x0..x1 */\r
-                                                       } \r
-                                               }  /* y = y0..y1 */\r
-                                       } /* precno */\r
-                               } /* resno */\r
-                       } /* compno */\r
-               } /* PCRL */\r
-               else {  /* CPRL */\r
-\r
-                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
-                               /* I suppose components have same XRsiz, YRsiz */\r
-                               int x0 = cstr_info->tile_Ox + tileno - (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tw * cstr_info->tile_x;\r
-                               int y0 = cstr_info->tile_Ox + (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tile_y;\r
-                               int x1 = x0 + cstr_info->tile_x;\r
-                               int y1 = y0 + cstr_info->tile_y;\r
-                               \r
-                               for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
-                                       int prec_max; \r
-                                       if (resno > cstr_info->numdecompos[compno])\r
-                                               break;\r
-                                       prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
-                                       for (precno = 0; precno < prec_max; precno++) {\r
-                                               int pcnx = cstr_info->tile[tileno].pw[resno];\r
-                                               int pcx = (int) pow( 2, cstr_info->tile[tileno].pdx[resno] + cstr_info->numdecompos[compno] - resno );\r
-                                               int pcy = (int) pow( 2, cstr_info->tile[tileno].pdy[resno] + cstr_info->numdecompos[compno] - resno );\r
-                                               int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
-                                               int precno_y = (int) floor( (float)precno/(float)pcnx );\r
-                                               for(y = y0; y < y1; y++) {\r
-                                                       if (precno_y*pcy == y ) {\r
-                                                               for (x = x0; x < x1; x++) {\r
-                                                                       if (precno_x*pcx == x ) {\r
-                                                                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
-                                                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
-                                                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = pack_nb;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = tileno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = compno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = precno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = resno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = layno;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = start_pos;\r
-                                                                                       ((int*)buffer)[buffer_pos++] = end_pos;\r
-                                                                                       pack_nb++; \r
-                                                                               }\r
-                                                                       }\r
-                                                               }/* x = x0..x1 */\r
-                                                       }\r
-                                               } /* y = y0..y1 */\r
-                                       } /* precno */\r
-                               } /* resno */\r
-                       } /* compno */\r
-               } /* CPRL */   \r
-       } /* tileno */\r
-\r
-       if (buffer_pos > *buffer_size) {\r
-               //opj_event_msg(j2k->cinfo, EVT_ERROR, "index creation: buffer_pos (%d) > buffer_size (%d)!\n", buffer_pos, *buffer_size);\r
-               fprintf(stderr, "index creation: buffer_pos (%d) > buffer_size (%d)!\n", buffer_pos, *buffer_size);\r
-               return 0;\r
-       }\r
-\r
-       return --buffer;\r
-}\r
-\r
-\r
-\r
-\r
-/* -------------------------------------------------------------------------- \r
-   ------------ Get the image byte[] from the Java object -------------------*/\r
-\r
-opj_image_t* loadImage(opj_cparameters_t *parameters, JNIEnv *env, jobject obj, jclass cls) {\r
-       int i,max,shift,w,h,depth;\r
-       opj_image_t * img = NULL;\r
-       int compno, numcomps;\r
-       opj_image_t * image = NULL;\r
-       opj_image_comp_t *comp;\r
-       opj_image_cmptparm_t cmptparm[3];       /* maximum of 3 components */\r
-       OPJ_COLOR_SPACE color_space;\r
-       jfieldID        fid;\r
-       jint            ji;\r
-       jbyteArray      jba;\r
-       jshortArray jsa;\r
-       jintArray       jia;\r
-       int                     len;\r
-       jbyte           *jbBody;\r
-       jshort          *jsBody;\r
-       jint            *jiBody;\r
-       boolean         isCopy;\r
-\r
-       // Image width, height and depth\r
-       fid = (*env)->GetFieldID(env, cls,"width", "I");\r
-       ji = (*env)->GetIntField(env, obj, fid);\r
-       w = ji;\r
-\r
-       fid = (*env)->GetFieldID(env, cls,"height", "I");\r
-       ji = (*env)->GetIntField(env, obj, fid);\r
-       h = ji;\r
-       \r
-       fid = (*env)->GetFieldID(env, cls,"depth", "I");\r
-       ji = (*env)->GetIntField(env, obj, fid);\r
-       depth = ji;\r
-\r
-       // Read the image\r
-       if (depth <=16) {\r
-               numcomps = 1;\r
-               color_space = CLRSPC_GRAY;\r
-       } else {\r
-               numcomps = 3;\r
-               color_space = CLRSPC_SRGB;\r
-       }\r
-       memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));\r
-\r
-       if (numcomps == 1) {\r
-               cmptparm[0].x0 = parameters->image_offset_x0;\r
-               cmptparm[0].y0 = parameters->image_offset_y0;\r
-               cmptparm[0].w = !cmptparm[0].x0 ? (w - 1) * parameters->subsampling_dx + 1 : cmptparm[0].x0 + (w - 1) * parameters->subsampling_dx + 1;\r
-               cmptparm[0].h = !cmptparm[0].y0 ? (h - 1) * parameters->subsampling_dy + 1 : cmptparm[0].y0 + (h - 1) * parameters->subsampling_dy + 1;\r
-               // Java types are always signed but we use them as unsigned types (shift of the negative part of \r
-               // the pixels of the images in Telemis before entering the encoder).\r
-               cmptparm[0].sgnd = 0;\r
-               if (depth<=16) \r
-                       cmptparm[0].prec=depth;\r
-               else \r
-                       cmptparm[0].prec = 8;\r
-               cmptparm[0].bpp = cmptparm[0].prec;\r
-               cmptparm[0].dx = parameters->subsampling_dx;\r
-               cmptparm[0].dy = parameters->subsampling_dy;\r
-               /*printf("C: component 0 initialised: x0=%d, y0=%d, w=%d, h=%d, sgnd=%d, bpp=%d, dx=%d, dy=%d, color_space=%d\n", cmptparm[0].x0, cmptparm[0].y0, cmptparm[0].w,\r
-                                       cmptparm[0].h, cmptparm[0].sgnd, cmptparm[0].bpp, cmptparm[0].dx, cmptparm[0].dy, color_space);*/\r
-       } else {\r
-               for(i = 0; i < numcomps; i++) {\r
-                       cmptparm[i].prec = 8;\r
-                       cmptparm[i].bpp = 8;\r
-                       cmptparm[i].sgnd = 0;\r
-                       cmptparm[i].dx = parameters->subsampling_dx;\r
-                       cmptparm[i].dy = parameters->subsampling_dy;\r
-                       cmptparm[i].w = w;\r
-                       cmptparm[i].h = h;\r
-               }\r
-       }\r
-       \r
-       /* create the image */\r
-       image = opj_image_create(numcomps, &cmptparm[0], color_space);\r
-\r
-       if (!image)\r
-               return NULL;\r
-\r
-       if (depth <=16) {\r
-               image->numcomps=1;\r
-       } else {\r
-               image->numcomps = 3;\r
-       }\r
-\r
-       /* set image offset and reference grid */\r
-       image->x0 = cmptparm[0].x0;\r
-       image->y0 = cmptparm[0].x0;\r
-       image->x1 = cmptparm[0].w;\r
-       image->y1 = cmptparm[0].h;\r
-\r
-       /* set image data */\r
-       for (compno=0; compno<numcomps; compno++) {\r
-               comp = &image->comps[compno];\r
-               max = -100000;\r
-               if (depth == 8) {\r
-                       fid = (*env)->GetFieldID(env, cls,"image8", "[B");      // byteArray []\r
-                       jba = (*env)->GetObjectField(env, obj, fid);\r
-                       len = (*env)->GetArrayLength(env, jba);\r
-                       \r
-                       jbBody = (*env)->GetPrimitiveArrayCritical(env, jba, &isCopy);\r
-                       //printf("C: before transfering 8 bpp image\n");\r
-                       if (comp->sgnd) {\r
-                               for(i=0; i< len;i++) {\r
-                                       comp->data[i] = (char) jbBody[i];\r
-                                       if (comp->data[i] > max) max = comp->data[i];\r
-                               }\r
-                       } else {\r
-                               for(i=0; i< len;i++) {\r
-                                       comp->data[i] = (unsigned char) jbBody[i];\r
-                                       if (comp->data[i] > max) max = comp->data[i];\r
-                               }\r
-                       }\r
-                       (*env)->ReleasePrimitiveArrayCritical(env, jba, jbBody, 0);\r
-               } else if(depth == 16) {\r
-                       fid = (*env)->GetFieldID(env, cls,"image16", "[S");     // shortArray []\r
-                       jsa = (*env)->GetObjectField(env, obj, fid);\r
-                       len = (*env)->GetArrayLength(env, jsa);\r
-                       \r
-                       jsBody = (*env)->GetPrimitiveArrayCritical(env, jsa, &isCopy);\r
-                       //printf("C: before transfering 16 bpp image\n");\r
-                       if (comp->sgnd) {       // Special behaviour to deal with signed elements ??\r
-                               comp->data[i] = (short) jsBody[i];\r
-                               for(i=0; i< len;i++) {\r
-                                       if (comp->data[i] > max) max = comp->data[i];\r
-                               }\r
-                       } else {\r
-                               for(i=0; i< len;i++) {\r
-                                       comp->data[i] = (unsigned short) jsBody[i];\r
-                                       if (comp->data[i] > max) max = comp->data[i];\r
-                               }\r
-                       }\r
-                       (*env)->ReleasePrimitiveArrayCritical(env, jsa, jsBody, 0);\r
-               } else if (depth == 24) {\r
-                       fid = (*env)->GetFieldID(env, cls,"image24", "[I");     // intArray []\r
-                       jia = (*env)->GetObjectField(env, obj, fid);\r
-                       len = (*env)->GetArrayLength(env, jia);\r
-                       shift = compno*8;\r
-\r
-                       jiBody = (*env)->GetPrimitiveArrayCritical(env, jia, &isCopy);\r
-                       //printf("C: before transfering 24 bpp image (component %d, signed = %d)\n", compno, comp->sgnd);\r
-                       if (comp->sgnd) {       // Special behaviour to deal with signed elements ?? XXXXX\r
-                               for(i=0; i< len;i++) {\r
-                                       comp->data[i] = ( ((int) jiBody[i]) & (0xFF << shift) ) >> shift;\r
-                                       if (comp->data[i] > max) max = comp->data[i];\r
-                               }\r
-                       } else {\r
-                               for(i=0; i< len;i++) {\r
-                                       comp->data[i] = ( ((unsigned int) jiBody[i]) & (0xFF << shift) ) >> shift;\r
-                                       if (comp->data[i] > max) max = comp->data[i];\r
-                               }\r
-                       }\r
-                       (*env)->ReleasePrimitiveArrayCritical(env, jia, jiBody, 0);\r
-               }\r
-               comp->bpp = int_floorlog2(max)+1;\r
-               comp->prec = comp->bpp;\r
-               //printf("C: component %d: max  %d, real bpp = %d\n", compno, max, comp->bpp);\r
-       }\r
-       return image;\r
-}\r
-\r
-\r
-/* --------------------------------------------------------------------------\r
-   --------------------   MAIN METHOD, CALLED BY JAVA -----------------------*/\r
-JNIEXPORT jlong JNICALL Java_org_openJpeg_OpenJPEGJavaEncoder_internalEncodeImageToJ2K(JNIEnv *env, jobject obj, jobjectArray javaParameters) {\r
-       int argc;               /* To simulate the command line parameters (taken from the javaParameters variable) and be able to re-use the */\r
-       char **argv;    /*  'parse_cmdline_decoder' method taken from the j2k_to_image project */\r
-       bool bSuccess;\r
-       opj_cparameters_t parameters;   /* compression parameters */\r
-       img_fol_t img_fol;\r
-       opj_event_mgr_t event_mgr;              /* event manager */\r
-       opj_image_t *image = NULL;\r
-       int i,j,num_images;\r
-       int imageno;\r
-       opj_codestream_info_t cstr_info;                /* Codestream information structure */\r
-       char indexfilename[OPJ_PATH_LEN];       /* index file name */\r
-\r
-       int* compressed_index = NULL;\r
-       int compressed_index_size=-1;\r
-       // ==> Access variables to the Java member variables\r
-       jsize           arraySize;\r
-       jclass          cls;\r
-       jobject         object;\r
-       jboolean        isCopy;\r
-       jfieldID        fid;\r
-       jbyteArray      jba;\r
-       jbyte           *jbBody;\r
-       callback_variables_t msgErrorCallback_vars;\r
-       // <== access variable to the Java member variables.\r
-\r
-       // For the encoding and storage into the file\r
-       opj_cinfo_t* cinfo;\r
-       int codestream_length;\r
-       opj_cio_t *cio = NULL;\r
-       FILE *f = NULL;\r
-\r
-       // JNI reference to the calling class\r
-       cls = (*env)->GetObjectClass(env, obj);\r
-       \r
-       // Pointers to be able to call a Java method for all the info and error messages\r
-       msgErrorCallback_vars.env = env;\r
-       msgErrorCallback_vars.jobj = &obj;\r
-       msgErrorCallback_vars.message_mid = (*env)->GetMethodID(env, cls, "logMessage", "(Ljava/lang/String;)V");\r
-       msgErrorCallback_vars.error_mid = (*env)->GetMethodID(env, cls, "logError", "(Ljava/lang/String;)V");\r
-\r
-       arraySize = (*env)->GetArrayLength(env, javaParameters);\r
-       argc = (int) arraySize +1;\r
-       argv = malloc(argc*sizeof(char*));\r
-       argv[0] = "ProgramName.exe";    // The program name: useless\r
-       j=0;\r
-       for (i=1; i<argc; i++) {\r
-               object = (*env)->GetObjectArrayElement(env, javaParameters, i-1);\r
-               argv[i] = (*env)->GetStringUTFChars(env, object, &isCopy);\r
-       }\r
-\r
-       /*printf("C: ");\r
-       for (i=0; i<argc; i++) {\r
-               printf("[%s]",argv[i]);\r
-       }\r
-       printf("\n");*/\r
-\r
-       /*\r
-       configure the event callbacks\r
-       */\r
-       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));\r
-       event_mgr.error_handler = error_callback;\r
-       event_mgr.warning_handler = warning_callback;\r
-       event_mgr.info_handler = info_callback;\r
-\r
-       /* set encoding parameters to default values */\r
-       opj_set_default_encoder_parameters(&parameters);\r
-       parameters.cod_format = J2K_CFMT;\r
-       //parameters.index_on = 1;\r
-\r
-       /* Initialize indexfilename and img_fol */\r
-       *indexfilename = 0;\r
-       memset(&img_fol,0,sizeof(img_fol_t));\r
-\r
-       /* parse input and get user encoding parameters */\r
-       if (parse_cmdline_encoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {\r
-               // Release the Java arguments array\r
-               for (i=1; i<argc; i++)\r
-                       (*env)->ReleaseStringUTFChars(env, (*env)->GetObjectArrayElement(env, javaParameters, i-1), argv[i]);\r
-               return -1;\r
-       }\r
-\r
-       // Release the Java arguments array\r
-       for (i=1; i<argc; i++)\r
-               (*env)->ReleaseStringUTFChars(env, (*env)->GetObjectArrayElement(env, javaParameters, i-1), argv[i]);\r
-\r
-       if (parameters.cp_cinema){\r
-               cinema_parameters(&parameters);\r
-       }\r
-                               \r
-\r
-       /* Create comment for codestream */\r
-       if(parameters.cp_comment == NULL) {\r
-               const char comment[] = "Created by JavaOpenJPEG version ";\r
-               const size_t clen = strlen(comment);\r
-               const char *version = opj_version();\r
-/* UniPG>> */\r
-#ifdef USE_JPWL\r
-               parameters.cp_comment = (char*)malloc(clen+strlen(version)+11);\r
-               sprintf(parameters.cp_comment,"%s%s with JPWL", comment, version);\r
-#else\r
-               parameters.cp_comment = (char*)malloc(clen+strlen(version)+1);\r
-               sprintf(parameters.cp_comment,"%s%s", comment, version);\r
-#endif\r
-/* <<UniPG */\r
-\r
-       }\r
-\r
-       /* Read directory if necessary */\r
-       num_images=1;\r
-\r
-       /*Encoding image one by one*/\r
-       for(imageno=0;imageno<num_images;imageno++)\r
-       {\r
-               image = NULL;\r
-               fprintf(stderr,"\n");\r
-\r
-               image = loadImage(&parameters, env, obj, cls);\r
-               //printf("C: after load image: image = %d\n", image);\r
-               if (!image) {\r
-                       fprintf(stderr, "Unable to load image\n");\r
-                       return -1; \r
-               }\r
-\r
-               /* Decide if MCT should be used */\r
-               parameters.tcp_mct = image->numcomps == 3 ? 1 : 0;\r
-\r
-               if(parameters.cp_cinema){\r
-                       cinema_setup_encoder(&parameters,image,&img_fol);\r
-               }\r
-\r
-               /* encode the destination image */\r
-               /* ---------------------------- */\r
-               /* get a J2K compressor handle */\r
-               if (parameters.cod_format == J2K_CFMT) {        /* J2K format output */\r
-                       cinfo = opj_create_compress(CODEC_J2K);\r
-               } else {                                                                        /* JP2 format output */\r
-                       cinfo = opj_create_compress(CODEC_JP2);\r
-               }\r
-               /* catch events using our callbacks and give a local context */\r
-               opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, &msgErrorCallback_vars);\r
-\r
-               /* setup the encoder parameters using the current image and user parameters */\r
-               opj_setup_encoder(cinfo, &parameters, image);\r
-\r
-               /* open a byte stream for writing */\r
-               /* allocate memory for all tiles */\r
-               cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);\r
-\r
-               /* encode the image */\r
-               bSuccess = opj_encode_with_info(cinfo, cio, image, &cstr_info);\r
-               printf("C: after opj_encode_with_info\n");\r
-               if (!bSuccess) {\r
-                       opj_cio_close(cio);\r
-                       fprintf(stderr, "failed to encode image\n");\r
-                       return -1;\r
-               }\r
-               codestream_length = cio_tell(cio);\r
-\r
-               /* write the index on disk, if needed (-x 'filename') */\r
-               if (*indexfilename) {\r
-                       bSuccess = write_index_file(&cstr_info, indexfilename);\r
-                       if (bSuccess) {\r
-                               fprintf(stderr, "Failed to output index file into [%s]\n", indexfilename);\r
-                       }\r
-               }\r
-\r
-               compressed_index = create_index_into_byte_array(&cstr_info, &compressed_index_size);\r
-               /* Allocates the Java compressedIndex byte[] and sends this index into the Java object */\r
-               fid = (*env)->GetFieldID(env, cls,"compressedIndex", "[B");\r
-               jba = (*env)->NewByteArray(env, compressed_index_size+1);\r
-               jbBody = (*env)->GetPrimitiveArrayCritical(env, jba, 0);\r
-               memcpy(jbBody, compressed_index, compressed_index_size);\r
-               (*env)->ReleasePrimitiveArrayCritical(env, jba, jbBody, 0);\r
-               (*env)->SetObjectField(env, obj, fid, jba); \r
-               free(compressed_index);\r
-\r
-               /* write the generated codestream to disk ? */\r
-               if (parameters.outfile[0]!='\0') {\r
-                       f = fopen(parameters.outfile, "wb");\r
-                       if (!f) {\r
-                               fprintf(stderr, "failed to open [%s] for writing\n", parameters.outfile);\r
-                               return -1;\r
-                       }\r
-                       fwrite(cio->buffer, 1, codestream_length, f);\r
-                       fclose(f);\r
-                       fprintf(stdout,"Generated outfile [%s]\n",parameters.outfile);\r
-               }\r
-\r
-               /* Write the generated codestream to the Java pre-allocated compressedStream byte[] */\r
-               fid = (*env)->GetFieldID(env, cls,"compressedStream", "[B");\r
-               jba = (*env)->GetObjectField(env, obj, fid);\r
-               jbBody = (*env)->GetPrimitiveArrayCritical(env, jba, 0);\r
-               memcpy(jbBody, cio->buffer, codestream_length);\r
-               (*env)->ReleasePrimitiveArrayCritical(env, jba, jbBody, 0);\r
-\r
-               /* close and free the byte stream */\r
-               opj_cio_close(cio);\r
-\r
-               /* free remaining compression structures */\r
-               opj_destroy_compress(cinfo);\r
-               opj_destroy_cstr_info(&cstr_info);\r
-\r
-               /* free image data */\r
-               opj_image_destroy(image);\r
-       }\r
-\r
-       /* free user parameters structure */\r
-  if(parameters.cp_comment) free(parameters.cp_comment);\r
-       if(parameters.cp_matrice) free(parameters.cp_matrice);\r
-\r
-       return codestream_length;\r
-}\r
diff --git a/JavaOpenJPEG/JavaOpenJPEGDecoder.c b/JavaOpenJPEG/JavaOpenJPEGDecoder.c
deleted file mode 100644 (file)
index decc137..0000000
+++ /dev/null
@@ -1,883 +0,0 @@
-/*\r
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
- * Copyright (c) 2002-2007, Professor Benoit Macq\r
- * Copyright (c) 2001-2003, David Janssens\r
- * Copyright (c) 2002-2003, Yannick Verschueren\r
- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe\r
- * Copyright (c) 2005, Herve Drolon, FreeImage Team\r
- * Copyright (c) 2006-2007, Parvatha Elangovan\r
- * Copyright (c) 2007, Patrick Piscaglia (Telemis)\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-#include <stdio.h>\r
-#include <string.h>\r
-#include <stdlib.h>\r
-#include <jni.h>\r
-#include <math.h>\r
-\r
-#include "openjpeg.h"\r
-#include "getopt.h"\r
-#include "convert.h"\r
-#include "dirent.h"\r
-#include "org_openJpeg_OpenJPEGJavaDecoder.h"\r
-\r
-#ifndef _WIN32\r
-#define stricmp strcasecmp\r
-#define strnicmp strncasecmp\r
-#endif\r
-\r
-#include "format_defs.h"\r
-\r
-typedef struct callback_variables {\r
-       JNIEnv *env;\r
-       /** 'jclass' object used to call a Java method from the C */\r
-       jobject *jobj;\r
-       /** 'jclass' object used to call a Java method from the C */\r
-       jmethodID message_mid;\r
-       jmethodID error_mid;\r
-} callback_variables_t;\r
-\r
-typedef struct dircnt{\r
-       /** Buffer for holding images read from Directory*/\r
-       char *filename_buf;\r
-       /** Pointer to the buffer*/\r
-       char **filename;\r
-}dircnt_t;\r
-\r
-\r
-typedef struct img_folder{\r
-       /** The directory path of the folder containing input images*/\r
-       char *imgdirpath;\r
-       /** Output format*/\r
-       char *out_format;\r
-       /** Enable option*/\r
-       char set_imgdir;\r
-       /** Enable Cod Format for output*/\r
-       char set_out_format;\r
-\r
-}img_fol_t;\r
-\r
-\r
-void decode_help_display() {\r
-       fprintf(stdout,"HELP\n----\n\n");\r
-       fprintf(stdout,"- the -h option displays this help information on screen\n\n");\r
-\r
-/* UniPG>> */\r
-       fprintf(stdout,"List of parameters for the JPEG 2000 "\r
-#ifdef USE_JPWL\r
-               "+ JPWL "\r
-#endif /* USE_JPWL */\r
-               "decoder:\n");\r
-/* <<UniPG */\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"\n");\r
-       fprintf(stdout,"  -ImgDir \n");\r
-       fprintf(stdout,"        Image file Directory path \n");\r
-       fprintf(stdout,"  -OutFor \n");\r
-       fprintf(stdout,"    REQUIRED only if -ImgDir is used\n");\r
-       fprintf(stdout,"          Need to specify only format without filename <BMP>  \n");\r
-       fprintf(stdout,"    Currently accepts PGM, PPM, PNM, PGX, BMP format\n");\r
-       fprintf(stdout,"  -i <compressed file>\n");\r
-       fprintf(stdout,"    REQUIRED only if an Input image directory not specified\n");\r
-       fprintf(stdout,"    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n");\r
-       fprintf(stdout,"    is identified based on its suffix.\n");\r
-       fprintf(stdout,"  -o <decompressed file>\n");\r
-       fprintf(stdout,"    REQUIRED\n");\r
-       fprintf(stdout,"    Currently accepts PGM-files, PPM-files, PNM-files, PGX-files and\n");\r
-       fprintf(stdout,"    BMP-files. Binary data is written to the file (not ascii). If a PGX\n");\r
-       fprintf(stdout,"    filename is given, there will be as many output files as there are\n");\r
-       fprintf(stdout,"    components: an indice starting from 0 will then be appended to the\n");\r
-       fprintf(stdout,"    output filename, just before the \"pgx\" extension. If a PGM filename\n");\r
-       fprintf(stdout,"    is given and there are more than one component, only the first component\n");\r
-       fprintf(stdout,"    will be written to the file.\n");\r
-       fprintf(stdout,"  -r <reduce factor>\n");\r
-       fprintf(stdout,"    Set the number of highest resolution levels to be discarded. The\n");\r
-       fprintf(stdout,"    image resolution is effectively divided by 2 to the power of the\n");\r
-       fprintf(stdout,"    number of discarded levels. The reduce factor is limited by the\n");\r
-       fprintf(stdout,"    smallest total number of decomposition levels among tiles.\n");\r
-       fprintf(stdout,"  -l <number of quality layers to decode>\n");\r
-       fprintf(stdout,"    Set the maximum number of quality layers to decode. If there are\n");\r
-       fprintf(stdout,"    less quality layers than the specified number, all the quality layers\n");\r
-       fprintf(stdout,"    are decoded.\n");\r
-/* UniPG>> */\r
-#ifdef USE_JPWL\r
-       fprintf(stdout,"  -W <options>\n");\r
-       fprintf(stdout,"    Activates the JPWL correction capability, if the codestream complies.\n");\r
-       fprintf(stdout,"    Options can be a comma separated list of <param=val> tokens:\n");\r
-       fprintf(stdout,"    c, c=numcomps\n");\r
-       fprintf(stdout,"       numcomps is the number of expected components in the codestream\n");\r
-       fprintf(stdout,"       (search of first EPB rely upon this, default is %d)\n", JPWL_EXPECTED_COMPONENTS);\r
-#endif /* USE_JPWL */\r
-/* <<UniPG */\r
-       fprintf(stdout,"\n");\r
-}\r
-\r
-/* -------------------------------------------------------------------------- */\r
-\r
-int get_num_images(char *imgdirpath){\r
-       DIR *dir;\r
-       struct dirent* content; \r
-       int num_images = 0;\r
-\r
-       /*Reading the input images from given input directory*/\r
-\r
-       dir= opendir(imgdirpath);\r
-       if(!dir){\r
-               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);\r
-               return 0;\r
-       }\r
-       \r
-       while((content=readdir(dir))!=NULL){\r
-               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )\r
-                       continue;\r
-               num_images++;\r
-       }\r
-       return num_images;\r
-}\r
-\r
-int load_images(dircnt_t *dirptr, char *imgdirpath){\r
-       DIR *dir;\r
-       struct dirent* content; \r
-       int i = 0;\r
-\r
-       /*Reading the input images from given input directory*/\r
-\r
-       dir= opendir(imgdirpath);\r
-       if(!dir){\r
-               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);\r
-               return 1;\r
-       }else   {\r
-               fprintf(stderr,"Folder opened successfully\n");\r
-       }\r
-       \r
-       while((content=readdir(dir))!=NULL){\r
-               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )\r
-                       continue;\r
-\r
-               strcpy(dirptr->filename[i],content->d_name);\r
-               i++;\r
-       }\r
-       return 0;       \r
-}\r
-\r
-int get_file_format(char *filename) {\r
-       unsigned int i;\r
-       static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "tga", "j2k", "jp2", "jpt", "j2c" };\r
-       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
-       char * ext = strrchr(filename, '.');\r
-       if (ext == NULL)\r
-               return -1;\r
-       ext++;\r
-       if(ext) {\r
-               for(i = 0; i < sizeof(format)/sizeof(*format); i++) {\r
-                       if(strnicmp(ext, extension[i], 3) == 0) {\r
-                               return format[i];\r
-                       }\r
-               }\r
-       }\r
-\r
-       return -1;\r
-}\r
-\r
-\r
-/* -------------------------------------------------------------------------- */\r
-\r
-int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol) {\r
-       /* parse the command line */\r
-       int totlen;\r
-       option_t long_option[]={\r
-               {"ImgDir",REQ_ARG, NULL ,'y'},\r
-               {"OutFor",REQ_ARG, NULL ,'O'},\r
-       };\r
-\r
-/* UniPG>> */\r
-       const char optlist[] = "i:o:r:l:hx:"\r
-\r
-#ifdef USE_JPWL\r
-                                       "W:"\r
-#endif /* USE_JPWL */\r
-                                       ;\r
-       /*for (i=0; i<argc; i++) {\r
-               printf("[%s]",argv[i]);\r
-       }\r
-       printf("\n");*/\r
-\r
-/* <<UniPG */\r
-       totlen=sizeof(long_option);\r
-       img_fol->set_out_format = 0;\r
-       reset_options_reading();\r
-\r
-       while (1) {\r
-               int c = getopt_long(argc, argv,optlist,long_option,totlen);\r
-               if (c == -1)\r
-                       break;\r
-               switch (c) {\r
-                       case 'i':                       /* input file */\r
-                       {\r
-                               char *infile = optarg;\r
-                               parameters->decod_format = get_file_format(infile);\r
-                               switch(parameters->decod_format) {\r
-                                       case J2K_CFMT:\r
-                                       case JP2_CFMT:\r
-                                       case JPT_CFMT:\r
-                                               break;\r
-                                       default:\r
-                                               fprintf(stderr, \r
-                                                       "!! Unrecognized format for infile : %s [accept only *.j2k, *.jp2, *.jpc or *.jpt] !!\n\n", \r
-                                                       infile);\r
-                                               return 1;\r
-                               }\r
-                               strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);\r
-                       }\r
-                       break;\r
-                               \r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 'o':                       /* output file */\r
-                       {\r
-                               char *outfile = optarg;\r
-                               parameters->cod_format = get_file_format(outfile);\r
-                               switch(parameters->cod_format) {\r
-                                       case PGX_DFMT:\r
-                                       case PXM_DFMT:\r
-                                       case BMP_DFMT:\r
-                                       case TIF_DFMT:\r
-                                       case RAW_DFMT:\r
-                                       case TGA_DFMT:\r
-                                               break;\r
-                                       default:\r
-                                               fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outfile);\r
-                                               return 1;\r
-                               }\r
-                               strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);\r
-                       }\r
-                       break;\r
-                       \r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 'O':                       /* output format */\r
-                       {\r
-                               char outformat[50];\r
-                               char *of = optarg;\r
-                               sprintf(outformat,".%s",of);\r
-                               img_fol->set_out_format = 1;\r
-                               parameters->cod_format = get_file_format(outformat);\r
-                               switch(parameters->cod_format) {\r
-                                       case PGX_DFMT:\r
-                                               img_fol->out_format = "pgx";\r
-                                               break;\r
-                                       case PXM_DFMT:\r
-                                               img_fol->out_format = "ppm";\r
-                                               break;\r
-                                       case BMP_DFMT:\r
-                                               img_fol->out_format = "bmp";\r
-                                               break;\r
-                                       case TIF_DFMT:\r
-                                               img_fol->out_format = "tif";\r
-                                               break;\r
-                                       case RAW_DFMT:\r
-                                               img_fol->out_format = "raw";\r
-                                               break;\r
-                                       case TGA_DFMT:\r
-                                               img_fol->out_format = "raw";\r
-                                               break;\r
-                                       default:\r
-                                               fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outformat);\r
-                                               return 1;\r
-                                               break;\r
-                               }\r
-                       }\r
-                       break;\r
-\r
-                               /* ----------------------------------------------------- */\r
-\r
-\r
-                       case 'r':               /* reduce option */\r
-                       {\r
-                               sscanf(optarg, "%d", &parameters->cp_reduce);\r
-                       }\r
-                       break;\r
-                       \r
-                               /* ----------------------------------------------------- */\r
-      \r
-\r
-                       case 'l':               /* layering option */\r
-                       {\r
-                               sscanf(optarg, "%d", &parameters->cp_layer);\r
-                       }\r
-                       break;\r
-                       \r
-                               /* ----------------------------------------------------- */\r
-\r
-                       case 'h':                       /* display an help description */\r
-                               decode_help_display();\r
-                               return 1;                               \r
-\r
-                               /* ------------------------------------------------------ */\r
-\r
-                       case 'y':                       /* Image Directory path */\r
-                               {\r
-                                       img_fol->imgdirpath = (char*)malloc(strlen(optarg) + 1);\r
-                                       strcpy(img_fol->imgdirpath,optarg);\r
-                                       img_fol->set_imgdir=1;\r
-                               }\r
-                               break;\r
-                               /* ----------------------------------------------------- */\r
-/* UniPG>> */\r
-#ifdef USE_JPWL\r
-                       \r
-                       case 'W':                       /* activate JPWL correction */\r
-                       {\r
-                               char *token = NULL;\r
-\r
-                               token = strtok(optarg, ",");\r
-                               while(token != NULL) {\r
-\r
-                                       /* search expected number of components */\r
-                                       if (*token == 'c') {\r
-\r
-                                               static int compno;\r
-\r
-                                               compno = JPWL_EXPECTED_COMPONENTS; /* predefined no. of components */\r
-\r
-                                               if(sscanf(token, "c=%d", &compno) == 1) {\r
-                                                       /* Specified */\r
-                                                       if ((compno < 1) || (compno > 256)) {\r
-                                                               fprintf(stderr, "ERROR -> invalid number of components c = %d\n", compno);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       parameters->jpwl_exp_comps = compno;\r
-\r
-                                               } else if (!strcmp(token, "c")) {\r
-                                                       /* default */\r
-                                                       parameters->jpwl_exp_comps = compno; /* auto for default size */\r
-\r
-                                               } else {\r
-                                                       fprintf(stderr, "ERROR -> invalid components specified = %s\n", token);\r
-                                                       return 1;\r
-                                               };\r
-                                       }\r
-\r
-                                       /* search maximum number of tiles */\r
-                                       if (*token == 't') {\r
-\r
-                                               static int tileno;\r
-\r
-                                               tileno = JPWL_MAXIMUM_TILES; /* maximum no. of tiles */\r
-\r
-                                               if(sscanf(token, "t=%d", &tileno) == 1) {\r
-                                                       /* Specified */\r
-                                                       if ((tileno < 1) || (tileno > JPWL_MAXIMUM_TILES)) {\r
-                                                               fprintf(stderr, "ERROR -> invalid number of tiles t = %d\n", tileno);\r
-                                                               return 1;\r
-                                                       }\r
-                                                       parameters->jpwl_max_tiles = tileno;\r
-\r
-                                               } else if (!strcmp(token, "t")) {\r
-                                                       /* default */\r
-                                                       parameters->jpwl_max_tiles = tileno; /* auto for default size */\r
-\r
-                                               } else {\r
-                                                       fprintf(stderr, "ERROR -> invalid tiles specified = %s\n", token);\r
-                                                       return 1;\r
-                                               };\r
-                                       }\r
-\r
-                                       /* next token or bust */\r
-                                       token = strtok(NULL, ",");\r
-                               };\r
-                               parameters->jpwl_correct = true;\r
-                               fprintf(stdout, "JPWL correction capability activated\n");\r
-                               fprintf(stdout, "- expecting %d components\n", parameters->jpwl_exp_comps);\r
-                       }\r
-                       break;  \r
-#endif /* USE_JPWL */\r
-/* <<UniPG */            \r
-\r
-                               /* ----------------------------------------------------- */\r
-                       \r
-                       default:\r
-                               fprintf(stderr,"WARNING -> this option is not valid \"-%c %s\"\n",c, optarg);\r
-                               break;\r
-               }\r
-       }\r
-\r
-       /* No check for possible errors before the -i and -o options are of course not mandatory*/\r
-\r
-       return 0;\r
-}\r
-\r
-/* -------------------------------------------------------------------------- */\r
-\r
-/**\r
-error callback returning the message to Java andexpecting a callback_variables_t client object\r
-*/\r
-void error_callback(const char *msg, void *client_data) {\r
-       callback_variables_t* vars = (callback_variables_t*) client_data;\r
-       JNIEnv *env = vars->env;\r
-       jstring jbuffer;\r
-\r
-       jbuffer = (*env)->NewStringUTF(env, msg);\r
-       (*env)->ExceptionClear(env);\r
-       (*env)->CallVoidMethod(env, *(vars->jobj), vars->error_mid, jbuffer);\r
-\r
-       if ((*env)->ExceptionOccurred(env)) {\r
-               fprintf(stderr,"C: Exception during call back method\n");\r
-               (*env)->ExceptionDescribe(env);\r
-               (*env)->ExceptionClear(env);\r
-       }\r
-       (*env)->DeleteLocalRef(env, jbuffer);\r
-}\r
-/**\r
-warning callback returning the message to Java andexpecting a callback_variables_t client object\r
-*/\r
-void warning_callback(const char *msg, void *client_data) {\r
-       callback_variables_t* vars = (callback_variables_t*) client_data;\r
-       JNIEnv *env = vars->env;\r
-       jstring jbuffer;\r
-\r
-       jbuffer = (*env)->NewStringUTF(env, msg);\r
-       (*env)->ExceptionClear(env);\r
-       (*env)->CallVoidMethod(env, *(vars->jobj), vars->message_mid, jbuffer);\r
-       \r
-       if ((*env)->ExceptionOccurred(env)) {\r
-               fprintf(stderr,"C: Exception during call back method\n");\r
-               (*env)->ExceptionDescribe(env);\r
-               (*env)->ExceptionClear(env);\r
-       }\r
-       (*env)->DeleteLocalRef(env, jbuffer);\r
-}\r
-/**\r
-information callback returning the message to Java andexpecting a callback_variables_t client object\r
-*/\r
-void info_callback(const char *msg, void *client_data) {\r
-       callback_variables_t* vars = (callback_variables_t*) client_data;\r
-       JNIEnv *env = vars->env;\r
-       jstring jbuffer;\r
-\r
-       jbuffer = (*env)->NewStringUTF(env, msg);\r
-       (*env)->ExceptionClear(env);\r
-       (*env)->CallVoidMethod(env, *(vars->jobj), vars->message_mid, jbuffer);\r
-\r
-       if ((*env)->ExceptionOccurred(env)) {\r
-               fprintf(stderr,"C: Exception during call back method\n");\r
-               (*env)->ExceptionDescribe(env);\r
-               (*env)->ExceptionClear(env);\r
-       }\r
-       (*env)->DeleteLocalRef(env, jbuffer);\r
-}\r
-\r
-\r
-/* --------------------------------------------------------------------------\r
-   --------------------   MAIN METHOD, CALLED BY JAVA -----------------------*/\r
-JNIEXPORT jint JNICALL Java_org_openJpeg_OpenJPEGJavaDecoder_internalDecodeJ2KtoImage(JNIEnv *env, jobject obj, jobjectArray javaParameters) {\r
-       int argc;               /* To simulate the command line parameters (taken from the javaParameters variable) and be able to re-use the */\r
-       char **argv;    /*  'parse_cmdline_decoder' method taken from the j2k_to_image project */\r
-       opj_dparameters_t parameters;   /* decompression parameters */\r
-       img_fol_t img_fol;\r
-       opj_event_mgr_t event_mgr;              /* event manager */\r
-       opj_image_t *image = NULL;\r
-       FILE *fsrc = NULL;\r
-       unsigned char *src = NULL;\r
-       int file_length;\r
-       int num_images;\r
-       int i,j,imageno;\r
-       opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */\r
-       opj_cio_t *cio = NULL;\r
-       int w,h;\r
-       long min_value, max_value;\r
-       short tempS; unsigned char tempUC, tempUC1, tempUC2;\r
-       // ==> Access variables to the Java member variables\r
-       jsize           arraySize;\r
-       jclass          cls;\r
-       jobject         object;\r
-       jboolean        isCopy;\r
-       jfieldID        fid;\r
-       jbyteArray      jba;\r
-       jshortArray jsa;\r
-       jintArray       jia;\r
-       jbyte           *jbBody, *ptrBBody;\r
-       jshort          *jsBody, *ptrSBody;\r
-       jint            *jiBody, *ptrIBody;\r
-       callback_variables_t msgErrorCallback_vars;\r
-       // <=== access variable to Java member variables */\r
-       int *ptr, *ptr1, *ptr2;                         // <== To transfer the decoded image to Java\r
-\r
-       /* configure the event callbacks */\r
-       memset(&event_mgr, 0, sizeof(opj_event_mgr_t)); \r
-       event_mgr.error_handler = error_callback;\r
-       event_mgr.warning_handler = warning_callback;\r
-       event_mgr.info_handler = info_callback;\r
-\r
-       // JNI reference to the calling class\r
-       cls = (*env)->GetObjectClass(env, obj);\r
-\r
-       // Pointers to be able to call a Java method for all the info and error messages\r
-       msgErrorCallback_vars.env = env;\r
-       msgErrorCallback_vars.jobj = &obj;\r
-       msgErrorCallback_vars.message_mid = (*env)->GetMethodID(env, cls, "logMessage", "(Ljava/lang/String;)V");\r
-       msgErrorCallback_vars.error_mid = (*env)->GetMethodID(env, cls, "logError", "(Ljava/lang/String;)V");\r
-\r
-       // Get the String[] containing the parameters, and converts it into a char** to simulate command line arguments.\r
-       arraySize = (*env)->GetArrayLength(env, javaParameters);\r
-       argc = (int) arraySize +1;\r
-       argv = malloc(argc*sizeof(char*));\r
-       argv[0] = "ProgramName.exe";    // The program name: useless\r
-       j=0;\r
-       for (i=1; i<argc; i++) {\r
-               object = (*env)->GetObjectArrayElement(env, javaParameters, i-1);\r
-               argv[i] = (*env)->GetStringUTFChars(env, object, &isCopy);\r
-       }\r
-\r
-       /*printf("C: decoder params = ");\r
-       for (i=0; i<argc; i++) {\r
-               printf("[%s]",argv[i]);\r
-       }\r
-       printf("\n");*/\r
-\r
-       /* set decoding parameters to default values */\r
-       opj_set_default_decoder_parameters(&parameters);\r
-       parameters.decod_format = J2K_CFMT;\r
-\r
-       /* parse input and get user encoding parameters */\r
-       if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol) == 1) {\r
-               // Release the Java arguments array\r
-               for (i=1; i<argc; i++)\r
-                       (*env)->ReleaseStringUTFChars(env, (*env)->GetObjectArrayElement(env, javaParameters, i-1), argv[i]);\r
-               return -1;\r
-       }\r
-       // Release the Java arguments array\r
-       for (i=1; i<argc; i++)\r
-               (*env)->ReleaseStringUTFChars(env, (*env)->GetObjectArrayElement(env, javaParameters, i-1), argv[i]);\r
-\r
-       num_images=1;\r
-\r
-       // Get additional information from the Java object variables\r
-       fid = (*env)->GetFieldID(env, cls,"skippedResolutions", "I");\r
-       parameters.cp_reduce = (short) (*env)->GetIntField(env, obj, fid);\r
-\r
-       /*Decoding image one by one*/\r
-       for(imageno = 0; imageno < num_images ; imageno++)\r
-       {\r
-               image = NULL;\r
-               fprintf(stderr,"\n");\r
-\r
-               /* read the input file and put it in memory into the 'src' object, if the -i option is given in JavaParameters.\r
-                  Implemented for debug purpose. */\r
-               /* -------------------------------------------------------------- */\r
-               if (parameters.infile && parameters.infile[0]!='\0') {\r
-                       //printf("C: opening [%s]\n", parameters.infile);\r
-                       fsrc = fopen(parameters.infile, "rb");\r
-                       if (!fsrc) {\r
-                               fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);\r
-                               return 1;\r
-                       }\r
-                       fseek(fsrc, 0, SEEK_END);\r
-                       file_length = ftell(fsrc);\r
-                       fseek(fsrc, 0, SEEK_SET);\r
-                       src = (unsigned char *) malloc(file_length);\r
-                       fread(src, 1, file_length, fsrc);\r
-                       fclose(fsrc);\r
-                       //printf("C: %d bytes read from file\n",file_length);\r
-               } else {\r
-                       // Preparing the transfer of the codestream from Java to C\r
-                       //printf("C: before transfering codestream\n");\r
-                       fid = (*env)->GetFieldID(env, cls,"compressedStream", "[B");\r
-                       jba = (*env)->GetObjectField(env, obj, fid);\r
-                       file_length = (*env)->GetArrayLength(env, jba);\r
-                       jbBody = (*env)->GetByteArrayElements(env, jba, &isCopy);\r
-                       src = (unsigned char*)jbBody;\r
-               }\r
-\r
-               /* decode the code-stream */\r
-               /* ---------------------- */\r
-\r
-               switch(parameters.decod_format) {\r
-               case J2K_CFMT:\r
-               {\r
-                       /* JPEG-2000 codestream */\r
-\r
-                       /* get a decoder handle */\r
-                       dinfo = opj_create_decompress(CODEC_J2K);\r
-\r
-                       /* catch events using our callbacks and give a local context */\r
-                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, &msgErrorCallback_vars);\r
-\r
-                       /* setup the decoder decoding parameters using user parameters */\r
-                       opj_setup_decoder(dinfo, &parameters);\r
-\r
-                       /* open a byte stream */\r
-                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);\r
-\r
-                       /* decode the stream and fill the image structure */\r
-                       image = opj_decode(dinfo, cio);\r
-                       if(!image) {\r
-                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");\r
-                               opj_destroy_decompress(dinfo);\r
-                               opj_cio_close(cio);\r
-                               return 1;\r
-                       }\r
-\r
-                       /* close the byte stream */\r
-                       opj_cio_close(cio);\r
-               }\r
-               break;\r
-\r
-               case JP2_CFMT:\r
-               {\r
-                       /* JPEG 2000 compressed image data */\r
-\r
-                       /* get a decoder handle */\r
-                       dinfo = opj_create_decompress(CODEC_JP2);\r
-\r
-                       /* catch events using our callbacks and give a local context */\r
-                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, &msgErrorCallback_vars);\r
-\r
-                       /* setup the decoder decoding parameters using the current image and user parameters */\r
-                       opj_setup_decoder(dinfo, &parameters);\r
-\r
-                       /* open a byte stream */\r
-                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);\r
-\r
-                       /* decode the stream and fill the image structure */\r
-                       image = opj_decode(dinfo, cio);\r
-                       if(!image) {\r
-                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");\r
-                               opj_destroy_decompress(dinfo);\r
-                               opj_cio_close(cio);\r
-                               return 1;\r
-                       }\r
-\r
-                       /* close the byte stream */\r
-                       opj_cio_close(cio);\r
-\r
-               }\r
-               break;\r
-\r
-               case JPT_CFMT:\r
-               {\r
-                       /* JPEG 2000, JPIP */\r
-\r
-                       /* get a decoder handle */\r
-                       dinfo = opj_create_decompress(CODEC_JPT);\r
-\r
-                       /* catch events using our callbacks and give a local context */\r
-                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, &msgErrorCallback_vars);\r
-\r
-                       /* setup the decoder decoding parameters using user parameters */\r
-                       opj_setup_decoder(dinfo, &parameters);\r
-\r
-                       /* open a byte stream */\r
-                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);\r
-\r
-                       /* decode the stream and fill the image structure */\r
-                       image = opj_decode(dinfo, cio);\r
-                       if(!image) {\r
-                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");\r
-                               opj_destroy_decompress(dinfo);\r
-                               opj_cio_close(cio);\r
-                               return 1;\r
-                       }\r
-\r
-                       /* close the byte stream */\r
-                       opj_cio_close(cio);\r
-               }\r
-               break;\r
-\r
-               default:\r
-                       fprintf(stderr, "skipping file..\n");\r
-                       continue;\r
-       }\r
-\r
-               /* free the memory containing the code-stream */\r
-               if (parameters.infile && parameters.infile[0]!='\0') {\r
-                       free(src);\r
-               } else {\r
-                       (*env)->ReleaseByteArrayElements(env, jba, jbBody, 0);\r
-               }\r
-               src = NULL;\r
-\r
-               /* create output image.\r
-                       If the -o parameter is given in the JavaParameters, write the decoded version into a file.\r
-                       Implemented for debug purpose. */\r
-               /* ---------------------------------- */\r
-               switch (parameters.cod_format) {\r
-               case PXM_DFMT:                  /* PNM PGM PPM */\r
-                       if (imagetopnm(image, parameters.outfile)) {\r
-                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);\r
-                       }\r
-                       else {\r
-                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);\r
-                       }\r
-                       break;\r
-\r
-               case PGX_DFMT:                  /* PGX */\r
-                       if(imagetopgx(image, parameters.outfile)){\r
-                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);\r
-                       }\r
-                       else {\r
-                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);\r
-                       }\r
-                       break;\r
-\r
-               case BMP_DFMT:                  /* BMP */\r
-                       if(imagetobmp(image, parameters.outfile)){\r
-                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);\r
-                       }\r
-                       else {\r
-                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);\r
-                       }\r
-                       break;\r
-\r
-               }\r
-\r
-               // ========= Return the image to the Java structure ===============\r
-#ifdef CHECK_THRESHOLDS\r
-               printf("C: checking thresholds\n");\r
-#endif\r
-               // First compute the real with and height, in function of the resolutions decoded.\r
-               //wr = (image->comps[0].w + (1 << image->comps[0].factor) -1) >> image->comps[0].factor;\r
-               //hr = (image->comps[0].h + (1 << image->comps[0].factor) -1) >> image->comps[0].factor;\r
-               w = image->comps[0].w;\r
-               h = image->comps[0].h;\r
-\r
-               if (image->numcomps==3) {       // 3 components color image\r
-                       ptr = image->comps[0].data;\r
-                       ptr1 = image->comps[1].data;\r
-                       ptr2 = image->comps[2].data;\r
-#ifdef CHECK_THRESHOLDS \r
-                       if (image->comps[0].sgnd) {\r
-                               min_value = -128;\r
-                               max_value = 127;\r
-                       } else {\r
-                               min_value = 0;\r
-                               max_value = 255;\r
-                       }\r
-#endif                 \r
-                       // Get the pointer to the Java structure where the data must be copied\r
-                       fid = (*env)->GetFieldID(env, cls,"image24", "[I");\r
-                       jia = (*env)->GetObjectField(env, obj, fid);\r
-                       jiBody = (*env)->GetIntArrayElements(env, jia, 0);\r
-                       ptrIBody = jiBody;\r
-                       printf("C: transfering image24: %d int to Java pointer=%d\n",image->numcomps*w*h, ptrIBody);\r
-\r
-                       for (i=0; i<w*h; i++) {\r
-                               tempUC = (unsigned char)(ptr[i]);\r
-                               tempUC1 = (unsigned char)(ptr1[i]);\r
-                               tempUC2 = (unsigned char)(ptr2[i]);\r
-#ifdef CHECK_THRESHOLDS\r
-                               if (tempUC < min_value)\r
-                                       tempUC=min_value;\r
-                               else if (tempUC > max_value)\r
-                                       tempUC=max_value;\r
-                               if (tempUC1 < min_value)\r
-                                       tempUC1=min_value;\r
-                               else if (tempUC1 > max_value)\r
-                                       tempUC1=max_value;\r
-                               if (tempUC2 < min_value)\r
-                                       tempUC2=min_value;\r
-                               else if (tempUC2 > max_value)\r
-                                       tempUC2=max_value;\r
-#endif\r
-                               *(ptrIBody++)  = (int) ( (tempUC2<<16) + (tempUC1<<8) + tempUC );\r
-                       }\r
-                       (*env)->ReleaseIntArrayElements(env, jia, jiBody, 0);\r
-\r
-               } else {        // 1 component 8 or 16 bpp image\r
-                       ptr = image->comps[0].data;\r
-                       printf("C: before transfering a %d bpp image to java (length = %d)\n",image->comps[0].prec ,w*h);\r
-                       if (image->comps[0].prec<=8) {\r
-                               fid = (*env)->GetFieldID(env, cls,"image8", "[B");\r
-                               jba = (*env)->GetObjectField(env, obj, fid);\r
-                               jbBody = (*env)->GetByteArrayElements(env, jba, 0);\r
-                               ptrBBody = jbBody;\r
-#ifdef CHECK_THRESHOLDS \r
-                               if (image->comps[0].sgnd) {\r
-                                       min_value = -128;\r
-                                       max_value = 127;\r
-                               } else {\r
-                                       min_value = 0;\r
-                                       max_value = 255;\r
-                               }\r
-#endif                                                         \r
-                               //printf("C: transfering %d shorts to Java image8 pointer = %d\n", wr*hr,ptrSBody);\r
-                               for (i=0; i<w*h; i++) {\r
-                                       tempUC = (unsigned char) (ptr[i]);\r
-#ifdef CHECK_THRESHOLDS\r
-                                       if (tempUC<min_value)\r
-                                               tempUC = min_value;\r
-                                       else if (tempUC > max_value)\r
-                                               tempUC = max_value;\r
-#endif\r
-                                       *(ptrBBody++) = tempUC;\r
-                               }\r
-                               (*env)->ReleaseByteArrayElements(env, jba, jbBody, 0);\r
-                               printf("C: image8 transfered to Java\n");\r
-                       } else {\r
-                               fid = (*env)->GetFieldID(env, cls,"image16", "[S");\r
-                               jsa = (*env)->GetObjectField(env, obj, fid);\r
-                               jsBody = (*env)->GetShortArrayElements(env, jsa, 0);\r
-                               ptrSBody = jsBody;\r
-#ifdef CHECK_THRESHOLDS \r
-                               if (image->comps[0].sgnd) {\r
-                                       min_value = -32768;\r
-                                       max_value = 32767;\r
-                               } else {\r
-                                       min_value = 0;\r
-                                       max_value = 65535;\r
-                               }\r
-                               printf("C: minValue = %d, maxValue = %d\n", min_value, max_value);\r
-#endif                         \r
-                               printf("C: transfering %d shorts to Java image16 pointer = %d\n", w*h,ptrSBody);\r
-                               for (i=0; i<w*h; i++) {\r
-                                       tempS = (short) (ptr[i]);\r
-#ifdef CHECK_THRESHOLDS\r
-                                       if (tempS<min_value) {\r
-                                               printf("C: value %d truncated to %d\n", tempS, min_value);\r
-                                               tempS = min_value;\r
-                                       } else if (tempS > max_value) {\r
-                                               printf("C: value %d truncated to %d\n", tempS, max_value);\r
-                                               tempS = max_value;\r
-                                       }\r
-#endif\r
-                                       *(ptrSBody++) = tempS;\r
-                               }\r
-                               (*env)->ReleaseShortArrayElements(env, jsa, jsBody, 0);\r
-                               printf("C: image16 completely filled\n");\r
-                       }\r
-               }       \r
-\r
-\r
-               /* free remaining structures */\r
-               if(dinfo) {\r
-                       opj_destroy_decompress(dinfo);\r
-               }\r
-               /* free image data structure */\r
-               opj_image_destroy(image);\r
-\r
-       }\r
-       return 1; /* OK */\r
-}\r
-//end main\r
-\r
diff --git a/JavaOpenJPEG/Makefile b/JavaOpenJPEG/Makefile
deleted file mode 100644 (file)
index 9ac3e40..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-# Makefile for the main OpenJPEG codecs: j2k_to_image and image_to_j2k
-
-CFLAGS = -O3 -lstdc++ # -g -p -pg
-
-all: j2k_to_image image_to_j2k
-
-j2k_to_image: j2k_to_image.c ../libopenjpeg.a
-       gcc $(CFLAGS) ../common/getopt.c convert.c j2k_to_image.c -o j2k_to_image -L.. -lopenjpeg -I ../libopenjpeg/ -lm -ltiff
-
-image_to_j2k: image_to_j2k.c ../libopenjpeg.a
-       gcc $(CFLAGS) ../common/getopt.c convert.c image_to_j2k.c -o image_to_j2k -L.. -lopenjpeg -I ../libopenjpeg/ -lm -ltiff
-
-clean:
-       rm -f j2k_to_image image_to_j2k
diff --git a/JavaOpenJPEG/java-jni/include/jawt.h b/JavaOpenJPEG/java-jni/include/jawt.h
deleted file mode 100644 (file)
index 30a49ad..0000000
+++ /dev/null
@@ -1,278 +0,0 @@
-/*\r
- * @(#)jawt.h  1.10 03/12/19\r
- *\r
- * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
- * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
- */\r
-\r
-#ifndef _JAVASOFT_JAWT_H_\r
-#define _JAVASOFT_JAWT_H_\r
-\r
-#include "jni.h"\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-/*\r
- * AWT native interface (new in JDK 1.3)\r
- *\r
- * The AWT native interface allows a native C or C++ application a means\r
- * by which to access native structures in AWT.  This is to facilitate moving\r
- * legacy C and C++ applications to Java and to target the needs of the\r
- * community who, at present, wish to do their own native rendering to canvases\r
- * for performance reasons.  Standard extensions such as Java3D also require a\r
- * means to access the underlying native data structures of AWT.\r
- *\r
- * There may be future extensions to this API depending on demand.\r
- *\r
- * A VM does not have to implement this API in order to pass the JCK.\r
- * It is recommended, however, that this API is implemented on VMs that support\r
- * standard extensions, such as Java3D.\r
- *\r
- * Since this is a native API, any program which uses it cannot be considered\r
- * 100% pure java.\r
- */\r
-\r
-/*\r
- * AWT Native Drawing Surface (JAWT_DrawingSurface).\r
- *\r
- * For each platform, there is a native drawing surface structure.  This\r
- * platform-specific structure can be found in jawt_md.h.  It is recommended\r
- * that additional platforms follow the same model.  It is also recommended\r
- * that VMs on Win32 and Solaris support the existing structures in jawt_md.h.\r
- *\r
- *******************\r
- * EXAMPLE OF USAGE:\r
- *******************\r
- *\r
- * In Win32, a programmer wishes to access the HWND of a canvas to perform\r
- * native rendering into it.  The programmer has declared the paint() method\r
- * for their canvas subclass to be native:\r
- *\r
- *\r
- * MyCanvas.java:\r
- *\r
- * import java.awt.*;\r
- *\r
- * public class MyCanvas extends Canvas {\r
- *\r
- *     static {\r
- *         System.loadLibrary("mylib");\r
- *     }\r
- *\r
- *     public native void paint(Graphics g);\r
- * }\r
- *\r
- *\r
- * myfile.c:\r
- *\r
- * #include "jawt_md.h"\r
- * #include <assert.h>\r
- *\r
- * JNIEXPORT void JNICALL\r
- * Java_MyCanvas_paint(JNIEnv* env, jobject canvas, jobject graphics)\r
- * {\r
- *     JAWT awt;\r
- *     JAWT_DrawingSurface* ds;\r
- *     JAWT_DrawingSurfaceInfo* dsi;\r
- *     JAWT_Win32DrawingSurfaceInfo* dsi_win;\r
- *     jboolean result;\r
- *     jint lock;\r
- *\r
- *     // Get the AWT\r
- *     awt.version = JAWT_VERSION_1_3;\r
- *     result = JAWT_GetAWT(env, &awt);\r
- *     assert(result != JNI_FALSE);\r
- *\r
- *     // Get the drawing surface\r
- *     ds = awt.GetDrawingSurface(env, canvas);\r
- *     assert(ds != NULL);\r
- *\r
- *     // Lock the drawing surface\r
- *     lock = ds->Lock(ds);\r
- *     assert((lock & JAWT_LOCK_ERROR) == 0);\r
- *\r
- *     // Get the drawing surface info\r
- *     dsi = ds->GetDrawingSurfaceInfo(ds);\r
- *\r
- *     // Get the platform-specific drawing info\r
- *     dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo;\r
- *\r
- *     //////////////////////////////\r
- *     // !!! DO PAINTING HERE !!! //\r
- *     //////////////////////////////\r
- *\r
- *     // Free the drawing surface info\r
- *     ds->FreeDrawingSurfaceInfo(dsi);\r
- *\r
- *     // Unlock the drawing surface\r
- *     ds->Unlock(ds);\r
- *\r
- *     // Free the drawing surface\r
- *     awt.FreeDrawingSurface(ds);\r
- * }\r
- *\r
- */\r
-\r
-/*\r
- * JAWT_Rectangle\r
- * Structure for a native rectangle.\r
- */\r
-typedef struct jawt_Rectangle {\r
-    jint x;\r
-    jint y;\r
-    jint width;\r
-    jint height;\r
-} JAWT_Rectangle;\r
-\r
-struct jawt_DrawingSurface;\r
-\r
-/*\r
- * JAWT_DrawingSurfaceInfo\r
- * Structure for containing the underlying drawing information of a component.\r
- */\r
-typedef struct jawt_DrawingSurfaceInfo {\r
-    /*\r
-     * Pointer to the platform-specific information.  This can be safely\r
-     * cast to a JAWT_Win32DrawingSurfaceInfo on Windows or a\r
-     * JAWT_X11DrawingSurfaceInfo on Solaris.  See jawt_md.h for details.\r
-     */\r
-    void* platformInfo;\r
-    /* Cached pointer to the underlying drawing surface */\r
-    struct jawt_DrawingSurface* ds;\r
-    /* Bounding rectangle of the drawing surface */\r
-    JAWT_Rectangle bounds;\r
-    /* Number of rectangles in the clip */\r
-    jint clipSize;\r
-    /* Clip rectangle array */\r
-    JAWT_Rectangle* clip;\r
-} JAWT_DrawingSurfaceInfo;\r
-\r
-#define JAWT_LOCK_ERROR                 0x00000001\r
-#define JAWT_LOCK_CLIP_CHANGED          0x00000002\r
-#define JAWT_LOCK_BOUNDS_CHANGED        0x00000004\r
-#define JAWT_LOCK_SURFACE_CHANGED       0x00000008\r
-\r
-/*\r
- * JAWT_DrawingSurface\r
- * Structure for containing the underlying drawing information of a component.\r
- * All operations on a JAWT_DrawingSurface MUST be performed from the same\r
- * thread as the call to GetDrawingSurface.\r
- */\r
-typedef struct jawt_DrawingSurface {\r
-    /*\r
-     * Cached reference to the Java environment of the calling thread.\r
-     * If Lock(), Unlock(), GetDrawingSurfaceInfo() or\r
-     * FreeDrawingSurfaceInfo() are called from a different thread,\r
-     * this data member should be set before calling those functions.\r
-     */\r
-    JNIEnv* env;\r
-    /* Cached reference to the target object */\r
-    jobject target;\r
-    /*\r
-     * Lock the surface of the target component for native rendering.\r
-     * When finished drawing, the surface must be unlocked with\r
-     * Unlock().  This function returns a bitmask with one or more of the\r
-     * following values:\r
-     *\r
-     * JAWT_LOCK_ERROR - When an error has occurred and the surface could not\r
-     * be locked.\r
-     *\r
-     * JAWT_LOCK_CLIP_CHANGED - When the clip region has changed.\r
-     *\r
-     * JAWT_LOCK_BOUNDS_CHANGED - When the bounds of the surface have changed.\r
-     *\r
-     * JAWT_LOCK_SURFACE_CHANGED - When the surface itself has changed\r
-     */\r
-    jint (JNICALL *Lock)\r
-        (struct jawt_DrawingSurface* ds);\r
-    /*\r
-     * Get the drawing surface info.\r
-     * The value returned may be cached, but the values may change if\r
-     * additional calls to Lock() or Unlock() are made.\r
-     * Lock() must be called before this can return a valid value.\r
-     * Returns NULL if an error has occurred.\r
-     * When finished with the returned value, FreeDrawingSurfaceInfo must be\r
-     * called.\r
-     */\r
-    JAWT_DrawingSurfaceInfo* (JNICALL *GetDrawingSurfaceInfo)\r
-        (struct jawt_DrawingSurface* ds);\r
-    /*\r
-     * Free the drawing surface info.\r
-     */\r
-    void (JNICALL *FreeDrawingSurfaceInfo)\r
-        (JAWT_DrawingSurfaceInfo* dsi);\r
-    /* \r
-     * Unlock the drawing surface of the target component for native rendering.\r
-     */\r
-    void (JNICALL *Unlock)\r
-        (struct jawt_DrawingSurface* ds);\r
-} JAWT_DrawingSurface;\r
-\r
-/*\r
- * JAWT\r
- * Structure for containing native AWT functions.\r
- */\r
-typedef struct jawt {\r
-    /*\r
-     * Version of this structure.  This must always be set before\r
-     * calling JAWT_GetAWT()\r
-     */\r
-    jint version;\r
-    /*\r
-     * Return a drawing surface from a target jobject.  This value\r
-     * may be cached.\r
-     * Returns NULL if an error has occurred.\r
-     * Target must be a java.awt.Component (should be a Canvas\r
-     * or Window for native rendering).\r
-     * FreeDrawingSurface() must be called when finished with the\r
-     * returned JAWT_DrawingSurface.\r
-     */\r
-    JAWT_DrawingSurface* (JNICALL *GetDrawingSurface)\r
-        (JNIEnv* env, jobject target);\r
-    /*\r
-     * Free the drawing surface allocated in GetDrawingSurface.\r
-     */\r
-    void (JNICALL *FreeDrawingSurface)\r
-        (JAWT_DrawingSurface* ds);\r
-    /*\r
-     * Since 1.4\r
-     * Locks the entire AWT for synchronization purposes\r
-     */\r
-    void (JNICALL *Lock)(JNIEnv* env);\r
-    /*\r
-     * Since 1.4\r
-     * Unlocks the entire AWT for synchronization purposes\r
-     */\r
-    void (JNICALL *Unlock)(JNIEnv* env);\r
-    /*\r
-     * Since 1.4\r
-     * Returns a reference to a java.awt.Component from a native\r
-     * platform handle.  On Windows, this corresponds to an HWND;\r
-     * on Solaris and Linux, this is a Drawable.  For other platforms,\r
-     * see the appropriate machine-dependent header file for a description.\r
-     * The reference returned by this function is a local\r
-     * reference that is only valid in this environment.\r
-     * This function returns a NULL reference if no component could be\r
-     * found with matching platform information.\r
-     */\r
-    jobject (JNICALL *GetComponent)(JNIEnv* env, void* platformInfo);\r
-\r
-} JAWT;\r
-\r
-/*\r
- * Get the AWT native structure.  This function returns JNI_FALSE if\r
- * an error occurs.\r
- */\r
-_JNI_IMPORT_OR_EXPORT_\r
-jboolean JNICALL JAWT_GetAWT(JNIEnv* env, JAWT* awt);\r
-\r
-#define JAWT_VERSION_1_3 0x00010003\r
-#define JAWT_VERSION_1_4 0x00010004\r
-\r
-#ifdef __cplusplus\r
-} /* extern "C" */\r
-#endif\r
-\r
-#endif /* !_JAVASOFT_JAWT_H_ */\r
diff --git a/JavaOpenJPEG/java-jni/include/jdwpTransport.h b/JavaOpenJPEG/java-jni/include/jdwpTransport.h
deleted file mode 100644 (file)
index 1d78009..0000000
+++ /dev/null
@@ -1,237 +0,0 @@
-/*\r
- * @(#)jdwpTransport.h 1.7 03/12/19\r
- *\r
- * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
- * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
- */\r
-\r
-/*\r
- * Java Debug Wire Protocol Transport Service Provider Interface.\r
- */\r
-\r
-#ifndef JDWPTRANSPORT_H\r
-#define JDWPTRANSPORT_H\r
-\r
-#include "jni.h"\r
-\r
-enum {\r
-    JDWPTRANSPORT_VERSION_1_0 = 0x00010000\r
-};\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-struct jdwpTransportNativeInterface_;\r
-\r
-struct _jdwpTransportEnv;\r
-\r
-#ifdef __cplusplus\r
-typedef _jdwpTransportEnv jdwpTransportEnv;\r
-#else\r
-typedef const struct jdwpTransportNativeInterface_ *jdwpTransportEnv;\r
-#endif /* __cplusplus */\r
-\r
-/*\r
- * Errors. Universal errors with JVMTI/JVMDI equivalents keep the\r
- * values the same.\r
- */\r
-typedef enum {\r
-    JDWPTRANSPORT_ERROR_NONE = 0,\r
-    JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT = 103,\r
-    JDWPTRANSPORT_ERROR_OUT_OF_MEMORY = 110,\r
-    JDWPTRANSPORT_ERROR_INTERNAL = 113,\r
-    JDWPTRANSPORT_ERROR_ILLEGAL_STATE = 201,\r
-    JDWPTRANSPORT_ERROR_IO_ERROR = 202,\r
-    JDWPTRANSPORT_ERROR_TIMEOUT = 203,\r
-    JDWPTRANSPORT_ERROR_MSG_NOT_AVAILABLE = 204\r
-} jdwpTransportError;\r
-    \r
-\r
-/*\r
- * Structure to define capabilities\r
- */\r
-typedef struct {\r
-    unsigned int can_timeout_attach     :1;\r
-    unsigned int can_timeout_accept     :1;\r
-    unsigned int can_timeout_handshake  :1;\r
-    unsigned int reserved3              :1;\r
-    unsigned int reserved4              :1;\r
-    unsigned int reserved5              :1;\r
-    unsigned int reserved6              :1;\r
-    unsigned int reserved7              :1;\r
-    unsigned int reserved8              :1;\r
-    unsigned int reserved9              :1;\r
-    unsigned int reserved10             :1;\r
-    unsigned int reserved11             :1;\r
-    unsigned int reserved12             :1;\r
-    unsigned int reserved13             :1;\r
-    unsigned int reserved14            :1;\r
-    unsigned int reserved15            :1;\r
-} JDWPTransportCapabilities;\r
-\r
-\r
-/*\r
- * Structures to define packet layout.\r
- * \r
- * See: http://java.sun.com/j2se/1.5/docs/guide/jpda/jdwp-spec.html\r
- */\r
-\r
-enum {\r
-    JDWPTRANSPORT_FLAGS_NONE    = 0x0,\r
-    JDWPTRANSPORT_FLAGS_REPLY   = 0x80\r
-};\r
-\r
-typedef struct {\r
-    jint len; \r
-    jint id;\r
-    jbyte flags;\r
-    jbyte cmdSet;\r
-    jbyte cmd;\r
-    jbyte *data;\r
-} jdwpCmdPacket;\r
-\r
-typedef struct {\r
-    jint len;\r
-    jint id;\r
-    jbyte flags;\r
-    jshort errorCode;\r
-    jbyte *data;\r
-} jdwpReplyPacket;\r
-\r
-typedef struct {\r
-    union {\r
-        jdwpCmdPacket cmd;\r
-        jdwpReplyPacket reply;\r
-    } type;\r
-} jdwpPacket;\r
-\r
-/*\r
- * JDWP functions called by the transport.\r
- */\r
-typedef struct jdwpTransportCallback {\r
-    void *(*alloc)(jint numBytes);   /* Call this for all allocations */\r
-    void (*free)(void *buffer);      /* Call this for all deallocations */\r
-} jdwpTransportCallback;\r
-\r
-typedef jint (JNICALL *jdwpTransport_OnLoad_t)(JavaVM *jvm,\r
-                                              jdwpTransportCallback *callback,\r
-                                              jint version,\r
-                                              jdwpTransportEnv** env);\r
-\r
-\r
-\r
-/* Function Interface */\r
-\r
-struct jdwpTransportNativeInterface_ {\r
-    /*  1 :  RESERVED */\r
-    void *reserved1;\r
-\r
-    /* 2 : Get Capabilities */\r
-    jdwpTransportError (JNICALL *GetCapabilities)(jdwpTransportEnv* env,\r
-        JDWPTransportCapabilities *capabilities_ptr);\r
-\r
-    /*  3 : Attach */\r
-    jdwpTransportError (JNICALL *Attach)(jdwpTransportEnv* env,\r
-       const char* address,\r
-       jlong attach_timeout,\r
-       jlong handshake_timeout);\r
-\r
-    /*  4: StartListening */\r
-    jdwpTransportError (JNICALL *StartListening)(jdwpTransportEnv* env,\r
-       const char* address, \r
-       char** actual_address);\r
-\r
-    /*  5: StopListening */\r
-    jdwpTransportError (JNICALL *StopListening)(jdwpTransportEnv* env);\r
-\r
-    /*  6: Accept */\r
-    jdwpTransportError (JNICALL *Accept)(jdwpTransportEnv* env,\r
-       jlong accept_timeout, \r
-       jlong handshake_timeout);\r
-\r
-    /*  7: IsOpen */\r
-    jboolean (JNICALL *IsOpen)(jdwpTransportEnv* env);\r
-\r
-    /*  8: Close */\r
-    jdwpTransportError (JNICALL *Close)(jdwpTransportEnv* env);\r
-\r
-    /*  9: ReadPacket */\r
-    jdwpTransportError (JNICALL *ReadPacket)(jdwpTransportEnv* env,\r
-       jdwpPacket *pkt);\r
-\r
-    /*  10: Write Packet */\r
-    jdwpTransportError (JNICALL *WritePacket)(jdwpTransportEnv* env,\r
-       const jdwpPacket* pkt);\r
-\r
-    /*  11:  GetLastError */\r
-    jdwpTransportError (JNICALL *GetLastError)(jdwpTransportEnv* env,\r
-       char** error);\r
-\r
-};\r
-\r
-\r
-/*\r
- * Use inlined functions so that C++ code can use syntax such as\r
- *     env->Attach("mymachine:5000", 10*1000, 0);\r
- *\r
- * rather than using C's :-\r
- *\r
- *     (*env)->Attach(env, "mymachine:5000", 10*1000, 0);\r
- */\r
-struct _jdwpTransportEnv {\r
-    const struct jdwpTransportNativeInterface_ *functions;\r
-#ifdef __cplusplus\r
-\r
-    jdwpTransportError GetCapabilities(JDWPTransportCapabilities *capabilities_ptr) {\r
-       return functions->GetCapabilities(this, capabilities_ptr);\r
-    }\r
-\r
-    jdwpTransportError Attach(const char* address, jlong attach_timeout,\r
-               jlong handshake_timeout) {\r
-       return functions->Attach(this, address, attach_timeout, handshake_timeout);\r
-    }\r
-\r
-    jdwpTransportError StartListening(const char* address,\r
-               char** actual_address) {\r
-       return functions->StartListening(this, address, actual_address);\r
-    }\r
-\r
-    jdwpTransportError StopListening(void) {\r
-       return functions->StopListening(this);\r
-    }\r
-\r
-    jdwpTransportError Accept(jlong accept_timeout, jlong handshake_timeout) {\r
-       return functions->Accept(this, accept_timeout, handshake_timeout);\r
-    }\r
-\r
-    jboolean IsOpen(void) {\r
-        return functions->IsOpen(this);\r
-    }\r
-\r
-    jdwpTransportError Close(void) {\r
-        return functions->Close(this);\r
-    }\r
-\r
-    jdwpTransportError ReadPacket(jdwpPacket *pkt) {\r
-       return functions->ReadPacket(this, pkt);\r
-    }\r
-\r
-    jdwpTransportError WritePacket(const jdwpPacket* pkt) {\r
-       return functions->WritePacket(this, pkt);\r
-    }\r
-\r
-    jdwpTransportError GetLastError(char** error) {\r
-       return functions->GetLastError(this, error);\r
-    }\r
-\r
-\r
-#endif /* __cplusplus */\r
-};\r
-\r
-#ifdef __cplusplus\r
-} /* extern "C" */\r
-#endif /* __cplusplus */\r
-\r
-#endif /* JDWPTRANSPORT_H */\r
-\r
diff --git a/JavaOpenJPEG/java-jni/include/jni.h b/JavaOpenJPEG/java-jni/include/jni.h
deleted file mode 100644 (file)
index cb3baef..0000000
+++ /dev/null
@@ -1,1951 +0,0 @@
-/*\r
- * @(#)jni.h   1.56 03/12/19\r
- *\r
- * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
- * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
- */\r
-\r
-/*\r
- * We used part of Netscape's Java Runtime Interface (JRI) as the starting\r
- * point of our design and implementation.\r
- */\r
-\r
-/******************************************************************************\r
- * Java Runtime Interface\r
- * Copyright (c) 1996 Netscape Communications Corporation. All rights reserved.\r
- *****************************************************************************/\r
-\r
-#ifndef _JAVASOFT_JNI_H_\r
-#define _JAVASOFT_JNI_H_\r
-\r
-#include <stdio.h>\r
-#include <stdarg.h>\r
-\r
-/* jni_md.h contains the machine-dependent typedefs for jbyte, jint\r
-   and jlong */\r
-\r
-#include "jni_md.h"\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-/*\r
- * JNI Types\r
- */\r
-\r
-#ifndef JNI_TYPES_ALREADY_DEFINED_IN_JNI_MD_H\r
-\r
-typedef unsigned char  jboolean;\r
-typedef unsigned short jchar;\r
-typedef short          jshort;\r
-typedef float          jfloat;\r
-typedef double         jdouble;\r
-\r
-typedef jint            jsize;\r
-\r
-#ifdef __cplusplus\r
-\r
-class _jobject {};\r
-class _jclass : public _jobject {};\r
-class _jthrowable : public _jobject {};\r
-class _jstring : public _jobject {};\r
-class _jarray : public _jobject {};\r
-class _jbooleanArray : public _jarray {};\r
-class _jbyteArray : public _jarray {};\r
-class _jcharArray : public _jarray {};\r
-class _jshortArray : public _jarray {};\r
-class _jintArray : public _jarray {};\r
-class _jlongArray : public _jarray {};\r
-class _jfloatArray : public _jarray {};\r
-class _jdoubleArray : public _jarray {};\r
-class _jobjectArray : public _jarray {};\r
-\r
-typedef _jobject *jobject;\r
-typedef _jclass *jclass;\r
-typedef _jthrowable *jthrowable;\r
-typedef _jstring *jstring;\r
-typedef _jarray *jarray;\r
-typedef _jbooleanArray *jbooleanArray;\r
-typedef _jbyteArray *jbyteArray;\r
-typedef _jcharArray *jcharArray;\r
-typedef _jshortArray *jshortArray;\r
-typedef _jintArray *jintArray;\r
-typedef _jlongArray *jlongArray;\r
-typedef _jfloatArray *jfloatArray;\r
-typedef _jdoubleArray *jdoubleArray;\r
-typedef _jobjectArray *jobjectArray;\r
-\r
-#else\r
-\r
-struct _jobject;\r
-\r
-typedef struct _jobject *jobject;\r
-typedef jobject jclass;\r
-typedef jobject jthrowable;\r
-typedef jobject jstring;\r
-typedef jobject jarray;\r
-typedef jarray jbooleanArray;\r
-typedef jarray jbyteArray;\r
-typedef jarray jcharArray;\r
-typedef jarray jshortArray;\r
-typedef jarray jintArray;\r
-typedef jarray jlongArray;\r
-typedef jarray jfloatArray;\r
-typedef jarray jdoubleArray;\r
-typedef jarray jobjectArray;\r
-\r
-#endif\r
-\r
-typedef jobject jweak;\r
-\r
-typedef union jvalue {\r
-    jboolean z;\r
-    jbyte    b;\r
-    jchar    c;\r
-    jshort   s;\r
-    jint     i;\r
-    jlong    j;\r
-    jfloat   f;\r
-    jdouble  d;\r
-    jobject  l;\r
-} jvalue;\r
-\r
-struct _jfieldID;\r
-typedef struct _jfieldID *jfieldID;\r
-\r
-struct _jmethodID;\r
-typedef struct _jmethodID *jmethodID;\r
-\r
-#endif /* JNI_TYPES_ALREADY_DEFINED_IN_JNI_MD_H */\r
-\r
-/*\r
- * jboolean constants\r
- */\r
-\r
-#define JNI_FALSE 0\r
-#define JNI_TRUE 1\r
-\r
-/*\r
- * possible return values for JNI functions.\r
- */\r
-\r
-#define JNI_OK           0                 /* success */\r
-#define JNI_ERR          (-1)              /* unknown error */\r
-#define JNI_EDETACHED    (-2)              /* thread detached from the VM */\r
-#define JNI_EVERSION     (-3)              /* JNI version error */\r
-#define JNI_ENOMEM       (-4)              /* not enough memory */\r
-#define JNI_EEXIST       (-5)              /* VM already created */\r
-#define JNI_EINVAL       (-6)              /* invalid arguments */\r
-\r
-/*\r
- * used in ReleaseScalarArrayElements\r
- */\r
-\r
-#define JNI_COMMIT 1\r
-#define JNI_ABORT 2\r
-\r
-/*\r
- * used in RegisterNatives to describe native method name, signature,\r
- * and function pointer.\r
- */\r
-\r
-typedef struct {\r
-    char *name;\r
-    char *signature;\r
-    void *fnPtr;\r
-} JNINativeMethod;\r
-\r
-/*\r
- * JNI Native Method Interface.\r
- */\r
-\r
-struct JNINativeInterface_;\r
-\r
-struct JNIEnv_;\r
-\r
-#ifdef __cplusplus\r
-typedef JNIEnv_ JNIEnv;\r
-#else\r
-typedef const struct JNINativeInterface_ *JNIEnv;\r
-#endif\r
-\r
-/*\r
- * JNI Invocation Interface.\r
- */\r
-\r
-struct JNIInvokeInterface_;\r
-\r
-struct JavaVM_;\r
-\r
-#ifdef __cplusplus\r
-typedef JavaVM_ JavaVM;\r
-#else\r
-typedef const struct JNIInvokeInterface_ *JavaVM;\r
-#endif\r
-\r
-struct JNINativeInterface_ {\r
-    void *reserved0;\r
-    void *reserved1;\r
-    void *reserved2;\r
-\r
-    void *reserved3;\r
-    jint (JNICALL *GetVersion)(JNIEnv *env);\r
-\r
-    jclass (JNICALL *DefineClass)\r
-      (JNIEnv *env, const char *name, jobject loader, const jbyte *buf,\r
-       jsize len);\r
-    jclass (JNICALL *FindClass)\r
-      (JNIEnv *env, const char *name);\r
-\r
-    jmethodID (JNICALL *FromReflectedMethod)\r
-      (JNIEnv *env, jobject method);\r
-    jfieldID (JNICALL *FromReflectedField)\r
-      (JNIEnv *env, jobject field);\r
-\r
-    jobject (JNICALL *ToReflectedMethod)\r
-      (JNIEnv *env, jclass cls, jmethodID methodID, jboolean isStatic);\r
-\r
-    jclass (JNICALL *GetSuperclass)\r
-      (JNIEnv *env, jclass sub);\r
-    jboolean (JNICALL *IsAssignableFrom)\r
-      (JNIEnv *env, jclass sub, jclass sup);\r
-\r
-    jobject (JNICALL *ToReflectedField)\r
-      (JNIEnv *env, jclass cls, jfieldID fieldID, jboolean isStatic);\r
-\r
-    jint (JNICALL *Throw)\r
-      (JNIEnv *env, jthrowable obj);\r
-    jint (JNICALL *ThrowNew)\r
-      (JNIEnv *env, jclass clazz, const char *msg);\r
-    jthrowable (JNICALL *ExceptionOccurred)\r
-      (JNIEnv *env);\r
-    void (JNICALL *ExceptionDescribe)\r
-      (JNIEnv *env);\r
-    void (JNICALL *ExceptionClear)\r
-      (JNIEnv *env);\r
-    void (JNICALL *FatalError)\r
-      (JNIEnv *env, const char *msg);\r
-\r
-    jint (JNICALL *PushLocalFrame)\r
-      (JNIEnv *env, jint capacity);\r
-    jobject (JNICALL *PopLocalFrame)\r
-      (JNIEnv *env, jobject result);\r
-\r
-    jobject (JNICALL *NewGlobalRef)\r
-      (JNIEnv *env, jobject lobj);\r
-    void (JNICALL *DeleteGlobalRef)\r
-      (JNIEnv *env, jobject gref);\r
-    void (JNICALL *DeleteLocalRef)\r
-      (JNIEnv *env, jobject obj);\r
-    jboolean (JNICALL *IsSameObject)\r
-      (JNIEnv *env, jobject obj1, jobject obj2);\r
-    jobject (JNICALL *NewLocalRef)\r
-      (JNIEnv *env, jobject ref);\r
-    jint (JNICALL *EnsureLocalCapacity)\r
-      (JNIEnv *env, jint capacity);\r
-\r
-    jobject (JNICALL *AllocObject)\r
-      (JNIEnv *env, jclass clazz);\r
-    jobject (JNICALL *NewObject)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
-    jobject (JNICALL *NewObjectV)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
-    jobject (JNICALL *NewObjectA)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
-\r
-    jclass (JNICALL *GetObjectClass)\r
-      (JNIEnv *env, jobject obj);\r
-    jboolean (JNICALL *IsInstanceOf)\r
-      (JNIEnv *env, jobject obj, jclass clazz);\r
-\r
-    jmethodID (JNICALL *GetMethodID)\r
-      (JNIEnv *env, jclass clazz, const char *name, const char *sig);\r
-\r
-    jobject (JNICALL *CallObjectMethod)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
-    jobject (JNICALL *CallObjectMethodV)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
-    jobject (JNICALL *CallObjectMethodA)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);\r
-\r
-    jboolean (JNICALL *CallBooleanMethod)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
-    jboolean (JNICALL *CallBooleanMethodV)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
-    jboolean (JNICALL *CallBooleanMethodA)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);\r
-\r
-    jbyte (JNICALL *CallByteMethod)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
-    jbyte (JNICALL *CallByteMethodV)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
-    jbyte (JNICALL *CallByteMethodA)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
-\r
-    jchar (JNICALL *CallCharMethod)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
-    jchar (JNICALL *CallCharMethodV)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
-    jchar (JNICALL *CallCharMethodA)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
-\r
-    jshort (JNICALL *CallShortMethod)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
-    jshort (JNICALL *CallShortMethodV)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
-    jshort (JNICALL *CallShortMethodA)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
-\r
-    jint (JNICALL *CallIntMethod)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
-    jint (JNICALL *CallIntMethodV)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
-    jint (JNICALL *CallIntMethodA)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
-\r
-    jlong (JNICALL *CallLongMethod)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
-    jlong (JNICALL *CallLongMethodV)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
-    jlong (JNICALL *CallLongMethodA)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
-\r
-    jfloat (JNICALL *CallFloatMethod)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
-    jfloat (JNICALL *CallFloatMethodV)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
-    jfloat (JNICALL *CallFloatMethodA)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
-\r
-    jdouble (JNICALL *CallDoubleMethod)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
-    jdouble (JNICALL *CallDoubleMethodV)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
-    jdouble (JNICALL *CallDoubleMethodA)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
-\r
-    void (JNICALL *CallVoidMethod)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
-    void (JNICALL *CallVoidMethodV)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
-    void (JNICALL *CallVoidMethodA)\r
-      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);\r
-\r
-    jobject (JNICALL *CallNonvirtualObjectMethod)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
-    jobject (JNICALL *CallNonvirtualObjectMethodV)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       va_list args);\r
-    jobject (JNICALL *CallNonvirtualObjectMethodA)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       const jvalue * args);\r
-\r
-    jboolean (JNICALL *CallNonvirtualBooleanMethod)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
-    jboolean (JNICALL *CallNonvirtualBooleanMethodV)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       va_list args);\r
-    jboolean (JNICALL *CallNonvirtualBooleanMethodA)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       const jvalue * args);\r
-\r
-    jbyte (JNICALL *CallNonvirtualByteMethod)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
-    jbyte (JNICALL *CallNonvirtualByteMethodV)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       va_list args);\r
-    jbyte (JNICALL *CallNonvirtualByteMethodA)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       const jvalue *args);\r
-\r
-    jchar (JNICALL *CallNonvirtualCharMethod)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
-    jchar (JNICALL *CallNonvirtualCharMethodV)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       va_list args);\r
-    jchar (JNICALL *CallNonvirtualCharMethodA)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       const jvalue *args);\r
-\r
-    jshort (JNICALL *CallNonvirtualShortMethod)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
-    jshort (JNICALL *CallNonvirtualShortMethodV)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       va_list args);\r
-    jshort (JNICALL *CallNonvirtualShortMethodA)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       const jvalue *args);\r
-\r
-    jint (JNICALL *CallNonvirtualIntMethod)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
-    jint (JNICALL *CallNonvirtualIntMethodV)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       va_list args);\r
-    jint (JNICALL *CallNonvirtualIntMethodA)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       const jvalue *args);\r
-\r
-    jlong (JNICALL *CallNonvirtualLongMethod)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
-    jlong (JNICALL *CallNonvirtualLongMethodV)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       va_list args);\r
-    jlong (JNICALL *CallNonvirtualLongMethodA)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       const jvalue *args);\r
-\r
-    jfloat (JNICALL *CallNonvirtualFloatMethod)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
-    jfloat (JNICALL *CallNonvirtualFloatMethodV)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       va_list args);\r
-    jfloat (JNICALL *CallNonvirtualFloatMethodA)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       const jvalue *args);\r
-\r
-    jdouble (JNICALL *CallNonvirtualDoubleMethod)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
-    jdouble (JNICALL *CallNonvirtualDoubleMethodV)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       va_list args);\r
-    jdouble (JNICALL *CallNonvirtualDoubleMethodA)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       const jvalue *args);\r
-\r
-    void (JNICALL *CallNonvirtualVoidMethod)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
-    void (JNICALL *CallNonvirtualVoidMethodV)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       va_list args);\r
-    void (JNICALL *CallNonvirtualVoidMethodA)\r
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
-       const jvalue * args);\r
-\r
-    jfieldID (JNICALL *GetFieldID)\r
-      (JNIEnv *env, jclass clazz, const char *name, const char *sig);\r
-\r
-    jobject (JNICALL *GetObjectField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
-    jboolean (JNICALL *GetBooleanField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
-    jbyte (JNICALL *GetByteField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
-    jchar (JNICALL *GetCharField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
-    jshort (JNICALL *GetShortField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
-    jint (JNICALL *GetIntField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
-    jlong (JNICALL *GetLongField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
-    jfloat (JNICALL *GetFloatField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
-    jdouble (JNICALL *GetDoubleField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
-\r
-    void (JNICALL *SetObjectField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jobject val);\r
-    void (JNICALL *SetBooleanField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jboolean val);\r
-    void (JNICALL *SetByteField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jbyte val);\r
-    void (JNICALL *SetCharField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jchar val);\r
-    void (JNICALL *SetShortField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jshort val);\r
-    void (JNICALL *SetIntField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jint val);\r
-    void (JNICALL *SetLongField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jlong val);\r
-    void (JNICALL *SetFloatField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jfloat val);\r
-    void (JNICALL *SetDoubleField)\r
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jdouble val);\r
-\r
-    jmethodID (JNICALL *GetStaticMethodID)\r
-      (JNIEnv *env, jclass clazz, const char *name, const char *sig);\r
-\r
-    jobject (JNICALL *CallStaticObjectMethod)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
-    jobject (JNICALL *CallStaticObjectMethodV)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
-    jobject (JNICALL *CallStaticObjectMethodA)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
-\r
-    jboolean (JNICALL *CallStaticBooleanMethod)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
-    jboolean (JNICALL *CallStaticBooleanMethodV)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
-    jboolean (JNICALL *CallStaticBooleanMethodA)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
-\r
-    jbyte (JNICALL *CallStaticByteMethod)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
-    jbyte (JNICALL *CallStaticByteMethodV)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
-    jbyte (JNICALL *CallStaticByteMethodA)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
-\r
-    jchar (JNICALL *CallStaticCharMethod)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
-    jchar (JNICALL *CallStaticCharMethodV)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
-    jchar (JNICALL *CallStaticCharMethodA)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
-\r
-    jshort (JNICALL *CallStaticShortMethod)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
-    jshort (JNICALL *CallStaticShortMethodV)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
-    jshort (JNICALL *CallStaticShortMethodA)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
-\r
-    jint (JNICALL *CallStaticIntMethod)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
-    jint (JNICALL *CallStaticIntMethodV)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
-    jint (JNICALL *CallStaticIntMethodA)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
-\r
-    jlong (JNICALL *CallStaticLongMethod)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
-    jlong (JNICALL *CallStaticLongMethodV)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
-    jlong (JNICALL *CallStaticLongMethodA)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
-\r
-    jfloat (JNICALL *CallStaticFloatMethod)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
-    jfloat (JNICALL *CallStaticFloatMethodV)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
-    jfloat (JNICALL *CallStaticFloatMethodA)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
-\r
-    jdouble (JNICALL *CallStaticDoubleMethod)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
-    jdouble (JNICALL *CallStaticDoubleMethodV)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
-    jdouble (JNICALL *CallStaticDoubleMethodA)\r
-      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
-\r
-    void (JNICALL *CallStaticVoidMethod)\r
-      (JNIEnv *env, jclass cls, jmethodID methodID, ...);\r
-    void (JNICALL *CallStaticVoidMethodV)\r
-      (JNIEnv *env, jclass cls, jmethodID methodID, va_list args);\r
-    void (JNICALL *CallStaticVoidMethodA)\r
-      (JNIEnv *env, jclass cls, jmethodID methodID, const jvalue * args);\r
-\r
-    jfieldID (JNICALL *GetStaticFieldID)\r
-      (JNIEnv *env, jclass clazz, const char *name, const char *sig);\r
-    jobject (JNICALL *GetStaticObjectField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
-    jboolean (JNICALL *GetStaticBooleanField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
-    jbyte (JNICALL *GetStaticByteField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
-    jchar (JNICALL *GetStaticCharField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
-    jshort (JNICALL *GetStaticShortField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
-    jint (JNICALL *GetStaticIntField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
-    jlong (JNICALL *GetStaticLongField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
-    jfloat (JNICALL *GetStaticFloatField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
-    jdouble (JNICALL *GetStaticDoubleField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
-\r
-    void (JNICALL *SetStaticObjectField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jobject value);\r
-    void (JNICALL *SetStaticBooleanField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jboolean value);\r
-    void (JNICALL *SetStaticByteField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jbyte value);\r
-    void (JNICALL *SetStaticCharField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jchar value);\r
-    void (JNICALL *SetStaticShortField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jshort value);\r
-    void (JNICALL *SetStaticIntField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jint value);\r
-    void (JNICALL *SetStaticLongField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jlong value);\r
-    void (JNICALL *SetStaticFloatField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jfloat value);\r
-    void (JNICALL *SetStaticDoubleField)\r
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jdouble value);\r
-\r
-    jstring (JNICALL *NewString)\r
-      (JNIEnv *env, const jchar *unicode, jsize len);\r
-    jsize (JNICALL *GetStringLength)\r
-      (JNIEnv *env, jstring str);\r
-    const jchar *(JNICALL *GetStringChars)\r
-      (JNIEnv *env, jstring str, jboolean *isCopy);\r
-    void (JNICALL *ReleaseStringChars)\r
-      (JNIEnv *env, jstring str, const jchar *chars);\r
-\r
-    jstring (JNICALL *NewStringUTF)\r
-      (JNIEnv *env, const char *utf);\r
-    jsize (JNICALL *GetStringUTFLength)\r
-      (JNIEnv *env, jstring str);\r
-    const char* (JNICALL *GetStringUTFChars)\r
-      (JNIEnv *env, jstring str, jboolean *isCopy);\r
-    void (JNICALL *ReleaseStringUTFChars)\r
-      (JNIEnv *env, jstring str, const char* chars);\r
-\r
-\r
-    jsize (JNICALL *GetArrayLength)\r
-      (JNIEnv *env, jarray array);\r
-\r
-    jobjectArray (JNICALL *NewObjectArray)\r
-      (JNIEnv *env, jsize len, jclass clazz, jobject init);\r
-    jobject (JNICALL *GetObjectArrayElement)\r
-      (JNIEnv *env, jobjectArray array, jsize index);\r
-    void (JNICALL *SetObjectArrayElement)\r
-      (JNIEnv *env, jobjectArray array, jsize index, jobject val);\r
-\r
-    jbooleanArray (JNICALL *NewBooleanArray)\r
-      (JNIEnv *env, jsize len);\r
-    jbyteArray (JNICALL *NewByteArray)\r
-      (JNIEnv *env, jsize len);\r
-    jcharArray (JNICALL *NewCharArray)\r
-      (JNIEnv *env, jsize len);\r
-    jshortArray (JNICALL *NewShortArray)\r
-      (JNIEnv *env, jsize len);\r
-    jintArray (JNICALL *NewIntArray)\r
-      (JNIEnv *env, jsize len);\r
-    jlongArray (JNICALL *NewLongArray)\r
-      (JNIEnv *env, jsize len);\r
-    jfloatArray (JNICALL *NewFloatArray)\r
-      (JNIEnv *env, jsize len);\r
-    jdoubleArray (JNICALL *NewDoubleArray)\r
-      (JNIEnv *env, jsize len);\r
-\r
-    jboolean * (JNICALL *GetBooleanArrayElements)\r
-      (JNIEnv *env, jbooleanArray array, jboolean *isCopy);\r
-    jbyte * (JNICALL *GetByteArrayElements)\r
-      (JNIEnv *env, jbyteArray array, jboolean *isCopy);\r
-    jchar * (JNICALL *GetCharArrayElements)\r
-      (JNIEnv *env, jcharArray array, jboolean *isCopy);\r
-    jshort * (JNICALL *GetShortArrayElements)\r
-      (JNIEnv *env, jshortArray array, jboolean *isCopy);\r
-    jint * (JNICALL *GetIntArrayElements)\r
-      (JNIEnv *env, jintArray array, jboolean *isCopy);\r
-    jlong * (JNICALL *GetLongArrayElements)\r
-      (JNIEnv *env, jlongArray array, jboolean *isCopy);\r
-    jfloat * (JNICALL *GetFloatArrayElements)\r
-      (JNIEnv *env, jfloatArray array, jboolean *isCopy);\r
-    jdouble * (JNICALL *GetDoubleArrayElements)\r
-      (JNIEnv *env, jdoubleArray array, jboolean *isCopy);\r
-\r
-    void (JNICALL *ReleaseBooleanArrayElements)\r
-      (JNIEnv *env, jbooleanArray array, jboolean *elems, jint mode);\r
-    void (JNICALL *ReleaseByteArrayElements)\r
-      (JNIEnv *env, jbyteArray array, jbyte *elems, jint mode);\r
-    void (JNICALL *ReleaseCharArrayElements)\r
-      (JNIEnv *env, jcharArray array, jchar *elems, jint mode);\r
-    void (JNICALL *ReleaseShortArrayElements)\r
-      (JNIEnv *env, jshortArray array, jshort *elems, jint mode);\r
-    void (JNICALL *ReleaseIntArrayElements)\r
-      (JNIEnv *env, jintArray array, jint *elems, jint mode);\r
-    void (JNICALL *ReleaseLongArrayElements)\r
-      (JNIEnv *env, jlongArray array, jlong *elems, jint mode);\r
-    void (JNICALL *ReleaseFloatArrayElements)\r
-      (JNIEnv *env, jfloatArray array, jfloat *elems, jint mode);\r
-    void (JNICALL *ReleaseDoubleArrayElements)\r
-      (JNIEnv *env, jdoubleArray array, jdouble *elems, jint mode);\r
-\r
-    void (JNICALL *GetBooleanArrayRegion)\r
-      (JNIEnv *env, jbooleanArray array, jsize start, jsize l, jboolean *buf);\r
-    void (JNICALL *GetByteArrayRegion)\r
-      (JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);\r
-    void (JNICALL *GetCharArrayRegion)\r
-      (JNIEnv *env, jcharArray array, jsize start, jsize len, jchar *buf);\r
-    void (JNICALL *GetShortArrayRegion)\r
-      (JNIEnv *env, jshortArray array, jsize start, jsize len, jshort *buf);\r
-    void (JNICALL *GetIntArrayRegion)\r
-      (JNIEnv *env, jintArray array, jsize start, jsize len, jint *buf);\r
-    void (JNICALL *GetLongArrayRegion)\r
-      (JNIEnv *env, jlongArray array, jsize start, jsize len, jlong *buf);\r
-    void (JNICALL *GetFloatArrayRegion)\r
-      (JNIEnv *env, jfloatArray array, jsize start, jsize len, jfloat *buf);\r
-    void (JNICALL *GetDoubleArrayRegion)\r
-      (JNIEnv *env, jdoubleArray array, jsize start, jsize len, jdouble *buf);\r
-\r
-    void (JNICALL *SetBooleanArrayRegion)\r
-      (JNIEnv *env, jbooleanArray array, jsize start, jsize l, const jboolean *buf);\r
-    void (JNICALL *SetByteArrayRegion)\r
-      (JNIEnv *env, jbyteArray array, jsize start, jsize len, const jbyte *buf);\r
-    void (JNICALL *SetCharArrayRegion)\r
-      (JNIEnv *env, jcharArray array, jsize start, jsize len, const jchar *buf);\r
-    void (JNICALL *SetShortArrayRegion)\r
-      (JNIEnv *env, jshortArray array, jsize start, jsize len, const jshort *buf);\r
-    void (JNICALL *SetIntArrayRegion)\r
-      (JNIEnv *env, jintArray array, jsize start, jsize len, const jint *buf);\r
-    void (JNICALL *SetLongArrayRegion)\r
-      (JNIEnv *env, jlongArray array, jsize start, jsize len, const jlong *buf);\r
-    void (JNICALL *SetFloatArrayRegion)\r
-      (JNIEnv *env, jfloatArray array, jsize start, jsize len, const jfloat *buf);\r
-    void (JNICALL *SetDoubleArrayRegion)\r
-      (JNIEnv *env, jdoubleArray array, jsize start, jsize len, const jdouble *buf);\r
-\r
-    jint (JNICALL *RegisterNatives)\r
-      (JNIEnv *env, jclass clazz, const JNINativeMethod *methods,\r
-       jint nMethods);\r
-    jint (JNICALL *UnregisterNatives)\r
-      (JNIEnv *env, jclass clazz);\r
-\r
-    jint (JNICALL *MonitorEnter)\r
-      (JNIEnv *env, jobject obj);\r
-    jint (JNICALL *MonitorExit)\r
-      (JNIEnv *env, jobject obj);\r
-\r
-    jint (JNICALL *GetJavaVM)\r
-      (JNIEnv *env, JavaVM **vm);\r
-\r
-    void (JNICALL *GetStringRegion)\r
-      (JNIEnv *env, jstring str, jsize start, jsize len, jchar *buf);\r
-    void (JNICALL *GetStringUTFRegion)\r
-      (JNIEnv *env, jstring str, jsize start, jsize len, char *buf);\r
-\r
-    void * (JNICALL *GetPrimitiveArrayCritical)\r
-      (JNIEnv *env, jarray array, jboolean *isCopy);\r
-    void (JNICALL *ReleasePrimitiveArrayCritical)\r
-      (JNIEnv *env, jarray array, void *carray, jint mode);\r
-\r
-    const jchar * (JNICALL *GetStringCritical)\r
-      (JNIEnv *env, jstring string, jboolean *isCopy);\r
-    void (JNICALL *ReleaseStringCritical)\r
-      (JNIEnv *env, jstring string, const jchar *cstring);\r
-\r
-    jweak (JNICALL *NewWeakGlobalRef)\r
-       (JNIEnv *env, jobject obj);\r
-    void (JNICALL *DeleteWeakGlobalRef)\r
-       (JNIEnv *env, jweak ref);\r
-\r
-    jboolean (JNICALL *ExceptionCheck)\r
-       (JNIEnv *env);\r
-\r
-    jobject (JNICALL *NewDirectByteBuffer)\r
-       (JNIEnv* env, void* address, jlong capacity);\r
-    void* (JNICALL *GetDirectBufferAddress)\r
-       (JNIEnv* env, jobject buf);\r
-    jlong (JNICALL *GetDirectBufferCapacity)\r
-       (JNIEnv* env, jobject buf);\r
-};\r
-\r
-/*\r
- * We use inlined functions for C++ so that programmers can write:\r
- *\r
- *    env->FindClass("java/lang/String")\r
- *\r
- * in C++ rather than:\r
- *\r
- *    (*env)->FindClass(env, "java/lang/String")\r
- *\r
- * in C.\r
- */\r
-\r
-struct JNIEnv_ {\r
-    const struct JNINativeInterface_ *functions;\r
-#ifdef __cplusplus\r
-\r
-    jint GetVersion() {\r
-        return functions->GetVersion(this);\r
-    }\r
-    jclass DefineClass(const char *name, jobject loader, const jbyte *buf,\r
-                      jsize len) {\r
-        return functions->DefineClass(this, name, loader, buf, len);\r
-    }\r
-    jclass FindClass(const char *name) {\r
-        return functions->FindClass(this, name);\r
-    }\r
-    jmethodID FromReflectedMethod(jobject method) {\r
-        return functions->FromReflectedMethod(this,method);\r
-    }\r
-    jfieldID FromReflectedField(jobject field) {\r
-        return functions->FromReflectedField(this,field);\r
-    }\r
-\r
-    jobject ToReflectedMethod(jclass cls, jmethodID methodID, jboolean isStatic) {\r
-        return functions->ToReflectedMethod(this, cls, methodID, isStatic);\r
-    }\r
-\r
-    jclass GetSuperclass(jclass sub) {\r
-        return functions->GetSuperclass(this, sub);\r
-    }\r
-    jboolean IsAssignableFrom(jclass sub, jclass sup) {\r
-        return functions->IsAssignableFrom(this, sub, sup);\r
-    }\r
-\r
-    jobject ToReflectedField(jclass cls, jfieldID fieldID, jboolean isStatic) {\r
-        return functions->ToReflectedField(this,cls,fieldID,isStatic);\r
-    }\r
-\r
-    jint Throw(jthrowable obj) {\r
-        return functions->Throw(this, obj);\r
-    }\r
-    jint ThrowNew(jclass clazz, const char *msg) {\r
-        return functions->ThrowNew(this, clazz, msg);\r
-    }\r
-    jthrowable ExceptionOccurred() {\r
-        return functions->ExceptionOccurred(this);\r
-    }\r
-    void ExceptionDescribe() {\r
-        functions->ExceptionDescribe(this);\r
-    }\r
-    void ExceptionClear() {\r
-        functions->ExceptionClear(this);\r
-    }\r
-    void FatalError(const char *msg) {\r
-        functions->FatalError(this, msg);\r
-    }\r
-\r
-    jint PushLocalFrame(jint capacity) {\r
-        return functions->PushLocalFrame(this,capacity);\r
-    }\r
-    jobject PopLocalFrame(jobject result) {\r
-        return functions->PopLocalFrame(this,result);\r
-    }\r
-\r
-    jobject NewGlobalRef(jobject lobj) {\r
-        return functions->NewGlobalRef(this,lobj);\r
-    }\r
-    void DeleteGlobalRef(jobject gref) {\r
-        functions->DeleteGlobalRef(this,gref);\r
-    }\r
-    void DeleteLocalRef(jobject obj) {\r
-        functions->DeleteLocalRef(this, obj);\r
-    }\r
-\r
-    jboolean IsSameObject(jobject obj1, jobject obj2) {\r
-        return functions->IsSameObject(this,obj1,obj2);\r
-    }\r
-\r
-    jobject NewLocalRef(jobject ref) {\r
-        return functions->NewLocalRef(this,ref);\r
-    }\r
-    jint EnsureLocalCapacity(jint capacity) {\r
-        return functions->EnsureLocalCapacity(this,capacity);\r
-    }\r
-\r
-    jobject AllocObject(jclass clazz) {\r
-        return functions->AllocObject(this,clazz);\r
-    }\r
-    jobject NewObject(jclass clazz, jmethodID methodID, ...) {\r
-        va_list args;\r
-       jobject result;\r
-       va_start(args, methodID);\r
-        result = functions->NewObjectV(this,clazz,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jobject NewObjectV(jclass clazz, jmethodID methodID,\r
-                      va_list args) {\r
-        return functions->NewObjectV(this,clazz,methodID,args);\r
-    }\r
-    jobject NewObjectA(jclass clazz, jmethodID methodID,\r
-                      const jvalue *args) {\r
-        return functions->NewObjectA(this,clazz,methodID,args);\r
-    }\r
-\r
-    jclass GetObjectClass(jobject obj) {\r
-        return functions->GetObjectClass(this,obj);\r
-    }\r
-    jboolean IsInstanceOf(jobject obj, jclass clazz) {\r
-        return functions->IsInstanceOf(this,obj,clazz);\r
-    }\r
-\r
-    jmethodID GetMethodID(jclass clazz, const char *name,\r
-                         const char *sig) {\r
-        return functions->GetMethodID(this,clazz,name,sig);\r
-    }\r
-\r
-    jobject CallObjectMethod(jobject obj, jmethodID methodID, ...) {\r
-        va_list args;\r
-       jobject result;\r
-       va_start(args,methodID);\r
-       result = functions->CallObjectMethodV(this,obj,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jobject CallObjectMethodV(jobject obj, jmethodID methodID,\r
-                       va_list args) {\r
-        return functions->CallObjectMethodV(this,obj,methodID,args);\r
-    }\r
-    jobject CallObjectMethodA(jobject obj, jmethodID methodID,\r
-                       const jvalue * args) {\r
-        return functions->CallObjectMethodA(this,obj,methodID,args);\r
-    }\r
-\r
-    jboolean CallBooleanMethod(jobject obj,\r
-                              jmethodID methodID, ...) {\r
-        va_list args;\r
-       jboolean result;\r
-       va_start(args,methodID);\r
-       result = functions->CallBooleanMethodV(this,obj,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jboolean CallBooleanMethodV(jobject obj, jmethodID methodID,\r
-                               va_list args) {\r
-        return functions->CallBooleanMethodV(this,obj,methodID,args);\r
-    }\r
-    jboolean CallBooleanMethodA(jobject obj, jmethodID methodID,\r
-                               const jvalue * args) {\r
-        return functions->CallBooleanMethodA(this,obj,methodID, args);\r
-    }\r
-\r
-    jbyte CallByteMethod(jobject obj, jmethodID methodID, ...) {\r
-        va_list args;\r
-       jbyte result;\r
-       va_start(args,methodID);\r
-       result = functions->CallByteMethodV(this,obj,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jbyte CallByteMethodV(jobject obj, jmethodID methodID,\r
-                         va_list args) {\r
-        return functions->CallByteMethodV(this,obj,methodID,args);\r
-    }\r
-    jbyte CallByteMethodA(jobject obj, jmethodID methodID,\r
-                         const jvalue * args) {\r
-        return functions->CallByteMethodA(this,obj,methodID,args);\r
-    }\r
-\r
-    jchar CallCharMethod(jobject obj, jmethodID methodID, ...) {\r
-        va_list args;\r
-       jchar result;\r
-       va_start(args,methodID);\r
-       result = functions->CallCharMethodV(this,obj,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jchar CallCharMethodV(jobject obj, jmethodID methodID,\r
-                         va_list args) {\r
-        return functions->CallCharMethodV(this,obj,methodID,args);\r
-    }\r
-    jchar CallCharMethodA(jobject obj, jmethodID methodID,\r
-                         const jvalue * args) {\r
-        return functions->CallCharMethodA(this,obj,methodID,args);\r
-    }\r
-\r
-    jshort CallShortMethod(jobject obj, jmethodID methodID, ...) {\r
-        va_list args;\r
-       jshort result;\r
-       va_start(args,methodID);\r
-       result = functions->CallShortMethodV(this,obj,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jshort CallShortMethodV(jobject obj, jmethodID methodID,\r
-                           va_list args) {\r
-        return functions->CallShortMethodV(this,obj,methodID,args);\r
-    }\r
-    jshort CallShortMethodA(jobject obj, jmethodID methodID,\r
-                           const jvalue * args) {\r
-        return functions->CallShortMethodA(this,obj,methodID,args);\r
-    }\r
-\r
-    jint CallIntMethod(jobject obj, jmethodID methodID, ...) {\r
-        va_list args;\r
-       jint result;\r
-       va_start(args,methodID);\r
-       result = functions->CallIntMethodV(this,obj,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jint CallIntMethodV(jobject obj, jmethodID methodID,\r
-                       va_list args) {\r
-        return functions->CallIntMethodV(this,obj,methodID,args);\r
-    }\r
-    jint CallIntMethodA(jobject obj, jmethodID methodID,\r
-                       const jvalue * args) {\r
-        return functions->CallIntMethodA(this,obj,methodID,args);\r
-    }\r
-\r
-    jlong CallLongMethod(jobject obj, jmethodID methodID, ...) {\r
-        va_list args;\r
-       jlong result;\r
-       va_start(args,methodID);\r
-       result = functions->CallLongMethodV(this,obj,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jlong CallLongMethodV(jobject obj, jmethodID methodID,\r
-                         va_list args) {\r
-        return functions->CallLongMethodV(this,obj,methodID,args);\r
-    }\r
-    jlong CallLongMethodA(jobject obj, jmethodID methodID,\r
-                         const jvalue * args) {\r
-        return functions->CallLongMethodA(this,obj,methodID,args);\r
-    }\r
-\r
-    jfloat CallFloatMethod(jobject obj, jmethodID methodID, ...) {\r
-        va_list args;\r
-       jfloat result;\r
-       va_start(args,methodID);\r
-       result = functions->CallFloatMethodV(this,obj,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jfloat CallFloatMethodV(jobject obj, jmethodID methodID,\r
-                           va_list args) {\r
-        return functions->CallFloatMethodV(this,obj,methodID,args);\r
-    }\r
-    jfloat CallFloatMethodA(jobject obj, jmethodID methodID,\r
-                           const jvalue * args) {\r
-        return functions->CallFloatMethodA(this,obj,methodID,args);\r
-    }\r
-\r
-    jdouble CallDoubleMethod(jobject obj, jmethodID methodID, ...) {\r
-        va_list args;\r
-       jdouble result;\r
-       va_start(args,methodID);\r
-       result = functions->CallDoubleMethodV(this,obj,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jdouble CallDoubleMethodV(jobject obj, jmethodID methodID,\r
-                       va_list args) {\r
-        return functions->CallDoubleMethodV(this,obj,methodID,args);\r
-    }\r
-    jdouble CallDoubleMethodA(jobject obj, jmethodID methodID,\r
-                       const jvalue * args) {\r
-        return functions->CallDoubleMethodA(this,obj,methodID,args);\r
-    }\r
-\r
-    void CallVoidMethod(jobject obj, jmethodID methodID, ...) {\r
-        va_list args;\r
-       va_start(args,methodID);\r
-       functions->CallVoidMethodV(this,obj,methodID,args);\r
-       va_end(args);\r
-    }\r
-    void CallVoidMethodV(jobject obj, jmethodID methodID,\r
-                        va_list args) {\r
-        functions->CallVoidMethodV(this,obj,methodID,args);\r
-    }\r
-    void CallVoidMethodA(jobject obj, jmethodID methodID,\r
-                        const jvalue * args) {\r
-        functions->CallVoidMethodA(this,obj,methodID,args);\r
-    }\r
-\r
-    jobject CallNonvirtualObjectMethod(jobject obj, jclass clazz,\r
-                                      jmethodID methodID, ...) {\r
-        va_list args;\r
-       jobject result;\r
-       va_start(args,methodID);\r
-       result = functions->CallNonvirtualObjectMethodV(this,obj,clazz,\r
-                                                       methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jobject CallNonvirtualObjectMethodV(jobject obj, jclass clazz,\r
-                                       jmethodID methodID, va_list args) {\r
-        return functions->CallNonvirtualObjectMethodV(this,obj,clazz,\r
-                                                     methodID,args);\r
-    }\r
-    jobject CallNonvirtualObjectMethodA(jobject obj, jclass clazz,\r
-                                       jmethodID methodID, const jvalue * args) {\r
-        return functions->CallNonvirtualObjectMethodA(this,obj,clazz,\r
-                                                     methodID,args);\r
-    }\r
-\r
-    jboolean CallNonvirtualBooleanMethod(jobject obj, jclass clazz,\r
-                                        jmethodID methodID, ...) {\r
-        va_list args;\r
-       jboolean result;\r
-       va_start(args,methodID);\r
-       result = functions->CallNonvirtualBooleanMethodV(this,obj,clazz,\r
-                                                        methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jboolean CallNonvirtualBooleanMethodV(jobject obj, jclass clazz,\r
-                                         jmethodID methodID, va_list args) {\r
-        return functions->CallNonvirtualBooleanMethodV(this,obj,clazz,\r
-                                                      methodID,args);\r
-    }\r
-    jboolean CallNonvirtualBooleanMethodA(jobject obj, jclass clazz,\r
-                                         jmethodID methodID, const jvalue * args) {\r
-        return functions->CallNonvirtualBooleanMethodA(this,obj,clazz,\r
-                                                      methodID, args);\r
-    }\r
-\r
-    jbyte CallNonvirtualByteMethod(jobject obj, jclass clazz,\r
-                                  jmethodID methodID, ...) {\r
-        va_list args;\r
-       jbyte result;\r
-       va_start(args,methodID);\r
-       result = functions->CallNonvirtualByteMethodV(this,obj,clazz,\r
-                                                     methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jbyte CallNonvirtualByteMethodV(jobject obj, jclass clazz,\r
-                                   jmethodID methodID, va_list args) {\r
-        return functions->CallNonvirtualByteMethodV(this,obj,clazz,\r
-                                                   methodID,args);\r
-    }\r
-    jbyte CallNonvirtualByteMethodA(jobject obj, jclass clazz,\r
-                                   jmethodID methodID, const jvalue * args) {\r
-        return functions->CallNonvirtualByteMethodA(this,obj,clazz,\r
-                                                   methodID,args);\r
-    }\r
-\r
-    jchar CallNonvirtualCharMethod(jobject obj, jclass clazz,\r
-                                  jmethodID methodID, ...) {\r
-        va_list args;\r
-       jchar result;\r
-       va_start(args,methodID);\r
-       result = functions->CallNonvirtualCharMethodV(this,obj,clazz,\r
-                                                     methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jchar CallNonvirtualCharMethodV(jobject obj, jclass clazz,\r
-                                   jmethodID methodID, va_list args) {\r
-        return functions->CallNonvirtualCharMethodV(this,obj,clazz,\r
-                                                   methodID,args);\r
-    }\r
-    jchar CallNonvirtualCharMethodA(jobject obj, jclass clazz,\r
-                                   jmethodID methodID, const jvalue * args) {\r
-        return functions->CallNonvirtualCharMethodA(this,obj,clazz,\r
-                                                   methodID,args);\r
-    }\r
-\r
-    jshort CallNonvirtualShortMethod(jobject obj, jclass clazz,\r
-                                    jmethodID methodID, ...) {\r
-        va_list args;\r
-       jshort result;\r
-       va_start(args,methodID);\r
-       result = functions->CallNonvirtualShortMethodV(this,obj,clazz,\r
-                                                      methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jshort CallNonvirtualShortMethodV(jobject obj, jclass clazz,\r
-                                     jmethodID methodID, va_list args) {\r
-        return functions->CallNonvirtualShortMethodV(this,obj,clazz,\r
-                                                    methodID,args);\r
-    }\r
-    jshort CallNonvirtualShortMethodA(jobject obj, jclass clazz,\r
-                                     jmethodID methodID, const jvalue * args) {\r
-        return functions->CallNonvirtualShortMethodA(this,obj,clazz,\r
-                                                    methodID,args);\r
-    }\r
-\r
-    jint CallNonvirtualIntMethod(jobject obj, jclass clazz,\r
-                                jmethodID methodID, ...) {\r
-        va_list args;\r
-       jint result;\r
-       va_start(args,methodID);\r
-       result = functions->CallNonvirtualIntMethodV(this,obj,clazz,\r
-                                                    methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jint CallNonvirtualIntMethodV(jobject obj, jclass clazz,\r
-                                 jmethodID methodID, va_list args) {\r
-        return functions->CallNonvirtualIntMethodV(this,obj,clazz,\r
-                                                  methodID,args);\r
-    }\r
-    jint CallNonvirtualIntMethodA(jobject obj, jclass clazz,\r
-                                 jmethodID methodID, const jvalue * args) {\r
-        return functions->CallNonvirtualIntMethodA(this,obj,clazz,\r
-                                                  methodID,args);\r
-    }\r
-\r
-    jlong CallNonvirtualLongMethod(jobject obj, jclass clazz,\r
-                                  jmethodID methodID, ...) {\r
-        va_list args;\r
-       jlong result;\r
-       va_start(args,methodID);\r
-       result = functions->CallNonvirtualLongMethodV(this,obj,clazz,\r
-                                                     methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jlong CallNonvirtualLongMethodV(jobject obj, jclass clazz,\r
-                                   jmethodID methodID, va_list args) {\r
-        return functions->CallNonvirtualLongMethodV(this,obj,clazz,\r
-                                                   methodID,args);\r
-    }\r
-    jlong CallNonvirtualLongMethodA(jobject obj, jclass clazz,\r
-                                   jmethodID methodID, const jvalue * args) {\r
-        return functions->CallNonvirtualLongMethodA(this,obj,clazz,\r
-                                                   methodID,args);\r
-    }\r
-\r
-    jfloat CallNonvirtualFloatMethod(jobject obj, jclass clazz,\r
-                                    jmethodID methodID, ...) {\r
-        va_list args;\r
-       jfloat result;\r
-       va_start(args,methodID);\r
-       result = functions->CallNonvirtualFloatMethodV(this,obj,clazz,\r
-                                                      methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jfloat CallNonvirtualFloatMethodV(jobject obj, jclass clazz,\r
-                                     jmethodID methodID,\r
-                                     va_list args) {\r
-        return functions->CallNonvirtualFloatMethodV(this,obj,clazz,\r
-                                                    methodID,args);\r
-    }\r
-    jfloat CallNonvirtualFloatMethodA(jobject obj, jclass clazz,\r
-                                     jmethodID methodID,\r
-                                     const jvalue * args) {\r
-        return functions->CallNonvirtualFloatMethodA(this,obj,clazz,\r
-                                                    methodID,args);\r
-    }\r
-\r
-    jdouble CallNonvirtualDoubleMethod(jobject obj, jclass clazz,\r
-                                      jmethodID methodID, ...) {\r
-        va_list args;\r
-       jdouble result;\r
-       va_start(args,methodID);\r
-       result = functions->CallNonvirtualDoubleMethodV(this,obj,clazz,\r
-                                                       methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jdouble CallNonvirtualDoubleMethodV(jobject obj, jclass clazz,\r
-                                       jmethodID methodID,\r
-                                       va_list args) {\r
-        return functions->CallNonvirtualDoubleMethodV(this,obj,clazz,\r
-                                                     methodID,args);\r
-    }\r
-    jdouble CallNonvirtualDoubleMethodA(jobject obj, jclass clazz,\r
-                                       jmethodID methodID,\r
-                                       const jvalue * args) {\r
-        return functions->CallNonvirtualDoubleMethodA(this,obj,clazz,\r
-                                                     methodID,args);\r
-    }\r
-\r
-    void CallNonvirtualVoidMethod(jobject obj, jclass clazz,\r
-                                 jmethodID methodID, ...) {\r
-        va_list args;\r
-       va_start(args,methodID);\r
-       functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);\r
-       va_end(args);\r
-    }\r
-    void CallNonvirtualVoidMethodV(jobject obj, jclass clazz,\r
-                                  jmethodID methodID,\r
-                                  va_list args) {\r
-        functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);\r
-    }\r
-    void CallNonvirtualVoidMethodA(jobject obj, jclass clazz,\r
-                                  jmethodID methodID,\r
-                                  const jvalue * args) {\r
-        functions->CallNonvirtualVoidMethodA(this,obj,clazz,methodID,args);\r
-    }\r
-\r
-    jfieldID GetFieldID(jclass clazz, const char *name,\r
-                       const char *sig) {\r
-        return functions->GetFieldID(this,clazz,name,sig);\r
-    }\r
-\r
-    jobject GetObjectField(jobject obj, jfieldID fieldID) {\r
-        return functions->GetObjectField(this,obj,fieldID);\r
-    }\r
-    jboolean GetBooleanField(jobject obj, jfieldID fieldID) {\r
-        return functions->GetBooleanField(this,obj,fieldID);\r
-    }\r
-    jbyte GetByteField(jobject obj, jfieldID fieldID) {\r
-        return functions->GetByteField(this,obj,fieldID);\r
-    }\r
-    jchar GetCharField(jobject obj, jfieldID fieldID) {\r
-        return functions->GetCharField(this,obj,fieldID);\r
-    }\r
-    jshort GetShortField(jobject obj, jfieldID fieldID) {\r
-        return functions->GetShortField(this,obj,fieldID);\r
-    }\r
-    jint GetIntField(jobject obj, jfieldID fieldID) {\r
-        return functions->GetIntField(this,obj,fieldID);\r
-    }\r
-    jlong GetLongField(jobject obj, jfieldID fieldID) {\r
-        return functions->GetLongField(this,obj,fieldID);\r
-    }\r
-    jfloat GetFloatField(jobject obj, jfieldID fieldID) {\r
-        return functions->GetFloatField(this,obj,fieldID);\r
-    }\r
-    jdouble GetDoubleField(jobject obj, jfieldID fieldID) {\r
-        return functions->GetDoubleField(this,obj,fieldID);\r
-    }\r
-\r
-    void SetObjectField(jobject obj, jfieldID fieldID, jobject val) {\r
-        functions->SetObjectField(this,obj,fieldID,val);\r
-    }\r
-    void SetBooleanField(jobject obj, jfieldID fieldID,\r
-                        jboolean val) {\r
-        functions->SetBooleanField(this,obj,fieldID,val);\r
-    }\r
-    void SetByteField(jobject obj, jfieldID fieldID,\r
-                     jbyte val) {\r
-        functions->SetByteField(this,obj,fieldID,val);\r
-    }\r
-    void SetCharField(jobject obj, jfieldID fieldID,\r
-                     jchar val) {\r
-        functions->SetCharField(this,obj,fieldID,val);\r
-    }\r
-    void SetShortField(jobject obj, jfieldID fieldID,\r
-                      jshort val) {\r
-        functions->SetShortField(this,obj,fieldID,val);\r
-    }\r
-    void SetIntField(jobject obj, jfieldID fieldID,\r
-                    jint val) {\r
-        functions->SetIntField(this,obj,fieldID,val);\r
-    }\r
-    void SetLongField(jobject obj, jfieldID fieldID,\r
-                     jlong val) {\r
-        functions->SetLongField(this,obj,fieldID,val);\r
-    }\r
-    void SetFloatField(jobject obj, jfieldID fieldID,\r
-                      jfloat val) {\r
-        functions->SetFloatField(this,obj,fieldID,val);\r
-    }\r
-    void SetDoubleField(jobject obj, jfieldID fieldID,\r
-                       jdouble val) {\r
-        functions->SetDoubleField(this,obj,fieldID,val);\r
-    }\r
-\r
-    jmethodID GetStaticMethodID(jclass clazz, const char *name,\r
-                               const char *sig) {\r
-        return functions->GetStaticMethodID(this,clazz,name,sig);\r
-    }\r
-\r
-    jobject CallStaticObjectMethod(jclass clazz, jmethodID methodID,\r
-                            ...) {\r
-        va_list args;\r
-       jobject result;\r
-       va_start(args,methodID);\r
-       result = functions->CallStaticObjectMethodV(this,clazz,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jobject CallStaticObjectMethodV(jclass clazz, jmethodID methodID,\r
-                             va_list args) {\r
-        return functions->CallStaticObjectMethodV(this,clazz,methodID,args);\r
-    }\r
-    jobject CallStaticObjectMethodA(jclass clazz, jmethodID methodID,\r
-                             const jvalue *args) {\r
-        return functions->CallStaticObjectMethodA(this,clazz,methodID,args);\r
-    }\r
-\r
-    jboolean CallStaticBooleanMethod(jclass clazz,\r
-                                    jmethodID methodID, ...) {\r
-        va_list args;\r
-       jboolean result;\r
-       va_start(args,methodID);\r
-       result = functions->CallStaticBooleanMethodV(this,clazz,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jboolean CallStaticBooleanMethodV(jclass clazz,\r
-                                     jmethodID methodID, va_list args) {\r
-        return functions->CallStaticBooleanMethodV(this,clazz,methodID,args);\r
-    }\r
-    jboolean CallStaticBooleanMethodA(jclass clazz,\r
-                                     jmethodID methodID, const jvalue *args) {\r
-        return functions->CallStaticBooleanMethodA(this,clazz,methodID,args);\r
-    }\r
-\r
-    jbyte CallStaticByteMethod(jclass clazz,\r
-                              jmethodID methodID, ...) {\r
-        va_list args;\r
-       jbyte result;\r
-       va_start(args,methodID);\r
-       result = functions->CallStaticByteMethodV(this,clazz,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jbyte CallStaticByteMethodV(jclass clazz,\r
-                               jmethodID methodID, va_list args) {\r
-        return functions->CallStaticByteMethodV(this,clazz,methodID,args);\r
-    }\r
-    jbyte CallStaticByteMethodA(jclass clazz,\r
-                               jmethodID methodID, const jvalue *args) {\r
-        return functions->CallStaticByteMethodA(this,clazz,methodID,args);\r
-    }\r
-\r
-    jchar CallStaticCharMethod(jclass clazz,\r
-                              jmethodID methodID, ...) {\r
-        va_list args;\r
-       jchar result;\r
-       va_start(args,methodID);\r
-       result = functions->CallStaticCharMethodV(this,clazz,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jchar CallStaticCharMethodV(jclass clazz,\r
-                               jmethodID methodID, va_list args) {\r
-        return functions->CallStaticCharMethodV(this,clazz,methodID,args);\r
-    }\r
-    jchar CallStaticCharMethodA(jclass clazz,\r
-                               jmethodID methodID, const jvalue *args) {\r
-        return functions->CallStaticCharMethodA(this,clazz,methodID,args);\r
-    }\r
-\r
-    jshort CallStaticShortMethod(jclass clazz,\r
-                                jmethodID methodID, ...) {\r
-        va_list args;\r
-       jshort result;\r
-       va_start(args,methodID);\r
-       result = functions->CallStaticShortMethodV(this,clazz,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jshort CallStaticShortMethodV(jclass clazz,\r
-                                 jmethodID methodID, va_list args) {\r
-        return functions->CallStaticShortMethodV(this,clazz,methodID,args);\r
-    }\r
-    jshort CallStaticShortMethodA(jclass clazz,\r
-                                 jmethodID methodID, const jvalue *args) {\r
-        return functions->CallStaticShortMethodA(this,clazz,methodID,args);\r
-    }\r
-\r
-    jint CallStaticIntMethod(jclass clazz,\r
-                            jmethodID methodID, ...) {\r
-        va_list args;\r
-       jint result;\r
-       va_start(args,methodID);\r
-       result = functions->CallStaticIntMethodV(this,clazz,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jint CallStaticIntMethodV(jclass clazz,\r
-                             jmethodID methodID, va_list args) {\r
-        return functions->CallStaticIntMethodV(this,clazz,methodID,args);\r
-    }\r
-    jint CallStaticIntMethodA(jclass clazz,\r
-                             jmethodID methodID, const jvalue *args) {\r
-        return functions->CallStaticIntMethodA(this,clazz,methodID,args);\r
-    }\r
-\r
-    jlong CallStaticLongMethod(jclass clazz,\r
-                              jmethodID methodID, ...) {\r
-        va_list args;\r
-       jlong result;\r
-       va_start(args,methodID);\r
-       result = functions->CallStaticLongMethodV(this,clazz,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jlong CallStaticLongMethodV(jclass clazz,\r
-                               jmethodID methodID, va_list args) {\r
-        return functions->CallStaticLongMethodV(this,clazz,methodID,args);\r
-    }\r
-    jlong CallStaticLongMethodA(jclass clazz,\r
-                               jmethodID methodID, const jvalue *args) {\r
-        return functions->CallStaticLongMethodA(this,clazz,methodID,args);\r
-    }\r
-\r
-    jfloat CallStaticFloatMethod(jclass clazz,\r
-                                jmethodID methodID, ...) {\r
-        va_list args;\r
-       jfloat result;\r
-       va_start(args,methodID);\r
-       result = functions->CallStaticFloatMethodV(this,clazz,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jfloat CallStaticFloatMethodV(jclass clazz,\r
-                                 jmethodID methodID, va_list args) {\r
-        return functions->CallStaticFloatMethodV(this,clazz,methodID,args);\r
-    }\r
-    jfloat CallStaticFloatMethodA(jclass clazz,\r
-                                 jmethodID methodID, const jvalue *args) {\r
-        return functions->CallStaticFloatMethodA(this,clazz,methodID,args);\r
-    }\r
-\r
-    jdouble CallStaticDoubleMethod(jclass clazz,\r
-                                  jmethodID methodID, ...) {\r
-        va_list args;\r
-       jdouble result;\r
-       va_start(args,methodID);\r
-       result = functions->CallStaticDoubleMethodV(this,clazz,methodID,args);\r
-       va_end(args);\r
-       return result;\r
-    }\r
-    jdouble CallStaticDoubleMethodV(jclass clazz,\r
-                                   jmethodID methodID, va_list args) {\r
-        return functions->CallStaticDoubleMethodV(this,clazz,methodID,args);\r
-    }\r
-    jdouble CallStaticDoubleMethodA(jclass clazz,\r
-                                   jmethodID methodID, const jvalue *args) {\r
-        return functions->CallStaticDoubleMethodA(this,clazz,methodID,args);\r
-    }\r
-\r
-    void CallStaticVoidMethod(jclass cls, jmethodID methodID, ...) {\r
-        va_list args;\r
-       va_start(args,methodID);\r
-       functions->CallStaticVoidMethodV(this,cls,methodID,args);\r
-       va_end(args);\r
-    }\r
-    void CallStaticVoidMethodV(jclass cls, jmethodID methodID,\r
-                              va_list args) {\r
-        functions->CallStaticVoidMethodV(this,cls,methodID,args);\r
-    }\r
-    void CallStaticVoidMethodA(jclass cls, jmethodID methodID,\r
-                              const jvalue * args) {\r
-        functions->CallStaticVoidMethodA(this,cls,methodID,args);\r
-    }\r
-\r
-    jfieldID GetStaticFieldID(jclass clazz, const char *name,\r
-                             const char *sig) {\r
-        return functions->GetStaticFieldID(this,clazz,name,sig);\r
-    }\r
-    jobject GetStaticObjectField(jclass clazz, jfieldID fieldID) {\r
-        return functions->GetStaticObjectField(this,clazz,fieldID);\r
-    }\r
-    jboolean GetStaticBooleanField(jclass clazz, jfieldID fieldID) {\r
-        return functions->GetStaticBooleanField(this,clazz,fieldID);\r
-    }\r
-    jbyte GetStaticByteField(jclass clazz, jfieldID fieldID) {\r
-        return functions->GetStaticByteField(this,clazz,fieldID);\r
-    }\r
-    jchar GetStaticCharField(jclass clazz, jfieldID fieldID) {\r
-        return functions->GetStaticCharField(this,clazz,fieldID);\r
-    }\r
-    jshort GetStaticShortField(jclass clazz, jfieldID fieldID) {\r
-        return functions->GetStaticShortField(this,clazz,fieldID);\r
-    }\r
-    jint GetStaticIntField(jclass clazz, jfieldID fieldID) {\r
-        return functions->GetStaticIntField(this,clazz,fieldID);\r
-    }\r
-    jlong GetStaticLongField(jclass clazz, jfieldID fieldID) {\r
-        return functions->GetStaticLongField(this,clazz,fieldID);\r
-    }\r
-    jfloat GetStaticFloatField(jclass clazz, jfieldID fieldID) {\r
-        return functions->GetStaticFloatField(this,clazz,fieldID);\r
-    }\r
-    jdouble GetStaticDoubleField(jclass clazz, jfieldID fieldID) {\r
-        return functions->GetStaticDoubleField(this,clazz,fieldID);\r
-    }\r
-\r
-    void SetStaticObjectField(jclass clazz, jfieldID fieldID,\r
-                       jobject value) {\r
-      functions->SetStaticObjectField(this,clazz,fieldID,value);\r
-    }\r
-    void SetStaticBooleanField(jclass clazz, jfieldID fieldID,\r
-                       jboolean value) {\r
-      functions->SetStaticBooleanField(this,clazz,fieldID,value);\r
-    }\r
-    void SetStaticByteField(jclass clazz, jfieldID fieldID,\r
-                       jbyte value) {\r
-      functions->SetStaticByteField(this,clazz,fieldID,value);\r
-    }\r
-    void SetStaticCharField(jclass clazz, jfieldID fieldID,\r
-                       jchar value) {\r
-      functions->SetStaticCharField(this,clazz,fieldID,value);\r
-    }\r
-    void SetStaticShortField(jclass clazz, jfieldID fieldID,\r
-                       jshort value) {\r
-      functions->SetStaticShortField(this,clazz,fieldID,value);\r
-    }\r
-    void SetStaticIntField(jclass clazz, jfieldID fieldID,\r
-                       jint value) {\r
-      functions->SetStaticIntField(this,clazz,fieldID,value);\r
-    }\r
-    void SetStaticLongField(jclass clazz, jfieldID fieldID,\r
-                       jlong value) {\r
-      functions->SetStaticLongField(this,clazz,fieldID,value);\r
-    }\r
-    void SetStaticFloatField(jclass clazz, jfieldID fieldID,\r
-                       jfloat value) {\r
-      functions->SetStaticFloatField(this,clazz,fieldID,value);\r
-    }\r
-    void SetStaticDoubleField(jclass clazz, jfieldID fieldID,\r
-                       jdouble value) {\r
-      functions->SetStaticDoubleField(this,clazz,fieldID,value);\r
-    }\r
-\r
-    jstring NewString(const jchar *unicode, jsize len) {\r
-        return functions->NewString(this,unicode,len);\r
-    }\r
-    jsize GetStringLength(jstring str) {\r
-        return functions->GetStringLength(this,str);\r
-    }\r
-    const jchar *GetStringChars(jstring str, jboolean *isCopy) {\r
-        return functions->GetStringChars(this,str,isCopy);\r
-    }\r
-    void ReleaseStringChars(jstring str, const jchar *chars) {\r
-        functions->ReleaseStringChars(this,str,chars);\r
-    }\r
-\r
-    jstring NewStringUTF(const char *utf) {\r
-        return functions->NewStringUTF(this,utf);\r
-    }\r
-    jsize GetStringUTFLength(jstring str) {\r
-        return functions->GetStringUTFLength(this,str);\r
-    }\r
-    const char* GetStringUTFChars(jstring str, jboolean *isCopy) {\r
-        return functions->GetStringUTFChars(this,str,isCopy);\r
-    }\r
-    void ReleaseStringUTFChars(jstring str, const char* chars) {\r
-        functions->ReleaseStringUTFChars(this,str,chars);\r
-    }\r
-\r
-    jsize GetArrayLength(jarray array) {\r
-        return functions->GetArrayLength(this,array);\r
-    }\r
-\r
-    jobjectArray NewObjectArray(jsize len, jclass clazz,\r
-                               jobject init) {\r
-        return functions->NewObjectArray(this,len,clazz,init);\r
-    }\r
-    jobject GetObjectArrayElement(jobjectArray array, jsize index) {\r
-        return functions->GetObjectArrayElement(this,array,index);\r
-    }\r
-    void SetObjectArrayElement(jobjectArray array, jsize index,\r
-                              jobject val) {\r
-        functions->SetObjectArrayElement(this,array,index,val);\r
-    }\r
-\r
-    jbooleanArray NewBooleanArray(jsize len) {\r
-        return functions->NewBooleanArray(this,len);\r
-    }\r
-    jbyteArray NewByteArray(jsize len) {\r
-        return functions->NewByteArray(this,len);\r
-    }\r
-    jcharArray NewCharArray(jsize len) {\r
-        return functions->NewCharArray(this,len);\r
-    }\r
-    jshortArray NewShortArray(jsize len) {\r
-        return functions->NewShortArray(this,len);\r
-    }\r
-    jintArray NewIntArray(jsize len) {\r
-        return functions->NewIntArray(this,len);\r
-    }\r
-    jlongArray NewLongArray(jsize len) {\r
-        return functions->NewLongArray(this,len);\r
-    }\r
-    jfloatArray NewFloatArray(jsize len) {\r
-        return functions->NewFloatArray(this,len);\r
-    }\r
-    jdoubleArray NewDoubleArray(jsize len) {\r
-        return functions->NewDoubleArray(this,len);\r
-    }\r
-\r
-    jboolean * GetBooleanArrayElements(jbooleanArray array, jboolean *isCopy) {\r
-        return functions->GetBooleanArrayElements(this,array,isCopy);\r
-    }\r
-    jbyte * GetByteArrayElements(jbyteArray array, jboolean *isCopy) {\r
-        return functions->GetByteArrayElements(this,array,isCopy);\r
-    }\r
-    jchar * GetCharArrayElements(jcharArray array, jboolean *isCopy) {\r
-        return functions->GetCharArrayElements(this,array,isCopy);\r
-    }\r
-    jshort * GetShortArrayElements(jshortArray array, jboolean *isCopy) {\r
-        return functions->GetShortArrayElements(this,array,isCopy);\r
-    }\r
-    jint * GetIntArrayElements(jintArray array, jboolean *isCopy) {\r
-        return functions->GetIntArrayElements(this,array,isCopy);\r
-    }\r
-    jlong * GetLongArrayElements(jlongArray array, jboolean *isCopy) {\r
-        return functions->GetLongArrayElements(this,array,isCopy);\r
-    }\r
-    jfloat * GetFloatArrayElements(jfloatArray array, jboolean *isCopy) {\r
-        return functions->GetFloatArrayElements(this,array,isCopy);\r
-    }\r
-    jdouble * GetDoubleArrayElements(jdoubleArray array, jboolean *isCopy) {\r
-        return functions->GetDoubleArrayElements(this,array,isCopy);\r
-    }\r
-\r
-    void ReleaseBooleanArrayElements(jbooleanArray array,\r
-                                    jboolean *elems,\r
-                                    jint mode) {\r
-        functions->ReleaseBooleanArrayElements(this,array,elems,mode);\r
-    }\r
-    void ReleaseByteArrayElements(jbyteArray array,\r
-                                 jbyte *elems,\r
-                                 jint mode) {\r
-        functions->ReleaseByteArrayElements(this,array,elems,mode);\r
-    }\r
-    void ReleaseCharArrayElements(jcharArray array,\r
-                                 jchar *elems,\r
-                                 jint mode) {\r
-        functions->ReleaseCharArrayElements(this,array,elems,mode);\r
-    }\r
-    void ReleaseShortArrayElements(jshortArray array,\r
-                                  jshort *elems,\r
-                                  jint mode) {\r
-        functions->ReleaseShortArrayElements(this,array,elems,mode);\r
-    }\r
-    void ReleaseIntArrayElements(jintArray array,\r
-                                jint *elems,\r
-                                jint mode) {\r
-        functions->ReleaseIntArrayElements(this,array,elems,mode);\r
-    }\r
-    void ReleaseLongArrayElements(jlongArray array,\r
-                                 jlong *elems,\r
-                                 jint mode) {\r
-        functions->ReleaseLongArrayElements(this,array,elems,mode);\r
-    }\r
-    void ReleaseFloatArrayElements(jfloatArray array,\r
-                                  jfloat *elems,\r
-                                  jint mode) {\r
-        functions->ReleaseFloatArrayElements(this,array,elems,mode);\r
-    }\r
-    void ReleaseDoubleArrayElements(jdoubleArray array,\r
-                                   jdouble *elems,\r
-                                   jint mode) {\r
-        functions->ReleaseDoubleArrayElements(this,array,elems,mode);\r
-    }\r
-\r
-    void GetBooleanArrayRegion(jbooleanArray array,\r
-                              jsize start, jsize len, jboolean *buf) {\r
-        functions->GetBooleanArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void GetByteArrayRegion(jbyteArray array,\r
-                           jsize start, jsize len, jbyte *buf) {\r
-        functions->GetByteArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void GetCharArrayRegion(jcharArray array,\r
-                           jsize start, jsize len, jchar *buf) {\r
-        functions->GetCharArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void GetShortArrayRegion(jshortArray array,\r
-                            jsize start, jsize len, jshort *buf) {\r
-        functions->GetShortArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void GetIntArrayRegion(jintArray array,\r
-                          jsize start, jsize len, jint *buf) {\r
-        functions->GetIntArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void GetLongArrayRegion(jlongArray array,\r
-                           jsize start, jsize len, jlong *buf) {\r
-        functions->GetLongArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void GetFloatArrayRegion(jfloatArray array,\r
-                            jsize start, jsize len, jfloat *buf) {\r
-        functions->GetFloatArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void GetDoubleArrayRegion(jdoubleArray array,\r
-                             jsize start, jsize len, jdouble *buf) {\r
-        functions->GetDoubleArrayRegion(this,array,start,len,buf);\r
-    }\r
-\r
-    void SetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len,\r
-                              const jboolean *buf) {\r
-        functions->SetBooleanArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void SetByteArrayRegion(jbyteArray array, jsize start, jsize len,\r
-                           const jbyte *buf) {\r
-        functions->SetByteArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void SetCharArrayRegion(jcharArray array, jsize start, jsize len,\r
-                           const jchar *buf) {\r
-        functions->SetCharArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void SetShortArrayRegion(jshortArray array, jsize start, jsize len,\r
-                            const jshort *buf) {\r
-        functions->SetShortArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void SetIntArrayRegion(jintArray array, jsize start, jsize len,\r
-                          const jint *buf) {\r
-        functions->SetIntArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void SetLongArrayRegion(jlongArray array, jsize start, jsize len,\r
-                           const jlong *buf) {\r
-        functions->SetLongArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void SetFloatArrayRegion(jfloatArray array, jsize start, jsize len,\r
-                            const jfloat *buf) {\r
-        functions->SetFloatArrayRegion(this,array,start,len,buf);\r
-    }\r
-    void SetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len,\r
-                             const jdouble *buf) {\r
-        functions->SetDoubleArrayRegion(this,array,start,len,buf);\r
-    }\r
-\r
-    jint RegisterNatives(jclass clazz, const JNINativeMethod *methods,\r
-                        jint nMethods) {\r
-        return functions->RegisterNatives(this,clazz,methods,nMethods);\r
-    }\r
-    jint UnregisterNatives(jclass clazz) {\r
-        return functions->UnregisterNatives(this,clazz);\r
-    }\r
-\r
-    jint MonitorEnter(jobject obj) {\r
-        return functions->MonitorEnter(this,obj);\r
-    }\r
-    jint MonitorExit(jobject obj) {\r
-        return functions->MonitorExit(this,obj);\r
-    }\r
-\r
-    jint GetJavaVM(JavaVM **vm) {\r
-        return functions->GetJavaVM(this,vm);\r
-    }\r
-\r
-    void GetStringRegion(jstring str, jsize start, jsize len, jchar *buf) {\r
-        functions->GetStringRegion(this,str,start,len,buf);\r
-    }\r
-    void GetStringUTFRegion(jstring str, jsize start, jsize len, char *buf) {\r
-        functions->GetStringUTFRegion(this,str,start,len,buf);\r
-    }\r
-\r
-    void * GetPrimitiveArrayCritical(jarray array, jboolean *isCopy) {\r
-        return functions->GetPrimitiveArrayCritical(this,array,isCopy);\r
-    }\r
-    void ReleasePrimitiveArrayCritical(jarray array, void *carray, jint mode) {\r
-        functions->ReleasePrimitiveArrayCritical(this,array,carray,mode);\r
-    }\r
-\r
-    const jchar * GetStringCritical(jstring string, jboolean *isCopy) {\r
-        return functions->GetStringCritical(this,string,isCopy);\r
-    }\r
-    void ReleaseStringCritical(jstring string, const jchar *cstring) {\r
-        functions->ReleaseStringCritical(this,string,cstring);\r
-    }\r
-\r
-    jweak NewWeakGlobalRef(jobject obj) {\r
-        return functions->NewWeakGlobalRef(this,obj);\r
-    }\r
-    void DeleteWeakGlobalRef(jweak ref) {\r
-        functions->DeleteWeakGlobalRef(this,ref);\r
-    }\r
-\r
-    jboolean ExceptionCheck() {\r
-       return functions->ExceptionCheck(this);\r
-    }\r
-\r
-    jobject NewDirectByteBuffer(void* address, jlong capacity) {\r
-        return functions->NewDirectByteBuffer(this, address, capacity);\r
-    }\r
-    void* GetDirectBufferAddress(jobject buf) {\r
-        return functions->GetDirectBufferAddress(this, buf);\r
-    }\r
-    jlong GetDirectBufferCapacity(jobject buf) {\r
-        return functions->GetDirectBufferCapacity(this, buf);\r
-    }\r
-\r
-#endif /* __cplusplus */\r
-};\r
-\r
-typedef struct JavaVMOption {\r
-    char *optionString;\r
-    void *extraInfo;\r
-} JavaVMOption;\r
-\r
-typedef struct JavaVMInitArgs {\r
-    jint version;\r
-\r
-    jint nOptions;\r
-    JavaVMOption *options;\r
-    jboolean ignoreUnrecognized;\r
-} JavaVMInitArgs;\r
-\r
-typedef struct JavaVMAttachArgs {\r
-    jint version;\r
-\r
-    char *name;\r
-    jobject group;\r
-} JavaVMAttachArgs;\r
-\r
-/* These structures will be VM-specific. */\r
-\r
-typedef struct JDK1_1InitArgs {\r
-    jint version;\r
-\r
-    char **properties;\r
-    jint checkSource;\r
-    jint nativeStackSize;\r
-    jint javaStackSize;\r
-    jint minHeapSize;\r
-    jint maxHeapSize;\r
-    jint verifyMode;\r
-    char *classpath;\r
-\r
-    jint (JNICALL *vfprintf)(FILE *fp, const char *format, va_list args);\r
-    void (JNICALL *exit)(jint code);\r
-    void (JNICALL *abort)(void);\r
-\r
-    jint enableClassGC;\r
-    jint enableVerboseGC;\r
-    jint disableAsyncGC;\r
-    jint verbose;\r
-    jboolean debugging;\r
-    jint debugPort;\r
-} JDK1_1InitArgs;\r
-\r
-typedef struct JDK1_1AttachArgs {\r
-    void * __padding; /* C compilers don't allow empty structures. */\r
-} JDK1_1AttachArgs;\r
-\r
-#define JDK1_2\r
-#define JDK1_4\r
-\r
-/* End VM-specific. */\r
-\r
-struct JNIInvokeInterface_ {\r
-    void *reserved0;\r
-    void *reserved1;\r
-    void *reserved2;\r
-\r
-    jint (JNICALL *DestroyJavaVM)(JavaVM *vm);\r
-\r
-    jint (JNICALL *AttachCurrentThread)(JavaVM *vm, void **penv, void *args);\r
-\r
-    jint (JNICALL *DetachCurrentThread)(JavaVM *vm);\r
-\r
-    jint (JNICALL *GetEnv)(JavaVM *vm, void **penv, jint version);\r
-\r
-    jint (JNICALL *AttachCurrentThreadAsDaemon)(JavaVM *vm, void **penv, void *args);\r
-};\r
-\r
-struct JavaVM_ {\r
-    const struct JNIInvokeInterface_ *functions;\r
-#ifdef __cplusplus\r
-\r
-    jint DestroyJavaVM() {\r
-        return functions->DestroyJavaVM(this);\r
-    }\r
-    jint AttachCurrentThread(void **penv, void *args) {\r
-        return functions->AttachCurrentThread(this, penv, args);\r
-    }\r
-    jint DetachCurrentThread() {\r
-        return functions->DetachCurrentThread(this);\r
-    }\r
-\r
-    jint GetEnv(void **penv, jint version) {\r
-        return functions->GetEnv(this, penv, version);\r
-    }\r
-    jint AttachCurrentThreadAsDaemon(void **penv, void *args) {\r
-        return functions->AttachCurrentThreadAsDaemon(this, penv, args);\r
-    }\r
-#endif\r
-};\r
-\r
-#ifdef _JNI_IMPLEMENTATION_\r
-#define _JNI_IMPORT_OR_EXPORT_ JNIEXPORT\r
-#else\r
-#define _JNI_IMPORT_OR_EXPORT_ JNIIMPORT\r
-#endif\r
-_JNI_IMPORT_OR_EXPORT_ jint JNICALL\r
-JNI_GetDefaultJavaVMInitArgs(void *args);\r
-\r
-_JNI_IMPORT_OR_EXPORT_ jint JNICALL\r
-JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args);\r
-\r
-_JNI_IMPORT_OR_EXPORT_ jint JNICALL\r
-JNI_GetCreatedJavaVMs(JavaVM **, jsize, jsize *);\r
-\r
-/* Defined by native libraries. */\r
-JNIEXPORT jint JNICALL\r
-JNI_OnLoad(JavaVM *vm, void *reserved);\r
-\r
-JNIEXPORT void JNICALL\r
-JNI_OnUnload(JavaVM *vm, void *reserved);\r
-\r
-#define JNI_VERSION_1_1 0x00010001\r
-#define JNI_VERSION_1_2 0x00010002\r
-#define JNI_VERSION_1_4 0x00010004\r
-\r
-#ifdef __cplusplus\r
-} /* extern "C" */\r
-#endif /* __cplusplus */\r
-\r
-#endif /* !_JAVASOFT_JNI_H_ */\r
diff --git a/JavaOpenJPEG/java-jni/include/jvmdi.h b/JavaOpenJPEG/java-jni/include/jvmdi.h
deleted file mode 100644 (file)
index d39c4a9..0000000
+++ /dev/null
@@ -1,1012 +0,0 @@
-/*\r
- * @(#)jvmdi.h 1.48 03/12/19\r
- *\r
- * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
- * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
- */\r
-\r
-/*\r
- *   Java Virtual Machine Debug Interface\r
- *\r
- *   Defines debugging functionality that a VM should provide.  \r
- *\r
- *   Should not overlap functionality in jni.h\r
- */\r
-\r
-#ifndef _JAVASOFT_JVMDI_H_\r
-#define _JAVASOFT_JVMDI_H_\r
-\r
-#include "jni.h"\r
-\r
-#define JVMDI_VERSION_1    0x20010000\r
-#define JVMDI_VERSION_1_1  0x20010001\r
-#define JVMDI_VERSION_1_2  0x20010002\r
-#define JVMDI_VERSION_1_3  0x20010003\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-typedef jobject jthread;\r
-\r
-typedef jobject jthreadGroup;\r
-\r
-struct _jframeID;\r
-typedef struct _jframeID *jframeID;\r
-\r
-  /* specifies program location "pc" - often byte code index */\r
-typedef jlong jlocation;\r
-\r
-  /* The jmethodID for methods that have been replaced */\r
-  /* via RedefineClasses - used when the implementation */\r
-  /* does not wish to retain replaced jmethodIDs */\r
-#define OBSOLETE_METHOD_ID ((jmethodID)(NULL))\r
-\r
-  /*\r
-   *  Errors\r
-   */\r
-\r
-typedef jint jvmdiError;\r
-\r
-  /* no error */\r
-#define JVMDI_ERROR_NONE                 ((jvmdiError)0)\r
-\r
-  /*\r
-   * Errors on thread operations\r
-   */\r
-\r
-  /* invalid thread */\r
-#define JVMDI_ERROR_INVALID_THREAD       ((jvmdiError)10)\r
-  /* invalid thread group */\r
-#define JVMDI_ERROR_INVALID_THREAD_GROUP ((jvmdiError)11)\r
-  /* invalid thread priority */\r
-#define JVMDI_ERROR_INVALID_PRIORITY     ((jvmdiError)12)\r
-  /* thread not suspended */\r
-#define JVMDI_ERROR_THREAD_NOT_SUSPENDED ((jvmdiError)13)\r
-  /* thread already suspended */\r
-#define JVMDI_ERROR_THREAD_SUSPENDED     ((jvmdiError)14)\r
-\r
-  /* \r
-   * Errors on object and class operations\r
-   */\r
-\r
-  /* invalid object (implementation not required to gracefully catch) */\r
-#define JVMDI_ERROR_INVALID_OBJECT       ((jvmdiError)20)\r
-  /* invalid class (implementation not required to gracefully catch) */\r
-#define JVMDI_ERROR_INVALID_CLASS        ((jvmdiError)21)\r
-  /* class not prepared */\r
-#define JVMDI_ERROR_CLASS_NOT_PREPARED   ((jvmdiError)22)\r
-  /* invalid methodID (implementation not required to gracefully catch) */\r
-#define JVMDI_ERROR_INVALID_METHODID     ((jvmdiError)23)\r
-  /* invalid location */\r
-#define JVMDI_ERROR_INVALID_LOCATION     ((jvmdiError)24)\r
-  /* invalid fieldID (implementation not required to gracefully catch) */\r
-#define JVMDI_ERROR_INVALID_FIELDID      ((jvmdiError)25)\r
-\r
-  /*\r
-   * Errors on frame operations\r
-   */\r
-\r
-  /* invalid frameID (implementation not required to gracefully catch) */\r
-#define JVMDI_ERROR_INVALID_FRAMEID      ((jvmdiError)30)\r
-  /* there are no more frames on the stack */\r
-#define JVMDI_ERROR_NO_MORE_FRAMES       ((jvmdiError)31)\r
-  /* operation cannot be performed on this frame */\r
-#define JVMDI_ERROR_OPAQUE_FRAME         ((jvmdiError)32)\r
-  /* operation can only be performed on current frame */\r
-#define JVMDI_ERROR_NOT_CURRENT_FRAME    ((jvmdiError)33)\r
-  /* type mismatch (implementation not required to gracefully catch) */\r
-#define JVMDI_ERROR_TYPE_MISMATCH        ((jvmdiError)34)\r
-  /* invalid slot */\r
-#define JVMDI_ERROR_INVALID_SLOT         ((jvmdiError)35)\r
-\r
-  /*\r
-   * Errors on set/clear/find operations\r
-   */\r
-\r
-  /* item already present */\r
-#define JVMDI_ERROR_DUPLICATE            ((jvmdiError)40)\r
-  /* item not found */\r
-#define JVMDI_ERROR_NOT_FOUND            ((jvmdiError)41)\r
-\r
-  /*\r
-   * Errors on monitor operations\r
-   */\r
-\r
-  /* invalid monitor */\r
-#define JVMDI_ERROR_INVALID_MONITOR      ((jvmdiError)50)\r
-  /* wait, notify, notify all tried without entering monitor  */\r
-#define JVMDI_ERROR_NOT_MONITOR_OWNER    ((jvmdiError)51)\r
-  /* waiting thread interrupted */\r
-#define JVMDI_ERROR_INTERRUPT            ((jvmdiError)52)\r
-  \r
-  /*\r
-   * Class redefinition / operand stack errors\r
-   */\r
-\r
-  /* The equivalent of ClassFormatError */\r
-#define JVMDI_ERROR_INVALID_CLASS_FORMAT          ((jvmdiError)60)\r
-  /* The equivalent of ClassCircularityError */\r
-#define JVMDI_ERROR_CIRCULAR_CLASS_DEFINITION     ((jvmdiError)61)\r
-  /* The class bytes fail verification */\r
-#define JVMDI_ERROR_FAILS_VERIFICATION            ((jvmdiError)62)\r
-  /* The new class version adds new methods */\r
-  /* and can_add_method is false */\r
-#define JVMDI_ERROR_ADD_METHOD_NOT_IMPLEMENTED    ((jvmdiError)63)\r
-  /* The new class version changes fields */ \r
-  /* and can_unrestrictedly_redefine_classes is false */\r
-#define JVMDI_ERROR_SCHEMA_CHANGE_NOT_IMPLEMENTED ((jvmdiError)64)\r
-  /* bci/operand stack/local var combination is not verifiably */\r
-  /* type safe */\r
-#define JVMDI_ERROR_INVALID_TYPESTATE             ((jvmdiError)65)\r
-  /* A direct superclass is different for the new class */\r
-  /* version, or the set of directly implemented */\r
-  /* interfaces is different */\r
-  /* and can_unrestrictedly_redefine_classes is false */\r
-#define JVMDI_ERROR_HIERARCHY_CHANGE_NOT_IMPLEMENTED ((jvmdiError)66)\r
-  /* The new class version does not declare a method */\r
-  /* declared in the old class version */\r
-  /* and can_unrestrictedly_redefine_classes is false */\r
-#define JVMDI_ERROR_DELETE_METHOD_NOT_IMPLEMENTED ((jvmdiError)67)\r
-  /* A class file has a version number not supported */\r
-  /* by this VM. */\r
-#define JVMDI_ERROR_UNSUPPORTED_VERSION           ((jvmdiError)68)\r
-  /* The class name defined in the new class file is */\r
-  /* different from the name in the old class object */\r
-#define JVMDI_ERROR_NAMES_DONT_MATCH              ((jvmdiError)69)\r
-  /* The new class version has different modifiers and */\r
-  /* can_unrestrictedly_redefine_classes is false */\r
-#define JVMDI_ERROR_CLASS_MODIFIERS_CHANGE_NOT_IMPLEMENTED   ((jvmdiError)70)\r
-  /* A method in the new class version has different modifiers */\r
-  /* than its counterpart in the old class version */\r
-  /* and can_unrestrictedly_redefine_classes is false */\r
-#define JVMDI_ERROR_METHOD_MODIFIERS_CHANGE_NOT_IMPLEMENTED  ((jvmdiError)71)\r
-\r
-  /*\r
-   * Miscellaneous errors\r
-   */\r
-\r
-  /* Not yet implemented */\r
-#define JVMDI_ERROR_NOT_IMPLEMENTED      ((jvmdiError)99)\r
-  /* null pointer */\r
-#define JVMDI_ERROR_NULL_POINTER         ((jvmdiError)100)\r
-  /* information is absent */\r
-#define JVMDI_ERROR_ABSENT_INFORMATION   ((jvmdiError)101)\r
-  /* invalid event type  */\r
-#define JVMDI_ERROR_INVALID_EVENT_TYPE   ((jvmdiError)102)\r
-  /* invalid argument  */\r
-#define JVMDI_ERROR_ILLEGAL_ARGUMENT     ((jvmdiError)103)\r
-\r
-  /*\r
-   * Universal errors. These errors may be returned by\r
-   * any JVMDI function, not just the ones for which they are listed\r
-   * below.\r
-   */\r
-\r
-  /* no more memory available for allocation */\r
-#define JVMDI_ERROR_OUT_OF_MEMORY        ((jvmdiError)110)\r
-  /* debugging has not been enabled in this VM */\r
-#define JVMDI_ERROR_ACCESS_DENIED        ((jvmdiError)111)\r
-  /* VM is dead (implementation not required to gracefully catch) */\r
-#define JVMDI_ERROR_VM_DEAD              ((jvmdiError)112)\r
-  /* internal error  */\r
-#define JVMDI_ERROR_INTERNAL             ((jvmdiError)113)\r
-  /* Thread calling JVMDI function not attached to VM */\r
-#define JVMDI_ERROR_UNATTACHED_THREAD    ((jvmdiError)115)\r
-\r
-\r
-  /*\r
-   *  Threads\r
-   */\r
-\r
-  /* Thread status is unknown */\r
-#define JVMDI_THREAD_STATUS_UNKNOWN      ((jint)-1)\r
-  /* Thread is waiting to die */\r
-#define JVMDI_THREAD_STATUS_ZOMBIE       ((jint)0)\r
-  /* Thread is runnable */\r
-#define JVMDI_THREAD_STATUS_RUNNING      ((jint)1)\r
-  /* Thread is sleeping - Thread.sleep() or JVM_Sleep() was called */\r
-#define JVMDI_THREAD_STATUS_SLEEPING     ((jint)2)\r
-  /* Thread is waiting on a java monitor */\r
-#define JVMDI_THREAD_STATUS_MONITOR      ((jint)3)\r
-  /* Thread is waiting - Thread.wait() or JVM_MonitorWait() was called */\r
-#define JVMDI_THREAD_STATUS_WAIT         ((jint)4)\r
-\r
-  /* Thread is suspended - Thread.suspend(), JVM_Suspend() or\r
-   * JVMDI_Suspend was called */\r
-#define JVMDI_SUSPEND_STATUS_SUSPENDED   ((jint)0x1)\r
-  /* Thread is at a breakpoint */\r
-#define JVMDI_SUSPEND_STATUS_BREAK       ((jint)0x2)\r
-\r
-\r
-  /* Thread priority constants */\r
-#define JVMDI_THREAD_MIN_PRIORITY   ((jint)1)\r
-#define JVMDI_THREAD_NORM_PRIORITY  ((jint)5)\r
-#define JVMDI_THREAD_MAX_PRIORITY   ((jint)10)\r
-\r
-typedef struct {\r
-    char *name;\r
-    jint  priority;\r
-    jboolean is_daemon;\r
-    jthreadGroup thread_group;\r
-    jobject context_class_loader;\r
-} JVMDI_thread_info;\r
-\r
-typedef struct {\r
-    jthreadGroup parent;\r
-    char *name;\r
-    jint  max_priority;\r
-    jboolean is_daemon;\r
-} JVMDI_thread_group_info;\r
-\r
-#define JVMDI_DISABLE ((jint) 0)\r
-#define JVMDI_ENABLE  ((jint) 1)\r
-\r
-/*\r
- * Initial function for debug threads created through JVMDI\r
- */\r
-typedef void (*JVMDI_StartFunction)(void *);\r
-\r
-/*\r
- * Type for debug monitors created through JVMDI\r
- */\r
-typedef void *JVMDI_RawMonitor;\r
-\r
-#define JVMDI_MONITOR_WAIT_FOREVER ((jlong)(-1))\r
-\r
-/*\r
- * Monitor information\r
- */\r
-typedef struct {\r
-    jthread owner;\r
-    jint entry_count;\r
-    jint waiter_count;\r
-    jthread *waiters;\r
-} JVMDI_monitor_info;\r
-\r
-typedef struct {\r
-    jint owned_monitor_count;\r
-    jobject *owned_monitors;\r
-} JVMDI_owned_monitor_info;\r
-\r
-  /*\r
-   *  Events\r
-   */\r
-\r
-    /* kind = JVMDI_EVENT_SINGLE_STEP */\r
-    typedef struct { \r
-        jthread thread;\r
-        jclass clazz;\r
-        jmethodID method;\r
-        jlocation location;\r
-    } JVMDI_single_step_event_data;\r
-                       \r
-    /* kind = JVMDI_EVENT_BREAKPOINT */\r
-    typedef struct { \r
-        jthread thread;\r
-        jclass clazz;\r
-        jmethodID method;\r
-        jlocation location;\r
-    } JVMDI_breakpoint_event_data;\r
-    \r
-    /* kind = JVMDI_EVENT_FIELD_ACCESS */\r
-    typedef struct { \r
-        jthread thread;\r
-        jclass clazz;\r
-        jmethodID method;\r
-        jlocation location;\r
-        jclass field_clazz;\r
-        jobject object;\r
-        jfieldID field;\r
-    } JVMDI_field_access_event_data;\r
-    \r
-    /* kind = JVMDI_EVENT_FIELD_MODIFICATION */\r
-    typedef struct { \r
-        jthread thread;\r
-        jclass clazz;\r
-        jmethodID method;\r
-        jlocation location;\r
-        jclass field_clazz;\r
-        jobject object;\r
-        jfieldID field;\r
-        char signature_type;\r
-        jvalue new_value;\r
-    } JVMDI_field_modification_event_data;\r
-    \r
-    /* kind = JVMDI_EVENT_FRAME_POP */\r
-    /* kind = JVMDI_EVENT_METHOD_ENTRY */\r
-    /* kind = JVMDI_EVENT_METHOD_EXIT */\r
-    typedef struct { \r
-        jthread thread;\r
-        jclass clazz;\r
-        jmethodID method;\r
-        jframeID frame;\r
-    } JVMDI_frame_event_data;\r
-    \r
-    /* kind = JVMDI_EVENT_EXCEPTION */\r
-    typedef struct { \r
-        jthread thread;\r
-        jclass clazz;\r
-        jmethodID method;\r
-        jlocation location;\r
-        jobject exception;\r
-        jclass catch_clazz;\r
-        jmethodID catch_method;\r
-        jlocation catch_location;\r
-    } JVMDI_exception_event_data;\r
-    \r
-    /* kind = JVMDI_EVENT_EXCEPTION_CATCH */\r
-    typedef struct { \r
-        jthread thread;\r
-        jclass clazz;\r
-        jmethodID method;\r
-        jlocation location;\r
-        jobject exception;\r
-    } JVMDI_exception_catch_event_data;\r
-    \r
-    /* kind = JVMDI_EVENT_USER_DEFINED */\r
-    typedef struct { \r
-        jobject object;\r
-        jint key;\r
-    } JVMDI_user_event_data;\r
-    \r
-    /* kind = JVMDI_EVENT_THREAD_END or */\r
-    /* JVMDI_EVENT_THREAD_START */\r
-    typedef struct { \r
-        jthread thread;\r
-    } JVMDI_thread_change_event_data;\r
-    \r
-    /* kind = JVMDI_EVENT_CLASS_LOAD, */\r
-    /* JVMDI_EVENT_CLASS_UNLOAD, or */\r
-    /* JVMDI_EVENT_CLASS_PREPARE */\r
-    typedef struct { \r
-        jthread thread;\r
-        jclass clazz;\r
-    } JVMDI_class_event_data;\r
-    \r
-/* This stucture passes information about the event.\r
- * location is the index of the last instruction executed. \r
- */\r
-typedef struct {\r
-    jint kind;         /* the discriminant */\r
-\r
-    union {\r
-       /* kind = JVMDI_EVENT_SINGLE_STEP */\r
-        JVMDI_single_step_event_data single_step;\r
-                       \r
-        /* kind = JVMDI_EVENT_BREAKPOINT */\r
-        JVMDI_breakpoint_event_data breakpoint;\r
-\r
-        /* kind = JVMDI_EVENT_FRAME_POP */\r
-        /* kind = JVMDI_EVENT_METHOD_ENTRY */\r
-        /* kind = JVMDI_EVENT_METHOD_EXIT */\r
-        JVMDI_frame_event_data frame;\r
-\r
-        /* kind = JVMDI_EVENT_FIELD_ACCESS */\r
-        JVMDI_field_access_event_data field_access;\r
-\r
-        /* kind = JVMDI_EVENT_FIELD_MODIFICATION */\r
-        JVMDI_field_modification_event_data field_modification;\r
-\r
-        /* kind = JVMDI_EVENT_EXCEPTION */\r
-        JVMDI_exception_event_data exception;\r
-\r
-        /* kind = JVMDI_EVENT_EXCEPTION_CATCH */\r
-        JVMDI_exception_catch_event_data exception_catch;\r
-\r
-        /* kind = JVMDI_EVENT_USER_DEFINED */\r
-        JVMDI_user_event_data user;\r
-                       \r
-        /* kind = JVMDI_EVENT_THREAD_END or */\r
-        /* JVMDI_EVENT_THREAD_START */\r
-        JVMDI_thread_change_event_data thread_change;\r
-                       \r
-        /* kind = JVMDI_EVENT_CLASS_LOAD, */\r
-        /* JVMDI_EVENT_CLASS_UNLOAD, or */\r
-        /* JVMDI_EVENT_CLASS_PREPARE */\r
-        JVMDI_class_event_data class_event;\r
-                       \r
-        /* kind = JVMDI_EVENT_VM_DEATH, JVMDI_EVENT_VM_INIT */\r
-        /* no additional fields */             \r
-    } u;\r
-} JVMDI_Event;\r
-\r
-       /*** event kinds ***/\r
-#define JVMDI_EVENT_SINGLE_STEP   ((jint)1)\r
-#define JVMDI_EVENT_BREAKPOINT    ((jint)2)\r
-#define JVMDI_EVENT_FRAME_POP     ((jint)3)\r
-#define JVMDI_EVENT_EXCEPTION     ((jint)4)\r
-#define JVMDI_EVENT_USER_DEFINED  ((jint)5)\r
-#define JVMDI_EVENT_THREAD_START  ((jint)6)\r
-#define JVMDI_EVENT_THREAD_END    ((jint)7)\r
-#define JVMDI_EVENT_CLASS_PREPARE ((jint)8)\r
-#define JVMDI_EVENT_CLASS_UNLOAD  ((jint)9)\r
-#define JVMDI_EVENT_CLASS_LOAD    ((jint)10)\r
-#define JVMDI_EVENT_FIELD_ACCESS       ((jint)20)\r
-#define JVMDI_EVENT_FIELD_MODIFICATION ((jint)21)\r
-#define JVMDI_EVENT_EXCEPTION_CATCH    ((jint)30)\r
-#define JVMDI_EVENT_METHOD_ENTRY       ((jint)40)\r
-#define JVMDI_EVENT_METHOD_EXIT        ((jint)41)\r
-#define JVMDI_EVENT_VM_INIT            ((jint)90)\r
-#define JVMDI_EVENT_VM_DEATH           ((jint)99)\r
-\r
-#define JVMDI_MAX_EVENT_TYPE_VAL       ((jint)99)\r
-\r
-\r
-\r
-/* event handler hook */\r
-typedef void (*JVMDI_EventHook)(JNIEnv *env, JVMDI_Event *event);\r
-\r
-typedef jvmdiError (*JVMDI_AllocHook) (jlong size, jbyte** memPtr);\r
-typedef jvmdiError (*JVMDI_DeallocHook) (jbyte* buffer);\r
-\r
-/*\r
- * Class states used in JVMDI_GetClassStatus\r
- */\r
-#define JVMDI_CLASS_STATUS_VERIFIED          ((jint)0x01)\r
-#define JVMDI_CLASS_STATUS_PREPARED          ((jint)0x02)\r
-#define JVMDI_CLASS_STATUS_INITIALIZED       ((jint)0x04)\r
- /* Error prevents initialization */\r
-#define JVMDI_CLASS_STATUS_ERROR             ((jint)0x08) \r
-\r
-/* structure for returning line number information \r
- */\r
-typedef struct {\r
-    jlocation start_location;\r
-    jint line_number;\r
-} JVMDI_line_number_entry;\r
-\r
-\r
-/* structure for returning local variable information \r
- */\r
-typedef struct {\r
-    jlocation start_location;   /* variable valid start_location */\r
-    jint length;                /* upto start_location+length */ \r
-    char *name;                 /* name in UTF8 */\r
-    char *signature;            /* type signature in UTF8 */\r
-    jint slot;                  /* variable slot, see JVMDI_GetLocal*()  */\r
-} JVMDI_local_variable_entry;\r
-\r
-/* structure for returning exception handler information \r
- */\r
-typedef struct {\r
-    jlocation start_location;\r
-    jlocation end_location;\r
-    jlocation handler_location;\r
-    jclass exception;           /* if null, all exceptions */\r
-} JVMDI_exception_handler_entry;\r
-\r
-#define JVMDI_OPERAND_TYPE_REFERENCE      ((jint)1)\r
-#define JVMDI_OPERAND_TYPE_INT            ((jint)2)\r
-#define JVMDI_OPERAND_TYPE_FLOAT          ((jint)3)\r
-#define JVMDI_OPERAND_TYPE_LONG0          ((jint)4) /* least sig. 32 bits */\r
-#define JVMDI_OPERAND_TYPE_LONG1          ((jint)5) /* most sig. 32 bits */\r
-#define JVMDI_OPERAND_TYPE_DOUBLE0        ((jint)6) /* least sig. 32 bits */\r
-#define JVMDI_OPERAND_TYPE_DOUBLE1        ((jint)7) /* most sig. 32 bits */\r
-#define JVMDI_OPERAND_TYPE_RETURN_ADDRESS ((jint)8)\r
-\r
-typedef struct {\r
-    jint word;                 /* 32 bit operand stack quantities */\r
-    jint type;                 /* type encoding of the operand word */\r
-                               /* one of JVMDI_OPERAND_TYPE_* */\r
-} JVMDI_operand_stack_element;\r
-\r
-typedef struct { \r
-    jint instance_field_count; /* number of instance fields referencing obj */\r
-    struct JVMDI_instance_field {\r
-        jobject instance;      /* instance referencing obj */\r
-        jfieldID field;        /* field holding reference */\r
-    } *instance_fields;        /* instanceField_count of them */\r
-     \r
-    jint static_field_count;   /* number of static fields referencing obj */\r
-    struct JVMDI_static_field {\r
-        jclass clazz;          /* class referencing obj */\r
-        jfieldID static_field; /* field holding reference */\r
-    } *static_fields;          /* static_field_count of them */\r
-    \r
-    jint array_element_count;  /* number of array elements referencing obj */\r
-    struct JVMDI_array_element {\r
-        jobjectArray array;    /* array referencing obj */\r
-        jint index;            /* index holding reference */\r
-    } *array_elements;         /* array_element_count of them */\r
-    \r
-    jint frame_slot_count;     /* number of frame slots referencing obj */\r
-    struct JVMDI_frame_slot {\r
-        jthread thread;        /* thread of the frame */\r
-        jframeID frame;        /* frame referencing obj */\r
-        jint slot;             /* slot holding reference */\r
-    } *frame_slots;            /* frame_slot_count of them */\r
-} JVMDI_object_reference_info;\r
-\r
-/* structure for defining a class\r
-*/\r
-typedef struct {\r
-    jclass clazz;              /* Class object for this class */\r
-    jint class_byte_count;     /* number of bytes defining class (below) */\r
-    jbyte *class_bytes;        /* bytes defining class (in JVM spec */\r
-                               /* Class File Format) */\r
-} JVMDI_class_definition;\r
-\r
-  /* For backwards compatibility */\r
-#define can_change_schema can_unrestrictedly_redefine_classes\r
-\r
-typedef struct {\r
-    unsigned int can_watch_field_modification      : 1;\r
-    unsigned int can_watch_field_access            : 1;\r
-    unsigned int can_get_bytecodes                 : 1;\r
-    unsigned int can_get_synthetic_attribute       : 1;\r
-    unsigned int can_get_owned_monitor_info        : 1;\r
-    unsigned int can_get_current_contended_monitor : 1;\r
-    unsigned int can_get_monitor_info              : 1;\r
-    unsigned int can_get_heap_info                 : 1;\r
-    unsigned int can_get_operand_stack             : 1;\r
-    unsigned int can_set_operand_stack             : 1;\r
-    unsigned int can_pop_frame                     : 1;\r
-    unsigned int can_get_class_definition          : 1;\r
-    unsigned int can_redefine_classes              : 1; \r
-    unsigned int can_add_method                    : 1;\r
-    unsigned int can_unrestrictedly_redefine_classes : 1;\r
-    unsigned int can_suspend_resume_thread_lists   : 1;\r
-} JVMDI_capabilities;\r
-\r
-typedef struct JVMDI_Interface_1_ {\r
-    jvmdiError (JNICALL *SetEventHook)\r
-      (JVMDI_EventHook hook);\r
-    jvmdiError (JNICALL *SetEventNotificationMode)\r
-      (jint mode, jint eventType, jthread thread, ...);\r
-\r
-    jvmdiError (JNICALL *GetThreadStatus)\r
-      (jthread thread,\r
-       jint *threadStatusPtr, jint *suspendStatusPtr);\r
-    jvmdiError (JNICALL *GetAllThreads)\r
-      (jint *threadsCountPtr, jthread **threadsPtr);\r
-    jvmdiError (JNICALL *SuspendThread)\r
-      (jthread thread); \r
-    jvmdiError (JNICALL *ResumeThread)\r
-      (jthread thread);\r
-    jvmdiError (JNICALL *StopThread)\r
-      (jthread thread, jobject exception);\r
-    jvmdiError (JNICALL *InterruptThread)\r
-      (jthread thread);\r
-    jvmdiError (JNICALL *GetThreadInfo)\r
-      (jthread thread, JVMDI_thread_info *infoPtr);\r
-    jvmdiError (JNICALL *GetOwnedMonitorInfo)\r
-      (jthread thread, JVMDI_owned_monitor_info *infoPtr);\r
-    jvmdiError (JNICALL *GetCurrentContendedMonitor)\r
-      (jthread thread, jobject *monitor);\r
-    jvmdiError (JNICALL *RunDebugThread)\r
-      (jthread thread, JVMDI_StartFunction proc, void *arg,\r
-       int priority);\r
-\r
-    jvmdiError (JNICALL *GetTopThreadGroups)\r
-      (jint *groupCountPtr, jthreadGroup **groupsPtr);\r
-    jvmdiError (JNICALL *GetThreadGroupInfo)\r
-      (jthreadGroup group, JVMDI_thread_group_info *infoPtr);\r
-    jvmdiError (JNICALL *GetThreadGroupChildren)\r
-      (jthreadGroup group, \r
-       jint *threadCountPtr, jthread **threadsPtr,\r
-       jint *groupCountPtr, jthreadGroup **groupsPtr);\r
-\r
-    jvmdiError (JNICALL *GetFrameCount)\r
-      (jthread thread, jint *countPtr);\r
-    jvmdiError (JNICALL *GetCurrentFrame)\r
-      (jthread thread, jframeID *framePtr);\r
-    jvmdiError (JNICALL *GetCallerFrame)\r
-      (jframeID called, jframeID *framePtr);\r
-    jvmdiError (JNICALL *GetFrameLocation)\r
-      (jframeID frame, jclass *classPtr, jmethodID *methodPtr,\r
-       jlocation *locationPtr);\r
-    jvmdiError (JNICALL *NotifyFramePop)\r
-      (jframeID frame); \r
-    jvmdiError (JNICALL *GetLocalObject)\r
-      (jframeID frame, jint slot, jobject *valuePtr);\r
-    jvmdiError (JNICALL *GetLocalInt)\r
-      (jframeID frame, jint slot, jint *valuePtr);\r
-    jvmdiError (JNICALL *GetLocalLong)\r
-      (jframeID frame, jint slot, jlong *valuePtr);\r
-    jvmdiError (JNICALL *GetLocalFloat)\r
-      (jframeID frame, jint slot, jfloat *valuePtr);\r
-    jvmdiError (JNICALL *GetLocalDouble)\r
-      (jframeID frame, jint slot, jdouble *valuePtr);\r
-    jvmdiError (JNICALL *SetLocalObject)\r
-      (jframeID frame, jint slot, jobject value);\r
-    jvmdiError (JNICALL *SetLocalInt)\r
-      (jframeID frame, jint slot, jint value);\r
-    jvmdiError (JNICALL *SetLocalLong)\r
-      (jframeID frame, jint slot, jlong value);\r
-    jvmdiError (JNICALL *SetLocalFloat)\r
-      (jframeID frame, jint slot, jfloat value);\r
-    jvmdiError (JNICALL *SetLocalDouble)\r
-      (jframeID frame, jint slot, jdouble value);\r
-\r
-    jvmdiError (JNICALL *CreateRawMonitor)\r
-      (char *name, JVMDI_RawMonitor *monitorPtr);\r
-    jvmdiError (JNICALL *DestroyRawMonitor)\r
-      (JVMDI_RawMonitor monitor);\r
-    jvmdiError (JNICALL *RawMonitorEnter)\r
-      (JVMDI_RawMonitor monitor);\r
-    jvmdiError (JNICALL *RawMonitorExit)\r
-      (JVMDI_RawMonitor monitor);\r
-    jvmdiError (JNICALL *RawMonitorWait)\r
-      (JVMDI_RawMonitor monitor, jlong millis);\r
-    jvmdiError (JNICALL *RawMonitorNotify)\r
-      (JVMDI_RawMonitor monitor);\r
-    jvmdiError (JNICALL *RawMonitorNotifyAll)\r
-      (JVMDI_RawMonitor monitor);\r
-\r
-    jvmdiError (JNICALL *SetBreakpoint)\r
-      (jclass clazz, jmethodID method, jlocation location);\r
-    jvmdiError (JNICALL *ClearBreakpoint)\r
-      (jclass clazz, jmethodID method, jlocation location);\r
-    jvmdiError (JNICALL *ClearAllBreakpoints)\r
-      ();\r
-\r
-    jvmdiError (JNICALL *SetFieldAccessWatch)\r
-      (jclass clazz, jfieldID field);\r
-    jvmdiError (JNICALL *ClearFieldAccessWatch)\r
-      (jclass clazz, jfieldID field);\r
-    jvmdiError (JNICALL *SetFieldModificationWatch)\r
-      (jclass clazz, jfieldID field);\r
-    jvmdiError (JNICALL *ClearFieldModificationWatch)\r
-      (jclass clazz, jfieldID field);\r
-\r
-    jvmdiError (JNICALL *SetAllocationHooks)\r
-      (JVMDI_AllocHook ahook, JVMDI_DeallocHook dhook);\r
-    jvmdiError (JNICALL *Allocate)\r
-      (jlong size, jbyte** memPtr);\r
-    jvmdiError (JNICALL *Deallocate)\r
-      (jbyte* mem);\r
-\r
-    jvmdiError (JNICALL *GetClassSignature)\r
-      (jclass clazz, char **sigPtr);\r
-    jvmdiError (JNICALL *GetClassStatus)\r
-      (jclass clazz, jint *statusPtr);\r
-    jvmdiError (JNICALL *GetSourceFileName)\r
-      (jclass clazz, char **sourceNamePtr);\r
-    jvmdiError (JNICALL *GetClassModifiers)\r
-      (jclass clazz, jint *modifiersPtr);\r
-    jvmdiError (JNICALL *GetClassMethods)\r
-      (jclass clazz, jint *methodCountPtr, jmethodID **methodsPtr);\r
-    jvmdiError (JNICALL *GetClassFields)\r
-       (jclass clazz, jint *fieldCountPtr, jfieldID **fieldsPtr);\r
-    jvmdiError (JNICALL *GetImplementedInterfaces)\r
-      (jclass clazz, jint *interfaceCountPtr, jclass **interfacesPtr);\r
-    jvmdiError (JNICALL *IsInterface)\r
-      (jclass clazz, jboolean *isInterfacePtr);\r
-    jvmdiError (JNICALL *IsArrayClass)\r
-      (jclass clazz, jboolean *isArrayClassPtr);\r
-    jvmdiError (JNICALL *GetClassLoader)\r
-      (jclass clazz, jobject *classloaderPtr);\r
-\r
-    jvmdiError (JNICALL *GetObjectHashCode)\r
-      (jobject object, jint *hashCodePtr);\r
-    jvmdiError (JNICALL *GetMonitorInfo)\r
-      (jobject object, JVMDI_monitor_info *infoPtr);\r
-\r
-    jvmdiError (JNICALL *GetFieldName)\r
-      (jclass clazz, jfieldID field, char **namePtr, char **signaturePtr);\r
-    jvmdiError (JNICALL *GetFieldDeclaringClass)\r
-      (jclass clazz, jfieldID field, jclass *declaringClassPtr);\r
-    jvmdiError (JNICALL *GetFieldModifiers)\r
-      (jclass clazz, jfieldID field, jint *modifiersPtr);\r
-    jvmdiError (JNICALL *IsFieldSynthetic)\r
-      (jclass clazz, jfieldID field, jboolean *isSyntheticPtr);\r
-\r
-    jvmdiError (JNICALL *GetMethodName)\r
-      (jclass clazz, jmethodID method, \r
-       char **namePtr, char **signaturePtr);\r
-    jvmdiError (JNICALL *GetMethodDeclaringClass)\r
-      (jclass clazz, jmethodID method, jclass *declaringClassPtr);\r
-    jvmdiError (JNICALL *GetMethodModifiers)\r
-      (jclass clazz, jmethodID method, jint *modifiersPtr);\r
-    jvmdiError (JNICALL *GetMaxStack)\r
-      (jclass clazz, jmethodID method, jint *maxPtr);\r
-    jvmdiError (JNICALL *GetMaxLocals)\r
-      (jclass clazz, jmethodID method, jint *maxPtr);\r
-    jvmdiError (JNICALL *GetArgumentsSize)\r
-      (jclass clazz, jmethodID method, jint *sizePtr);\r
-    jvmdiError (JNICALL *GetLineNumberTable)\r
-      (jclass clazz, jmethodID method,\r
-       jint *entryCountPtr, JVMDI_line_number_entry **tablePtr);\r
-    jvmdiError (JNICALL *GetMethodLocation)\r
-      (jclass clazz, jmethodID method,\r
-       jlocation *startLocationPtr, jlocation *endLocationPtr);\r
-    jvmdiError (JNICALL *GetLocalVariableTable)\r
-      (jclass clazz, jmethodID method,\r
-       jint *entryCountPtr, JVMDI_local_variable_entry **tablePtr);\r
-    jvmdiError (JNICALL *GetExceptionHandlerTable)\r
-      (jclass clazz, jmethodID method,\r
-       jint *entryCountPtr, JVMDI_exception_handler_entry **tablePtr);\r
-    jvmdiError (JNICALL *GetThrownExceptions)\r
-      (jclass clazz, jmethodID method,\r
-       jint *exceptionCountPtr, jclass **exceptionsPtr);\r
-    jvmdiError (JNICALL *GetBytecodes)\r
-      (jclass clazz, jmethodID method,\r
-       jint *bytecodeCountPtr, jbyte **bytecodesPtr);\r
-    jvmdiError (JNICALL *IsMethodNative)\r
-      (jclass clazz, jmethodID method, jboolean *isNativePtr);\r
-    jvmdiError (JNICALL *IsMethodSynthetic)\r
-      (jclass clazz, jmethodID method, jboolean *isSyntheticPtr);\r
-\r
-    jvmdiError (JNICALL *GetLoadedClasses)\r
-      (jint *classCountPtr, jclass **classesPtr);\r
-    jvmdiError (JNICALL *GetClassLoaderClasses)\r
-      (jobject initiatingLoader, jint *classesCountPtr, \r
-       jclass **classesPtr);\r
-\r
-    jvmdiError (JNICALL *PopFrame)\r
-      (jthread thread);\r
-    jvmdiError (JNICALL *SetFrameLocation)\r
-      (jframeID frame, jlocation location);\r
-    jvmdiError (JNICALL *GetOperandStack)\r
-      (jframeID frame, jint *operandStackSizePtr, \r
-       JVMDI_operand_stack_element **operandStackPtr);\r
-    jvmdiError (JNICALL *SetOperandStack)\r
-      (jframeID frame, jint operandStackSize, \r
-       JVMDI_operand_stack_element *operandStack);\r
-    jvmdiError (JNICALL *AllInstances)\r
-      (jclass clazz, jint *instanceCountPtr, jobject **instancesPtr);\r
-    jvmdiError (JNICALL *References)\r
-      (jobject obj, JVMDI_object_reference_info *refs);\r
-    jvmdiError (JNICALL *GetClassDefinition)\r
-      (jclass clazz, JVMDI_class_definition *classDefPtr);\r
-    jvmdiError (JNICALL *RedefineClasses)\r
-      (jint classCount, JVMDI_class_definition *classDefs);\r
-\r
-    jvmdiError (JNICALL *GetVersionNumber)\r
-      (jint *versionPtr);\r
-    jvmdiError (JNICALL *GetCapabilities)\r
-      (JVMDI_capabilities *capabilitiesPtr);\r
-\r
-    jvmdiError (JNICALL *GetSourceDebugExtension)\r
-      (jclass clazz, char **sourceDebugExtension);\r
-    jvmdiError (JNICALL *IsMethodObsolete)\r
-      (jclass clazz, jmethodID method, jboolean *isObsoletePtr);\r
-\r
-    jvmdiError (JNICALL *SuspendThreadList)\r
-      (jint reqCount, jthread *reqList, jvmdiError *results); \r
-    jvmdiError (JNICALL *ResumeThreadList)\r
-      (jint reqCount, jthread *reqList, jvmdiError *results); \r
-} JVMDI_Interface_1;\r
-  \r
-#ifndef NO_JVMDI_MACROS\r
-\r
-#define JVMDI_ERROR_DUPLICATE_BREAKPOINT JVMDI_ERROR_DUPLICATE\r
-#define JVMDI_ERROR_NO_SUCH_BREAKPOINT   JVMDI_ERROR_NOT_FOUND\r
-#define JVMDI_ERROR_DUPLICATE_FRAME_POP  JVMDI_ERROR_DUPLICATE\r
-\r
-\r
-static JVMDI_Interface_1 *jvmdi_interface = NULL;\r
-static JavaVM *j_vm;\r
-\r
-#ifdef __cplusplus\r
-#define SetJVMDIfromJNIEnv(a_env) ( (jvmdi_interface == NULL)?  \\r
-              ((a_env)->GetJavaVM(&j_vm),  \\r
-               (j_vm)->GetEnv((void **)&jvmdi_interface,  \\r
-                               JVMDI_VERSION_1)):0)\r
-#else\r
-#define SetJVMDIfromJNIEnv(a_env) ( (jvmdi_interface == NULL)?  \\r
-              ((*a_env)->GetJavaVM(a_env, &j_vm), \\r
-               (*j_vm)->GetEnv(j_vm, (void **)&jvmdi_interface, \\r
-                               JVMDI_VERSION_1)):0)\r
-#endif\r
-\r
-#define JVMDI_SetEventHook(a_env, a1) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->SetEventHook(a1) )\r
-#define JVMDI_GetThreadStatus(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetThreadStatus(a1, a2, a3) )\r
-#define JVMDI_GetAllThreads(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetAllThreads(a1, a2) )\r
-#define JVMDI_SuspendThread(a_env, a1) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->SuspendThread(a1) )\r
-#define JVMDI_ResumeThread(a_env, a1) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->ResumeThread(a1) )\r
-#define JVMDI_StopThread(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->StopThread(a1, a2) )\r
-#define JVMDI_InterruptThread(a_env, a1) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->InterruptThread(a1) )\r
-#define JVMDI_SetSingleStep(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->SetEventNotificationMode( \\r
-                                       (a2) ? JVMDI_ENABLE : JVMDI_DISABLE, \\r
-                                        JVMDI_EVENT_SINGLE_STEP, a1) )\r
-#define JVMDI_GetThreadInfo(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetThreadInfo(a1, a2) )\r
-#define JVMDI_RunDebugThread(a_env, a1, a2, a3, a4) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->RunDebugThread(a1, a2, a3, a4) )\r
-#define JVMDI_GetTopThreadGroups(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetTopThreadGroups(a1, a2) )\r
-#define JVMDI_GetThreadGroupInfo(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetThreadGroupInfo(a1, a2) )\r
-#define JVMDI_GetThreadGroupChildren(a_env, a1, a2, a3, a4, a5) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetThreadGroupChildren(a1, a2, a3, a4, a5) )\r
-#define JVMDI_GetCurrentFrame(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetCurrentFrame(a1, a2) )\r
-#define JVMDI_GetCallerFrame(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetCallerFrame(a1, a2) )\r
-#define JVMDI_GetFrameLocation(a_env, a1, a2, a3, a4) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetFrameLocation(a1, a2, a3, a4) )\r
-#define JVMDI_NotifyFramePop(a_env, a1) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->NotifyFramePop(a1) )\r
-#define JVMDI_GetLocalObject(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetLocalObject(a1, a2, a3) )\r
-#define JVMDI_GetLocalInt(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetLocalInt(a1, a2, a3) )\r
-#define JVMDI_GetLocalLong(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetLocalLong(a1, a2, a3) )\r
-#define JVMDI_GetLocalFloat(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetLocalFloat(a1, a2, a3) )\r
-#define JVMDI_GetLocalDouble(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetLocalDouble(a1, a2, a3) )\r
-#define JVMDI_SetLocalObject(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->SetLocalObject(a1, a2, a3) )\r
-#define JVMDI_SetLocalInt(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->SetLocalInt(a1, a2, a3) )\r
-#define JVMDI_SetLocalLong(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->SetLocalLong(a1, a2, a3) )\r
-#define JVMDI_SetLocalFloat(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->SetLocalFloat(a1, a2, a3) )\r
-#define JVMDI_SetLocalDouble(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->SetLocalDouble(a1, a2, a3) )\r
-#define JVMDI_CreateRawMonitor(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->CreateRawMonitor(a1, a2) )\r
-#define JVMDI_DestroyRawMonitor(a_env, a1) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->DestroyRawMonitor(a1) )\r
-#define JVMDI_RawMonitorEnter(a_env, a1) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->RawMonitorEnter(a1) )\r
-#define JVMDI_RawMonitorExit(a_env, a1) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->RawMonitorExit(a1) )\r
-#define JVMDI_RawMonitorWait(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->RawMonitorWait(a1, a2) )\r
-#define JVMDI_RawMonitorNotify(a_env, a1) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->RawMonitorNotify(a1) )\r
-#define JVMDI_RawMonitorNotifyAll(a_env, a1) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->RawMonitorNotifyAll(a1) )\r
-#define JVMDI_SetBreakpoint(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->SetBreakpoint(a1, a2, a3) )\r
-#define JVMDI_ClearBreakpoint(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->ClearBreakpoint(a1, a2, a3) )\r
-#define JVMDI_ClearAllBreakpoints(a_env) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->ClearAllBreakpoints() )\r
-#define JVMDI_SetAllocationHooks(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->SetAllocationHooks(a1, a2) )\r
-#define JVMDI_Allocate(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->Allocate(a1, a2) )\r
-#define JVMDI_Deallocate(a_env, a1) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->Deallocate(a1) )\r
-#define JVMDI_GetClassSignature(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetClassSignature(a1, a2) )\r
-#define JVMDI_GetClassStatus(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetClassStatus(a1, a2) )\r
-#define JVMDI_GetSourceFileName(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetSourceFileName(a1, a2) )\r
-#define JVMDI_GetClassModifiers(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetClassModifiers(a1, a2) )\r
-#define JVMDI_GetClassMethods(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetClassMethods(a1, a2, a3) )\r
-#define JVMDI_GetClassFields(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetClassFields(a1, a2, a3) )\r
-#define JVMDI_GetImplementedInterfaces(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetImplementedInterfaces(a1, a2, a3) )\r
-#define JVMDI_IsInterface(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->IsInterface(a1, a2) )\r
-#define JVMDI_IsArrayClass(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->IsArrayClass(a1, a2) )\r
-#define JVMDI_ClassLoader(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetClassLoader(a1, a2) )\r
-#define JVMDI_GetFieldName(a_env, a1, a2, a3, a4) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetFieldName(a1, a2, a3, a4) )\r
-#define JVMDI_GetFieldDeclaringClass(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetFieldDeclaringClass(a1, a2, a3) )\r
-#define JVMDI_GetFieldModifiers(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetFieldModifiers(a1, a2, a3) )\r
-#define JVMDI_GetMethodName(a_env, a1, a2, a3, a4) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetMethodName(a1, a2, a3, a4) )\r
-#define JVMDI_GetMethodDeclaringClass(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetMethodDeclaringClass(a1, a2, a3) )\r
-#define JVMDI_GetMethodModifiers(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetMethodModifiers(a1, a2, a3) )\r
-#define JVMDI_GetMaxStack(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetMaxStack(a1, a2, a3) )\r
-#define JVMDI_GetMaxLocals(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetMaxLocals(a1, a2, a3) )\r
-#define JVMDI_GetArgumentsSize(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetArgumentsSize(a1, a2, a3) )\r
-#define JVMDI_GetLineNumberTable(a_env, a1, a2, a3, a4) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetLineNumberTable(a1, a2, a3, a4) )\r
-#define JVMDI_GetMethodLocation(a_env, a1, a2, a3, a4) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetMethodLocation(a1, a2, a3, a4) )\r
-#define JVMDI_GetLocalVariableTable(a_env, a1, a2, a3, a4) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetLocalVariableTable(a1, a2, a3, a4) )\r
-#define JVMDI_GetExceptionHandlerTable(a_env, a1, a2, a3, a4) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetExceptionHandlerTable(a1, a2, a3, a4) )\r
-#define JVMDI_GetThrownExceptions(a_env, a1, a2, a3, a4) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetThrownExceptions(a1, a2, a3, a4) )\r
-#define JVMDI_GetBytecodes(a_env, a1, a2, a3, a4) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetBytecodes(a1, a2, a3, a4) )\r
-#define JVMDI_IsMethodNative(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->IsMethodNative(a1, a2, a3) )\r
-#define JVMDI_GetLoadedClasses(a_env, a1, a2) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetLoadedClasses(a1, a2) )\r
-#define JVMDI_GetClassLoaderClasses(a_env, a1, a2, a3) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetClassLoaderClasses(a1, a2, a3) )\r
-#define JVMDI_GetVersionNumber(a_env, a1) ( \\r
-              SetJVMDIfromJNIEnv(a_env), \\r
-              jvmdi_interface->GetVersionNumber(a1) )\r
-\r
-#endif /* !NO_JVMDI_MACROS */\r
-\r
-#ifdef __cplusplus\r
-} /* extern "C" */\r
-#endif /* __cplusplus */\r
-\r
-#endif /* !_JAVASOFT_JVMDI_H_ */\r
-\r
-\r
diff --git a/JavaOpenJPEG/java-jni/include/jvmpi.h b/JavaOpenJPEG/java-jni/include/jvmpi.h
deleted file mode 100644 (file)
index 557b231..0000000
+++ /dev/null
@@ -1,642 +0,0 @@
-/*\r
- * @(#)jvmpi.h 1.28 03/12/19\r
- *\r
- * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
- * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
- */\r
-\r
-#ifndef _JAVASOFT_JVMPI_H_\r
-#define _JAVASOFT_JVMPI_H_\r
-\r
-#include "jni.h"\r
-\r
-#define JVMPI_VERSION_1   ((jint)0x10000001)  /* implied 0 for minor version */\r
-#define JVMPI_VERSION_1_1 ((jint)0x10000002)\r
-#define JVMPI_VERSION_1_2 ((jint)0x10000003)\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-  typedef void (*jvmpi_void_function_of_void)(void *);\r
-#ifdef __cplusplus\r
-}\r
-#endif\r
-\r
-/****************************************************************\r
- * Profiler interface data structures.\r
- ****************************************************************/\r
-/* identifier types. */\r
-struct _jobjectID;\r
-typedef struct _jobjectID * jobjectID;       /* type of object ids */ \r
-\r
-/* raw monitors */\r
-struct _JVMPI_RawMonitor;\r
-typedef struct _JVMPI_RawMonitor * JVMPI_RawMonitor;\r
-\r
-/* call frame */\r
-typedef struct {\r
-    jint lineno;                      /* line number in the source file */\r
-    jmethodID method_id;              /* method executed in this frame */\r
-} JVMPI_CallFrame;\r
-\r
-/* call trace */\r
-typedef struct {\r
-    JNIEnv *env_id;                   /* Env where trace was recorded */\r
-    jint num_frames;                  /* number of frames in this trace */\r
-    JVMPI_CallFrame *frames;          /* frames */\r
-} JVMPI_CallTrace;\r
-\r
-/* method */\r
-typedef struct {\r
-    char *method_name;                /* name of method */\r
-    char *method_signature;           /* signature of method */\r
-    jint start_lineno;                /* -1 if native, abstract .. */\r
-    jint end_lineno;                  /* -1 if native, abstract .. */\r
-    jmethodID method_id;              /* id assigned to this method */\r
-} JVMPI_Method;\r
-\r
-/* Field */\r
-typedef struct {\r
-    char *field_name;                 /* name of field */\r
-    char *field_signature;            /* signature of field */\r
-} JVMPI_Field;\r
-\r
-/* line number info for a compiled method */\r
-typedef struct {\r
-    jint offset;                      /* offset from beginning of method */\r
-    jint lineno;                      /* lineno from beginning of src file */\r
-} JVMPI_Lineno;\r
-\r
-/* event */\r
-typedef struct {\r
-    jint event_type;                  /* event_type */\r
-    JNIEnv *env_id;                   /* env where this event occured */\r
-  \r
-    union {\r
-        struct {\r
-           const char *class_name;   /* class name */\r
-           char *source_name;        /* name of source file */\r
-           jint num_interfaces;      /* number of interfaces implemented */\r
-           jint num_methods;         /* number of methods in the class */\r
-           JVMPI_Method *methods;    /* methods */\r
-           jint num_static_fields;   /* number of static fields */\r
-           JVMPI_Field *statics;     /* static fields */\r
-           jint num_instance_fields; /* number of instance fields */\r
-           JVMPI_Field *instances;   /* instance fields */\r
-           jobjectID class_id;       /* id of the class object */\r
-       } class_load;\r
-\r
-        struct {\r
-           jobjectID class_id;       /* id of the class object */\r
-       } class_unload;\r
-\r
-        struct {\r
-           unsigned char *class_data;        /* content of class file */\r
-           jint class_data_len;              /* class file length */\r
-           unsigned char *new_class_data;    /* instrumented class file */\r
-           jint new_class_data_len;          /* new class file length */\r
-           void * (*malloc_f)(unsigned int); /* memory allocation function */\r
-       } class_load_hook;\r
-\r
-        struct {\r
-            jint arena_id;\r
-           jobjectID class_id;       /* id of object class */\r
-           jint is_array;            /* JVMPI_NORMAL_OBJECT, ... */\r
-           jint size;                /* size in number of bytes */\r
-           jobjectID obj_id;         /* id assigned to this object */\r
-        } obj_alloc;\r
-\r
-        struct {\r
-           jobjectID obj_id;         /* id of the object */\r
-       } obj_free;\r
-\r
-        struct {\r
-           jint arena_id;            /* cur arena id */\r
-           jobjectID obj_id;         /* cur object id */\r
-           jint new_arena_id;        /* new arena id */\r
-           jobjectID new_obj_id;     /* new object id */         \r
-       } obj_move;\r
-\r
-        struct {\r
-           jint arena_id;            /* id of arena */\r
-           const char *arena_name;   /* name of arena */\r
-       } new_arena;\r
-\r
-        struct {\r
-           jint arena_id;            /* id of arena */\r
-       } delete_arena;\r
-\r
-        struct {\r
-           char *thread_name;        /* name of thread */\r
-           char *group_name;         /* name of group */\r
-           char *parent_name;        /* name of parent */\r
-           jobjectID thread_id;      /* id of the thread object */\r
-           JNIEnv *thread_env_id;\r
-        } thread_start;\r
-\r
-        struct {\r
-           int dump_level;           /* level of the heap dump info */\r
-           char *begin;              /* where all the root records begin,\r
-                                        please see the heap dump buffer \r
-                                        format described below */\r
-           char *end;                /* where the object records end. */\r
-           jint num_traces;          /* number of thread traces, \r
-                                        0 if dump level = JVMPI_DUMP_LEVEL_0 */\r
-           JVMPI_CallTrace *traces;  /* thread traces collected during \r
-                                        heap dump */ \r
-       } heap_dump;\r
-\r
-        struct {\r
-           jobjectID obj_id;         /* object id */\r
-           jobject ref_id;           /* id assigned to the globalref */\r
-       } jni_globalref_alloc;\r
-      \r
-        struct {\r
-           jobject ref_id;           /* id of the global ref */\r
-       } jni_globalref_free;\r
-\r
-        struct {\r
-           jmethodID method_id;      /* method */\r
-       } method;\r
-\r
-        struct {\r
-           jmethodID method_id;      /* id of method */\r
-           jobjectID obj_id;         /* id of target object */\r
-       } method_entry2;\r
-\r
-        struct {\r
-           jmethodID method_id;        /* id of compiled method */\r
-           void *code_addr;            /* code start addr. in memory */\r
-           jint code_size;             /* code size */\r
-           jint lineno_table_size;     /* size of lineno table */\r
-           JVMPI_Lineno *lineno_table; /* lineno info */\r
-       } compiled_method_load;\r
-        \r
-        struct {\r
-           jmethodID method_id;        /* id of unloaded compiled method */\r
-       } compiled_method_unload;\r
-\r
-       struct {\r
-           jmethodID method_id; /* id of the method the instruction belongs to */\r
-           jint offset;         /* instruction offset in the method's bytecode */\r
-           union {\r
-               struct {\r
-                   jboolean is_true; /* whether true or false branch is taken  */\r
-               } if_info;\r
-               struct {\r
-                   jint key; /* top stack value used as an index */\r
-                   jint low; /* min value of the index           */\r
-                   jint hi;  /* max value of the index           */\r
-               } tableswitch_info;\r
-               struct {\r
-                   jint chosen_pair_index; /* actually chosen pair index (0-based)\r
-                                             * if chosen_pair_index == pairs_total then\r
-                                             * the 'default' branch is taken\r
-                                             */\r
-                   jint pairs_total;       /* total number of lookupswitch pairs */\r
-               } lookupswitch_info;\r
-           } u;\r
-       } instruction;\r
-       \r
-        struct {\r
-           char *begin;                /* beginning of dump buffer, \r
-                                          see below for format */\r
-           char *end;                  /* end of dump buffer */\r
-           jint num_traces;            /* number of traces */\r
-           JVMPI_CallTrace *traces;    /* traces of all threads */\r
-           jint *threads_status;       /* status of all threads */\r
-       } monitor_dump;\r
-\r
-        struct {\r
-           const char *name;           /* name of raw monitor */\r
-           JVMPI_RawMonitor id;        /* id */\r
-       } raw_monitor;\r
-\r
-        struct {\r
-           jobjectID object;           /* Java object */\r
-       } monitor;\r
-\r
-        struct {\r
-           jobjectID object;           /* Java object */\r
-           jlong timeout;              /* timeout period */\r
-       } monitor_wait;\r
-\r
-        struct {\r
-           jlong used_objects;\r
-           jlong used_object_space;\r
-           jlong total_object_space;\r
-       } gc_info;\r
-\r
-        struct {\r
-           jint data_len;\r
-           char *data;\r
-       } object_dump;\r
-    } u;\r
-} JVMPI_Event;\r
-\r
-/* interface functions */\r
-typedef struct {\r
-    jint version;   /* JVMPI version */\r
-    \r
-    /* ------interface implemented by the profiler------ */\r
-\r
-    /**\r
-     * Function called by the JVM to notify an event. \r
-     */\r
-    void (*NotifyEvent)(JVMPI_Event *event);\r
-  \r
-    /* ------interface implemented by the JVM------ */\r
-    \r
-    /**\r
-     * Function called by the profiler to enable/disable/send notification \r
-     * for a particular event type.  \r
-     * \r
-     * event_type - event_type\r
-     * arg - event specific arg\r
-     *\r
-     * return JVMPI_NOT_AVAILABLE, JVMPI_SUCCESS or JVMPI_FAIL\r
-     */\r
-    jint (*EnableEvent)(jint event_type, void *arg);\r
-    jint (*DisableEvent)(jint event_type, void *arg);\r
-    jint (*RequestEvent)(jint event_type, void *arg);\r
-  \r
-    /**\r
-     * Function called by the profiler to get a stack\r
-     * trace from the JVM.\r
-     *\r
-     * trace - trace data structure to be filled\r
-     * depth - maximum depth of the trace.\r
-     */\r
-    void (*GetCallTrace)(JVMPI_CallTrace *trace, jint depth);\r
-\r
-    /**\r
-     * Function called by profiler when it wants to exit/stop.\r
-     */\r
-    void (*ProfilerExit)(jint);\r
-\r
-    /**\r
-     * Utility functions provided by the JVM.\r
-     */\r
-    JVMPI_RawMonitor (*RawMonitorCreate)(char *lock_name);\r
-    void (*RawMonitorEnter)(JVMPI_RawMonitor lock_id);\r
-    void (*RawMonitorExit)(JVMPI_RawMonitor lock_id);\r
-    void (*RawMonitorWait)(JVMPI_RawMonitor lock_id, jlong ms);\r
-    void (*RawMonitorNotifyAll)(JVMPI_RawMonitor lock_id);\r
-    void (*RawMonitorDestroy)(JVMPI_RawMonitor lock_id);\r
-\r
-    /**\r
-     * Function called by the profiler to get the current thread's CPU time.\r
-     *\r
-     * return time in nanoseconds;\r
-     */\r
-    jlong (*GetCurrentThreadCpuTime)(void);\r
-\r
-    void (*SuspendThread)(JNIEnv *env);\r
-    void (*ResumeThread)(JNIEnv *env);\r
-    jint (*GetThreadStatus)(JNIEnv *env);\r
-    jboolean (*ThreadHasRun)(JNIEnv *env);\r
-\r
-    /* This function can be called safely only after JVMPI_EVENT_VM_INIT_DONE\r
-       notification by the JVM. */\r
-    jint (*CreateSystemThread)(char *name, jint priority, void (*f)(void *));\r
-\r
-    /* thread local storage access functions to avoid locking in time \r
-       critical functions */\r
-    void (*SetThreadLocalStorage)(JNIEnv *env_id, void *ptr);\r
-    void * (*GetThreadLocalStorage)(JNIEnv *env_id);\r
-\r
-    /* control GC */\r
-    void (*DisableGC)(void);\r
-    void (*EnableGC)(void);\r
-    void (*RunGC)(void);\r
-\r
-    jobjectID (*GetThreadObject)(JNIEnv *env);\r
-    jobjectID (*GetMethodClass)(jmethodID mid);\r
-\r
-    /* JNI <-> jobject conversions */\r
-    jobject   (*jobjectID2jobject)(jobjectID jid);\r
-    jobjectID (*jobject2jobjectID)(jobject jobj);\r
-\r
-    void (*SuspendThreadList)\r
-      (jint reqCount, JNIEnv **reqList, jint *results);\r
-    void (*ResumeThreadList)\r
-      (jint reqCount, JNIEnv **reqList, jint *results);\r
-} JVMPI_Interface;\r
-\r
-/* type of argument passed to RequestEvent for heap dumps */\r
-typedef struct {\r
-    jint heap_dump_level;\r
-} JVMPI_HeapDumpArg;\r
-\r
-/**********************************************************************\r
- * Constants and formats used in JVM Profiler Interface.\r
- **********************************************************************/\r
-/*\r
- * Event type constants.\r
- */\r
-#define JVMPI_EVENT_METHOD_ENTRY            ((jint)1) \r
-#define JVMPI_EVENT_METHOD_ENTRY2           ((jint)2) \r
-#define JVMPI_EVENT_METHOD_EXIT             ((jint)3) \r
-\r
-#define JVMPI_EVENT_OBJECT_ALLOC            ((jint)4) \r
-#define JVMPI_EVENT_OBJECT_FREE             ((jint)5) \r
-#define JVMPI_EVENT_OBJECT_MOVE             ((jint)6) \r
-\r
-#define JVMPI_EVENT_COMPILED_METHOD_LOAD    ((jint)7) \r
-#define JVMPI_EVENT_COMPILED_METHOD_UNLOAD  ((jint)8) \r
-\r
-#define JVMPI_EVENT_INSTRUCTION_START       ((jint)9) \r
-\r
-#define JVMPI_EVENT_THREAD_START           ((jint)33) \r
-#define JVMPI_EVENT_THREAD_END             ((jint)34) \r
-\r
-#define JVMPI_EVENT_CLASS_LOAD_HOOK        ((jint)35) \r
-\r
-#define JVMPI_EVENT_HEAP_DUMP                     ((jint)37) \r
-#define JVMPI_EVENT_JNI_GLOBALREF_ALLOC           ((jint)38) \r
-#define JVMPI_EVENT_JNI_GLOBALREF_FREE            ((jint)39) \r
-#define JVMPI_EVENT_JNI_WEAK_GLOBALREF_ALLOC      ((jint)40) \r
-#define JVMPI_EVENT_JNI_WEAK_GLOBALREF_FREE       ((jint)41) \r
-#define JVMPI_EVENT_CLASS_LOAD                    ((jint)42) \r
-#define JVMPI_EVENT_CLASS_UNLOAD                  ((jint)43) \r
-#define JVMPI_EVENT_DATA_DUMP_REQUEST             ((jint)44) \r
-#define JVMPI_EVENT_DATA_RESET_REQUEST            ((jint)45) \r
-\r
-#define JVMPI_EVENT_JVM_INIT_DONE          ((jint)46) \r
-#define JVMPI_EVENT_JVM_SHUT_DOWN          ((jint)47) \r
-\r
-#define JVMPI_EVENT_ARENA_NEW              ((jint)48)\r
-#define JVMPI_EVENT_ARENA_DELETE           ((jint)49)\r
-\r
-#define JVMPI_EVENT_OBJECT_DUMP            ((jint)50)\r
-\r
-#define JVMPI_EVENT_RAW_MONITOR_CONTENDED_ENTER   ((jint)51)\r
-#define JVMPI_EVENT_RAW_MONITOR_CONTENDED_ENTERED ((jint)52)\r
-#define JVMPI_EVENT_RAW_MONITOR_CONTENDED_EXIT    ((jint)53)\r
-#define JVMPI_EVENT_MONITOR_CONTENDED_ENTER       ((jint)54)\r
-#define JVMPI_EVENT_MONITOR_CONTENDED_ENTERED     ((jint)55)\r
-#define JVMPI_EVENT_MONITOR_CONTENDED_EXIT        ((jint)56)\r
-#define JVMPI_EVENT_MONITOR_WAIT                  ((jint)57)\r
-#define JVMPI_EVENT_MONITOR_WAITED                ((jint)58)\r
-#define JVMPI_EVENT_MONITOR_DUMP                  ((jint)59)\r
-\r
-#define JVMPI_EVENT_GC_START                      ((jint)60)\r
-#define JVMPI_EVENT_GC_FINISH                     ((jint)61)\r
-\r
-#define JVMPI_MAX_EVENT_TYPE_VAL                  ((jint)61)\r
-\r
-/* old definitions, to be removed */\r
-#define JVMPI_EVENT_LOAD_COMPILED_METHOD          ((jint)7) \r
-#define JVMPI_EVENT_UNLOAD_COMPILED_METHOD        ((jint)8) \r
-#define JVMPI_EVENT_NEW_ARENA                     ((jint)48)\r
-#define JVMPI_EVENT_DELETE_ARENA                  ((jint)49)\r
-#define JVMPI_EVENT_DUMP_DATA_REQUEST             ((jint)44) \r
-#define JVMPI_EVENT_RESET_DATA_REQUEST            ((jint)45) \r
-#define JVMPI_EVENT_OBJ_ALLOC                     ((jint)4) \r
-#define JVMPI_EVENT_OBJ_FREE                      ((jint)5) \r
-#define JVMPI_EVENT_OBJ_MOVE                      ((jint)6) \r
-\r
-#define JVMPI_REQUESTED_EVENT                     ((jint)0x10000000)\r
-\r
-\r
\r
-/* \r
- * enabling/disabling event notification.\r
- */\r
-/* results */\r
-#define JVMPI_SUCCESS                    ((jint)0)\r
-#define JVMPI_NOT_AVAILABLE              ((jint)1)\r
-#define JVMPI_FAIL                       ((jint)-1)\r
-\r
-/*\r
- * Thread status\r
- */\r
-enum {\r
-    JVMPI_THREAD_RUNNABLE = 1,\r
-    JVMPI_THREAD_MONITOR_WAIT,\r
-    JVMPI_THREAD_CONDVAR_WAIT\r
-};\r
-\r
-#define JVMPI_THREAD_SUSPENDED        0x8000\r
-#define JVMPI_THREAD_INTERRUPTED      0x4000\r
-\r
-/*\r
- * Thread priority\r
- */\r
-#define JVMPI_MINIMUM_PRIORITY     1\r
-#define JVMPI_MAXIMUM_PRIORITY     10\r
-#define JVMPI_NORMAL_PRIORITY      5\r
-\r
-/*\r
- * Object type constants.\r
- */\r
-#define JVMPI_NORMAL_OBJECT             ((jint)0)\r
-#define JVMPI_CLASS                     ((jint)2)\r
-#define JVMPI_BOOLEAN                   ((jint)4)\r
-#define JVMPI_CHAR                       ((jint)5)\r
-#define JVMPI_FLOAT                      ((jint)6)\r
-#define JVMPI_DOUBLE                     ((jint)7)\r
-#define JVMPI_BYTE                       ((jint)8)\r
-#define JVMPI_SHORT                      ((jint)9)\r
-#define JVMPI_INT                        ((jint)10)\r
-#define JVMPI_LONG                       ((jint)11)    \r
-\r
-/*\r
- * Monitor dump constants.\r
- */\r
-\r
-#define JVMPI_MONITOR_JAVA          0x01\r
-#define JVMPI_MONITOR_RAW           0x02\r
-\r
-/*\r
- * Heap dump constants.\r
- */\r
-#define JVMPI_GC_ROOT_UNKNOWN       0xff\r
-#define JVMPI_GC_ROOT_JNI_GLOBAL    0x01\r
-#define JVMPI_GC_ROOT_JNI_LOCAL     0x02\r
-#define JVMPI_GC_ROOT_JAVA_FRAME    0x03\r
-#define JVMPI_GC_ROOT_NATIVE_STACK  0x04\r
-#define JVMPI_GC_ROOT_STICKY_CLASS  0x05\r
-#define JVMPI_GC_ROOT_THREAD_BLOCK  0x06\r
-#define JVMPI_GC_ROOT_MONITOR_USED  0x07\r
-#define JVMPI_GC_ROOT_THREAD_OBJ    0x08\r
-\r
-#define JVMPI_GC_CLASS_DUMP         0x20\r
-#define JVMPI_GC_INSTANCE_DUMP      0x21 \r
-#define JVMPI_GC_OBJ_ARRAY_DUMP     0x22\r
-#define JVMPI_GC_PRIM_ARRAY_DUMP    0x23\r
-\r
-/*\r
- * Dump levels\r
- */\r
-#define JVMPI_DUMP_LEVEL_0    ((jint)0)\r
-#define JVMPI_DUMP_LEVEL_1    ((jint)1)\r
-#define JVMPI_DUMP_LEVEL_2    ((jint)2)\r
-\r
-/* Types used in dumps -\r
- *\r
- * u1: 1 byte\r
- * u2: 2 bytes\r
- * u4: 4 bytes\r
- * u8: 8 bytes\r
- *\r
- * ty: u1 where:\r
- *     JVMPI_CLASS:   object\r
- *     JVMPI_BOOLEAN: boolean\r
- *     JVMPI_CHAR:    char\r
- *     JVMPI_FLOAT:   float\r
- *     JVMPI_DOUBLE:  double\r
- *     JVMPI_BYTE:    byte\r
- *     JVMPI_SHORT:   short\r
- *     JVMPI_INT:     int\r
- *     JVMPI_LONG:    long\r
- *\r
- * vl: values, exact type depends on the type of the value:\r
- *     JVMPI_BOOLEAN & JVMPI_BYTE:   u1\r
- *     JVMPI_SHORT & JVMPI_CHAR:     u2\r
- *     JVMPI_INT & JVMPI_FLOAT:      u4\r
- *     JVMPI_LONG & JVMPI_DOUBLE:    u8\r
- *     JVMPI_CLASS:                  jobjectID\r
- */\r
-\r
-/* Format of the monitor dump buffer:\r
- *\r
- *               u1                          monitor type\r
- *\r
- *               JVMPI_MONITOR_JAVA          Java monitor\r
- *\r
- *                          jobjectID        object\r
- *                          JNIEnv *         owner thread\r
- *                          u4               entry count\r
- *                          u4               # of threads waiting to enter\r
- *                          [JNIEnv *]*      threads waiting to enter\r
- *                          u4               # of threads waiting to be notified\r
- *                          [JNIEnv *]*      threads waiting to be notified\r
- *\r
- *               JVMPI_MONITOR_RAW           raw monitor\r
- *\r
- *                          char *           name\r
- *                          JVMPI_RawMonitor raw monitor\r
- *                          JNIEnv *         owner thread\r
- *                          u4               entry count\r
- *                          u4               # of threads waiting to enter\r
- *                          [JNIEnv *]*      threads waiting to enter\r
- *                          u4               # of threads waiting to be notified\r
- *                          [JNIEnv *]*      threads waiting to be notified\r
- */\r
-\r
-/* Format of the heap dump buffer depends on the dump level \r
- * specified in the JVMPI_HeapDumpArg passed to RequestEvent as arg. \r
- * The default is JVMPI_DUMP_LEVEL_2.\r
- *\r
- * JVMPI_DUMP_LEVEL_0:\r
- * \r
- *               u1                          object type (JVMPI_CLASS ...)\r
- *               jobjectID                   object\r
- *\r
- * JVMPI_DUMP_LEVEL_1 and JVMPI_DUMP_LEVEL_2 use the following format:  \r
- * In the case of JVMPI_DUMP_LEVEL_1 the values of primitive fields in object \r
- * instance dumps , the values of primitive statics in class dumps and the \r
- * values of primitive arrays are excluded.  JVMPI_DUMP_LEVEL_2 includes the\r
- * primitive values.\r
- *\r
- *               u1                          record type\r
- *\r
- *               JVMPI_GC_ROOT_UNKNOWN       unknown root\r
- *\r
- *                          jobjectID        object\r
- *\r
- *               JVMPI_GC_ROOT_JNI_GLOBAL    JNI global ref root\r
- *\r
- *                          jobjectID        object\r
- *                          jobject          JNI global reference\r
- *\r
- *               JVMPI_GC_ROOT_JNI_LOCAL     JNI local ref\r
- *\r
- *                          jobjectID        object\r
- *                          JNIEnv *         thread\r
- *                          u4               frame # in stack trace (-1 for empty)\r
- *\r
- *               JVMPI_GC_ROOT_JAVA_FRAME    Java stack frame\r
- *\r
- *                          jobjectID        object\r
- *                          JNIEnv *         thread\r
- *                          u4               frame # in stack trace (-1 for empty)\r
- *\r
- *               JVMPI_GC_ROOT_NATIVE_STACK  Native stack\r
- *\r
- *                          jobjectID        object\r
- *                          JNIEnv *         thread\r
- *\r
- *               JVMPI_GC_ROOT_STICKY_CLASS  System class\r
- *\r
- *                          jobjectID        class object\r
- *\r
- *               JVMPI_GC_ROOT_THREAD_BLOCK  Reference from thread block\r
- *\r
- *                          jobjectID        thread object\r
- *                          JNIEnv *         thread\r
- *\r
- *               JVMPI_GC_ROOT_MONITOR_USED  Busy monitor\r
- *\r
- *                          jobjectID        object\r
- *\r
- *               JVMPI_GC_CLASS_DUMP         dump of a class object\r
- *\r
- *                          jobjectID        class\r
- *                          jobjectID        super\r
- *                          jobjectID        class loader\r
- *                          jobjectID        signers\r
- *                          jobjectID        protection domain\r
- *                          jobjectID        class name\r
- *                          void *           reserved\r
- *\r
- *                          u4               instance size (in bytes)\r
- *\r
- *                          [jobjectID]*     interfaces\r
- *\r
- *                          u2               size of constant pool\r
- *                          [u2,             constant pool index,\r
- *                           ty,             type, \r
- *                           vl]*            value\r
- *\r
- *                          [vl]*            static field values\r
- *\r
- *               JVMPI_GC_INSTANCE_DUMP      dump of a normal object\r
- *\r
- *                          jobjectID        object\r
- *                          jobjectID        class\r
- *                          u4               number of bytes that follow\r
- *                          [vl]*            instance field values (class, followed\r
- *                                           by super, super's super ...)\r
- *\r
- *               JVMPI_GC_OBJ_ARRAY_DUMP     dump of an object array\r
- *\r
- *                          jobjectID        array object\r
- *                          u4               number of elements\r
- *                          jobjectID        element class\r
- *                          [jobjectID]*     elements\r
- *\r
- *               JVMPI_GC_PRIM_ARRAY_DUMP    dump of a primitive array\r
- *\r
- *                          jobjectID        array object\r
- *                          u4               number of elements\r
- *                          ty               element type\r
- *                          [vl]*            elements\r
- *\r
- */\r
-\r
-/* Format of the dump received in JVMPI_EVENT_OBJECT_DUMP:\r
- * All the records have JVMPI_DUMP_LEVEL_2 information.\r
- *\r
- *               u1                          record type\r
- *\r
- *                     followed by a:\r
- *\r
- *                          JVMPI_GC_CLASS_DUMP,\r
- *                          JVMPI_GC_INSTANCE_DUMP,\r
- *                          JVMPI_GC_OBJ_ARRAY_DUMP, or\r
- *                          JVMPI_GC_PRIM_ARRAY_DUMP record.\r
- */\r
-\r
-#endif /* !_JAVASOFT_JVMPI_H_ */\r
diff --git a/JavaOpenJPEG/java-jni/include/jvmti.h b/JavaOpenJPEG/java-jni/include/jvmti.h
deleted file mode 100644 (file)
index de24e3e..0000000
+++ /dev/null
@@ -1,2181 +0,0 @@
-#ifdef USE_PRAGMA_IDENT_HDR\r
-#pragma ident "@(#)jvmtiLib.xsl        1.32 04/06/01 20:19:53 JVM"\r
-#endif\r
-/*\r
- * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.\r
- * SUN PROPRIETARY/CONFIDENTIAL.  Use is subject to license terms.\r
- */\r
-\r
-    /* AUTOMATICALLY GENERATED FILE - DO NOT EDIT */\r
-\r
-\r
-    /* Include file for the Java(tm) Virtual Machine Tool Interface */\r
-\r
-#ifndef _JAVA_JVMTI_H_\r
-#define _JAVA_JVMTI_H_\r
-\r
-#include "jni.h"\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-enum {\r
-    JVMTI_VERSION_1   = 0x30010000,\r
-    JVMTI_VERSION_1_0 = 0x30010000,\r
-\r
-    JVMTI_VERSION = 0x30000000 + (1 * 0x10000) + (0 * 0x100) + 33  /* version: 1.0.33 */\r
-};\r
-\r
-JNIEXPORT jint JNICALL \r
-Agent_OnLoad(JavaVM *vm, char *options, void *reserved);\r
-\r
-JNIEXPORT void JNICALL \r
-Agent_OnUnload(JavaVM *vm);\r
-\r
-    /* Forward declaration of the environment */\r
-        \r
-struct _jvmtiEnv;\r
-\r
-struct jvmtiInterface_1_;\r
-  \r
-#ifdef __cplusplus\r
-typedef _jvmtiEnv jvmtiEnv;\r
-#else\r
-typedef const struct jvmtiInterface_1_ *jvmtiEnv;\r
-#endif /* __cplusplus */\r
-\r
-/* Derived Base Types */\r
-\r
-typedef jobject jthread;\r
-typedef jobject jthreadGroup;\r
-typedef jlong jlocation;\r
-struct _jrawMonitorID;\r
-typedef struct _jrawMonitorID *jrawMonitorID;\r
-typedef struct JNINativeInterface_ jniNativeInterface;\r
-\r
-    /* Constants */\r
-\r
-\r
-    /* Thread State Flags */ \r
-\r
-enum {\r
-    JVMTI_THREAD_STATE_ALIVE = 0x0001,\r
-    JVMTI_THREAD_STATE_TERMINATED = 0x0002,\r
-    JVMTI_THREAD_STATE_RUNNABLE = 0x0004,\r
-    JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER = 0x0400,\r
-    JVMTI_THREAD_STATE_WAITING = 0x0080,\r
-    JVMTI_THREAD_STATE_WAITING_INDEFINITELY = 0x0010,\r
-    JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT = 0x0020,\r
-    JVMTI_THREAD_STATE_SLEEPING = 0x0040,\r
-    JVMTI_THREAD_STATE_IN_OBJECT_WAIT = 0x0100,\r
-    JVMTI_THREAD_STATE_PARKED = 0x0200,\r
-    JVMTI_THREAD_STATE_SUSPENDED = 0x100000,\r
-    JVMTI_THREAD_STATE_INTERRUPTED = 0x200000,\r
-    JVMTI_THREAD_STATE_IN_NATIVE = 0x400000,\r
-    JVMTI_THREAD_STATE_VENDOR_1 = 0x10000000,\r
-    JVMTI_THREAD_STATE_VENDOR_2 = 0x20000000,\r
-    JVMTI_THREAD_STATE_VENDOR_3 = 0x40000000\r
-};\r
-\r
-    /* java.lang.Thread.State Conversion Masks */ \r
-\r
-enum {\r
-    JVMTI_JAVA_LANG_THREAD_STATE_MASK = JVMTI_THREAD_STATE_TERMINATED | JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_RUNNABLE | JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER | JVMTI_THREAD_STATE_WAITING | JVMTI_THREAD_STATE_WAITING_INDEFINITELY | JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT,\r
-    JVMTI_JAVA_LANG_THREAD_STATE_NEW = 0,\r
-    JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED = JVMTI_THREAD_STATE_TERMINATED,\r
-    JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE = JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_RUNNABLE,\r
-    JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED = JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER,\r
-    JVMTI_JAVA_LANG_THREAD_STATE_WAITING = JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_WAITING | JVMTI_THREAD_STATE_WAITING_INDEFINITELY,\r
-    JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING = JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_WAITING | JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT\r
-};\r
-\r
-    /* Thread Priority Constants */ \r
-\r
-enum {\r
-    JVMTI_THREAD_MIN_PRIORITY = 1,\r
-    JVMTI_THREAD_NORM_PRIORITY = 5,\r
-    JVMTI_THREAD_MAX_PRIORITY = 10\r
-};\r
-\r
-    /* Heap Object Filter Enumeration */ \r
-\r
-typedef enum {\r
-    JVMTI_HEAP_OBJECT_TAGGED = 1,\r
-    JVMTI_HEAP_OBJECT_UNTAGGED = 2,\r
-    JVMTI_HEAP_OBJECT_EITHER = 3\r
-} jvmtiHeapObjectFilter;\r
-\r
-    /* Heap Root Kind Enumeration */ \r
-\r
-typedef enum {\r
-    JVMTI_HEAP_ROOT_JNI_GLOBAL = 1,\r
-    JVMTI_HEAP_ROOT_SYSTEM_CLASS = 2,\r
-    JVMTI_HEAP_ROOT_MONITOR = 3,\r
-    JVMTI_HEAP_ROOT_STACK_LOCAL = 4,\r
-    JVMTI_HEAP_ROOT_JNI_LOCAL = 5,\r
-    JVMTI_HEAP_ROOT_THREAD = 6,\r
-    JVMTI_HEAP_ROOT_OTHER = 7\r
-} jvmtiHeapRootKind;\r
-\r
-    /* Object Reference Enumeration */ \r
-\r
-typedef enum {\r
-    JVMTI_REFERENCE_CLASS = 1,\r
-    JVMTI_REFERENCE_FIELD = 2,\r
-    JVMTI_REFERENCE_ARRAY_ELEMENT = 3,\r
-    JVMTI_REFERENCE_CLASS_LOADER = 4,\r
-    JVMTI_REFERENCE_SIGNERS = 5,\r
-    JVMTI_REFERENCE_PROTECTION_DOMAIN = 6,\r
-    JVMTI_REFERENCE_INTERFACE = 7,\r
-    JVMTI_REFERENCE_STATIC_FIELD = 8,\r
-    JVMTI_REFERENCE_CONSTANT_POOL = 9\r
-} jvmtiObjectReferenceKind;\r
-\r
-    /* Iteration Control Enumeration */ \r
-\r
-typedef enum {\r
-    JVMTI_ITERATION_CONTINUE = 1,\r
-    JVMTI_ITERATION_IGNORE = 2,\r
-    JVMTI_ITERATION_ABORT = 0\r
-} jvmtiIterationControl;\r
-\r
-    /* Class Status Flags */ \r
-\r
-enum {\r
-    JVMTI_CLASS_STATUS_VERIFIED = 1,\r
-    JVMTI_CLASS_STATUS_PREPARED = 2,\r
-    JVMTI_CLASS_STATUS_INITIALIZED = 4,\r
-    JVMTI_CLASS_STATUS_ERROR = 8,\r
-    JVMTI_CLASS_STATUS_ARRAY = 16,\r
-    JVMTI_CLASS_STATUS_PRIMITIVE = 32\r
-};\r
-\r
-    /* Event Enable/Disable */ \r
-\r
-typedef enum {\r
-    JVMTI_ENABLE = 1,\r
-    JVMTI_DISABLE = 0\r
-} jvmtiEventMode;\r
-\r
-    /* Extension Function/Event Parameter Types */ \r
-\r
-typedef enum {\r
-    JVMTI_TYPE_JBYTE = 101,\r
-    JVMTI_TYPE_JCHAR = 102,\r
-    JVMTI_TYPE_JSHORT = 103,\r
-    JVMTI_TYPE_JINT = 104,\r
-    JVMTI_TYPE_JLONG = 105,\r
-    JVMTI_TYPE_JFLOAT = 106,\r
-    JVMTI_TYPE_JDOUBLE = 107,\r
-    JVMTI_TYPE_JBOOLEAN = 108,\r
-    JVMTI_TYPE_JOBJECT = 109,\r
-    JVMTI_TYPE_JTHREAD = 110,\r
-    JVMTI_TYPE_JCLASS = 111,\r
-    JVMTI_TYPE_JVALUE = 112,\r
-    JVMTI_TYPE_JFIELDID = 113,\r
-    JVMTI_TYPE_JMETHODID = 114,\r
-    JVMTI_TYPE_CCHAR = 115,\r
-    JVMTI_TYPE_CVOID = 116,\r
-    JVMTI_TYPE_JNIENV = 117\r
-} jvmtiParamTypes;\r
-\r
-    /* Extension Function/Event Parameter Kinds */ \r
-\r
-typedef enum {\r
-    JVMTI_KIND_IN = 91,\r
-    JVMTI_KIND_IN_PTR = 92,\r
-    JVMTI_KIND_IN_BUF = 93,\r
-    JVMTI_KIND_ALLOC_BUF = 94,\r
-    JVMTI_KIND_ALLOC_ALLOC_BUF = 95,\r
-    JVMTI_KIND_OUT = 96,\r
-    JVMTI_KIND_OUT_BUF = 97\r
-} jvmtiParamKind;\r
-\r
-    /* Timer Kinds */ \r
-\r
-typedef enum {\r
-    JVMTI_TIMER_USER_CPU = 30,\r
-    JVMTI_TIMER_TOTAL_CPU = 31,\r
-    JVMTI_TIMER_ELAPSED = 32\r
-} jvmtiTimerKind;\r
-\r
-    /* Phases of execution */ \r
-\r
-typedef enum {\r
-    JVMTI_PHASE_ONLOAD = 1,\r
-    JVMTI_PHASE_PRIMORDIAL = 2,\r
-    JVMTI_PHASE_START = 6,\r
-    JVMTI_PHASE_LIVE = 4,\r
-    JVMTI_PHASE_DEAD = 8\r
-} jvmtiPhase;\r
-\r
-    /* Version Interface Types */ \r
-\r
-enum {\r
-    JVMTI_VERSION_INTERFACE_JNI = 0x00000000,\r
-    JVMTI_VERSION_INTERFACE_JVMTI = 0x30000000\r
-};\r
-\r
-    /* Version Masks */ \r
-\r
-enum {\r
-    JVMTI_VERSION_MASK_INTERFACE_TYPE = 0x70000000,\r
-    JVMTI_VERSION_MASK_MAJOR = 0x0FFF0000,\r
-    JVMTI_VERSION_MASK_MINOR = 0x0000FF00,\r
-    JVMTI_VERSION_MASK_MICRO = 0x000000FF\r
-};\r
-\r
-    /* Version Shifts */ \r
-\r
-enum {\r
-    JVMTI_VERSION_SHIFT_MAJOR = 16,\r
-    JVMTI_VERSION_SHIFT_MINOR = 8,\r
-    JVMTI_VERSION_SHIFT_MICRO = 0\r
-};\r
-\r
-    /* Verbose Flag Enumeration */ \r
-\r
-typedef enum {\r
-    JVMTI_VERBOSE_OTHER = 0,\r
-    JVMTI_VERBOSE_GC = 1,\r
-    JVMTI_VERBOSE_CLASS = 2,\r
-    JVMTI_VERBOSE_JNI = 4\r
-} jvmtiVerboseFlag;\r
-\r
-    /* JLocation Format Enumeration */ \r
-\r
-typedef enum {\r
-    JVMTI_JLOCATION_JVMBCI = 1,\r
-    JVMTI_JLOCATION_MACHINEPC = 2,\r
-    JVMTI_JLOCATION_OTHER = 0\r
-} jvmtiJlocationFormat;\r
-\r
-    /* Errors */\r
-\r
-typedef enum {\r
-    JVMTI_ERROR_NONE = 0,\r
-    JVMTI_ERROR_INVALID_THREAD = 10,\r
-    JVMTI_ERROR_INVALID_THREAD_GROUP = 11,\r
-    JVMTI_ERROR_INVALID_PRIORITY = 12,\r
-    JVMTI_ERROR_THREAD_NOT_SUSPENDED = 13,\r
-    JVMTI_ERROR_THREAD_SUSPENDED = 14,\r
-    JVMTI_ERROR_THREAD_NOT_ALIVE = 15,\r
-    JVMTI_ERROR_INVALID_OBJECT = 20,\r
-    JVMTI_ERROR_INVALID_CLASS = 21,\r
-    JVMTI_ERROR_CLASS_NOT_PREPARED = 22,\r
-    JVMTI_ERROR_INVALID_METHODID = 23,\r
-    JVMTI_ERROR_INVALID_LOCATION = 24,\r
-    JVMTI_ERROR_INVALID_FIELDID = 25,\r
-    JVMTI_ERROR_NO_MORE_FRAMES = 31,\r
-    JVMTI_ERROR_OPAQUE_FRAME = 32,\r
-    JVMTI_ERROR_TYPE_MISMATCH = 34,\r
-    JVMTI_ERROR_INVALID_SLOT = 35,\r
-    JVMTI_ERROR_DUPLICATE = 40,\r
-    JVMTI_ERROR_NOT_FOUND = 41,\r
-    JVMTI_ERROR_INVALID_MONITOR = 50,\r
-    JVMTI_ERROR_NOT_MONITOR_OWNER = 51,\r
-    JVMTI_ERROR_INTERRUPT = 52,\r
-    JVMTI_ERROR_INVALID_CLASS_FORMAT = 60,\r
-    JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION = 61,\r
-    JVMTI_ERROR_FAILS_VERIFICATION = 62,\r
-    JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED = 63,\r
-    JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED = 64,\r
-    JVMTI_ERROR_INVALID_TYPESTATE = 65,\r
-    JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED = 66,\r
-    JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED = 67,\r
-    JVMTI_ERROR_UNSUPPORTED_VERSION = 68,\r
-    JVMTI_ERROR_NAMES_DONT_MATCH = 69,\r
-    JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED = 70,\r
-    JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED = 71,\r
-    JVMTI_ERROR_UNMODIFIABLE_CLASS = 79,\r
-    JVMTI_ERROR_NOT_AVAILABLE = 98,\r
-    JVMTI_ERROR_MUST_POSSESS_CAPABILITY = 99,\r
-    JVMTI_ERROR_NULL_POINTER = 100,\r
-    JVMTI_ERROR_ABSENT_INFORMATION = 101,\r
-    JVMTI_ERROR_INVALID_EVENT_TYPE = 102,\r
-    JVMTI_ERROR_ILLEGAL_ARGUMENT = 103,\r
-    JVMTI_ERROR_NATIVE_METHOD = 104,\r
-    JVMTI_ERROR_OUT_OF_MEMORY = 110,\r
-    JVMTI_ERROR_ACCESS_DENIED = 111,\r
-    JVMTI_ERROR_WRONG_PHASE = 112,\r
-    JVMTI_ERROR_INTERNAL = 113,\r
-    JVMTI_ERROR_UNATTACHED_THREAD = 115,\r
-    JVMTI_ERROR_INVALID_ENVIRONMENT = 116,\r
-    JVMTI_ERROR_MAX = 116\r
-} jvmtiError;\r
-\r
-    /* Event IDs */\r
-\r
-typedef enum {\r
-    JVMTI_MIN_EVENT_TYPE_VAL = 50,\r
-    JVMTI_EVENT_VM_INIT = 50,\r
-    JVMTI_EVENT_VM_DEATH = 51,\r
-    JVMTI_EVENT_THREAD_START = 52,\r
-    JVMTI_EVENT_THREAD_END = 53,\r
-    JVMTI_EVENT_CLASS_FILE_LOAD_HOOK = 54,\r
-    JVMTI_EVENT_CLASS_LOAD = 55,\r
-    JVMTI_EVENT_CLASS_PREPARE = 56,\r
-    JVMTI_EVENT_VM_START = 57,\r
-    JVMTI_EVENT_EXCEPTION = 58,\r
-    JVMTI_EVENT_EXCEPTION_CATCH = 59,\r
-    JVMTI_EVENT_SINGLE_STEP = 60,\r
-    JVMTI_EVENT_FRAME_POP = 61,\r
-    JVMTI_EVENT_BREAKPOINT = 62,\r
-    JVMTI_EVENT_FIELD_ACCESS = 63,\r
-    JVMTI_EVENT_FIELD_MODIFICATION = 64,\r
-    JVMTI_EVENT_METHOD_ENTRY = 65,\r
-    JVMTI_EVENT_METHOD_EXIT = 66,\r
-    JVMTI_EVENT_NATIVE_METHOD_BIND = 67,\r
-    JVMTI_EVENT_COMPILED_METHOD_LOAD = 68,\r
-    JVMTI_EVENT_COMPILED_METHOD_UNLOAD = 69,\r
-    JVMTI_EVENT_DYNAMIC_CODE_GENERATED = 70,\r
-    JVMTI_EVENT_DATA_DUMP_REQUEST = 71,\r
-    JVMTI_EVENT_MONITOR_WAIT = 73,\r
-    JVMTI_EVENT_MONITOR_WAITED = 74,\r
-    JVMTI_EVENT_MONITOR_CONTENDED_ENTER = 75,\r
-    JVMTI_EVENT_MONITOR_CONTENDED_ENTERED = 76,\r
-    JVMTI_EVENT_GARBAGE_COLLECTION_START = 81,\r
-    JVMTI_EVENT_GARBAGE_COLLECTION_FINISH = 82,\r
-    JVMTI_EVENT_OBJECT_FREE = 83,\r
-    JVMTI_EVENT_VM_OBJECT_ALLOC = 84,\r
-    JVMTI_MAX_EVENT_TYPE_VAL = 84\r
-} jvmtiEvent;\r
-\r
-\r
-    /* Function Types */\r
-\r
-typedef void (JNICALL *jvmtiStartFunction)\r
-    (jvmtiEnv* jvmti_env, JNIEnv* jni_env, void* arg);\r
-\r
-typedef jvmtiIterationControl (JNICALL *jvmtiHeapObjectCallback)\r
-    (jlong class_tag, jlong size, jlong* tag_ptr, void* user_data);\r
-\r
-typedef jvmtiIterationControl (JNICALL *jvmtiHeapRootCallback)\r
-    (jvmtiHeapRootKind root_kind, jlong class_tag, jlong size, jlong* tag_ptr, void* user_data);\r
-\r
-typedef jvmtiIterationControl (JNICALL *jvmtiStackReferenceCallback)\r
-    (jvmtiHeapRootKind root_kind, jlong class_tag, jlong size, jlong* tag_ptr, jlong thread_tag, jint depth, jmethodID method, jint slot, void* user_data);\r
-\r
-typedef jvmtiIterationControl (JNICALL *jvmtiObjectReferenceCallback)\r
-    (jvmtiObjectReferenceKind reference_kind, jlong class_tag, jlong size, jlong* tag_ptr, jlong referrer_tag, jint referrer_index, void* user_data);\r
-\r
-typedef jvmtiError (JNICALL *jvmtiExtensionFunction)\r
-    (jvmtiEnv* jvmti_env,  ...);\r
-\r
-typedef void (JNICALL *jvmtiExtensionEvent)\r
-    (jvmtiEnv* jvmti_env,  ...);\r
-\r
-\r
-    /* Structure Types */\r
-\r
-typedef struct {\r
-    char* name;\r
-    jint priority;\r
-    jboolean is_daemon;\r
-    jthreadGroup thread_group;\r
-    jobject context_class_loader;\r
-} jvmtiThreadInfo;\r
-\r
-typedef struct {\r
-    jthreadGroup parent;\r
-    char* name;\r
-    jint max_priority;\r
-    jboolean is_daemon;\r
-} jvmtiThreadGroupInfo;\r
-\r
-typedef struct {\r
-    jmethodID method;\r
-    jlocation location;\r
-} jvmtiFrameInfo;\r
-\r
-typedef struct {\r
-    jthread thread;\r
-    jint state;\r
-    jvmtiFrameInfo* frame_buffer;\r
-    jint frame_count;\r
-} jvmtiStackInfo;\r
-\r
-typedef struct {\r
-    jclass klass;\r
-    jint class_byte_count;\r
-    const unsigned char* class_bytes;\r
-} jvmtiClassDefinition;\r
-\r
-typedef struct {\r
-    jthread owner;\r
-    jint entry_count;\r
-    jint waiter_count;\r
-    jthread* waiters;\r
-    jint notify_waiter_count;\r
-    jthread* notify_waiters;\r
-} jvmtiMonitorUsage;\r
-\r
-typedef struct {\r
-    jlocation start_location;\r
-    jint line_number;\r
-} jvmtiLineNumberEntry;\r
-\r
-typedef struct {\r
-    jlocation start_location;\r
-    jint length;\r
-    char* name;\r
-    char* signature;\r
-    char* generic_signature;\r
-    jint slot;\r
-} jvmtiLocalVariableEntry;\r
-\r
-typedef struct {\r
-    char* name;\r
-    jvmtiParamKind kind;\r
-    jvmtiParamTypes base_type;\r
-    jboolean null_ok;\r
-} jvmtiParamInfo;\r
-\r
-typedef struct {\r
-    jvmtiExtensionFunction func;\r
-    char* id;\r
-    char* short_description;\r
-    jint param_count;\r
-    jvmtiParamInfo* params;\r
-    jint error_count;\r
-    jvmtiError* errors;\r
-} jvmtiExtensionFunctionInfo;\r
-\r
-typedef struct {\r
-    jint extension_event_index;\r
-    char* id;\r
-    char* short_description;\r
-    jint param_count;\r
-    jvmtiParamInfo* params;\r
-} jvmtiExtensionEventInfo;\r
-\r
-typedef struct {\r
-    jlong max_value;\r
-    jboolean may_skip_forward;\r
-    jboolean may_skip_backward;\r
-    jvmtiTimerKind kind;\r
-    jlong reserved1;\r
-    jlong reserved2;\r
-} jvmtiTimerInfo;\r
-\r
-typedef struct {\r
-    const void* start_address;\r
-    jlocation location;\r
-} jvmtiAddrLocationMap;\r
-\r
-typedef struct {\r
-    unsigned int can_tag_objects : 1;\r
-    unsigned int can_generate_field_modification_events : 1;\r
-    unsigned int can_generate_field_access_events : 1;\r
-    unsigned int can_get_bytecodes : 1;\r
-    unsigned int can_get_synthetic_attribute : 1;\r
-    unsigned int can_get_owned_monitor_info : 1;\r
-    unsigned int can_get_current_contended_monitor : 1;\r
-    unsigned int can_get_monitor_info : 1;\r
-    unsigned int can_pop_frame : 1;\r
-    unsigned int can_redefine_classes : 1;\r
-    unsigned int can_signal_thread : 1;\r
-    unsigned int can_get_source_file_name : 1;\r
-    unsigned int can_get_line_numbers : 1;\r
-    unsigned int can_get_source_debug_extension : 1;\r
-    unsigned int can_access_local_variables : 1;\r
-    unsigned int can_maintain_original_method_order : 1;\r
-    unsigned int can_generate_single_step_events : 1;\r
-    unsigned int can_generate_exception_events : 1;\r
-    unsigned int can_generate_frame_pop_events : 1;\r
-    unsigned int can_generate_breakpoint_events : 1;\r
-    unsigned int can_suspend : 1;\r
-    unsigned int can_redefine_any_class : 1;\r
-    unsigned int can_get_current_thread_cpu_time : 1;\r
-    unsigned int can_get_thread_cpu_time : 1;\r
-    unsigned int can_generate_method_entry_events : 1;\r
-    unsigned int can_generate_method_exit_events : 1;\r
-    unsigned int can_generate_all_class_hook_events : 1;\r
-    unsigned int can_generate_compiled_method_load_events : 1;\r
-    unsigned int can_generate_monitor_events : 1;\r
-    unsigned int can_generate_vm_object_alloc_events : 1;\r
-    unsigned int can_generate_native_method_bind_events : 1;\r
-    unsigned int can_generate_garbage_collection_events : 1;\r
-    unsigned int can_generate_object_free_events : 1;\r
-    unsigned int : 15;\r
-    unsigned int : 16;\r
-    unsigned int : 16;\r
-    unsigned int : 16;\r
-    unsigned int : 16;\r
-    unsigned int : 16;\r
-} jvmtiCapabilities;\r
-\r
-\r
-    /* Event Definitions */\r
-\r
-typedef void (JNICALL *jvmtiEventReserved)(void);\r
-\r
-\r
-typedef void (JNICALL *jvmtiEventBreakpoint)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jmethodID method, \r
-     jlocation location);\r
-\r
-typedef void (JNICALL *jvmtiEventClassFileLoadHook)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jclass class_being_redefined, \r
-     jobject loader, \r
-     const char* name, \r
-     jobject protection_domain, \r
-     jint class_data_len, \r
-     const unsigned char* class_data, \r
-     jint* new_class_data_len, \r
-     unsigned char** new_class_data);\r
-\r
-typedef void (JNICALL *jvmtiEventClassLoad)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jclass klass);\r
-\r
-typedef void (JNICALL *jvmtiEventClassPrepare)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jclass klass);\r
-\r
-typedef void (JNICALL *jvmtiEventCompiledMethodLoad)\r
-    (jvmtiEnv *jvmti_env, \r
-     jmethodID method, \r
-     jint code_size, \r
-     const void* code_addr, \r
-     jint map_length, \r
-     const jvmtiAddrLocationMap* map, \r
-     const void* compile_info);\r
-\r
-typedef void (JNICALL *jvmtiEventCompiledMethodUnload)\r
-    (jvmtiEnv *jvmti_env, \r
-     jmethodID method, \r
-     const void* code_addr);\r
-\r
-typedef void (JNICALL *jvmtiEventDataDumpRequest)\r
-    (jvmtiEnv *jvmti_env);\r
-\r
-typedef void (JNICALL *jvmtiEventDynamicCodeGenerated)\r
-    (jvmtiEnv *jvmti_env, \r
-     const char* name, \r
-     const void* address, \r
-     jint length);\r
-\r
-typedef void (JNICALL *jvmtiEventException)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jmethodID method, \r
-     jlocation location, \r
-     jobject exception, \r
-     jmethodID catch_method, \r
-     jlocation catch_location);\r
-\r
-typedef void (JNICALL *jvmtiEventExceptionCatch)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jmethodID method, \r
-     jlocation location, \r
-     jobject exception);\r
-\r
-typedef void (JNICALL *jvmtiEventFieldAccess)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jmethodID method, \r
-     jlocation location, \r
-     jclass field_klass, \r
-     jobject object, \r
-     jfieldID field);\r
-\r
-typedef void (JNICALL *jvmtiEventFieldModification)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jmethodID method, \r
-     jlocation location, \r
-     jclass field_klass, \r
-     jobject object, \r
-     jfieldID field, \r
-     char signature_type, \r
-     jvalue new_value);\r
-\r
-typedef void (JNICALL *jvmtiEventFramePop)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jmethodID method, \r
-     jboolean was_popped_by_exception);\r
-\r
-typedef void (JNICALL *jvmtiEventGarbageCollectionFinish)\r
-    (jvmtiEnv *jvmti_env);\r
-\r
-typedef void (JNICALL *jvmtiEventGarbageCollectionStart)\r
-    (jvmtiEnv *jvmti_env);\r
-\r
-typedef void (JNICALL *jvmtiEventMethodEntry)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jmethodID method);\r
-\r
-typedef void (JNICALL *jvmtiEventMethodExit)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jmethodID method, \r
-     jboolean was_popped_by_exception, \r
-     jvalue return_value);\r
-\r
-typedef void (JNICALL *jvmtiEventMonitorContendedEnter)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jobject object);\r
-\r
-typedef void (JNICALL *jvmtiEventMonitorContendedEntered)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jobject object);\r
-\r
-typedef void (JNICALL *jvmtiEventMonitorWait)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jobject object, \r
-     jlong timeout);\r
-\r
-typedef void (JNICALL *jvmtiEventMonitorWaited)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jobject object, \r
-     jboolean timed_out);\r
-\r
-typedef void (JNICALL *jvmtiEventNativeMethodBind)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jmethodID method, \r
-     void* address, \r
-     void** new_address_ptr);\r
-\r
-typedef void (JNICALL *jvmtiEventObjectFree)\r
-    (jvmtiEnv *jvmti_env, \r
-     jlong tag);\r
-\r
-typedef void (JNICALL *jvmtiEventSingleStep)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jmethodID method, \r
-     jlocation location);\r
-\r
-typedef void (JNICALL *jvmtiEventThreadEnd)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread);\r
-\r
-typedef void (JNICALL *jvmtiEventThreadStart)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread);\r
-\r
-typedef void (JNICALL *jvmtiEventVMDeath)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env);\r
-\r
-typedef void (JNICALL *jvmtiEventVMInit)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread);\r
-\r
-typedef void (JNICALL *jvmtiEventVMObjectAlloc)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env, \r
-     jthread thread, \r
-     jobject object, \r
-     jclass object_klass, \r
-     jlong size);\r
-\r
-typedef void (JNICALL *jvmtiEventVMStart)\r
-    (jvmtiEnv *jvmti_env, \r
-     JNIEnv* jni_env);\r
-\r
-    /* Event Callback Structure */\r
-\r
-typedef struct {\r
-                              /*   50 : VM Initialization Event */\r
-    jvmtiEventVMInit VMInit;\r
-                              /*   51 : VM Death Event */\r
-    jvmtiEventVMDeath VMDeath;\r
-                              /*   52 : Thread Start */\r
-    jvmtiEventThreadStart ThreadStart;\r
-                              /*   53 : Thread End */\r
-    jvmtiEventThreadEnd ThreadEnd;\r
-                              /*   54 : Class File Load Hook */\r
-    jvmtiEventClassFileLoadHook ClassFileLoadHook;\r
-                              /*   55 : Class Load */\r
-    jvmtiEventClassLoad ClassLoad;\r
-                              /*   56 : Class Prepare */\r
-    jvmtiEventClassPrepare ClassPrepare;\r
-                              /*   57 : VM Start Event */\r
-    jvmtiEventVMStart VMStart;\r
-                              /*   58 : Exception */\r
-    jvmtiEventException Exception;\r
-                              /*   59 : Exception Catch */\r
-    jvmtiEventExceptionCatch ExceptionCatch;\r
-                              /*   60 : Single Step */\r
-    jvmtiEventSingleStep SingleStep;\r
-                              /*   61 : Frame Pop */\r
-    jvmtiEventFramePop FramePop;\r
-                              /*   62 : Breakpoint */\r
-    jvmtiEventBreakpoint Breakpoint;\r
-                              /*   63 : Field Access */\r
-    jvmtiEventFieldAccess FieldAccess;\r
-                              /*   64 : Field Modification */\r
-    jvmtiEventFieldModification FieldModification;\r
-                              /*   65 : Method Entry */\r
-    jvmtiEventMethodEntry MethodEntry;\r
-                              /*   66 : Method Exit */\r
-    jvmtiEventMethodExit MethodExit;\r
-                              /*   67 : Native Method Bind */\r
-    jvmtiEventNativeMethodBind NativeMethodBind;\r
-                              /*   68 : Compiled Method Load */\r
-    jvmtiEventCompiledMethodLoad CompiledMethodLoad;\r
-                              /*   69 : Compiled Method Unload */\r
-    jvmtiEventCompiledMethodUnload CompiledMethodUnload;\r
-                              /*   70 : Dynamic Code Generated */\r
-    jvmtiEventDynamicCodeGenerated DynamicCodeGenerated;\r
-                              /*   71 : Data Dump Request */\r
-    jvmtiEventDataDumpRequest DataDumpRequest;\r
-                              /*   72 */\r
-    jvmtiEventReserved reserved72;\r
-                              /*   73 : Monitor Wait */\r
-    jvmtiEventMonitorWait MonitorWait;\r
-                              /*   74 : Monitor Waited */\r
-    jvmtiEventMonitorWaited MonitorWaited;\r
-                              /*   75 : Monitor Contended Enter */\r
-    jvmtiEventMonitorContendedEnter MonitorContendedEnter;\r
-                              /*   76 : Monitor Contended Entered */\r
-    jvmtiEventMonitorContendedEntered MonitorContendedEntered;\r
-                              /*   77 */\r
-    jvmtiEventReserved reserved77;\r
-                              /*   78 */\r
-    jvmtiEventReserved reserved78;\r
-                              /*   79 */\r
-    jvmtiEventReserved reserved79;\r
-                              /*   80 */\r
-    jvmtiEventReserved reserved80;\r
-                              /*   81 : Garbage Collection Start */\r
-    jvmtiEventGarbageCollectionStart GarbageCollectionStart;\r
-                              /*   82 : Garbage Collection Finish */\r
-    jvmtiEventGarbageCollectionFinish GarbageCollectionFinish;\r
-                              /*   83 : Object Free */\r
-    jvmtiEventObjectFree ObjectFree;\r
-                              /*   84 : VM Object Allocation */\r
-    jvmtiEventVMObjectAlloc VMObjectAlloc;\r
-} jvmtiEventCallbacks;\r
-\r
-\r
-    /* Function Interface */\r
-    \r
-typedef struct jvmtiInterface_1_ {\r
-\r
-  /*   1 :  RESERVED */\r
-  void *reserved1;\r
-\r
-  /*   2 : Set Event Notification Mode */\r
-  jvmtiError (JNICALL *SetEventNotificationMode) (jvmtiEnv* env, \r
-    jvmtiEventMode mode, \r
-    jvmtiEvent event_type, \r
-    jthread event_thread, \r
-     ...);\r
-\r
-  /*   3 :  RESERVED */\r
-  void *reserved3;\r
-\r
-  /*   4 : Get All Threads */\r
-  jvmtiError (JNICALL *GetAllThreads) (jvmtiEnv* env, \r
-    jint* threads_count_ptr, \r
-    jthread** threads_ptr);\r
-\r
-  /*   5 : Suspend Thread */\r
-  jvmtiError (JNICALL *SuspendThread) (jvmtiEnv* env, \r
-    jthread thread);\r
-\r
-  /*   6 : Resume Thread */\r
-  jvmtiError (JNICALL *ResumeThread) (jvmtiEnv* env, \r
-    jthread thread);\r
-\r
-  /*   7 : Stop Thread */\r
-  jvmtiError (JNICALL *StopThread) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jobject exception);\r
-\r
-  /*   8 : Interrupt Thread */\r
-  jvmtiError (JNICALL *InterruptThread) (jvmtiEnv* env, \r
-    jthread thread);\r
-\r
-  /*   9 : Get Thread Info */\r
-  jvmtiError (JNICALL *GetThreadInfo) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jvmtiThreadInfo* info_ptr);\r
-\r
-  /*   10 : Get Owned Monitor Info */\r
-  jvmtiError (JNICALL *GetOwnedMonitorInfo) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint* owned_monitor_count_ptr, \r
-    jobject** owned_monitors_ptr);\r
-\r
-  /*   11 : Get Current Contended Monitor */\r
-  jvmtiError (JNICALL *GetCurrentContendedMonitor) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jobject* monitor_ptr);\r
-\r
-  /*   12 : Run Agent Thread */\r
-  jvmtiError (JNICALL *RunAgentThread) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jvmtiStartFunction proc, \r
-    const void* arg, \r
-    jint priority);\r
-\r
-  /*   13 : Get Top Thread Groups */\r
-  jvmtiError (JNICALL *GetTopThreadGroups) (jvmtiEnv* env, \r
-    jint* group_count_ptr, \r
-    jthreadGroup** groups_ptr);\r
-\r
-  /*   14 : Get Thread Group Info */\r
-  jvmtiError (JNICALL *GetThreadGroupInfo) (jvmtiEnv* env, \r
-    jthreadGroup group, \r
-    jvmtiThreadGroupInfo* info_ptr);\r
-\r
-  /*   15 : Get Thread Group Children */\r
-  jvmtiError (JNICALL *GetThreadGroupChildren) (jvmtiEnv* env, \r
-    jthreadGroup group, \r
-    jint* thread_count_ptr, \r
-    jthread** threads_ptr, \r
-    jint* group_count_ptr, \r
-    jthreadGroup** groups_ptr);\r
-\r
-  /*   16 : Get Frame Count */\r
-  jvmtiError (JNICALL *GetFrameCount) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint* count_ptr);\r
-\r
-  /*   17 : Get Thread State */\r
-  jvmtiError (JNICALL *GetThreadState) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint* thread_state_ptr);\r
-\r
-  /*   18 :  RESERVED */\r
-  void *reserved18;\r
-\r
-  /*   19 : Get Frame Location */\r
-  jvmtiError (JNICALL *GetFrameLocation) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint depth, \r
-    jmethodID* method_ptr, \r
-    jlocation* location_ptr);\r
-\r
-  /*   20 : Notify Frame Pop */\r
-  jvmtiError (JNICALL *NotifyFramePop) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint depth);\r
-\r
-  /*   21 : Get Local Variable - Object */\r
-  jvmtiError (JNICALL *GetLocalObject) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint depth, \r
-    jint slot, \r
-    jobject* value_ptr);\r
-\r
-  /*   22 : Get Local Variable - Int */\r
-  jvmtiError (JNICALL *GetLocalInt) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint depth, \r
-    jint slot, \r
-    jint* value_ptr);\r
-\r
-  /*   23 : Get Local Variable - Long */\r
-  jvmtiError (JNICALL *GetLocalLong) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint depth, \r
-    jint slot, \r
-    jlong* value_ptr);\r
-\r
-  /*   24 : Get Local Variable - Float */\r
-  jvmtiError (JNICALL *GetLocalFloat) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint depth, \r
-    jint slot, \r
-    jfloat* value_ptr);\r
-\r
-  /*   25 : Get Local Variable - Double */\r
-  jvmtiError (JNICALL *GetLocalDouble) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint depth, \r
-    jint slot, \r
-    jdouble* value_ptr);\r
-\r
-  /*   26 : Set Local Variable - Object */\r
-  jvmtiError (JNICALL *SetLocalObject) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint depth, \r
-    jint slot, \r
-    jobject value);\r
-\r
-  /*   27 : Set Local Variable - Int */\r
-  jvmtiError (JNICALL *SetLocalInt) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint depth, \r
-    jint slot, \r
-    jint value);\r
-\r
-  /*   28 : Set Local Variable - Long */\r
-  jvmtiError (JNICALL *SetLocalLong) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint depth, \r
-    jint slot, \r
-    jlong value);\r
-\r
-  /*   29 : Set Local Variable - Float */\r
-  jvmtiError (JNICALL *SetLocalFloat) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint depth, \r
-    jint slot, \r
-    jfloat value);\r
-\r
-  /*   30 : Set Local Variable - Double */\r
-  jvmtiError (JNICALL *SetLocalDouble) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint depth, \r
-    jint slot, \r
-    jdouble value);\r
-\r
-  /*   31 : Create Raw Monitor */\r
-  jvmtiError (JNICALL *CreateRawMonitor) (jvmtiEnv* env, \r
-    const char* name, \r
-    jrawMonitorID* monitor_ptr);\r
-\r
-  /*   32 : Destroy Raw Monitor */\r
-  jvmtiError (JNICALL *DestroyRawMonitor) (jvmtiEnv* env, \r
-    jrawMonitorID monitor);\r
-\r
-  /*   33 : Raw Monitor Enter */\r
-  jvmtiError (JNICALL *RawMonitorEnter) (jvmtiEnv* env, \r
-    jrawMonitorID monitor);\r
-\r
-  /*   34 : Raw Monitor Exit */\r
-  jvmtiError (JNICALL *RawMonitorExit) (jvmtiEnv* env, \r
-    jrawMonitorID monitor);\r
-\r
-  /*   35 : Raw Monitor Wait */\r
-  jvmtiError (JNICALL *RawMonitorWait) (jvmtiEnv* env, \r
-    jrawMonitorID monitor, \r
-    jlong millis);\r
-\r
-  /*   36 : Raw Monitor Notify */\r
-  jvmtiError (JNICALL *RawMonitorNotify) (jvmtiEnv* env, \r
-    jrawMonitorID monitor);\r
-\r
-  /*   37 : Raw Monitor Notify All */\r
-  jvmtiError (JNICALL *RawMonitorNotifyAll) (jvmtiEnv* env, \r
-    jrawMonitorID monitor);\r
-\r
-  /*   38 : Set Breakpoint */\r
-  jvmtiError (JNICALL *SetBreakpoint) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    jlocation location);\r
-\r
-  /*   39 : Clear Breakpoint */\r
-  jvmtiError (JNICALL *ClearBreakpoint) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    jlocation location);\r
-\r
-  /*   40 :  RESERVED */\r
-  void *reserved40;\r
-\r
-  /*   41 : Set Field Access Watch */\r
-  jvmtiError (JNICALL *SetFieldAccessWatch) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jfieldID field);\r
-\r
-  /*   42 : Clear Field Access Watch */\r
-  jvmtiError (JNICALL *ClearFieldAccessWatch) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jfieldID field);\r
-\r
-  /*   43 : Set Field Modification Watch */\r
-  jvmtiError (JNICALL *SetFieldModificationWatch) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jfieldID field);\r
-\r
-  /*   44 : Clear Field Modification Watch */\r
-  jvmtiError (JNICALL *ClearFieldModificationWatch) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jfieldID field);\r
-\r
-  /*   45 :  RESERVED */\r
-  void *reserved45;\r
-\r
-  /*   46 : Allocate */\r
-  jvmtiError (JNICALL *Allocate) (jvmtiEnv* env, \r
-    jlong size, \r
-    unsigned char** mem_ptr);\r
-\r
-  /*   47 : Deallocate */\r
-  jvmtiError (JNICALL *Deallocate) (jvmtiEnv* env, \r
-    unsigned char* mem);\r
-\r
-  /*   48 : Get Class Signature */\r
-  jvmtiError (JNICALL *GetClassSignature) (jvmtiEnv* env, \r
-    jclass klass, \r
-    char** signature_ptr, \r
-    char** generic_ptr);\r
-\r
-  /*   49 : Get Class Status */\r
-  jvmtiError (JNICALL *GetClassStatus) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jint* status_ptr);\r
-\r
-  /*   50 : Get Source File Name */\r
-  jvmtiError (JNICALL *GetSourceFileName) (jvmtiEnv* env, \r
-    jclass klass, \r
-    char** source_name_ptr);\r
-\r
-  /*   51 : Get Class Modifiers */\r
-  jvmtiError (JNICALL *GetClassModifiers) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jint* modifiers_ptr);\r
-\r
-  /*   52 : Get Class Methods */\r
-  jvmtiError (JNICALL *GetClassMethods) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jint* method_count_ptr, \r
-    jmethodID** methods_ptr);\r
-\r
-  /*   53 : Get Class Fields */\r
-  jvmtiError (JNICALL *GetClassFields) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jint* field_count_ptr, \r
-    jfieldID** fields_ptr);\r
-\r
-  /*   54 : Get Implemented Interfaces */\r
-  jvmtiError (JNICALL *GetImplementedInterfaces) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jint* interface_count_ptr, \r
-    jclass** interfaces_ptr);\r
-\r
-  /*   55 : Is Interface */\r
-  jvmtiError (JNICALL *IsInterface) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jboolean* is_interface_ptr);\r
-\r
-  /*   56 : Is Array Class */\r
-  jvmtiError (JNICALL *IsArrayClass) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jboolean* is_array_class_ptr);\r
-\r
-  /*   57 : Get Class Loader */\r
-  jvmtiError (JNICALL *GetClassLoader) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jobject* classloader_ptr);\r
-\r
-  /*   58 : Get Object Hash Code */\r
-  jvmtiError (JNICALL *GetObjectHashCode) (jvmtiEnv* env, \r
-    jobject object, \r
-    jint* hash_code_ptr);\r
-\r
-  /*   59 : Get Object Monitor Usage */\r
-  jvmtiError (JNICALL *GetObjectMonitorUsage) (jvmtiEnv* env, \r
-    jobject object, \r
-    jvmtiMonitorUsage* info_ptr);\r
-\r
-  /*   60 : Get Field Name (and Signature) */\r
-  jvmtiError (JNICALL *GetFieldName) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jfieldID field, \r
-    char** name_ptr, \r
-    char** signature_ptr, \r
-    char** generic_ptr);\r
-\r
-  /*   61 : Get Field Declaring Class */\r
-  jvmtiError (JNICALL *GetFieldDeclaringClass) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jfieldID field, \r
-    jclass* declaring_class_ptr);\r
-\r
-  /*   62 : Get Field Modifiers */\r
-  jvmtiError (JNICALL *GetFieldModifiers) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jfieldID field, \r
-    jint* modifiers_ptr);\r
-\r
-  /*   63 : Is Field Synthetic */\r
-  jvmtiError (JNICALL *IsFieldSynthetic) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jfieldID field, \r
-    jboolean* is_synthetic_ptr);\r
-\r
-  /*   64 : Get Method Name (and Signature) */\r
-  jvmtiError (JNICALL *GetMethodName) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    char** name_ptr, \r
-    char** signature_ptr, \r
-    char** generic_ptr);\r
-\r
-  /*   65 : Get Method Declaring Class */\r
-  jvmtiError (JNICALL *GetMethodDeclaringClass) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    jclass* declaring_class_ptr);\r
-\r
-  /*   66 : Get Method Modifiers */\r
-  jvmtiError (JNICALL *GetMethodModifiers) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    jint* modifiers_ptr);\r
-\r
-  /*   67 :  RESERVED */\r
-  void *reserved67;\r
-\r
-  /*   68 : Get Max Locals */\r
-  jvmtiError (JNICALL *GetMaxLocals) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    jint* max_ptr);\r
-\r
-  /*   69 : Get Arguments Size */\r
-  jvmtiError (JNICALL *GetArgumentsSize) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    jint* size_ptr);\r
-\r
-  /*   70 : Get Line Number Table */\r
-  jvmtiError (JNICALL *GetLineNumberTable) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    jint* entry_count_ptr, \r
-    jvmtiLineNumberEntry** table_ptr);\r
-\r
-  /*   71 : Get Method Location */\r
-  jvmtiError (JNICALL *GetMethodLocation) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    jlocation* start_location_ptr, \r
-    jlocation* end_location_ptr);\r
-\r
-  /*   72 : Get Local Variable Table */\r
-  jvmtiError (JNICALL *GetLocalVariableTable) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    jint* entry_count_ptr, \r
-    jvmtiLocalVariableEntry** table_ptr);\r
-\r
-  /*   73 :  RESERVED */\r
-  void *reserved73;\r
-\r
-  /*   74 :  RESERVED */\r
-  void *reserved74;\r
-\r
-  /*   75 : Get Bytecodes */\r
-  jvmtiError (JNICALL *GetBytecodes) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    jint* bytecode_count_ptr, \r
-    unsigned char** bytecodes_ptr);\r
-\r
-  /*   76 : Is Method Native */\r
-  jvmtiError (JNICALL *IsMethodNative) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    jboolean* is_native_ptr);\r
-\r
-  /*   77 : Is Method Synthetic */\r
-  jvmtiError (JNICALL *IsMethodSynthetic) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    jboolean* is_synthetic_ptr);\r
-\r
-  /*   78 : Get Loaded Classes */\r
-  jvmtiError (JNICALL *GetLoadedClasses) (jvmtiEnv* env, \r
-    jint* class_count_ptr, \r
-    jclass** classes_ptr);\r
-\r
-  /*   79 : Get Classloader Classes */\r
-  jvmtiError (JNICALL *GetClassLoaderClasses) (jvmtiEnv* env, \r
-    jobject initiating_loader, \r
-    jint* class_count_ptr, \r
-    jclass** classes_ptr);\r
-\r
-  /*   80 : Pop Frame */\r
-  jvmtiError (JNICALL *PopFrame) (jvmtiEnv* env, \r
-    jthread thread);\r
-\r
-  /*   81 :  RESERVED */\r
-  void *reserved81;\r
-\r
-  /*   82 :  RESERVED */\r
-  void *reserved82;\r
-\r
-  /*   83 :  RESERVED */\r
-  void *reserved83;\r
-\r
-  /*   84 :  RESERVED */\r
-  void *reserved84;\r
-\r
-  /*   85 :  RESERVED */\r
-  void *reserved85;\r
-\r
-  /*   86 :  RESERVED */\r
-  void *reserved86;\r
-\r
-  /*   87 : Redefine Classes */\r
-  jvmtiError (JNICALL *RedefineClasses) (jvmtiEnv* env, \r
-    jint class_count, \r
-    const jvmtiClassDefinition* class_definitions);\r
-\r
-  /*   88 : Get Version Number */\r
-  jvmtiError (JNICALL *GetVersionNumber) (jvmtiEnv* env, \r
-    jint* version_ptr);\r
-\r
-  /*   89 : Get Capabilities */\r
-  jvmtiError (JNICALL *GetCapabilities) (jvmtiEnv* env, \r
-    jvmtiCapabilities* capabilities_ptr);\r
-\r
-  /*   90 : Get Source Debug Extension */\r
-  jvmtiError (JNICALL *GetSourceDebugExtension) (jvmtiEnv* env, \r
-    jclass klass, \r
-    char** source_debug_extension_ptr);\r
-\r
-  /*   91 : Is Method Obsolete */\r
-  jvmtiError (JNICALL *IsMethodObsolete) (jvmtiEnv* env, \r
-    jmethodID method, \r
-    jboolean* is_obsolete_ptr);\r
-\r
-  /*   92 : Suspend Thread List */\r
-  jvmtiError (JNICALL *SuspendThreadList) (jvmtiEnv* env, \r
-    jint request_count, \r
-    const jthread* request_list, \r
-    jvmtiError* results);\r
-\r
-  /*   93 : Resume Thread List */\r
-  jvmtiError (JNICALL *ResumeThreadList) (jvmtiEnv* env, \r
-    jint request_count, \r
-    const jthread* request_list, \r
-    jvmtiError* results);\r
-\r
-  /*   94 :  RESERVED */\r
-  void *reserved94;\r
-\r
-  /*   95 :  RESERVED */\r
-  void *reserved95;\r
-\r
-  /*   96 :  RESERVED */\r
-  void *reserved96;\r
-\r
-  /*   97 :  RESERVED */\r
-  void *reserved97;\r
-\r
-  /*   98 :  RESERVED */\r
-  void *reserved98;\r
-\r
-  /*   99 :  RESERVED */\r
-  void *reserved99;\r
-\r
-  /*   100 : Get All Stack Traces */\r
-  jvmtiError (JNICALL *GetAllStackTraces) (jvmtiEnv* env, \r
-    jint max_frame_count, \r
-    jvmtiStackInfo** stack_info_ptr, \r
-    jint* thread_count_ptr);\r
-\r
-  /*   101 : Get Thread List Stack Traces */\r
-  jvmtiError (JNICALL *GetThreadListStackTraces) (jvmtiEnv* env, \r
-    jint thread_count, \r
-    const jthread* thread_list, \r
-    jint max_frame_count, \r
-    jvmtiStackInfo** stack_info_ptr);\r
-\r
-  /*   102 : Get Thread Local Storage */\r
-  jvmtiError (JNICALL *GetThreadLocalStorage) (jvmtiEnv* env, \r
-    jthread thread, \r
-    void** data_ptr);\r
-\r
-  /*   103 : Set Thread Local Storage */\r
-  jvmtiError (JNICALL *SetThreadLocalStorage) (jvmtiEnv* env, \r
-    jthread thread, \r
-    const void* data);\r
-\r
-  /*   104 : Get Stack Trace */\r
-  jvmtiError (JNICALL *GetStackTrace) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jint start_depth, \r
-    jint max_frame_count, \r
-    jvmtiFrameInfo* frame_buffer, \r
-    jint* count_ptr);\r
-\r
-  /*   105 :  RESERVED */\r
-  void *reserved105;\r
-\r
-  /*   106 : Get Tag */\r
-  jvmtiError (JNICALL *GetTag) (jvmtiEnv* env, \r
-    jobject object, \r
-    jlong* tag_ptr);\r
-\r
-  /*   107 : Set Tag */\r
-  jvmtiError (JNICALL *SetTag) (jvmtiEnv* env, \r
-    jobject object, \r
-    jlong tag);\r
-\r
-  /*   108 : Force Garbage Collection */\r
-  jvmtiError (JNICALL *ForceGarbageCollection) (jvmtiEnv* env);\r
-\r
-  /*   109 : Iterate Over Objects Reachable From Object */\r
-  jvmtiError (JNICALL *IterateOverObjectsReachableFromObject) (jvmtiEnv* env, \r
-    jobject object, \r
-    jvmtiObjectReferenceCallback object_reference_callback, \r
-    void* user_data);\r
-\r
-  /*   110 : Iterate Over Reachable Objects */\r
-  jvmtiError (JNICALL *IterateOverReachableObjects) (jvmtiEnv* env, \r
-    jvmtiHeapRootCallback heap_root_callback, \r
-    jvmtiStackReferenceCallback stack_ref_callback, \r
-    jvmtiObjectReferenceCallback object_ref_callback, \r
-    void* user_data);\r
-\r
-  /*   111 : Iterate Over Heap */\r
-  jvmtiError (JNICALL *IterateOverHeap) (jvmtiEnv* env, \r
-    jvmtiHeapObjectFilter object_filter, \r
-    jvmtiHeapObjectCallback heap_object_callback, \r
-    void* user_data);\r
-\r
-  /*   112 : Iterate Over Instances Of Class */\r
-  jvmtiError (JNICALL *IterateOverInstancesOfClass) (jvmtiEnv* env, \r
-    jclass klass, \r
-    jvmtiHeapObjectFilter object_filter, \r
-    jvmtiHeapObjectCallback heap_object_callback, \r
-    void* user_data);\r
-\r
-  /*   113 :  RESERVED */\r
-  void *reserved113;\r
-\r
-  /*   114 : Get Objects With Tags */\r
-  jvmtiError (JNICALL *GetObjectsWithTags) (jvmtiEnv* env, \r
-    jint tag_count, \r
-    const jlong* tags, \r
-    jint* count_ptr, \r
-    jobject** object_result_ptr, \r
-    jlong** tag_result_ptr);\r
-\r
-  /*   115 :  RESERVED */\r
-  void *reserved115;\r
-\r
-  /*   116 :  RESERVED */\r
-  void *reserved116;\r
-\r
-  /*   117 :  RESERVED */\r
-  void *reserved117;\r
-\r
-  /*   118 :  RESERVED */\r
-  void *reserved118;\r
-\r
-  /*   119 :  RESERVED */\r
-  void *reserved119;\r
-\r
-  /*   120 : Set JNI Function Table */\r
-  jvmtiError (JNICALL *SetJNIFunctionTable) (jvmtiEnv* env, \r
-    const jniNativeInterface* function_table);\r
-\r
-  /*   121 : Get JNI Function Table */\r
-  jvmtiError (JNICALL *GetJNIFunctionTable) (jvmtiEnv* env, \r
-    jniNativeInterface** function_table);\r
-\r
-  /*   122 : Set Event Callbacks */\r
-  jvmtiError (JNICALL *SetEventCallbacks) (jvmtiEnv* env, \r
-    const jvmtiEventCallbacks* callbacks, \r
-    jint size_of_callbacks);\r
-\r
-  /*   123 : Generate Events */\r
-  jvmtiError (JNICALL *GenerateEvents) (jvmtiEnv* env, \r
-    jvmtiEvent event_type);\r
-\r
-  /*   124 : Get Extension Functions */\r
-  jvmtiError (JNICALL *GetExtensionFunctions) (jvmtiEnv* env, \r
-    jint* extension_count_ptr, \r
-    jvmtiExtensionFunctionInfo** extensions);\r
-\r
-  /*   125 : Get Extension Events */\r
-  jvmtiError (JNICALL *GetExtensionEvents) (jvmtiEnv* env, \r
-    jint* extension_count_ptr, \r
-    jvmtiExtensionEventInfo** extensions);\r
-\r
-  /*   126 : Set Extension Event Callback */\r
-  jvmtiError (JNICALL *SetExtensionEventCallback) (jvmtiEnv* env, \r
-    jint extension_event_index, \r
-    jvmtiExtensionEvent callback);\r
-\r
-  /*   127 : Dispose Environment */\r
-  jvmtiError (JNICALL *DisposeEnvironment) (jvmtiEnv* env);\r
-\r
-  /*   128 : Get Error Name */\r
-  jvmtiError (JNICALL *GetErrorName) (jvmtiEnv* env, \r
-    jvmtiError error, \r
-    char** name_ptr);\r
-\r
-  /*   129 : Get JLocation Format */\r
-  jvmtiError (JNICALL *GetJLocationFormat) (jvmtiEnv* env, \r
-    jvmtiJlocationFormat* format_ptr);\r
-\r
-  /*   130 : Get System Properties */\r
-  jvmtiError (JNICALL *GetSystemProperties) (jvmtiEnv* env, \r
-    jint* count_ptr, \r
-    char*** property_ptr);\r
-\r
-  /*   131 : Get System Property */\r
-  jvmtiError (JNICALL *GetSystemProperty) (jvmtiEnv* env, \r
-    const char* property, \r
-    char** value_ptr);\r
-\r
-  /*   132 : Set System Property */\r
-  jvmtiError (JNICALL *SetSystemProperty) (jvmtiEnv* env, \r
-    const char* property, \r
-    const char* value);\r
-\r
-  /*   133 : Get Phase */\r
-  jvmtiError (JNICALL *GetPhase) (jvmtiEnv* env, \r
-    jvmtiPhase* phase_ptr);\r
-\r
-  /*   134 : Get Current Thread CPU Timer Information */\r
-  jvmtiError (JNICALL *GetCurrentThreadCpuTimerInfo) (jvmtiEnv* env, \r
-    jvmtiTimerInfo* info_ptr);\r
-\r
-  /*   135 : Get Current Thread CPU Time */\r
-  jvmtiError (JNICALL *GetCurrentThreadCpuTime) (jvmtiEnv* env, \r
-    jlong* nanos_ptr);\r
-\r
-  /*   136 : Get Thread CPU Timer Information */\r
-  jvmtiError (JNICALL *GetThreadCpuTimerInfo) (jvmtiEnv* env, \r
-    jvmtiTimerInfo* info_ptr);\r
-\r
-  /*   137 : Get Thread CPU Time */\r
-  jvmtiError (JNICALL *GetThreadCpuTime) (jvmtiEnv* env, \r
-    jthread thread, \r
-    jlong* nanos_ptr);\r
-\r
-  /*   138 : Get Timer Information */\r
-  jvmtiError (JNICALL *GetTimerInfo) (jvmtiEnv* env, \r
-    jvmtiTimerInfo* info_ptr);\r
-\r
-  /*   139 : Get Time */\r
-  jvmtiError (JNICALL *GetTime) (jvmtiEnv* env, \r
-    jlong* nanos_ptr);\r
-\r
-  /*   140 : Get Potential Capabilities */\r
-  jvmtiError (JNICALL *GetPotentialCapabilities) (jvmtiEnv* env, \r
-    jvmtiCapabilities* capabilities_ptr);\r
-\r
-  /*   141 :  RESERVED */\r
-  void *reserved141;\r
-\r
-  /*   142 : Add Capabilities */\r
-  jvmtiError (JNICALL *AddCapabilities) (jvmtiEnv* env, \r
-    const jvmtiCapabilities* capabilities_ptr);\r
-\r
-  /*   143 : Relinquish Capabilities */\r
-  jvmtiError (JNICALL *RelinquishCapabilities) (jvmtiEnv* env, \r
-    const jvmtiCapabilities* capabilities_ptr);\r
-\r
-  /*   144 : Get Available Processors */\r
-  jvmtiError (JNICALL *GetAvailableProcessors) (jvmtiEnv* env, \r
-    jint* processor_count_ptr);\r
-\r
-  /*   145 :  RESERVED */\r
-  void *reserved145;\r
-\r
-  /*   146 :  RESERVED */\r
-  void *reserved146;\r
-\r
-  /*   147 : Get Environment Local Storage */\r
-  jvmtiError (JNICALL *GetEnvironmentLocalStorage) (jvmtiEnv* env, \r
-    void** data_ptr);\r
-\r
-  /*   148 : Set Environment Local Storage */\r
-  jvmtiError (JNICALL *SetEnvironmentLocalStorage) (jvmtiEnv* env, \r
-    const void* data);\r
-\r
-  /*   149 : Add To Bootstrap Class Loader Search */\r
-  jvmtiError (JNICALL *AddToBootstrapClassLoaderSearch) (jvmtiEnv* env, \r
-    const char* segment);\r
-\r
-  /*   150 : Set Verbose Flag */\r
-  jvmtiError (JNICALL *SetVerboseFlag) (jvmtiEnv* env, \r
-    jvmtiVerboseFlag flag, \r
-    jboolean value);\r
-\r
-  /*   151 :  RESERVED */\r
-  void *reserved151;\r
-\r
-  /*   152 :  RESERVED */\r
-  void *reserved152;\r
-\r
-  /*   153 :  RESERVED */\r
-  void *reserved153;\r
-\r
-  /*   154 : Get Object Size */\r
-  jvmtiError (JNICALL *GetObjectSize) (jvmtiEnv* env, \r
-    jobject object, \r
-    jlong* size_ptr);\r
-\r
-} jvmtiInterface_1;\r
-\r
-struct _jvmtiEnv {\r
-    const struct jvmtiInterface_1_ *functions;\r
-#ifdef __cplusplus\r
-\r
-\r
-  jvmtiError Allocate(jlong size,\r
-            unsigned char** mem_ptr) {\r
-    return functions->Allocate(this, size, mem_ptr);\r
-  }\r
-\r
-  jvmtiError Deallocate(unsigned char* mem) {\r
-    return functions->Deallocate(this, mem);\r
-  }\r
-\r
-  jvmtiError GetThreadState(jthread thread,\r
-            jint* thread_state_ptr) {\r
-    return functions->GetThreadState(this, thread, thread_state_ptr);\r
-  }\r
-\r
-  jvmtiError GetAllThreads(jint* threads_count_ptr,\r
-            jthread** threads_ptr) {\r
-    return functions->GetAllThreads(this, threads_count_ptr, threads_ptr);\r
-  }\r
-\r
-  jvmtiError SuspendThread(jthread thread) {\r
-    return functions->SuspendThread(this, thread);\r
-  }\r
-\r
-  jvmtiError SuspendThreadList(jint request_count,\r
-            const jthread* request_list,\r
-            jvmtiError* results) {\r
-    return functions->SuspendThreadList(this, request_count, request_list, results);\r
-  }\r
-\r
-  jvmtiError ResumeThread(jthread thread) {\r
-    return functions->ResumeThread(this, thread);\r
-  }\r
-\r
-  jvmtiError ResumeThreadList(jint request_count,\r
-            const jthread* request_list,\r
-            jvmtiError* results) {\r
-    return functions->ResumeThreadList(this, request_count, request_list, results);\r
-  }\r
-\r
-  jvmtiError StopThread(jthread thread,\r
-            jobject exception) {\r
-    return functions->StopThread(this, thread, exception);\r
-  }\r
-\r
-  jvmtiError InterruptThread(jthread thread) {\r
-    return functions->InterruptThread(this, thread);\r
-  }\r
-\r
-  jvmtiError GetThreadInfo(jthread thread,\r
-            jvmtiThreadInfo* info_ptr) {\r
-    return functions->GetThreadInfo(this, thread, info_ptr);\r
-  }\r
-\r
-  jvmtiError GetOwnedMonitorInfo(jthread thread,\r
-            jint* owned_monitor_count_ptr,\r
-            jobject** owned_monitors_ptr) {\r
-    return functions->GetOwnedMonitorInfo(this, thread, owned_monitor_count_ptr, owned_monitors_ptr);\r
-  }\r
-\r
-  jvmtiError GetCurrentContendedMonitor(jthread thread,\r
-            jobject* monitor_ptr) {\r
-    return functions->GetCurrentContendedMonitor(this, thread, monitor_ptr);\r
-  }\r
-\r
-  jvmtiError RunAgentThread(jthread thread,\r
-            jvmtiStartFunction proc,\r
-            const void* arg,\r
-            jint priority) {\r
-    return functions->RunAgentThread(this, thread, proc, arg, priority);\r
-  }\r
-\r
-  jvmtiError SetThreadLocalStorage(jthread thread,\r
-            const void* data) {\r
-    return functions->SetThreadLocalStorage(this, thread, data);\r
-  }\r
-\r
-  jvmtiError GetThreadLocalStorage(jthread thread,\r
-            void** data_ptr) {\r
-    return functions->GetThreadLocalStorage(this, thread, data_ptr);\r
-  }\r
-\r
-  jvmtiError GetTopThreadGroups(jint* group_count_ptr,\r
-            jthreadGroup** groups_ptr) {\r
-    return functions->GetTopThreadGroups(this, group_count_ptr, groups_ptr);\r
-  }\r
-\r
-  jvmtiError GetThreadGroupInfo(jthreadGroup group,\r
-            jvmtiThreadGroupInfo* info_ptr) {\r
-    return functions->GetThreadGroupInfo(this, group, info_ptr);\r
-  }\r
-\r
-  jvmtiError GetThreadGroupChildren(jthreadGroup group,\r
-            jint* thread_count_ptr,\r
-            jthread** threads_ptr,\r
-            jint* group_count_ptr,\r
-            jthreadGroup** groups_ptr) {\r
-    return functions->GetThreadGroupChildren(this, group, thread_count_ptr, threads_ptr, group_count_ptr, groups_ptr);\r
-  }\r
-\r
-  jvmtiError GetStackTrace(jthread thread,\r
-            jint start_depth,\r
-            jint max_frame_count,\r
-            jvmtiFrameInfo* frame_buffer,\r
-            jint* count_ptr) {\r
-    return functions->GetStackTrace(this, thread, start_depth, max_frame_count, frame_buffer, count_ptr);\r
-  }\r
-\r
-  jvmtiError GetAllStackTraces(jint max_frame_count,\r
-            jvmtiStackInfo** stack_info_ptr,\r
-            jint* thread_count_ptr) {\r
-    return functions->GetAllStackTraces(this, max_frame_count, stack_info_ptr, thread_count_ptr);\r
-  }\r
-\r
-  jvmtiError GetThreadListStackTraces(jint thread_count,\r
-            const jthread* thread_list,\r
-            jint max_frame_count,\r
-            jvmtiStackInfo** stack_info_ptr) {\r
-    return functions->GetThreadListStackTraces(this, thread_count, thread_list, max_frame_count, stack_info_ptr);\r
-  }\r
-\r
-  jvmtiError GetFrameCount(jthread thread,\r
-            jint* count_ptr) {\r
-    return functions->GetFrameCount(this, thread, count_ptr);\r
-  }\r
-\r
-  jvmtiError PopFrame(jthread thread) {\r
-    return functions->PopFrame(this, thread);\r
-  }\r
-\r
-  jvmtiError GetFrameLocation(jthread thread,\r
-            jint depth,\r
-            jmethodID* method_ptr,\r
-            jlocation* location_ptr) {\r
-    return functions->GetFrameLocation(this, thread, depth, method_ptr, location_ptr);\r
-  }\r
-\r
-  jvmtiError NotifyFramePop(jthread thread,\r
-            jint depth) {\r
-    return functions->NotifyFramePop(this, thread, depth);\r
-  }\r
-\r
-  jvmtiError GetTag(jobject object,\r
-            jlong* tag_ptr) {\r
-    return functions->GetTag(this, object, tag_ptr);\r
-  }\r
-\r
-  jvmtiError SetTag(jobject object,\r
-            jlong tag) {\r
-    return functions->SetTag(this, object, tag);\r
-  }\r
-\r
-  jvmtiError ForceGarbageCollection() {\r
-    return functions->ForceGarbageCollection(this);\r
-  }\r
-\r
-  jvmtiError IterateOverObjectsReachableFromObject(jobject object,\r
-            jvmtiObjectReferenceCallback object_reference_callback,\r
-            void* user_data) {\r
-    return functions->IterateOverObjectsReachableFromObject(this, object, object_reference_callback, user_data);\r
-  }\r
-\r
-  jvmtiError IterateOverReachableObjects(jvmtiHeapRootCallback heap_root_callback,\r
-            jvmtiStackReferenceCallback stack_ref_callback,\r
-            jvmtiObjectReferenceCallback object_ref_callback,\r
-            void* user_data) {\r
-    return functions->IterateOverReachableObjects(this, heap_root_callback, stack_ref_callback, object_ref_callback, user_data);\r
-  }\r
-\r
-  jvmtiError IterateOverHeap(jvmtiHeapObjectFilter object_filter,\r
-            jvmtiHeapObjectCallback heap_object_callback,\r
-            void* user_data) {\r
-    return functions->IterateOverHeap(this, object_filter, heap_object_callback, user_data);\r
-  }\r
-\r
-  jvmtiError IterateOverInstancesOfClass(jclass klass,\r
-            jvmtiHeapObjectFilter object_filter,\r
-            jvmtiHeapObjectCallback heap_object_callback,\r
-            void* user_data) {\r
-    return functions->IterateOverInstancesOfClass(this, klass, object_filter, heap_object_callback, user_data);\r
-  }\r
-\r
-  jvmtiError GetObjectsWithTags(jint tag_count,\r
-            const jlong* tags,\r
-            jint* count_ptr,\r
-            jobject** object_result_ptr,\r
-            jlong** tag_result_ptr) {\r
-    return functions->GetObjectsWithTags(this, tag_count, tags, count_ptr, object_result_ptr, tag_result_ptr);\r
-  }\r
-\r
-  jvmtiError GetLocalObject(jthread thread,\r
-            jint depth,\r
-            jint slot,\r
-            jobject* value_ptr) {\r
-    return functions->GetLocalObject(this, thread, depth, slot, value_ptr);\r
-  }\r
-\r
-  jvmtiError GetLocalInt(jthread thread,\r
-            jint depth,\r
-            jint slot,\r
-            jint* value_ptr) {\r
-    return functions->GetLocalInt(this, thread, depth, slot, value_ptr);\r
-  }\r
-\r
-  jvmtiError GetLocalLong(jthread thread,\r
-            jint depth,\r
-            jint slot,\r
-            jlong* value_ptr) {\r
-    return functions->GetLocalLong(this, thread, depth, slot, value_ptr);\r
-  }\r
-\r
-  jvmtiError GetLocalFloat(jthread thread,\r
-            jint depth,\r
-            jint slot,\r
-            jfloat* value_ptr) {\r
-    return functions->GetLocalFloat(this, thread, depth, slot, value_ptr);\r
-  }\r
-\r
-  jvmtiError GetLocalDouble(jthread thread,\r
-            jint depth,\r
-            jint slot,\r
-            jdouble* value_ptr) {\r
-    return functions->GetLocalDouble(this, thread, depth, slot, value_ptr);\r
-  }\r
-\r
-  jvmtiError SetLocalObject(jthread thread,\r
-            jint depth,\r
-            jint slot,\r
-            jobject value) {\r
-    return functions->SetLocalObject(this, thread, depth, slot, value);\r
-  }\r
-\r
-  jvmtiError SetLocalInt(jthread thread,\r
-            jint depth,\r
-            jint slot,\r
-            jint value) {\r
-    return functions->SetLocalInt(this, thread, depth, slot, value);\r
-  }\r
-\r
-  jvmtiError SetLocalLong(jthread thread,\r
-            jint depth,\r
-            jint slot,\r
-            jlong value) {\r
-    return functions->SetLocalLong(this, thread, depth, slot, value);\r
-  }\r
-\r
-  jvmtiError SetLocalFloat(jthread thread,\r
-            jint depth,\r
-            jint slot,\r
-            jfloat value) {\r
-    return functions->SetLocalFloat(this, thread, depth, slot, value);\r
-  }\r
-\r
-  jvmtiError SetLocalDouble(jthread thread,\r
-            jint depth,\r
-            jint slot,\r
-            jdouble value) {\r
-    return functions->SetLocalDouble(this, thread, depth, slot, value);\r
-  }\r
-\r
-  jvmtiError SetBreakpoint(jmethodID method,\r
-            jlocation location) {\r
-    return functions->SetBreakpoint(this, method, location);\r
-  }\r
-\r
-  jvmtiError ClearBreakpoint(jmethodID method,\r
-            jlocation location) {\r
-    return functions->ClearBreakpoint(this, method, location);\r
-  }\r
-\r
-  jvmtiError SetFieldAccessWatch(jclass klass,\r
-            jfieldID field) {\r
-    return functions->SetFieldAccessWatch(this, klass, field);\r
-  }\r
-\r
-  jvmtiError ClearFieldAccessWatch(jclass klass,\r
-            jfieldID field) {\r
-    return functions->ClearFieldAccessWatch(this, klass, field);\r
-  }\r
-\r
-  jvmtiError SetFieldModificationWatch(jclass klass,\r
-            jfieldID field) {\r
-    return functions->SetFieldModificationWatch(this, klass, field);\r
-  }\r
-\r
-  jvmtiError ClearFieldModificationWatch(jclass klass,\r
-            jfieldID field) {\r
-    return functions->ClearFieldModificationWatch(this, klass, field);\r
-  }\r
-\r
-  jvmtiError GetLoadedClasses(jint* class_count_ptr,\r
-            jclass** classes_ptr) {\r
-    return functions->GetLoadedClasses(this, class_count_ptr, classes_ptr);\r
-  }\r
-\r
-  jvmtiError GetClassLoaderClasses(jobject initiating_loader,\r
-            jint* class_count_ptr,\r
-            jclass** classes_ptr) {\r
-    return functions->GetClassLoaderClasses(this, initiating_loader, class_count_ptr, classes_ptr);\r
-  }\r
-\r
-  jvmtiError GetClassSignature(jclass klass,\r
-            char** signature_ptr,\r
-            char** generic_ptr) {\r
-    return functions->GetClassSignature(this, klass, signature_ptr, generic_ptr);\r
-  }\r
-\r
-  jvmtiError GetClassStatus(jclass klass,\r
-            jint* status_ptr) {\r
-    return functions->GetClassStatus(this, klass, status_ptr);\r
-  }\r
-\r
-  jvmtiError GetSourceFileName(jclass klass,\r
-            char** source_name_ptr) {\r
-    return functions->GetSourceFileName(this, klass, source_name_ptr);\r
-  }\r
-\r
-  jvmtiError GetClassModifiers(jclass klass,\r
-            jint* modifiers_ptr) {\r
-    return functions->GetClassModifiers(this, klass, modifiers_ptr);\r
-  }\r
-\r
-  jvmtiError GetClassMethods(jclass klass,\r
-            jint* method_count_ptr,\r
-            jmethodID** methods_ptr) {\r
-    return functions->GetClassMethods(this, klass, method_count_ptr, methods_ptr);\r
-  }\r
-\r
-  jvmtiError GetClassFields(jclass klass,\r
-            jint* field_count_ptr,\r
-            jfieldID** fields_ptr) {\r
-    return functions->GetClassFields(this, klass, field_count_ptr, fields_ptr);\r
-  }\r
-\r
-  jvmtiError GetImplementedInterfaces(jclass klass,\r
-            jint* interface_count_ptr,\r
-            jclass** interfaces_ptr) {\r
-    return functions->GetImplementedInterfaces(this, klass, interface_count_ptr, interfaces_ptr);\r
-  }\r
-\r
-  jvmtiError IsInterface(jclass klass,\r
-            jboolean* is_interface_ptr) {\r
-    return functions->IsInterface(this, klass, is_interface_ptr);\r
-  }\r
-\r
-  jvmtiError IsArrayClass(jclass klass,\r
-            jboolean* is_array_class_ptr) {\r
-    return functions->IsArrayClass(this, klass, is_array_class_ptr);\r
-  }\r
-\r
-  jvmtiError GetClassLoader(jclass klass,\r
-            jobject* classloader_ptr) {\r
-    return functions->GetClassLoader(this, klass, classloader_ptr);\r
-  }\r
-\r
-  jvmtiError GetSourceDebugExtension(jclass klass,\r
-            char** source_debug_extension_ptr) {\r
-    return functions->GetSourceDebugExtension(this, klass, source_debug_extension_ptr);\r
-  }\r
-\r
-  jvmtiError RedefineClasses(jint class_count,\r
-            const jvmtiClassDefinition* class_definitions) {\r
-    return functions->RedefineClasses(this, class_count, class_definitions);\r
-  }\r
-\r
-  jvmtiError GetObjectSize(jobject object,\r
-            jlong* size_ptr) {\r
-    return functions->GetObjectSize(this, object, size_ptr);\r
-  }\r
-\r
-  jvmtiError GetObjectHashCode(jobject object,\r
-            jint* hash_code_ptr) {\r
-    return functions->GetObjectHashCode(this, object, hash_code_ptr);\r
-  }\r
-\r
-  jvmtiError GetObjectMonitorUsage(jobject object,\r
-            jvmtiMonitorUsage* info_ptr) {\r
-    return functions->GetObjectMonitorUsage(this, object, info_ptr);\r
-  }\r
-\r
-  jvmtiError GetFieldName(jclass klass,\r
-            jfieldID field,\r
-            char** name_ptr,\r
-            char** signature_ptr,\r
-            char** generic_ptr) {\r
-    return functions->GetFieldName(this, klass, field, name_ptr, signature_ptr, generic_ptr);\r
-  }\r
-\r
-  jvmtiError GetFieldDeclaringClass(jclass klass,\r
-            jfieldID field,\r
-            jclass* declaring_class_ptr) {\r
-    return functions->GetFieldDeclaringClass(this, klass, field, declaring_class_ptr);\r
-  }\r
-\r
-  jvmtiError GetFieldModifiers(jclass klass,\r
-            jfieldID field,\r
-            jint* modifiers_ptr) {\r
-    return functions->GetFieldModifiers(this, klass, field, modifiers_ptr);\r
-  }\r
-\r
-  jvmtiError IsFieldSynthetic(jclass klass,\r
-            jfieldID field,\r
-            jboolean* is_synthetic_ptr) {\r
-    return functions->IsFieldSynthetic(this, klass, field, is_synthetic_ptr);\r
-  }\r
-\r
-  jvmtiError GetMethodName(jmethodID method,\r
-            char** name_ptr,\r
-            char** signature_ptr,\r
-            char** generic_ptr) {\r
-    return functions->GetMethodName(this, method, name_ptr, signature_ptr, generic_ptr);\r
-  }\r
-\r
-  jvmtiError GetMethodDeclaringClass(jmethodID method,\r
-            jclass* declaring_class_ptr) {\r
-    return functions->GetMethodDeclaringClass(this, method, declaring_class_ptr);\r
-  }\r
-\r
-  jvmtiError GetMethodModifiers(jmethodID method,\r
-            jint* modifiers_ptr) {\r
-    return functions->GetMethodModifiers(this, method, modifiers_ptr);\r
-  }\r
-\r
-  jvmtiError GetMaxLocals(jmethodID method,\r
-            jint* max_ptr) {\r
-    return functions->GetMaxLocals(this, method, max_ptr);\r
-  }\r
-\r
-  jvmtiError GetArgumentsSize(jmethodID method,\r
-            jint* size_ptr) {\r
-    return functions->GetArgumentsSize(this, method, size_ptr);\r
-  }\r
-\r
-  jvmtiError GetLineNumberTable(jmethodID method,\r
-            jint* entry_count_ptr,\r
-            jvmtiLineNumberEntry** table_ptr) {\r
-    return functions->GetLineNumberTable(this, method, entry_count_ptr, table_ptr);\r
-  }\r
-\r
-  jvmtiError GetMethodLocation(jmethodID method,\r
-            jlocation* start_location_ptr,\r
-            jlocation* end_location_ptr) {\r
-    return functions->GetMethodLocation(this, method, start_location_ptr, end_location_ptr);\r
-  }\r
-\r
-  jvmtiError GetLocalVariableTable(jmethodID method,\r
-            jint* entry_count_ptr,\r
-            jvmtiLocalVariableEntry** table_ptr) {\r
-    return functions->GetLocalVariableTable(this, method, entry_count_ptr, table_ptr);\r
-  }\r
-\r
-  jvmtiError GetBytecodes(jmethodID method,\r
-            jint* bytecode_count_ptr,\r
-            unsigned char** bytecodes_ptr) {\r
-    return functions->GetBytecodes(this, method, bytecode_count_ptr, bytecodes_ptr);\r
-  }\r
-\r
-  jvmtiError IsMethodNative(jmethodID method,\r
-            jboolean* is_native_ptr) {\r
-    return functions->IsMethodNative(this, method, is_native_ptr);\r
-  }\r
-\r
-  jvmtiError IsMethodSynthetic(jmethodID method,\r
-            jboolean* is_synthetic_ptr) {\r
-    return functions->IsMethodSynthetic(this, method, is_synthetic_ptr);\r
-  }\r
-\r
-  jvmtiError IsMethodObsolete(jmethodID method,\r
-            jboolean* is_obsolete_ptr) {\r
-    return functions->IsMethodObsolete(this, method, is_obsolete_ptr);\r
-  }\r
-\r
-  jvmtiError CreateRawMonitor(const char* name,\r
-            jrawMonitorID* monitor_ptr) {\r
-    return functions->CreateRawMonitor(this, name, monitor_ptr);\r
-  }\r
-\r
-  jvmtiError DestroyRawMonitor(jrawMonitorID monitor) {\r
-    return functions->DestroyRawMonitor(this, monitor);\r
-  }\r
-\r
-  jvmtiError RawMonitorEnter(jrawMonitorID monitor) {\r
-    return functions->RawMonitorEnter(this, monitor);\r
-  }\r
-\r
-  jvmtiError RawMonitorExit(jrawMonitorID monitor) {\r
-    return functions->RawMonitorExit(this, monitor);\r
-  }\r
-\r
-  jvmtiError RawMonitorWait(jrawMonitorID monitor,\r
-            jlong millis) {\r
-    return functions->RawMonitorWait(this, monitor, millis);\r
-  }\r
-\r
-  jvmtiError RawMonitorNotify(jrawMonitorID monitor) {\r
-    return functions->RawMonitorNotify(this, monitor);\r
-  }\r
-\r
-  jvmtiError RawMonitorNotifyAll(jrawMonitorID monitor) {\r
-    return functions->RawMonitorNotifyAll(this, monitor);\r
-  }\r
-\r
-  jvmtiError SetJNIFunctionTable(const jniNativeInterface* function_table) {\r
-    return functions->SetJNIFunctionTable(this, function_table);\r
-  }\r
-\r
-  jvmtiError GetJNIFunctionTable(jniNativeInterface** function_table) {\r
-    return functions->GetJNIFunctionTable(this, function_table);\r
-  }\r
-\r
-  jvmtiError SetEventCallbacks(const jvmtiEventCallbacks* callbacks,\r
-            jint size_of_callbacks) {\r
-    return functions->SetEventCallbacks(this, callbacks, size_of_callbacks);\r
-  }\r
-\r
-  jvmtiError SetEventNotificationMode(jvmtiEventMode mode,\r
-            jvmtiEvent event_type,\r
-            jthread event_thread,\r
-             ...) {\r
-    return functions->SetEventNotificationMode(this, mode, event_type, event_thread);\r
-  }\r
-\r
-  jvmtiError GenerateEvents(jvmtiEvent event_type) {\r
-    return functions->GenerateEvents(this, event_type);\r
-  }\r
-\r
-  jvmtiError GetExtensionFunctions(jint* extension_count_ptr,\r
-            jvmtiExtensionFunctionInfo** extensions) {\r
-    return functions->GetExtensionFunctions(this, extension_count_ptr, extensions);\r
-  }\r
-\r
-  jvmtiError GetExtensionEvents(jint* extension_count_ptr,\r
-            jvmtiExtensionEventInfo** extensions) {\r
-    return functions->GetExtensionEvents(this, extension_count_ptr, extensions);\r
-  }\r
-\r
-  jvmtiError SetExtensionEventCallback(jint extension_event_index,\r
-            jvmtiExtensionEvent callback) {\r
-    return functions->SetExtensionEventCallback(this, extension_event_index, callback);\r
-  }\r
-\r
-  jvmtiError GetPotentialCapabilities(jvmtiCapabilities* capabilities_ptr) {\r
-    return functions->GetPotentialCapabilities(this, capabilities_ptr);\r
-  }\r
-\r
-  jvmtiError AddCapabilities(const jvmtiCapabilities* capabilities_ptr) {\r
-    return functions->AddCapabilities(this, capabilities_ptr);\r
-  }\r
-\r
-  jvmtiError RelinquishCapabilities(const jvmtiCapabilities* capabilities_ptr) {\r
-    return functions->RelinquishCapabilities(this, capabilities_ptr);\r
-  }\r
-\r
-  jvmtiError GetCapabilities(jvmtiCapabilities* capabilities_ptr) {\r
-    return functions->GetCapabilities(this, capabilities_ptr);\r
-  }\r
-\r
-  jvmtiError GetCurrentThreadCpuTimerInfo(jvmtiTimerInfo* info_ptr) {\r
-    return functions->GetCurrentThreadCpuTimerInfo(this, info_ptr);\r
-  }\r
-\r
-  jvmtiError GetCurrentThreadCpuTime(jlong* nanos_ptr) {\r
-    return functions->GetCurrentThreadCpuTime(this, nanos_ptr);\r
-  }\r
-\r
-  jvmtiError GetThreadCpuTimerInfo(jvmtiTimerInfo* info_ptr) {\r
-    return functions->GetThreadCpuTimerInfo(this, info_ptr);\r
-  }\r
-\r
-  jvmtiError GetThreadCpuTime(jthread thread,\r
-            jlong* nanos_ptr) {\r
-    return functions->GetThreadCpuTime(this, thread, nanos_ptr);\r
-  }\r
-\r
-  jvmtiError GetTimerInfo(jvmtiTimerInfo* info_ptr) {\r
-    return functions->GetTimerInfo(this, info_ptr);\r
-  }\r
-\r
-  jvmtiError GetTime(jlong* nanos_ptr) {\r
-    return functions->GetTime(this, nanos_ptr);\r
-  }\r
-\r
-  jvmtiError GetAvailableProcessors(jint* processor_count_ptr) {\r
-    return functions->GetAvailableProcessors(this, processor_count_ptr);\r
-  }\r
-\r
-  jvmtiError AddToBootstrapClassLoaderSearch(const char* segment) {\r
-    return functions->AddToBootstrapClassLoaderSearch(this, segment);\r
-  }\r
-\r
-  jvmtiError GetSystemProperties(jint* count_ptr,\r
-            char*** property_ptr) {\r
-    return functions->GetSystemProperties(this, count_ptr, property_ptr);\r
-  }\r
-\r
-  jvmtiError GetSystemProperty(const char* property,\r
-            char** value_ptr) {\r
-    return functions->GetSystemProperty(this, property, value_ptr);\r
-  }\r
-\r
-  jvmtiError SetSystemProperty(const char* property,\r
-            const char* value) {\r
-    return functions->SetSystemProperty(this, property, value);\r
-  }\r
-\r
-  jvmtiError GetPhase(jvmtiPhase* phase_ptr) {\r
-    return functions->GetPhase(this, phase_ptr);\r
-  }\r
-\r
-  jvmtiError DisposeEnvironment() {\r
-    return functions->DisposeEnvironment(this);\r
-  }\r
-\r
-  jvmtiError SetEnvironmentLocalStorage(const void* data) {\r
-    return functions->SetEnvironmentLocalStorage(this, data);\r
-  }\r
-\r
-  jvmtiError GetEnvironmentLocalStorage(void** data_ptr) {\r
-    return functions->GetEnvironmentLocalStorage(this, data_ptr);\r
-  }\r
-\r
-  jvmtiError GetVersionNumber(jint* version_ptr) {\r
-    return functions->GetVersionNumber(this, version_ptr);\r
-  }\r
-\r
-  jvmtiError GetErrorName(jvmtiError error,\r
-            char** name_ptr) {\r
-    return functions->GetErrorName(this, error, name_ptr);\r
-  }\r
-\r
-  jvmtiError SetVerboseFlag(jvmtiVerboseFlag flag,\r
-            jboolean value) {\r
-    return functions->SetVerboseFlag(this, flag, value);\r
-  }\r
-\r
-  jvmtiError GetJLocationFormat(jvmtiJlocationFormat* format_ptr) {\r
-    return functions->GetJLocationFormat(this, format_ptr);\r
-  }\r
-\r
-#endif /* __cplusplus */\r
-};\r
-\r
-\r
-#ifdef __cplusplus\r
-} /* extern "C" */\r
-#endif /* __cplusplus */\r
-\r
-#endif /* !_JAVA_JVMTI_H_ */\r
-\r
diff --git a/JavaOpenJPEG/java-jni/include/win32/jawt_md.h b/JavaOpenJPEG/java-jni/include/win32/jawt_md.h
deleted file mode 100644 (file)
index 5df3e46..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-/*\r
- * @(#)jawt_md.h       1.7 03/12/19\r
- *\r
- * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
- * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
- */\r
-\r
-#ifndef _JAVASOFT_JAWT_MD_H_\r
-#define _JAVASOFT_JAWT_MD_H_\r
-\r
-#include <windows.h>\r
-#include "jawt.h"\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-/*\r
- * Win32-specific declarations for AWT native interface.\r
- * See notes in jawt.h for an example of use.\r
- */\r
-typedef struct jawt_Win32DrawingSurfaceInfo {\r
-    /* Native window, DDB, or DIB handle */\r
-    union {\r
-        HWND hwnd;\r
-        HBITMAP hbitmap;\r
-        void* pbits;\r
-    };\r
-    /*\r
-     * This HDC should always be used instead of the HDC returned from\r
-     * BeginPaint() or any calls to GetDC().\r
-     */\r
-    HDC hdc;\r
-    HPALETTE hpalette;\r
-} JAWT_Win32DrawingSurfaceInfo;\r
-\r
-#ifdef __cplusplus\r
-}\r
-#endif\r
-\r
-#endif /* !_JAVASOFT_JAWT_MD_H_ */\r
diff --git a/JavaOpenJPEG/java-jni/include/win32/jni_md.h b/JavaOpenJPEG/java-jni/include/win32/jni_md.h
deleted file mode 100644 (file)
index fdc79a0..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-/*\r
- * @(#)jni_md.h        1.14 03/12/19\r
- *\r
- * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
- * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
- */\r
-\r
-#ifndef _JAVASOFT_JNI_MD_H_\r
-#define _JAVASOFT_JNI_MD_H_\r
-\r
-#define JNIEXPORT __declspec(dllexport)\r
-#define JNIIMPORT __declspec(dllimport)\r
-#define JNICALL __stdcall\r
-\r
-typedef long jint;\r
-typedef __int64 jlong;\r
-typedef signed char jbyte;\r
-\r
-#endif /* !_JAVASOFT_JNI_MD_H_ */\r
diff --git a/JavaOpenJPEG/java-jni/lib/jvm.lib b/JavaOpenJPEG/java-jni/lib/jvm.lib
deleted file mode 100644 (file)
index 672855a..0000000
Binary files a/JavaOpenJPEG/java-jni/lib/jvm.lib and /dev/null differ
diff --git a/JavaOpenJPEG/java-sources/org/openJpeg/OpenJPEGJavaDecoder.java b/JavaOpenJPEG/java-sources/org/openJpeg/OpenJPEGJavaDecoder.java
deleted file mode 100644 (file)
index 0bacc84..0000000
+++ /dev/null
@@ -1,250 +0,0 @@
-/*\r
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
- * Copyright (c) 2002-2007, Professor Benoit Macq\r
- * Copyright (c) 2002-2007, Patrick Piscaglia, Telemis s.a.\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */ \r
-package org.openJpeg;\r
-\r
-import java.util.Vector;\r
-\r
-/** This class decodes one J2K codestream into an image (width + height + depth + pixels[], \r
- * using the OpenJPEG.org library.\r
- * To be able to log messages, the called must register a IJavaJ2KDecoderLogger object.\r
- */\r
-public class OpenJPEGJavaDecoder {\r
-\r
-       public interface IJavaJ2KDecoderLogger {\r
-               public void logDecoderMessage(String message);\r
-               public void logDecoderError(String message);\r
-       }\r
-       \r
-    private static boolean isInitialized = false;\r
-    \r
-       // ===== decompression parameters =============>\r
-       // These value may be changed for each image\r
-    private String[] decoder_arguments = null;\r
-       /** number of resolutions decompositions */\r
-       private int nbResolutions = -1;\r
-       /** the quality layers */\r
-       private int[] layers = null;\r
-\r
-       /** Contains the 8 bpp version of the image. May NOT be filled together with image16 or image24.<P>\r
-        * We store in Java the 8 or 16 bpp version of the image while the decoder uses a 32 bpp version, because <UL>\r
-        * <LI> the storage capacity required is smaller\r
-        * <LI> the transfer Java <-- C will be faster\r
-        * <LI> the conversion byte/short ==> int will be done faster by the C\r
-        * </UL>*/\r
-       private byte[] image8 = null;\r
-       /** Contains the 16 bpp version of the image. May NOT be filled together with image8 or image24*/\r
-       private short[] image16 = null;\r
-       /** Contains the 24 bpp version of the image. May NOT be filled together with image8 or image16 */\r
-       private int[] image24 = null;\r
-       /** Holds the J2K compressed bytecode to decode */\r
-    private byte compressedStream[] = null;\r
-    /** Holds the compressed version of the index file, to be used by the decoder */\r
-    private byte compressedIndex[] = null;\r
-    /** Width and Height of the image */\r
-    private int width = -1;\r
-    private int height = -1;\r
-    private int depth = -1;\r
-    /** This parameter is never used in Java but is read by the C library to know the number of resolutions to skip when decoding, \r
-     * i.e. if there are 5 resolutions and skipped=1 ==> decode until resolution 4.  */\r
-    private int skippedResolutions = 0;\r
-    \r
-    private Vector<IJavaJ2KDecoderLogger> loggers = new Vector();\r
-\r
-\r
-    public OpenJPEGJavaDecoder(String openJPEGlibraryFullPathAndName, IJavaJ2KDecoderLogger messagesAndErrorsLogger) throws ExceptionInInitializerError\r
-    {\r
-       this(openJPEGlibraryFullPathAndName);\r
-       loggers.addElement(messagesAndErrorsLogger);\r
-    }\r
-\r
-    public OpenJPEGJavaDecoder(String openJPEGlibraryFullPathAndName) throws ExceptionInInitializerError\r
-    {\r
-       if (!isInitialized) {\r
-               try {\r
-                       System.load(openJPEGlibraryFullPathAndName);\r
-                       isInitialized = true;\r
-               } catch (Throwable t) {\r
-                       throw new ExceptionInInitializerError("OpenJPEG Java Decoder: probably impossible to find the C library");\r
-               }\r
-       }\r
-    }\r
-    \r
-    public void addLogger(IJavaJ2KDecoderLogger messagesAndErrorsLogger) {\r
-       loggers.addElement(messagesAndErrorsLogger);\r
-    }\r
-    \r
-    public void removeLogger(IJavaJ2KDecoderLogger messagesAndErrorsLogger) {\r
-       loggers.removeElement(messagesAndErrorsLogger);\r
-    }\r
-    \r
-    public int  decodeJ2KtoImage() {\r
-               if ((image16 == null || (image16 != null && image16.length != width*height)) && (depth==-1 || depth==16)) {\r
-                       image16 = new short[width*height];\r
-                       logMessage("OpenJPEGJavaDecoder.decompressImage: image16 length = " + image16.length + " (" + width + " x " + height + ") ");\r
-               }\r
-               if ((image8 == null || (image8 != null && image8.length != width*height)) && (depth==-1 || depth==8)) {\r
-                       image8 = new byte[width*height];\r
-                       logMessage("OpenJPEGJavaDecoder.decompressImage: image8 length = " + image8.length + " (" + width + " x " + height + ") ");\r
-               }\r
-               if ((image24 == null || (image24 != null && image24.length != width*height)) && (depth==-1 || depth==24)) {\r
-                       image24 = new int[width*height];\r
-                       logMessage("OpenJPEGJavaDecoder.decompressImage: image24 length = " + image24.length + " (" + width + " x " + height + ") ");\r
-               }\r
-               \r
-               String[] arguments = new String[0 + (decoder_arguments != null ? decoder_arguments.length : 0)];\r
-               int offset = 0;\r
-               if (decoder_arguments != null) {\r
-                       for (int i=0; i<decoder_arguments.length; i++) {\r
-                               arguments[i+offset] = decoder_arguments[i];\r
-                       }\r
-               }\r
-\r
-               return internalDecodeJ2KtoImage(arguments);\r
-    }\r
-    \r
-    /** \r
-     * Decode the j2k stream given in the codestream byte[] and fills the image8, image16 or image24 array, according to the bit depth.\r
-     */\r
-    private native int internalDecodeJ2KtoImage(String[] parameters);\r
-\r
-    /** Image depth in bpp */\r
-       public int getDepth() {\r
-               return depth;\r
-       }\r
-\r
-    /** Image depth in bpp */\r
-       public void setDepth(int depth) {\r
-               this.depth = depth;\r
-       }\r
-\r
-       /** Image height in pixels */\r
-       public int getHeight() {\r
-               return height;\r
-       }\r
-\r
-       /** Image height in pixels */\r
-       public void setHeight(int height) {\r
-               this.height = height;\r
-       }\r
-\r
-       /** Number of resolutions contained in the image */\r
-       public int getNbResolutions() {\r
-               return nbResolutions;\r
-       }\r
-\r
-       /** Number of resolutions contained in the image */\r
-       public void setNbResolutions(int nbResolutions) {\r
-               this.nbResolutions = nbResolutions;\r
-       }\r
-\r
-       /** Width of the image in pixels */\r
-       public int getWidth() {\r
-               return width;\r
-       }\r
-\r
-       /** Width of the image in pixels */\r
-       public void setWidth(int width) {\r
-               this.width = width;\r
-       }\r
-\r
-       /** Contains the decompressed version of the image, if the depth in is [9,16] bpp.\r
-        * Returns NULL otherwise.\r
-        */\r
-       public short[] getImage16() {\r
-               return image16;\r
-       }\r
-\r
-       /** Contains the decompressed version of the image, if the depth in is [17,24] bpp and the image is in color.\r
-        * Returns NULL otherwise.\r
-        */\r
-       public int[] getImage24() {\r
-               return image24;\r
-       }\r
-\r
-       /** Contains the decompressed version of the image, if the depth in is [1,8] bpp.\r
-        * Returns NULL otherwise.\r
-        */\r
-       public byte[] getImage8() {\r
-               return image8;\r
-       }\r
-\r
-       /** Sets the compressed version of the index file for this image.\r
-        * This index file is used by the decompressor\r
-        */\r
-       public void setCompressedIndex(byte[] compressedIndex) {\r
-               this.compressedIndex = compressedIndex;\r
-       }\r
-\r
-       /** Sets the codestream to be decoded */\r
-       public void setCompressedStream(byte[] compressedStream) {\r
-               this.compressedStream = compressedStream;\r
-       }\r
-\r
-       /** @return the compressed code stream length, or -1 if not defined */\r
-       public long getCodestreamLength() {\r
-               if (compressedStream == null)\r
-                       return -1;\r
-               else return compressedStream.length;\r
-       }\r
-       \r
-       /** This method is called either directly or by the C methods */\r
-       public void logMessage(String message) {\r
-               for (IJavaJ2KDecoderLogger logger:loggers)\r
-                       logger.logDecoderMessage(message);\r
-       }\r
-       \r
-       /** This method is called either directly or by the C methods */\r
-       public void logError(String error) {\r
-               for (IJavaJ2KDecoderLogger logger:loggers)\r
-                       logger.logDecoderError(error);\r
-       }\r
-\r
-       public void reset() {\r
-               nbResolutions = -1;\r
-               layers = null;\r
-               image8 = null;\r
-               image16 = null;\r
-               image24 = null;\r
-               compressedStream = null;\r
-           compressedIndex = null;\r
-           width = -1;\r
-           height = -1;\r
-           depth = -1;\r
-       }\r
-\r
-       public void setSkippedResolutions(int numberOfSkippedResolutions) {\r
-               skippedResolutions = numberOfSkippedResolutions;\r
-       }\r
-\r
-       /** Contains all the decoding arguments other than the input/output file */\r
-       public void setDecoderArguments(String[] argumentsForTheDecoder) {\r
-               decoder_arguments = argumentsForTheDecoder;\r
-       }\r
-\r
-\r
-}\r
diff --git a/JavaOpenJPEG/java-sources/org/openJpeg/OpenJPEGJavaEncoder.java b/JavaOpenJPEG/java-sources/org/openJpeg/OpenJPEGJavaEncoder.java
deleted file mode 100644 (file)
index 2c638cf..0000000
+++ /dev/null
@@ -1,338 +0,0 @@
-/*\r
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
- * Copyright (c) 2002-2007, Professor Benoit Macq\r
- * Copyright (c) 2002-2007, Patrick Piscaglia, Telemis s.a.\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */  \r
-package org.openJpeg;\r
-\r
-import java.io.File;\r
-import java.util.Vector;\r
-\r
-/** This class encodes one image into the J2K format, \r
- * using the OpenJPEG.org library.\r
- * To be able to log messages, the called must register a IJavaJ2KEncoderLogger object.\r
- */\r
-public class OpenJPEGJavaEncoder {\r
-\r
-       public interface IJavaJ2KEncoderLogger {\r
-               public void logEncoderMessage(String message);\r
-               public void logEncoderError(String message);\r
-       }\r
-       \r
-    private static boolean isInitialized = false;\r
-    \r
-       // ===== Compression parameters =============>\r
-       // These value may be changed for each image\r
-    private String[] encoder_arguments = null;\r
-       /** number of resolutions decompositions */\r
-       private int nbResolutions = -1;\r
-       /** the quality layers, expressed as compression rate */\r
-       private float[] ratioLayers = null;\r
-       /** the quality layers, expressed as PSNR values. This variable, if defined, has priority over the ratioLayers variable */\r
-       private float[] psnrLayers = null;\r
-       \r
-       /** Contains the 8 bpp version of the image. May NOT be filled together with image16 or image24.<P>\r
-        * We store the 8 or 16 bpp version of the original image while the encoder uses a 32 bpp version, because <UL>\r
-        * <LI> the storage capacity required is smaller\r
-        * <LI> the transfer Java --> C will be faster\r
-        * <LI> the conversion byte/short ==> int will be done faster by the C\r
-        * </UL>*/\r
-       private byte[] image8 = null;\r
-       /** Contains the 16 bpp version of the image. May NOT be filled together with image8 or image24*/\r
-       private short[] image16 = null;\r
-       /** Contains the 24 bpp version of the image. May NOT be filled together with image8 or image16 */\r
-       private int[] image24 = null;\r
-       /** Holds the result of the compression, i.e. the J2K compressed bytecode */\r
-    private byte compressedStream[] = null;\r
-    /** Holds the compressed stream length, which may be smaller than compressedStream.length if this byte[] is pre-allocated */\r
-    private long compressedStreamLength = -1;\r
-    /** Holds the compressed version of the index file, returned by the encoder */\r
-    private byte compressedIndex[] = null;\r
-    /** Width and Height of the image */\r
-    private int width = -1;\r
-    private int height = -1;\r
-    private int depth = -1;\r
-    /** Tile size. We suppose the same size for the horizontal and vertical tiles.\r
-     * If size == -1 ==> no tiling */\r
-    private int tileSize = -1;\r
-    // <===== Compression parameters =============\r
-    \r
-    private Vector<IJavaJ2KEncoderLogger> loggers = new Vector();\r
-\r
-    public OpenJPEGJavaEncoder(String openJPEGlibraryFullPathAndName, IJavaJ2KEncoderLogger messagesAndErrorsLogger) throws ExceptionInInitializerError\r
-    {\r
-       this(openJPEGlibraryFullPathAndName);\r
-       loggers.addElement(messagesAndErrorsLogger);\r
-    }\r
-\r
-    public OpenJPEGJavaEncoder(String openJPEGlibraryFullPathAndName) throws ExceptionInInitializerError\r
-    {\r
-       if (!isInitialized) {\r
-               try {\r
-                       String absolutePath = (new File(openJPEGlibraryFullPathAndName)).getCanonicalPath();\r
-                       System.load(absolutePath);\r
-                       isInitialized = true;\r
-               } catch (Throwable t) {\r
-                       t.printStackTrace();\r
-                       throw new ExceptionInInitializerError("OpenJPEG Java Encoder: probably impossible to find the C library");\r
-               }\r
-       }\r
-    }\r
-    \r
-    public void addLogger(IJavaJ2KEncoderLogger messagesAndErrorsLogger) {\r
-       loggers.addElement(messagesAndErrorsLogger);\r
-    }\r
-    \r
-    public void removeLogger(IJavaJ2KEncoderLogger messagesAndErrorsLogger) {\r
-       loggers.removeElement(messagesAndErrorsLogger);\r
-    }\r
-    \r
-    /** This method compresses the given image.<P>\r
-     * It returns the compressed J2K codestream into the compressedStream byte[].<P>\r
-     * It also returns the compression index as a compressed form, into the compressedIndex byte[].<P>\r
-     * One of the image8, image16 or image24 arrays must be correctly initialized and filled.<P>\r
-     * The width, height and depth variables must be correctly filled.<P>\r
-     * The nbResolutions, nbLayers and if needed the float[] psnrLayers or ratioLayers must also be filled before calling this method.\r
-     */\r
-    public void encodeImageToJ2K() {\r
-               // Need to allocate / reallocate the compressed stream buffer ? (size = max possible size = original image size)\r
-               if (compressedStream== null || (compressedStream.length != width*height*depth/8)) {\r
-                       logMessage("OpenJPEGJavaEncoder.encodeImageToJ2K: (re-)allocating " + (width*height*depth/8) + " bytes for the compressedStream");\r
-                       compressedStream = new byte[width*height*depth/8];\r
-               }\r
-               // Arguments = \r
-               // - number of resolutions "-n 5" : 2\r
-               // - size of tile "-t 512,512" : 2\r
-               // \r
-               // Image width, height, depth and pixels are directly fetched by C from the Java class\r
-               int nbArgs = 2 + (tileSize == -1 ? 0 : 2) + (encoder_arguments != null ? encoder_arguments.length : 0);\r
-               if (psnrLayers != null && psnrLayers.length>0 && psnrLayers[0] != 0)\r
-                       // If psnrLayers is defined and doesn't just express "lossless"\r
-                       nbArgs += 2;\r
-               else if (ratioLayers != null && ratioLayers.length>0 && ratioLayers[0]!=0.0)\r
-                       nbArgs += 2;\r
-               String[] arguments = new String[nbArgs];\r
-               int offset = 0;\r
-               arguments[offset] = "-n"; arguments[offset+1] = "" + nbResolutions; offset += 2;\r
-               if (tileSize!= -1) {\r
-                       arguments[offset++] = "-t"; \r
-                       arguments[offset++] = "" + tileSize + "," + tileSize;\r
-               }\r
-               // If PSNR layers are defined, use them to encode the images\r
-               if (psnrLayers != null && psnrLayers.length>0 && psnrLayers[0]!=-1) {\r
-                       arguments[offset++] = "-q";\r
-                       String s = "";\r
-                       for (int i=0; i<psnrLayers.length; i++)\r
-                               s += psnrLayers[i] + ",";\r
-                       arguments[offset++] = s.substring(0, s.length()-1);\r
-               } else if (ratioLayers != null && ratioLayers.length>0 && ratioLayers[0]!=0.0) {\r
-                       // Specify quality ratioLayers, as compression ratios\r
-                       arguments[offset++] = "-r";\r
-                       String s = "";\r
-                       for (int i=0; i<ratioLayers.length; i++)\r
-                               s += ratioLayers[i] + ",";\r
-                       arguments[offset++] = s.substring(0, s.length()-1);\r
-               }\r
-               if (encoder_arguments != null) {\r
-                       for (int i=0; i<encoder_arguments.length; i++) {\r
-                               arguments[i+offset] = encoder_arguments[i];\r
-                       }\r
-               }\r
-               logMessage("Encoder additional arguments = " + arrayToString(arguments));\r
-               long startTime = (new java.util.Date()).getTime();\r
-               compressedStreamLength = internalEncodeImageToJ2K(arguments);\r
-               logMessage("compression time = " + ((new java.util.Date()).getTime() - startTime) + " msec");\r
-    }\r
-    \r
-    /** \r
-     * Fills the compressedStream byte[] and the compressedIndex byte[]\r
-     * @return the codestream length.\r
-     */\r
-    private native long internalEncodeImageToJ2K(String[] parameters);\r
-\r
-    /** Image depth in bpp */\r
-       public int getDepth() {\r
-               return depth;\r
-       }\r
-\r
-    /** Image depth in bpp */\r
-       public void setDepth(int depth) {\r
-               this.depth = depth;\r
-       }\r
-\r
-       /** Image height in pixels  */\r
-       public int getHeight() {\r
-               return height;\r
-       }\r
-\r
-       /** Image height in pixels  */\r
-       public void setHeight(int height) {\r
-               this.height = height;\r
-       }\r
-\r
-       /** This method must be called in depth in [9,16].\r
-        * @param an array of shorts, containing width*height values\r
-        */\r
-       public void setImage16(short[] image16) {\r
-               this.image16 = image16;\r
-       }\r
-\r
-       /** This method must be called in depth in [17,24] for RGB images.\r
-        * @param an array of int, containing width*height values\r
-        */\r
-       public void setImage24(int[] image24) {\r
-               this.image24 = image24;\r
-       }\r
-\r
-       /** This method must be called in depth in [1,8].\r
-        * @param an array of bytes, containing width*height values\r
-        */\r
-       public void setImage8(byte[] image8) {\r
-               this.image8 = image8;\r
-       }\r
-\r
-       /** Return the ratioLayers, i.e. the compression ratio for each quality layer.\r
-        * If the last value is 0.0, last layer is lossless compressed.\r
-        */\r
-       public float[] getRatioLayers() {\r
-               return ratioLayers;\r
-       }\r
-\r
-       /**\r
-        * sets the quality layers.\r
-        * At least one level.\r
-        * Each level is expressed as a compression ratio (float).\r
-        * If the last value is 0.0, the last layer will be losslessly compressed\r
-        */\r
-       public void setRatioLayers(float[] layers) {\r
-               this.ratioLayers = layers;\r
-       }\r
-\r
-       /** Return the PSNR Layers, i.e. the target PSNR for each quality layer.\r
-        * If the last value is -1, last layer is lossless compressed.\r
-        */\r
-       public float[] getPsnrLayers() {\r
-               return psnrLayers;\r
-       }\r
-\r
-       /**\r
-        * sets the quality layers.\r
-        * At least one level.\r
-        * Each level is expressed as a target PSNR (float).\r
-        * If the last value is -1, the last layer will be losslessly compressed\r
-        */\r
-       public void setPsnrLayers(float[] layers) {\r
-               this.psnrLayers = layers;\r
-       }\r
-\r
-       /** Set the number of resolutions that must be created */\r
-       public void setNbResolutions(int nbResolutions) {\r
-               this.nbResolutions = nbResolutions;\r
-       }\r
-\r
-       public int getWidth() {\r
-               return width;\r
-       }\r
-\r
-       /** Width of the image, in pixels */\r
-       public void setWidth(int width) {\r
-               this.width = width;\r
-       }\r
-\r
-       /** Return the compressed index file.\r
-        * Syntax: TODO PP:\r
-        */\r
-       public byte[] getCompressedIndex() {\r
-               return compressedIndex;\r
-       }\r
-       \r
-       public void setCompressedIndex(byte[] index) {\r
-               compressedIndex = index;\r
-       }\r
-\r
-       public byte[] getCompressedStream() {\r
-               return compressedStream;\r
-       }\r
-\r
-       public void reset() {\r
-               nbResolutions = -1;\r
-               ratioLayers = null;\r
-               psnrLayers = null;\r
-               image8 = null;\r
-               image16 = null;\r
-               image24 = null;\r
-               compressedStream = null;\r
-           compressedIndex = null;\r
-           width = -1;\r
-           height = -1;\r
-           depth = -1;\r
-       }\r
-\r
-       public short[] getImage16() {\r
-               return image16;\r
-       }\r
-\r
-       public int[] getImage24() {\r
-               return image24;\r
-       }\r
-\r
-       public byte[] getImage8() {\r
-               return image8;\r
-       }\r
-       \r
-       /** Sets the size of the tiles. We assume square tiles */\r
-       public void setTileSize(int tileSize) {\r
-               this.tileSize = tileSize;\r
-       }\r
-       \r
-       /** Contains all the encoding arguments other than the input/output file, compression ratio, tile size */\r
-       public void setEncoderArguments(String[] argumentsForTheEncoder) {\r
-               encoder_arguments = argumentsForTheEncoder;\r
-       }\r
-\r
-       public void logMessage(String message) {\r
-               for (IJavaJ2KEncoderLogger logger:loggers)\r
-                       logger.logEncoderMessage(message);\r
-       }\r
-       \r
-       public void logError(String error) {\r
-               for (IJavaJ2KEncoderLogger logger:loggers)\r
-                       logger.logEncoderError(error);\r
-       }\r
-\r
-       public long getCompressedStreamLength() {\r
-               return compressedStreamLength;\r
-       }\r
-       \r
-       private String arrayToString(String[] array) {\r
-               if (array == null)\r
-                       return "NULL";\r
-               StringBuffer sb = new StringBuffer();\r
-               for (int i=0; i<array.length; i++)\r
-                       sb.append(array[i]).append(" ");\r
-               sb.delete(sb.length()-1, sb.length());\r
-               return sb.toString();\r
-       }\r
-}\r
diff --git a/JavaOpenJPEG/org_openJpeg_OpenJPEGJavaDecoder.h b/JavaOpenJPEG/org_openJpeg_OpenJPEGJavaDecoder.h
deleted file mode 100644 (file)
index 0e8de2e..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-/* DO NOT EDIT THIS FILE - it is machine generated */\r
-#include <jni.h>\r
-/* Header for class org_openJpeg_OpenJPEGJavaDecoder */\r
-\r
-#ifndef _Included_org_openJpeg_OpenJPEGJavaDecoder\r
-#define _Included_org_openJpeg_OpenJPEGJavaDecoder\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-/*\r
- * Class:     org_openJpeg_OpenJPEGJavaDecoder\r
- * Method:    internalDecodeJ2KtoImage\r
- * Signature: ([Ljava/lang/String;)I\r
- */\r
-JNIEXPORT jint JNICALL Java_org_openJpeg_OpenJPEGJavaDecoder_internalDecodeJ2KtoImage\r
-  (JNIEnv *, jobject, jobjectArray);\r
-\r
-#ifdef __cplusplus\r
-}\r
-#endif\r
-#endif\r
diff --git a/JavaOpenJPEG/org_openJpeg_OpenJPEGJavaEncoder.h b/JavaOpenJPEG/org_openJpeg_OpenJPEGJavaEncoder.h
deleted file mode 100644 (file)
index 22b3d95..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-/* DO NOT EDIT THIS FILE - it is machine generated */\r
-#include <jni.h>\r
-/* Header for class org_openJpeg_OpenJPEGJavaEncoder */\r
-\r
-#ifndef _Included_org_openJpeg_OpenJPEGJavaEncoder\r
-#define _Included_org_openJpeg_OpenJPEGJavaEncoder\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-/*\r
- * Class:     org_openJpeg_OpenJPEGJavaEncoder\r
- * Method:    internalEncodeImageToJ2K\r
- * Signature: ([Ljava/lang/String;)J\r
- */\r
-JNIEXPORT jlong JNICALL Java_org_openJpeg_OpenJPEGJavaEncoder_internalEncodeImageToJ2K\r
-  (JNIEnv *, jobject, jobjectArray);\r
-\r
-#ifdef __cplusplus\r
-}\r
-#endif\r
-#endif\r
diff --git a/OPJViewer/Makefile b/OPJViewer/Makefile
deleted file mode 100644 (file)
index b691dc7..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-# Makefile for OPJViewer\r
-\r
-# General configuration variables:\r
-CC = $(shell wx-config-2.8 --cxx)\r
-AR = ar\r
-\r
-CFLAGS = -DUSE_JPWL -DwxUSE_LIBOPENJPEG -DwxUSE_GUI=1 -DOPJ_STATIC -DOPJ_HTMLABOUT -DOPJ_INICONFIG -DUSE_JPSEC -DOPJ_MANYFORMATS $(shell wx-config-2.8 --cxxflags) # -g -p -pg -DUSE_JPWL\r
-\r
-OPJV_SRCS = source/imagjpeg2000.cpp source/wxj2kparser.cpp source/OPJViewer.cpp source/wxjp2parser.cpp source/OPJDialogs.cpp source/OPJThreads.cpp source/OPJAbout.cpp ../codec/index.c\r
-\r
-MODULES = $(OPJV_SRCS:.cpp=.o)\r
-\r
-all: opjviewer lib\r
-\r
-.cpp.o:\r
-       $(CC) $(CFLAGS) -c $< -o $@\r
-\r
-lib:\r
-       cd ../jpwl; make\r
-\r
-opjviewer: $(OPJV_SRCS) lib\r
-       $(CC) $(CFLAGS) -I .. -I ../codec -I ../libopenjpeg $(OPJV_SRCS) -o OPJViewer -L ../jpwl -lopenjpeg_JPWL -lm -lstdc++ -ltiff $(shell wx-config-2.8 --libs)\r
-\r
-\r
-clean:\r
-       rm -f OPJViewer *.o *.a\r
-       cd ../libopenjpeg; rm -f *.o\r
-\r
-\r
-\r
-\r
-#.cpp.o :\r
-#       $(CXX) -g -c `wx-config-2.8 --cxxflags` -I ../.. -D wxUSE_LIBOPENJPEG -D wxHACK_BOOLEAN -o $@ $<\r
-\r
-#all:    $(PROGRAM)\r
-\r
-#$(PROGRAM):     $(OBJECTS)\r
-#       $(CXX) -o $(PROGRAM) $(OBJECTS) -lopenjpeg -L ../.. `wx-config-2.8 --libs`\r
-\r
-#clean:\r
-#       rm -f *.o $(PROGRAM)\r
diff --git a/OPJViewer/OPJViewer.dsp b/OPJViewer/OPJViewer.dsp
deleted file mode 100644 (file)
index 4939f64..0000000
+++ /dev/null
@@ -1,290 +0,0 @@
-# Microsoft Developer Studio Project File - Name="OPJViewer" - Package Owner=<4>\r
-# Microsoft Developer Studio Generated Build File, Format Version 6.00\r
-# ** DO NOT EDIT **\r
-\r
-# TARGTYPE "Win32 (x86) Console Application" 0x0103\r
-\r
-CFG=OPJVIEWER - WIN32 RELEASE\r
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r
-!MESSAGE use the Export Makefile command and run\r
-!MESSAGE \r
-!MESSAGE NMAKE /f "OPJViewer.mak".\r
-!MESSAGE \r
-!MESSAGE You can specify a configuration when running NMAKE\r
-!MESSAGE by defining the macro CFG on the command line. For example:\r
-!MESSAGE \r
-!MESSAGE NMAKE /f "OPJViewer.mak" CFG="OPJVIEWER - WIN32 RELEASE"\r
-!MESSAGE \r
-!MESSAGE Possible choices for configuration are:\r
-!MESSAGE \r
-!MESSAGE "OPJViewer - Win32 Release" (based on "Win32 (x86) Console Application")\r
-!MESSAGE "OPJViewer - Win32 Debug" (based on "Win32 (x86) Console Application")\r
-!MESSAGE \r
-\r
-# Begin Project\r
-# PROP AllowPerConfigDependencies 0\r
-# PROP Scc_ProjName ""\r
-# PROP Scc_LocalPath ""\r
-CPP=cl.exe\r
-RSC=rc.exe\r
-\r
-!IF  "$(CFG)" == "OPJViewer - Win32 Release"\r
-\r
-# PROP BASE Use_MFC 0\r
-# PROP BASE Use_Debug_Libraries 0\r
-# PROP BASE Output_Dir "Release"\r
-# PROP BASE Intermediate_Dir "Release"\r
-# PROP BASE Target_Dir ""\r
-# PROP Use_MFC 0\r
-# PROP Use_Debug_Libraries 0\r
-# PROP Output_Dir "Release"\r
-# PROP Intermediate_Dir "Release"\r
-# PROP Ignore_Export_Lib 0\r
-# PROP Target_Dir ""\r
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
-# ADD CPP /nologo /G6 /MD /W3 /GX /O2 /I "$(WXWIN28)\lib\vc_lib\msw" /I "$(WXWIN28)\include" /I ".." /I "..\libopenjpeg" /I "$(MXFLIB)" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /D WINVER=0x400 /D "_MT" /D wxUSE_GUI=1 /D "wxUSE_LIBOPENJPEG" /D "OPJ_STATIC" /D "USE_JPWL" /D "USE_JPSEC" /D "OPJ_HTMLABOUT" /D "OPJ_MANYFORMATS" /D "OPJ_INICONFIG" /FR /FD /Zm200 /c\r
-# ADD BASE RSC /l 0x410 /d "NDEBUG"\r
-# ADD RSC /l 0x409 /i "$(WXWIN28)\include" /d "NDEBUG"\r
-BSC32=bscmake.exe\r
-# ADD BASE BSC32 /nologo\r
-# ADD BSC32 /nologo\r
-LINK32=link.exe\r
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib comctl32.lib rpcrt4.lib wsock32.lib wxzlib.lib wxregex.lib wxpng.lib wxjpeg.lib wxbase28.lib wxmsw28_core.lib wxmsw28_html.lib wxmsw28_adv.lib wxmsw28_core.lib wxbase28.lib wxtiff.lib wxjpeg.lib wxpng.lib wxzlib.lib wxregex.lib wxexpat.lib LibOpenJPEG_JPWL.lib mxflib.lib /nologo /subsystem:windows /machine:I386 /nodefaultlib:"libcmt.lib" /libpath:"$(WXWIN28)\lib\vc_lib" /libpath:"..\jpwl\Release" /libpath:"$(MXFLIB)\build\msvc\Release" /IGNORE:4089\r
-# SUBTRACT LINK32 /pdb:none /nodefaultlib\r
-# Begin Special Build Tool\r
-SOURCE="$(InputPath)"\r
-PostBuild_Desc=Update build number\r
-PostBuild_Cmds=buildupdate.bat\r
-# End Special Build Tool\r
-\r
-!ELSEIF  "$(CFG)" == "OPJViewer - Win32 Debug"\r
-\r
-# PROP BASE Use_MFC 0\r
-# PROP BASE Use_Debug_Libraries 1\r
-# PROP BASE Output_Dir "OPJViewer___Win32_Debug"\r
-# PROP BASE Intermediate_Dir "OPJViewer___Win32_Debug"\r
-# PROP BASE Target_Dir ""\r
-# PROP Use_MFC 0\r
-# PROP Use_Debug_Libraries 1\r
-# PROP Output_Dir "Debug"\r
-# PROP Intermediate_Dir "Debug"\r
-# PROP Ignore_Export_Lib 0\r
-# PROP Target_Dir ""\r
-# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c\r
-# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "$(WXWIN28)\INCLUDE" /I "$(WXWIN28)\lib\vc_lib\msw" /I "$(WXWIN28)\include" /I ".." /I "..\libopenjpeg" /I "$(MXFLIB)" /D "_DEBUG" /D "__WXDEBUG__" /D WXDEBUG=1 /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /D WINVER=0x400 /D "_MT" /D wxUSE_GUI=1 /D "wxUSE_LIBOPENJPEG" /D "OPJ_STATIC" /D "USE_JPWL" /D "OPJ_HTMLABOUT" /D "OPJ_INICONFIG" /D "OPJ_MANYFORMATS" /D "USE_JPSEC" /FR /FD /GZ /Zm200 /c\r
-# ADD BASE RSC /l 0x410 /d "_DEBUG"\r
-# ADD RSC /l 0x410 /i "$(WXWIN28)\include" /d "_DEBUG"\r
-BSC32=bscmake.exe\r
-# ADD BASE BSC32 /nologo\r
-# ADD BSC32 /nologo\r
-LINK32=link.exe\r
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib comctl32.lib rpcrt4.lib wsock32.lib wxzlibd.lib wxregexd.lib wxpngd.lib wxjpegd.lib wxtiffd.lib wxbase28d.lib wxmsw28d_core.lib wxmsw28d_html.lib wxmsw28d_adv.lib LibOpenJPEG_JPWLd.lib mxflib.lib /nologo /subsystem:windows /debug /machine:I386 /nodefaultlib:"libcmtd.lib" /pdbtype:sept /libpath:"$(WXWIN28)\lib\vc_lib" /libpath:"..\jpwl\Debug" /libpath:"$(MXFLIB)\build\msvc\Debug"\r
-# SUBTRACT LINK32 /pdb:none\r
-\r
-!ENDIF \r
-\r
-# Begin Target\r
-\r
-# Name "OPJViewer - Win32 Release"\r
-# Name "OPJViewer - Win32 Debug"\r
-# Begin Group "Source Files"\r
-\r
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"\r
-# Begin Source File\r
-\r
-SOURCE=.\source\imagjpeg2000.cpp\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\imagmxf.cpp\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=..\codec\index.c\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\OPJAbout.cpp\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\OPJDialogs.cpp\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\OPJThreads.cpp\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\OPJViewer.cpp\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wxj2kparser.cpp\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wxjp2parser.cpp\r
-# End Source File\r
-# End Group\r
-# Begin Group "Header Files"\r
-\r
-# PROP Default_Filter "h;hpp;hxx;hm;inl"\r
-# Begin Source File\r
-\r
-SOURCE=.\source\about_htm.h\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\build.h\r
-# PROP Exclude_From_Build 1\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\imagjpeg2000.h\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\imagmxf.h\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=..\codec\index.h\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\OPJViewer.h\r
-# End Source File\r
-# End Group\r
-# Begin Group "Resource Files"\r
-\r
-# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\blank.cur\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\bullseye.cur\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\cdrom.ico\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\computer.ico\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\cross.cur\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\drive.ico\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\file1.ico\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\floppy.ico\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\folder1.ico\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\folder2.ico\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\hand.cur\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\icon1.xpm\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\icon2.xpm\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\icon3.xpm\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\icon4.xpm\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\icon5.xpm\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\magnif1.cur\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\opj_logo.xpm\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\OPJChild.ico\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\OPJChild16.xpm\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\OPJViewer.ico\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\OPJViewer.rc\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\OPJViewer16.xpm\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\pbrush.cur\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\pencil.cur\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\pntleft.cur\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\pntright.cur\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\removble.ico\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\rightarr.cur\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\roller.cur\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\source\wx\msw\std.ico\r
-# End Source File\r
-# End Group\r
-# End Target\r
-# End Project\r
diff --git a/OPJViewer/OPJViewer.dsw b/OPJViewer/OPJViewer.dsw
deleted file mode 100644 (file)
index 772043d..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-Microsoft Developer Studio Workspace File, Format Version 6.00\r
-# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!\r
-\r
-###############################################################################\r
-\r
-Project: "LibOpenJPEG_JPWL"=..\jpwl\LibOpenJPEG_JPWL.dsp - Package Owner=<4>\r
-\r
-Package=<5>\r
-{{{\r
-}}}\r
-\r
-Package=<4>\r
-{{{\r
-}}}\r
-\r
-###############################################################################\r
-\r
-Project: "OPJViewer"=.\OPJViewer.dsp - Package Owner=<4>\r
-\r
-Package=<5>\r
-{{{\r
-}}}\r
-\r
-Package=<4>\r
-{{{\r
-    Begin Project Dependency\r
-    Project_Dep_Name LibOpenJPEG_JPWL\r
-    End Project Dependency\r
-}}}\r
-\r
-###############################################################################\r
-\r
-Project: "mxflib"="..\..\..\..\mxflib-1.0.0\build\msvc\mxflib.dsp" - Package Owner=<4>\r
-\r
-Package=<5>\r
-{{{\r
-}}}\r
-\r
-Package=<4>\r
-{{{\r
-}}}\r
-\r
-###############################################################################\r
-\r
-Global:\r
-\r
-Package=<5>\r
-{{{\r
-}}}\r
-\r
-Package=<3>\r
-{{{\r
-}}}\r
-\r
-###############################################################################\r
-\r
diff --git a/OPJViewer/OPJViewer.iss b/OPJViewer/OPJViewer.iss
deleted file mode 100644 (file)
index d4cfadb..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-; Script generated by the Inno Setup Script Wizard.\r
-; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!\r
-\r
-[Setup]\r
-AppName=OPJViewer\r
-AppVerName=OPJViewer 0.4 beta\r
-AppPublisher=OpenJPEG\r
-AppPublisherURL=http://www.openjpeg.org\r
-AppSupportURL=http://www.openjpeg.org\r
-AppUpdatesURL=http://www.openjpeg.org\r
-DefaultDirName={pf}\OPJViewer\r
-DefaultGroupName=OPJViewer\r
-OutputDir=setup\r
-OutputBaseFilename=OPJViewer04beta_setup\r
-Compression=lzma\r
-SolidCompression=true\r
-InfoBeforeFile=source\readmebefore.txt\r
-InfoAfterFile=source\readmeafter.txt\r
-LicenseFile=source\license.txt\r
-VersionInfoVersion=0.4.0.0\r
-VersionInfoCompany=OpenJPEG\r
-VersionInfoDescription=JPEG 2000 viewer\r
-ShowLanguageDialog=yes\r
-SetupIconFile=source\OPJViewer.ico\r
-\r
-[Languages]\r
-Name: english; MessagesFile: compiler:Default.isl\r
-\r
-[Tasks]\r
-Name: desktopicon; Description: {cm:CreateDesktopIcon}; GroupDescription: {cm:AdditionalIcons}; Flags: unchecked\r
-\r
-[Files]\r
-Source: Release\OPJViewer.exe; DestDir: {app}; Flags: ignoreversion\r
-;Source: about\about.htm; DestDir: {app}/about; Flags: ignoreversion\r
-;Source: about\opj_logo.png; DestDir: {app}/about; Flags: ignoreversion\r
-; NOTE: Don't use "Flags: ignoreversion" on any shared system files\r
-\r
-[Icons]\r
-Name: {group}\OPJViewer; Filename: {app}\OPJViewer.exe; WorkingDir: {app}; IconIndex: 0\r
-Name: {group}\{cm:UninstallProgram,OPJViewer}; Filename: {uninstallexe}\r
-Name: {userdesktop}\OPJViewer; Filename: {app}\OPJViewer.exe; Tasks: desktopicon; WorkingDir: {app}; IconIndex: 0\r
-\r
-[Run]\r
-Filename: {app}\OPJViewer.exe; Description: {cm:LaunchProgram,OPJViewer}; Flags: nowait postinstall skipifsilent; WorkingDir: {app}\r
-\r
-[Registry]\r
-Root: HKCU; Subkey: Software\OpenJPEG; ValueType: none; ValueData: 1; Flags: uninsdeletekey; Tasks: ; Languages: \r
-Root: HKCU; Subkey: Software\OpenJPEG\OPJViewer; ValueType: none; ValueData: 1; Flags: uninsdeletekey; Tasks: ; Languages: \r
diff --git a/OPJViewer/Readme.txt b/OPJViewer/Readme.txt
deleted file mode 100644 (file)
index 7eb3e46..0000000
+++ /dev/null
@@ -1,100 +0,0 @@
-===============================================================================\r
-       JPEG2000 Visualization Software - OPJViewer\r
-\r
-               Version 0.4 beta\r
-===============================================================================\r
-\r
-\r
-1. Scope\r
-=============\r
-\r
-This document describes the installation and use of the OPJViewer in the framework of OpenJPEG library.\r
-\r
-This implementation has been developed using the OpenJPEG library as decoding engine and wxWidgets 2.8 as GUI engine.\r
-\r
-If you find some bugs or if you have problems using the viewer, please send an e-mail to jpwl@diei.unipg.it\r
-\r
-2. Installing the viewer\r
-==========================\r
-\r
-There are two options available, at the moment:\r
-\r
-a) compile from source code\r
-b) download a precompiled binary.\r
-\r
-In order to use option a), it is mandatory to have compiled and built the LibOpenJPEG_JPWL library and the wxWidgets 2.8 framework (you have to download it from http://www.wxwidgets.org/ and compile the wx* libraries).\r
-\r
-2.1. Compiling the source code in Windows\r
--------------------------------------------\r
-\r
-The steps required to compile the viewer under windows are:\r
-\r
-a) Download at least the libopenjpeg, jpwl, and opjviewer folders from the SVN trunk.\r
-b) Open the OPJViewer.dsw workspace with Visual C++ 6 and activate the "OPJViewer - Win32 Release" configuration.\r
-c) In the configuration settings, go to the C++ tab and modify the wxWidgets paths in order to reflect your wx* install configuration (Preprocessor -> Additional include directories): simply update each instance of the two wx paths, do not remove or add them.\r
-d) In the configuration settings, go to the Link tab and modify the wxWidgets path in order to reflect your wx* install configuration (Input -> Additional library path): simply update the wx path.\r
-e) In the configuration settings, go to the Resources tab and modify the wxWidgets path in order to reflect your wx* install configuration (Additional resource include directories): simply update the wx path.\r
-f) Build!\r
-g) Run!\r
-h) (OPTIONAL) Prepare an installer by compiling the InnoSetup script OPJViewer.iss (you need to download InnoSetup from http://www.jrsoftware.org/isinfo.php).\r
-\r
-2.1.1 Additional libraries\r
-----------------------------\r
-\r
-Since we are also working on the Digital Cinema JPEG 2000, we are integrating the viewer with the MXF library, which is used to prepare the DCPs for digital movies. You can enable its linking in the code by specifying the USE_MXF preprocessor directive but, remember, the integration is at a very early stage.\r
-\r
-2.2. Compiling the source code in Unix-like systems\r
------------------------------------------------------\r
-\r
-The porting is possible and under way.\r
-\r
-\r
-3. General information on the viewer\r
-====================================\r
-\r
-This viewer is conceived to open and display information and image content of J2K, JP2, and MJ2 files.\r
-The viewer application interface is divided into three main panels:\r
-- a browsing pane;\r
-- a viewing pane;\r
-- a log/peek pane.\r
-\r
-The browsing pane will present the markers or boxes hierarchy, with position (byte number where marker/box starts and stops) and length information (i.e., inner length as signalled by marker/box and total length, with marker/box sign included), in the following form:\r
-\r
-filename\r
-|\r
-|_ #000: Marker/Box short name (Hex code)\r
-|  |\r
-|  |_ *** Marker/Box long name ***\r
-|  |_ startbyte > stopbyte, inner_length + marker/box sign length (total length)\r
-|  |_ Additional info, depending on the marker/box type\r
-|  |_ ...\r
-|\r
-|_ #001: Marker/Box short name (Hex code)\r
-|  |\r
-|  |_ ...\r
-|\r
-...\r
-\r
-\r
-The viewing pane will display the decoded image contained in the JPEG 2000 file.\r
-It should display correctly images as large as 4000x2000, provided that a couple of GB of RAM are available. Nothing is known about the display of larger sizes: let us know if you manage to get it working.\r
-\r
-\r
-The log/peek pane is shared among two different subpanels:\r
-\r
-- the log panel will report a lot of debugging info coming out from the wx GUI as well as from the openjpeg library\r
-- the peek pane tries to give a peek on the codestream/file portion which is currently selected in the browsing pane. It shows both hex and ascii values corresponding to the marker/box section. \r
-\r
-\r
-4. Known bugs and limitations\r
-===============================\r
-\r
-4.1. Bugs\r
------------\r
-\r
-* \r
-\r
-4.2. Limitations\r
-------------------\r
-\r
-* For mj2 files, rendering is only in B/W\r
diff --git a/OPJViewer/about/about.htm b/OPJViewer/about/about.htm
deleted file mode 100644 (file)
index fec6028..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-<html>\r
-<body bgcolor="#FFFFFF">\r
-<table cellspacing=7 cellpadding=1 border=0 width="100%">\r
-<tr>\r
-<td rowspan=3 valign=top align=center width=70>\r
-<img src="opj_logo.png"><br><br>\r
-</td>\r
-<td align=center>\r
-<font size=+2 color="#000000"><b>OPJViewer v0.2 alpha</b></font><br>\r
-<font size=+0 color="#000000"><b>A JPEG 2000 image viewer</b></font>\r
-</td>\r
-</tr>\r
-<tr height=3 valign=center>\r
-<td valign=center  bgcolor=#cc3300></td>\r
-</tr>\r
-<tr>\r
-<td align=justify>\r
-<center><font size=+0 color="#000000"><a href="http://www.openjpeg.org/">OpenJPEG</a></font></center>\r
-<font size=-1 color="#000000">The OpenJPEG library is an open-source JPEG 2000 codec written in C language.\r
-In addition to the basic codec, various other features are under development,\r
-among them the JP2 and MJ2 (Motion JPEG 2000) file formats, an indexing tool\r
-useful for the JPIP protocol, JPWL-tools for error-resilience, ...</font>\r
-</td>\r
-</tr>\r
-<tr>\r
-<td colspan=2 bgcolor="#CC3300" height=3 valign=center></td>\r
-</tr>\r
-<tr>\r
-<td colspan=2>\r
-<font size=-2 color="#444444">OpenJPEG is &copy; 2002-2007 <a href="http://www.tele.ucl.ac.be/">TELE</a> - <a href="http://www.uclouvain.be/">Universit� Catholique de Louvain</a></font><br>\r
-<font size=-2 color="#444444">OPJViewer is also &copy; 2005-2007 <a href="http://dsplab.diei.unipg.it/">DSPLab</a> - <a href="http://www.unipg.it/">Universit� degli studi di Perugia</a></font>\r
-</td>\r
-</tr>\r
-</table>\r
-</body>\r
-</html>\r
diff --git a/OPJViewer/about/opj_logo.png b/OPJViewer/about/opj_logo.png
deleted file mode 100644 (file)
index 0f43840..0000000
Binary files a/OPJViewer/about/opj_logo.png and /dev/null differ
diff --git a/OPJViewer/buildupdate.bat b/OPJViewer/buildupdate.bat
deleted file mode 100644 (file)
index 0aae1c1..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-::== buildupdate.bat\r
-@echo off\r
-setLocal EnableDelayedExpansion\r
-\r
-for /f "tokens=2,* delims=^(^) " %%a in ('find /v "" ^< .\source\build.h') do (\r
-rem echo %%a\r
-set /A M = %%a + 1\r
-echo Build %%a done^!\r
-echo wxT^("!M!"^) > buildtemp283746825t347\r
-)\r
-\r
-if exist buildtemp283746825t347 move /Y buildtemp283746825t347 .\source\build.h\r
-if exist buildtemp283746825t347 del /F /Q buildtemp283746825t347\r
-\r
-::==
\ No newline at end of file
diff --git a/OPJViewer/source/OPJAbout.cpp b/OPJViewer/source/OPJAbout.cpp
deleted file mode 100644 (file)
index ecc5f45..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-/*\r
- * Copyright (c) 2007, Digital Signal Processing Laboratory, Universita'� degli studi di Perugia (UPG), Italy\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-#ifdef USE_MXF\r
-#include "mxflib/mxflib.h"\r
-#endif // USE_MXF\r
-\r
-#include "OPJViewer.h"\r
-\r
-// about window for the frame\r
-void OPJFrame::OnAbout(wxCommandEvent& WXUNUSED(event))\r
-{\r
-#ifdef OPJ_HTMLABOUT\r
-#include "about_htm.h"\r
-#include "opj_logo.xpm"\r
-\r
-    wxBoxSizer *topsizer;\r
-    wxHtmlWindow *html;\r
-    wxDialog dlg(this, wxID_ANY, wxString(_("About")));\r
-\r
-    wxMemoryFSHandler::AddFile(wxT("opj_logo.xpm"), wxBitmap(opj_logo), wxBITMAP_TYPE_XPM);\r
-\r
-    topsizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-    html = new wxHtmlWindow(&dlg, wxID_ANY, wxDefaultPosition, wxSize(320, 250), wxHW_SCROLLBAR_NEVER);\r
-    html->SetBorders(0);\r
-    //html->LoadPage(wxT("about/about.htm"));\r
-       //html->SetPage("<html><body>Hello, world!</body></html>");\r
-       html->SetPage(htmlaboutpage);\r
-    html->SetSize(html->GetInternalRepresentation()->GetWidth(),\r
-                    html->GetInternalRepresentation()->GetHeight());\r
-\r
-    topsizer->Add(html, 1, wxALL, 10);\r
-\r
-    topsizer->Add(new wxStaticLine(&dlg, wxID_ANY), 0, wxEXPAND | wxLEFT | wxRIGHT, 10);\r
-\r
-    wxButton *bu1 = new wxButton(&dlg, wxID_OK, wxT("OK"));\r
-    bu1->SetDefault();\r
-\r
-    topsizer->Add(bu1, 0, wxALL | wxALIGN_RIGHT, 15);\r
-\r
-    dlg.SetSizer(topsizer);\r
-    topsizer->Fit(&dlg);\r
-\r
-    dlg.ShowModal();\r
-\r
-#else\r
-\r
-       wxMessageBox(wxString::Format(OPJ_APPLICATION_TITLEBAR\r
-                                                                 wxT("\n\n")\r
-                                                                 wxT("Built with %s and OpenJPEG ")\r
-                                                                 wxT(OPENJPEG_VERSION)\r
-                                                                 wxT("\non ") wxT(__DATE__) wxT(", ") wxT(__TIME__)\r
-                                                                 wxT("\nRunning under %s\n\n")\r
-                                                                 OPJ_APPLICATION_COPYRIGHT,\r
-                                                                 wxVERSION_STRING,\r
-                                                                 wxGetOsDescription().c_str()),\r
-                                wxT("About ") OPJ_APPLICATION_NAME,\r
-                                wxOK | wxICON_INFORMATION,\r
-                                this\r
-                                );\r
-\r
-#endif\r
-\r
-}\r
diff --git a/OPJViewer/source/OPJChild.ico b/OPJViewer/source/OPJChild.ico
deleted file mode 100644 (file)
index 7a12718..0000000
Binary files a/OPJViewer/source/OPJChild.ico and /dev/null differ
diff --git a/OPJViewer/source/OPJChild16.xpm b/OPJViewer/source/OPJChild16.xpm
deleted file mode 100644 (file)
index 48e8796..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-/* XPM */\r
-static char *OPJChild16[] = {\r
-/* columns rows colors chars-per-pixel */\r
-"16 16 6 1",\r
-"  c black",\r
-". c #008000",\r
-"X c red",\r
-"o c #800080",\r
-"O c gray100",\r
-"+ c None",\r
-/* pixels */\r
-"++++++++++++++++",\r
-"+OOOOOOOOOOOOOO+",\r
-"+OooooooooooooO+",\r
-"+OooooooooooooO+",\r
-"+OooOOOOOOOOOoO+",\r
-"+OooO.......OoO+",\r
-"+OooO.......OoO+",\r
-"+OooO..OOO..OoO+",\r
-"+OooO..OXO..OoO+",\r
-"+OooO..OOO..OoO+",\r
-"+OooO.......OoO+",\r
-"+OooO.......OoO+",\r
-"+OooOOOOOOOOOoO+",\r
-"+OooooooooooooO+",\r
-"+OOOOOOOOOOOOOO+",\r
-"++++++++++++++++"\r
-};\r
diff --git a/OPJViewer/source/OPJDialogs.cpp b/OPJViewer/source/OPJDialogs.cpp
deleted file mode 100644 (file)
index ed68ef3..0000000
+++ /dev/null
@@ -1,1373 +0,0 @@
-/*\r
- * Copyright (c) 2007, Digital Signal Processing Laboratory, Universita'� degli studi di Perugia (UPG), Italy\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-#include "OPJViewer.h"\r
-\r
-// ----------------------------------------------------------------------------\r
-// OPJDecoderDialog\r
-// ----------------------------------------------------------------------------\r
-\r
-IMPLEMENT_CLASS(OPJDecoderDialog, wxPropertySheetDialog)\r
-\r
-BEGIN_EVENT_TABLE(OPJDecoderDialog, wxPropertySheetDialog)\r
-       EVT_CHECKBOX(OPJDECO_ENABLEDECO, OPJDecoderDialog::OnEnableDeco)\r
-#ifdef USE_JPWL\r
-       EVT_CHECKBOX(OPJDECO_ENABLEJPWL, OPJDecoderDialog::OnEnableJPWL)\r
-#endif // USE_JPWL\r
-END_EVENT_TABLE()\r
-\r
-OPJDecoderDialog::OPJDecoderDialog(wxWindow* win, int dialogType)\r
-{\r
-       SetExtraStyle(wxDIALOG_EX_CONTEXTHELP|wxWS_EX_VALIDATE_RECURSIVELY);\r
-\r
-       Create(win, wxID_ANY, wxT("Decoder settings"),\r
-               wxDefaultPosition, wxDefaultSize,\r
-               wxDEFAULT_DIALOG_STYLE| (int) wxPlatform::IfNot(wxOS_WINDOWS_CE, wxRESIZE_BORDER)\r
-               );\r
-\r
-       CreateButtons(wxOK | wxCANCEL | (int)wxPlatform::IfNot(wxOS_WINDOWS_CE, wxHELP));\r
-\r
-       m_settingsNotebook = GetBookCtrl();\r
-\r
-       wxPanel* mainSettings = CreateMainSettingsPage(m_settingsNotebook);\r
-       wxPanel* jpeg2000Settings = CreatePart1SettingsPage(m_settingsNotebook);\r
-       if (!wxGetApp().m_enabledeco)\r
-               jpeg2000Settings->Enable(false);\r
-       wxPanel* mjpeg2000Settings = CreatePart3SettingsPage(m_settingsNotebook);\r
-       if (!wxGetApp().m_enabledeco)\r
-               mjpeg2000Settings->Enable(false);\r
-#ifdef USE_JPWL\r
-       wxPanel* jpwlSettings = CreatePart11SettingsPage(m_settingsNotebook);\r
-       if (!wxGetApp().m_enabledeco)\r
-               jpwlSettings->Enable(false);\r
-#endif // USE_JPWL\r
-\r
-       m_settingsNotebook->AddPage(mainSettings, wxT("Display"), false);\r
-       m_settingsNotebook->AddPage(jpeg2000Settings, wxT("JPEG 2000"), false);\r
-       m_settingsNotebook->AddPage(mjpeg2000Settings, wxT("MJPEG 2000"), false);\r
-#ifdef USE_JPWL\r
-       m_settingsNotebook->AddPage(jpwlSettings, wxT("JPWL"), false);\r
-#endif // USE_JPWL\r
-\r
-       LayoutDialog();\r
-}\r
-\r
-OPJDecoderDialog::~OPJDecoderDialog()\r
-{\r
-}\r
-\r
-wxPanel* OPJDecoderDialog::CreateMainSettingsPage(wxWindow* parent)\r
-{\r
-    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
-\r
-       // top sizer\r
-    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-               // sub top sizer\r
-               wxBoxSizer *subtopSizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-               // add decoding enabling check box\r
-               subtopSizer->Add(\r
-                       m_enabledecoCheck = new wxCheckBox(panel, OPJDECO_ENABLEDECO, wxT("Enable decoding"), wxDefaultPosition, wxDefaultSize),\r
-                       0, wxGROW | wxALL, 5);\r
-               m_enabledecoCheck->SetValue(wxGetApp().m_enabledeco);\r
-\r
-               // add parsing enabling check box\r
-               subtopSizer->Add(\r
-                       m_enableparseCheck = new wxCheckBox(panel, OPJDECO_ENABLEPARSE, wxT("Enable parsing"), wxDefaultPosition, wxDefaultSize),\r
-                       0, wxGROW | wxALL, 5);\r
-               m_enableparseCheck->SetValue(wxGetApp().m_enableparse);\r
-\r
-                       // resize settings, column\r
-                       wxString choices[] = {wxT("Don't resize"), wxT("Low quality"), wxT("High quality")};\r
-                       m_resizeBox = new wxRadioBox(panel, OPJDECO_RESMETHOD,\r
-                               wxT("Resize method"),\r
-                               wxDefaultPosition, wxDefaultSize,\r
-                               WXSIZEOF(choices),\r
-                               choices,\r
-                               1,\r
-                               wxRA_SPECIFY_ROWS);\r
-                       m_resizeBox->SetSelection(wxGetApp().m_resizemethod + 1);\r
-\r
-               subtopSizer->Add(m_resizeBox, 0, wxGROW | wxALL, 5);\r
-\r
-       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
-\r
-       // assign top and fit it\r
-    panel->SetSizer(topSizer);\r
-    topSizer->Fit(panel);\r
-\r
-    return panel;\r
-}\r
-\r
-wxPanel* OPJDecoderDialog::CreatePart3SettingsPage(wxWindow* parent)\r
-{\r
-    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
-\r
-       // top sizer\r
-    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-       // add some space\r
-       //topSizer->AddSpacer(5);\r
-\r
-               // sub top sizer\r
-               wxBoxSizer *subtopSizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-                       // frame settings, column\r
-                       wxStaticBox* frameBox = new wxStaticBox(panel, wxID_ANY, wxT("Frame"));\r
-                       wxBoxSizer* frameSizer = new wxStaticBoxSizer(frameBox, wxVERTICAL);\r
-\r
-                               // selected frame number, row\r
-                               wxBoxSizer* framenumSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               framenumSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Displayed frame:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 5);\r
-\r
-                               // add some horizontal space\r
-                               framenumSizer->Add(5, 5, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               framenumSizer->Add(\r
-                                       m_framenumCtrl = new wxSpinCtrl(panel, OPJDECO_FRAMENUM,\r
-                                                               wxString::Format(wxT("%d"), wxGetApp().m_framenum),\r
-                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
-                                                               wxSP_ARROW_KEYS,\r
-                                                               1, 100000, wxGetApp().m_framenum),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\r
-\r
-                       frameSizer->Add(framenumSizer, 0, wxGROW | wxALL, 5);\r
-\r
-               subtopSizer->Add(frameSizer, 0, wxGROW | wxALL, 5);\r
-\r
-       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
-\r
-       // assign top and fit it\r
-    panel->SetSizer(topSizer);\r
-    topSizer->Fit(panel);\r
-\r
-    return panel;\r
-}\r
-\r
-wxPanel* OPJDecoderDialog::CreatePart1SettingsPage(wxWindow* parent)\r
-{\r
-    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
-\r
-       // top sizer\r
-    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-       // add some space\r
-       //topSizer->AddSpacer(5);\r
-\r
-               // sub top sizer\r
-               wxBoxSizer *subtopSizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-                       // resolutions settings, column\r
-                       wxStaticBox* resolutionBox = new wxStaticBox(panel, wxID_ANY, wxT("Resolutions"));\r
-                       wxBoxSizer* resolutionSizer = new wxStaticBoxSizer(resolutionBox, wxVERTICAL);\r
-\r
-                               // reduce factor sizer, row\r
-                               wxBoxSizer* reduceSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               reduceSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Reduce factor:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 5);\r
-\r
-                               // add some horizontal space\r
-                               reduceSizer->Add(5, 5, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               reduceSizer->Add(\r
-                                       m_reduceCtrl = new wxSpinCtrl(panel, OPJDECO_REDUCEFACTOR,\r
-                                       wxString::Format(wxT("%d"), wxGetApp().m_reducefactor),\r
-                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
-                                                               wxSP_ARROW_KEYS,\r
-                                                               0, 10000, wxGetApp().m_reducefactor),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\r
-\r
-                       resolutionSizer->Add(reduceSizer, 0, wxGROW | wxALL, 5);\r
-\r
-               subtopSizer->Add(resolutionSizer, 0, wxGROW | wxALL, 5);\r
-\r
-                       // quality layer settings, column\r
-                       wxStaticBox* layerBox = new wxStaticBox(panel, wxID_ANY, wxT("Layers"));\r
-                       wxBoxSizer* layerSizer = new wxStaticBoxSizer(layerBox, wxVERTICAL);\r
-\r
-                               // quality layers sizer, row\r
-                               wxBoxSizer* qualitySizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               qualitySizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Quality layers:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 5);\r
-\r
-                               // add some horizontal space\r
-                               qualitySizer->Add(5, 5, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               qualitySizer->Add(\r
-                                       m_layerCtrl = new wxSpinCtrl(panel, OPJDECO_QUALITYLAYERS,\r
-                                                               wxString::Format(wxT("%d"), wxGetApp().m_qualitylayers),\r
-                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
-                                                               wxSP_ARROW_KEYS,\r
-                                                               0, 100000, wxGetApp().m_qualitylayers),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\r
-\r
-                       layerSizer->Add(qualitySizer, 0, wxGROW | wxALL, 5);\r
-\r
-               subtopSizer->Add(layerSizer, 0, wxGROW | wxALL, 5);\r
-\r
-                       // component settings, column\r
-                       wxStaticBox* compoBox = new wxStaticBox(panel, wxID_ANY, wxT("Components"));\r
-                       wxBoxSizer* compoSizer = new wxStaticBoxSizer(compoBox, wxVERTICAL);\r
-\r
-                               // quality layers sizer, row\r
-                               wxBoxSizer* numcompsSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               numcompsSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Component displayed:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 5);\r
-\r
-                               // add some horizontal space\r
-                               numcompsSizer->Add(5, 5, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               numcompsSizer->Add(\r
-                                       m_numcompsCtrl = new wxSpinCtrl(panel, OPJDECO_NUMCOMPS,\r
-                                                               wxString::Format(wxT("%d"), wxGetApp().m_components),\r
-                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
-                                                               wxSP_ARROW_KEYS,\r
-                                                               0, 100000, wxGetApp().m_components),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\r
-                               m_numcompsCtrl->Enable(true);\r
-\r
-                       compoSizer->Add(numcompsSizer, 0, wxGROW | wxALL, 5);\r
-\r
-               subtopSizer->Add(compoSizer, 0, wxGROW | wxALL, 5);\r
-\r
-       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
-\r
-       // assign top and fit it\r
-    panel->SetSizer(topSizer);\r
-    topSizer->Fit(panel);\r
-\r
-    return panel;\r
-}\r
-\r
-#ifdef USE_JPWL\r
-wxPanel* OPJDecoderDialog::CreatePart11SettingsPage(wxWindow* parent)\r
-{\r
-    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
-\r
-       // top sizer\r
-    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-       // add some space\r
-       //topSizer->AddSpacer(5);\r
-\r
-               // sub top sizer\r
-               wxBoxSizer *subtopSizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-               // add JPWL enabling check box\r
-               subtopSizer->Add(\r
-                       m_enablejpwlCheck = new wxCheckBox(panel, OPJDECO_ENABLEJPWL, wxT("Enable JPWL"), wxDefaultPosition, wxDefaultSize),\r
-                       0, wxGROW | wxALL, 5);\r
-               m_enablejpwlCheck->SetValue(wxGetApp().m_enablejpwl);\r
-\r
-                       // component settings, column\r
-                       wxStaticBox* compoBox = new wxStaticBox(panel, wxID_ANY, wxT("Components"));\r
-                       wxBoxSizer* compoSizer = new wxStaticBoxSizer(compoBox, wxVERTICAL);\r
-\r
-                               // expected components sizer, row\r
-                               wxBoxSizer* expcompsSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               expcompsSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Expected comps.:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 5);\r
-\r
-                               // add some horizontal space\r
-                               expcompsSizer->Add(5, 5, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               expcompsSizer->Add(\r
-                                       m_expcompsCtrl = new wxSpinCtrl(panel, OPJDECO_EXPCOMPS,\r
-                                                               wxString::Format(wxT("%d"), wxGetApp().m_expcomps),\r
-                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
-                                                               wxSP_ARROW_KEYS,\r
-                                                               1, 100000, wxGetApp().m_expcomps),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\r
-                               m_expcompsCtrl->Enable(wxGetApp().m_enablejpwl);\r
-\r
-                       compoSizer->Add(expcompsSizer, 0, wxGROW | wxALL, 5);\r
-\r
-               subtopSizer->Add(compoSizer, 0, wxGROW | wxALL, 5);\r
-\r
-                       // tiles settings, column\r
-                       wxStaticBox* tileBox = new wxStaticBox(panel, wxID_ANY, wxT("Tiles"));\r
-                       wxBoxSizer* tileSizer = new wxStaticBoxSizer(tileBox, wxVERTICAL);\r
-\r
-                               // maximum tiles sizer, row\r
-                               wxBoxSizer* maxtileSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               maxtileSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Max. no. of tiles:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 5);\r
-\r
-                               // add some horizontal space\r
-                               maxtileSizer->Add(5, 5, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               maxtileSizer->Add(\r
-                                       m_maxtilesCtrl = new wxSpinCtrl(panel, OPJDECO_MAXTILES,\r
-                                                               wxString::Format(wxT("%d"), wxGetApp().m_maxtiles),\r
-                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
-                                                               wxSP_ARROW_KEYS,\r
-                                                               1, 100000, wxGetApp().m_maxtiles),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\r
-                               m_maxtilesCtrl->Enable(wxGetApp().m_enablejpwl);\r
-\r
-                       tileSizer->Add(maxtileSizer, 0, wxGROW | wxALL, 5);\r
-\r
-               subtopSizer->Add(tileSizer, 0, wxGROW | wxALL, 5);\r
-\r
-       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
-\r
-       // assign top and fit it\r
-    panel->SetSizer(topSizer);\r
-    topSizer->Fit(panel);\r
-\r
-    return panel;\r
-}\r
-\r
-void OPJDecoderDialog::OnEnableDeco(wxCommandEvent& event)\r
-{\r
-       size_t pp;\r
-\r
-       if (event.IsChecked()) {\r
-               wxLogMessage(wxT("Decoding enabled"));\r
-               m_resizeBox->Enable(true);\r
-               // enable all tabs except ourselves\r
-               for (pp = 0; pp < m_settingsNotebook->GetPageCount(); pp++) {\r
-                       if (m_settingsNotebook->GetPageText(pp) != wxT("Display"))\r
-                               m_settingsNotebook->GetPage(pp)->Enable(true);\r
-               }\r
-       } else {\r
-               wxLogMessage(wxT("Decoding disabled"));\r
-               m_resizeBox->Enable(false);\r
-               // disable all tabs except ourselves\r
-               for (pp = 0; pp < m_settingsNotebook->GetPageCount(); pp++) {\r
-                       if (m_settingsNotebook->GetPageText(pp) != wxT("Display"))\r
-                               m_settingsNotebook->GetPage(pp)->Enable(false);\r
-               }\r
-       }\r
-\r
-}\r
-\r
-void OPJDecoderDialog::OnEnableJPWL(wxCommandEvent& event)\r
-{\r
-       if (event.IsChecked()) {\r
-               wxLogMessage(wxT("JPWL enabled"));\r
-               m_expcompsCtrl->Enable(true);\r
-               m_maxtilesCtrl->Enable(true);\r
-       } else {\r
-               wxLogMessage(wxT("JPWL disabled"));\r
-               m_expcompsCtrl->Enable(false);\r
-               m_maxtilesCtrl->Enable(false);\r
-       }\r
-\r
-}\r
-\r
-#endif // USE_JPWL\r
-\r
-\r
-\r
-\r
-// ----------------------------------------------------------------------------\r
-// OPJEncoderDialog\r
-// ----------------------------------------------------------------------------\r
-\r
-IMPLEMENT_CLASS(OPJEncoderDialog, wxPropertySheetDialog)\r
-\r
-BEGIN_EVENT_TABLE(OPJEncoderDialog, wxPropertySheetDialog)\r
-       EVT_CHECKBOX(OPJENCO_ENABLECOMM, OPJEncoderDialog::OnEnableComm)\r
-       EVT_CHECKBOX(OPJENCO_ENABLEINDEX, OPJEncoderDialog::OnEnableIdx)\r
-       EVT_CHECKBOX(OPJENCO_ENABLEPOC, OPJEncoderDialog::OnEnablePoc)\r
-       EVT_RADIOBUTTON(OPJENCO_RATERADIO, OPJEncoderDialog::OnRadioQualityRate)\r
-       EVT_RADIOBUTTON(OPJENCO_QUALITYRADIO, OPJEncoderDialog::OnRadioQualityRate)\r
-#ifdef USE_JPWL\r
-       EVT_CHECKBOX(OPJENCO_ENABLEJPWL, OPJEncoderDialog::OnEnableJPWL)\r
-       EVT_CHOICE(OPJENCO_HPROT, OPJEncoderDialog::OnHprotSelect)\r
-       EVT_CHOICE(OPJENCO_PPROT, OPJEncoderDialog::OnPprotSelect)\r
-       EVT_CHOICE(OPJENCO_SENSI, OPJEncoderDialog::OnSensiSelect)\r
-#endif // USE_JPWL\r
-END_EVENT_TABLE()\r
-\r
-OPJEncoderDialog::OPJEncoderDialog(wxWindow* win, int dialogType)\r
-{\r
-       SetExtraStyle(wxDIALOG_EX_CONTEXTHELP|wxWS_EX_VALIDATE_RECURSIVELY);\r
-\r
-       Create(win, wxID_ANY, wxT("Encoder settings"),\r
-               wxDefaultPosition, wxDefaultSize,\r
-               wxDEFAULT_DIALOG_STYLE| (int) wxPlatform::IfNot(wxOS_WINDOWS_CE, wxRESIZE_BORDER)\r
-               );\r
-\r
-       CreateButtons(wxOK | wxCANCEL | (int)wxPlatform::IfNot(wxOS_WINDOWS_CE, wxHELP));\r
-\r
-       m_settingsNotebook = GetBookCtrl();\r
-\r
-       wxPanel* jpeg2000_1Settings = CreatePart1_1SettingsPage(m_settingsNotebook);\r
-       wxPanel* jpeg2000_2Settings = CreatePart1_2SettingsPage(m_settingsNotebook);\r
-       wxPanel* mainSettings = CreateMainSettingsPage(m_settingsNotebook);\r
-#ifdef USE_JPWL\r
-       wxPanel* jpwlSettings = CreatePart11SettingsPage(m_settingsNotebook);\r
-#endif // USE_JPWL\r
-\r
-#ifdef USE_JPWL\r
-       m_settingsNotebook->AddPage(jpwlSettings, wxT("JPWL"), false);\r
-#endif // USE_JPWL\r
-       m_settingsNotebook->AddPage(jpeg2000_1Settings, wxT("JPEG 2000 - 1"), false);\r
-       m_settingsNotebook->AddPage(jpeg2000_2Settings, wxT("JPEG 2000 - 2"), false);\r
-       m_settingsNotebook->AddPage(mainSettings, wxT("General"), false);\r
-\r
-       LayoutDialog();\r
-}\r
-\r
-OPJEncoderDialog::~OPJEncoderDialog()\r
-{\r
-}\r
-\r
-wxPanel* OPJEncoderDialog::CreateMainSettingsPage(wxWindow* parent)\r
-{\r
-    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
-\r
-       // top sizer\r
-    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-               // sub top sizer\r
-               wxBoxSizer *subtopSizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
-\r
-       // assign top and fit it\r
-    panel->SetSizer(topSizer);\r
-    topSizer->Fit(panel);\r
-\r
-    return panel;\r
-}\r
-\r
-#ifdef USE_JPWL\r
-wxPanel* OPJEncoderDialog::CreatePart11SettingsPage(wxWindow* parent)\r
-{\r
-    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
-       int specno;\r
-\r
-       // top sizer\r
-    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-               // add JPWL enabling check box\r
-               topSizer->Add(\r
-                       m_enablejpwlCheck = new wxCheckBox(panel, OPJENCO_ENABLEJPWL, wxT("Enable JPWL"),\r
-                       wxDefaultPosition, wxDefaultSize),\r
-                       0, wxGROW | wxALL | wxALIGN_CENTER, 5);\r
-               m_enablejpwlCheck->SetValue(wxGetApp().m_enablejpwle);\r
-\r
-               // sub top sizer\r
-               wxFlexGridSizer *subtopSizer = new wxFlexGridSizer(2, 3, 3);\r
-\r
-                       // header settings, column\r
-                       wxStaticBox* headerBox = new wxStaticBox(panel, wxID_ANY, wxT("Header protection"));\r
-                       wxBoxSizer* headerSizer = new wxStaticBoxSizer(headerBox, wxVERTICAL);\r
-\r
-                               // info sizer, row\r
-                               wxBoxSizer* info1Sizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               info1Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
-                                                               wxT("Type")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
-\r
-                               // add some horizontal space\r
-                               info1Sizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add some text\r
-                               info1Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
-                                                               wxT("Tile part")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
-\r
-                       headerSizer->Add(info1Sizer, 0, wxGROW | wxALL, 0);\r
-\r
-                       // specify specs\r
-                       wxString hprotvalues[] = {wxT("None"), wxT("Pred."), wxT("CRC16"), wxT("CRC32"),\r
-                               wxT("RS37"), wxT("RS38"), wxT("RS40"), wxT("RS43"), wxT("RS45"), wxT("RS48"),\r
-                               wxT("RS51"), wxT("RS53"), wxT("RS56"), wxT("RS64"), wxT("RS75"), wxT("RS80"),\r
-                               wxT("RS85"), wxT("RS96"), wxT("RS112"), wxT("RS128")};\r
-                       for (specno = 0; specno < MYJPWL_MAX_NO_TILESPECS; specno++) {\r
-\r
-                                       // tile+hprot sizer, row\r
-                                       wxBoxSizer* tilehprotSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                                       // add the value selection\r
-                                       tilehprotSizer->Add(\r
-                                               m_hprotChoice[specno] = new wxChoice(panel, OPJENCO_HPROT,\r
-                                                       wxDefaultPosition, wxSize(60, wxDefaultCoord),\r
-                                                       WXSIZEOF(hprotvalues), hprotvalues),\r
-                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
-                                       m_hprotChoice[specno]->SetSelection(wxGetApp().m_hprotsel[specno]);\r
-\r
-                                       // add some horizontal space\r
-                                       tilehprotSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                                       // add the value control\r
-                                       tilehprotSizer->Add(\r
-                                               m_htileCtrl[specno] = new wxSpinCtrl(panel, OPJENCO_HTILE,\r
-                                                       wxString::Format(wxT("%d"), wxGetApp().m_htileval[specno]),\r
-                                                       wxDefaultPosition, wxSize(45, wxDefaultCoord),\r
-                                                       wxSP_ARROW_KEYS,\r
-                                                       0, JPWL_MAXIMUM_TILES - 1, 0),\r
-                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
-\r
-                               headerSizer->Add(tilehprotSizer, 0, wxGROW | wxALL, 0);\r
-                       }\r
-\r
-                       wxCommandEvent event1;\r
-                       OnHprotSelect(event1);\r
-\r
-               subtopSizer->Add(headerSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                       // packet settings, column\r
-                       wxStaticBox* packetBox = new wxStaticBox(panel, wxID_ANY, wxT("Packet protection"));\r
-                       wxBoxSizer* packetSizer = new wxStaticBoxSizer(packetBox, wxVERTICAL);\r
-\r
-                               // info sizer, row\r
-                               wxBoxSizer* info2Sizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               info2Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
-                                                               wxT("Type")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
-\r
-                               // add some horizontal space\r
-                               info2Sizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add some text\r
-                               info2Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
-                                                               wxT("Tile part")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
-\r
-                               // add some horizontal space\r
-                               info2Sizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add some text\r
-                               info2Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
-                                                               wxT("Packet")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
-\r
-                       packetSizer->Add(info2Sizer, 0, wxGROW | wxALL, 0);\r
-\r
-                       // specify specs\r
-                       wxString pprotvalues[] = {wxT("None"), wxT("Pred."), wxT("CRC16"), wxT("CRC32"),\r
-                               wxT("RS37"), wxT("RS38"), wxT("RS40"), wxT("RS43"), wxT("RS45"), wxT("RS48"),\r
-                               wxT("RS51"), wxT("RS53"), wxT("RS56"), wxT("RS64"), wxT("RS75"), wxT("RS80"),\r
-                               wxT("RS85"), wxT("RS96"), wxT("RS112"), wxT("RS128")};\r
-                       for (specno = 0; specno < MYJPWL_MAX_NO_TILESPECS; specno++) {\r
-\r
-                                       // tile+pprot sizer, row\r
-                                       wxBoxSizer* tilepprotSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                                       // add the value selection\r
-                                       tilepprotSizer->Add(\r
-                                               m_pprotChoice[specno] = new wxChoice(panel, OPJENCO_PPROT,\r
-                                                       wxDefaultPosition, wxSize(60, wxDefaultCoord),\r
-                                                       WXSIZEOF(pprotvalues), pprotvalues),\r
-                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
-                                       m_pprotChoice[specno]->SetSelection(wxGetApp().m_pprotsel[specno]);\r
-\r
-                                       // add some horizontal space\r
-                                       tilepprotSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                                       // add the value control\r
-                                       tilepprotSizer->Add(\r
-                                               m_ptileCtrl[specno] = new wxSpinCtrl(panel, OPJENCO_PTILE,\r
-                                                       wxString::Format(wxT("%d"), wxGetApp().m_ptileval[specno]),\r
-                                                       wxDefaultPosition, wxSize(45, wxDefaultCoord),\r
-                                                       wxSP_ARROW_KEYS,\r
-                                                       0, JPWL_MAXIMUM_TILES - 1, 0),\r
-                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
-\r
-                                       // add some horizontal space\r
-                                       tilepprotSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                                       // add the value control\r
-                                       tilepprotSizer->Add(\r
-                                               m_ppackCtrl[specno] = new wxSpinCtrl(panel, OPJENCO_PPACK,\r
-                                                       wxString::Format(wxT("%d"), wxGetApp().m_ppackval[specno]),\r
-                                                       wxDefaultPosition, wxSize(50, wxDefaultCoord),\r
-                                                       wxSP_ARROW_KEYS,\r
-                                                       0, 2047, 0),\r
-                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
-\r
-                               packetSizer->Add(tilepprotSizer, 0, wxGROW | wxALL, 0);\r
-                       }\r
-\r
-                       wxCommandEvent event2;\r
-                       OnPprotSelect(event2);\r
-\r
-               subtopSizer->Add(packetSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                       // sensitivity settings, column\r
-                       wxStaticBox* sensiBox = new wxStaticBox(panel, wxID_ANY, wxT("Sensitivity"));\r
-                       wxBoxSizer* sensiSizer = new wxStaticBoxSizer(sensiBox, wxVERTICAL);\r
-\r
-                               // info sizer, row\r
-                               wxBoxSizer* info3Sizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               info3Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
-                                                               wxT("Type")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
-\r
-                               // add some horizontal space\r
-                               info3Sizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add some text\r
-                               info3Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
-                                                               wxT("Tile part")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
-\r
-                       sensiSizer->Add(info3Sizer, 0, wxGROW | wxALL, 0);\r
-\r
-                       // specify specs\r
-                       wxString sensivalues[] = {wxT("None"), wxT("RELATIVE ERROR"), wxT("MSE"),\r
-                               wxT("MSE REDUCTION"), wxT("PSNR INCREMENT"), wxT("MAXERR"), wxT("TSE")};\r
-                       for (specno = 0; specno < MYJPWL_MAX_NO_TILESPECS; specno++) {\r
-\r
-                                       // tile+sensi sizer, row\r
-                                       wxBoxSizer* tilesensiSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                                       // add the value selection\r
-                                       tilesensiSizer->Add(\r
-                                               m_sensiChoice[specno] = new wxChoice(panel, OPJENCO_SENSI,\r
-                                                       wxDefaultPosition, wxSize(110, wxDefaultCoord),\r
-                                                       WXSIZEOF(sensivalues), sensivalues),\r
-                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
-                                       m_sensiChoice[specno]->SetSelection(wxGetApp().m_sensisel[specno]);\r
-\r
-                                       // add some horizontal space\r
-                                       tilesensiSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                                       // add the value control\r
-                                       tilesensiSizer->Add(\r
-                                               m_stileCtrl[specno] = new wxSpinCtrl(panel, OPJENCO_STILE,\r
-                                                       wxString::Format(wxT("%d"), wxGetApp().m_stileval[specno]),\r
-                                                       wxDefaultPosition, wxSize(45, wxDefaultCoord),\r
-                                                       wxSP_ARROW_KEYS,\r
-                                                       0, JPWL_MAXIMUM_TILES - 1, 0),\r
-                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
-\r
-                               sensiSizer->Add(tilesensiSizer, 0, wxGROW | wxALL, 0);\r
-                       }\r
-\r
-                       wxCommandEvent event3;\r
-                       OnSensiSelect(event3);\r
-\r
-               subtopSizer->Add(sensiSizer, 0, wxGROW | wxALL, 3);\r
-\r
-       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
-\r
-       // assign top and fit it\r
-    panel->SetSizer(topSizer);\r
-    topSizer->Fit(panel);\r
-\r
-    return panel;\r
-}\r
-#endif // USE_JPWL\r
-\r
-wxPanel* OPJEncoderDialog::CreatePart1_1SettingsPage(wxWindow* parent)\r
-{\r
-    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
-\r
-       // top sizer\r
-    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-       // add some space\r
-       //topSizer->AddSpacer(5);\r
-\r
-               // sub top sizer\r
-               wxFlexGridSizer *subtopSizer = new wxFlexGridSizer(2, 3, 3);\r
-\r
-                       // image settings, column\r
-                       wxStaticBox* imageBox = new wxStaticBox(panel, wxID_ANY, wxT("Image"));\r
-                       wxBoxSizer* imageSizer = new wxStaticBoxSizer(imageBox, wxVERTICAL);\r
-\r
-                               // subsampling factor sizer, row\r
-                               wxBoxSizer* subsSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               subsSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Subsampling:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                               // add some horizontal space\r
-                               subsSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               subsSizer->Add(\r
-                                       m_subsamplingCtrl = new wxTextCtrl(panel, OPJENCO_SUBSAMPLING,\r
-                                                               wxGetApp().m_subsampling,\r
-                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
-                                                               wxTE_LEFT),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                       imageSizer->Add(subsSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                               // origin sizer, row\r
-                               wxBoxSizer* imorigSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               imorigSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Origin:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                               // add some horizontal space\r
-                               imorigSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               imorigSizer->Add(\r
-                                       m_originCtrl = new wxTextCtrl(panel, OPJENCO_IMORIG,\r
-                                                               wxGetApp().m_origin,\r
-                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
-                                                               wxTE_LEFT),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                       imageSizer->Add(imorigSizer, 0, wxGROW | wxALL, 3);\r
-\r
-               subtopSizer->Add(imageSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                       // layer settings, column\r
-                       wxStaticBox* layerBox = new wxStaticBox(panel, wxID_ANY, wxT("Layers/compression"));\r
-                       wxBoxSizer* layerSizer = new wxStaticBoxSizer(layerBox, wxVERTICAL);\r
-\r
-                               // rate factor sizer, row\r
-                               wxBoxSizer* rateSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               /*rateSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Rate values:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);*/\r
-\r
-                               // add the radio button\r
-                               rateSizer->Add(\r
-                                       m_rateRadio = new wxRadioButton(panel, OPJENCO_RATERADIO, wxT("&Rate values"),\r
-                                                               wxDefaultPosition, wxDefaultSize,\r
-                                                               wxRB_GROUP),\r
-                                                               0, wxALL | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL\r
-                                                               );\r
-                               m_rateRadio->SetValue(!(wxGetApp().m_enablequality));\r
-\r
-                               // add some horizontal space\r
-                               rateSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               rateSizer->Add(\r
-                                       m_rateCtrl = new wxTextCtrl(panel, OPJENCO_RATEFACTOR,\r
-                                                               wxGetApp().m_rates,\r
-                                                               wxDefaultPosition, wxSize(100, wxDefaultCoord),\r
-                                                               wxTE_LEFT),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-                               if (wxGetApp().m_enablequality == true)\r
-                                       m_rateCtrl->Enable(false);\r
-\r
-                       layerSizer->Add(rateSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                               // quality factor sizer, row\r
-                               wxBoxSizer* qualitySizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               /*qualitySizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Quality values:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);*/\r
-\r
-                               // add the radio button\r
-                               qualitySizer->Add(\r
-                                       m_qualityRadio = new wxRadioButton(panel, OPJENCO_QUALITYRADIO, wxT("&Quality values"),\r
-                                                               wxDefaultPosition, wxDefaultSize),\r
-                                                               0, wxALL | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL\r
-                                                               );\r
-                               m_qualityRadio->SetValue(wxGetApp().m_enablequality);\r
-\r
-                               // add some horizontal space\r
-                               qualitySizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               qualitySizer->Add(\r
-                                       m_qualityCtrl = new wxTextCtrl(panel, OPJENCO_QUALITYFACTOR,\r
-                                                               wxGetApp().m_quality,\r
-                                                               wxDefaultPosition, wxSize(100, wxDefaultCoord),\r
-                                                               wxTE_LEFT),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-                               if (wxGetApp().m_enablequality == false)\r
-                                       m_qualityCtrl->Enable(false);\r
-\r
-                       layerSizer->Add(qualitySizer, 0, wxGROW | wxALL, 3);\r
-\r
-               subtopSizer->Add(layerSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                       // wavelet settings, column\r
-                       wxStaticBox* transformBox = new wxStaticBox(panel, wxID_ANY, wxT("Transforms"));\r
-                       wxBoxSizer* transformSizer = new wxStaticBoxSizer(transformBox, wxVERTICAL);\r
-\r
-                       // multiple component check box\r
-                       transformSizer->Add(\r
-                               m_mctCheck = new wxCheckBox(panel, OPJENCO_ENABLEMCT, wxT("Multiple component"),\r
-                               wxDefaultPosition, wxDefaultSize),\r
-                               0, wxGROW | wxALL, 3);\r
-                       m_mctCheck->SetValue(wxGetApp().m_multicomp);\r
-\r
-                       // irreversible wavelet check box\r
-                       transformSizer->Add(\r
-                               m_irrevCheck = new wxCheckBox(panel, OPJENCO_ENABLEIRREV, wxT("Irreversible wavelet"),\r
-                               wxDefaultPosition, wxDefaultSize),\r
-                               0, wxGROW | wxALL, 3);\r
-                       m_irrevCheck->SetValue(wxGetApp().m_irreversible);\r
-\r
-                               // resolution number sizer, row\r
-                               wxBoxSizer* resnumSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               resnumSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Resolutions:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                               // add some horizontal space\r
-                               resnumSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               resnumSizer->Add(\r
-                                       m_resolutionsCtrl = new wxSpinCtrl(panel, OPJENCO_RESNUMBER,\r
-                                                               wxString::Format(wxT("%d"), wxGetApp().m_resolutions),\r
-                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
-                                                               wxSP_ARROW_KEYS,\r
-                                                               1, 256, 6),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                       transformSizer->Add(resnumSizer, 0, wxGROW | wxALL, 3);\r
-\r
-               subtopSizer->Add(transformSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                       // codestream settings, column\r
-                       wxStaticBox* codestreamBox = new wxStaticBox(panel, wxID_ANY, wxT("Codestream"));\r
-                       wxBoxSizer* codestreamSizer = new wxStaticBoxSizer(codestreamBox, wxVERTICAL);\r
-\r
-                               // codeblock sizer, row\r
-                               wxBoxSizer* codeblockSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               codeblockSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Codeblocks size:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                               // add some horizontal space\r
-                               codeblockSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               codeblockSizer->Add(\r
-                                       m_cbsizeCtrl = new wxTextCtrl(panel, OPJENCO_CODEBLOCKSIZE,\r
-                                                               wxGetApp().m_cbsize,\r
-                                                               wxDefaultPosition, wxSize(100, wxDefaultCoord),\r
-                                                               wxTE_LEFT),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                       codestreamSizer->Add(codeblockSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                               // precinct sizer, row\r
-                               wxBoxSizer* precinctSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               precinctSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Precincts size:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                               // add some horizontal space\r
-                               precinctSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               precinctSizer->Add(\r
-                                       m_prsizeCtrl = new wxTextCtrl(panel, OPJENCO_PRECINCTSIZE,\r
-                                                               wxGetApp().m_prsize,\r
-                                                               wxDefaultPosition, wxSize(100, wxDefaultCoord),\r
-                                                               wxTE_LEFT),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                       codestreamSizer->Add(precinctSizer, 0, wxGROW | wxALL, 3);\r
-\r
-               subtopSizer->Add(codestreamSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                       // tile settings, column\r
-                       wxStaticBox* tileBox = new wxStaticBox(panel, wxID_ANY, wxT("Tiles"));\r
-                       wxBoxSizer* tileSizer = new wxStaticBoxSizer(tileBox, wxVERTICAL);\r
-\r
-                               // tile size sizer, row\r
-                               wxBoxSizer* tilesizeSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               tilesizeSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Size:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                               // add some horizontal space\r
-                               tilesizeSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               tilesizeSizer->Add(\r
-                                       m_tsizeCtrl = new wxTextCtrl(panel, OPJENCO_TILESIZE,\r
-                                                               wxGetApp().m_tsize,\r
-                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
-                                                               wxTE_LEFT),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                       tileSizer->Add(tilesizeSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                               // tile origin sizer, row\r
-                               wxBoxSizer* tilorigSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               tilorigSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Origin:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                               // add some horizontal space\r
-                               tilorigSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               tilorigSizer->Add(\r
-                                       m_toriginCtrl = new wxTextCtrl(panel, OPJENCO_TILORIG,\r
-                                                               wxGetApp().m_torigin,\r
-                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
-                                                               wxTE_LEFT),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                       tileSizer->Add(tilorigSizer, 0, wxGROW | wxALL, 3);\r
-\r
-               subtopSizer->Add(tileSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                       // progression and profile settings, column\r
-                       wxString choices[] = {wxT("LRCP"), wxT("RLCP"), wxT("RPCL"), wxT("PCRL"), wxT("CPRL"),\r
-                               wxT("DCI2K24"), wxT("DCI2K48"), wxT("DCI4K")};\r
-                       progressionBox = new wxRadioBox(panel, OPJENCO_PROGRESSION,\r
-                               wxT("Progression order/profile"),\r
-                               wxDefaultPosition, wxDefaultSize,\r
-                               WXSIZEOF(choices),\r
-                               choices,\r
-                               3,\r
-                               wxRA_SPECIFY_COLS);\r
-                       progressionBox->SetSelection(wxGetApp().m_progression);\r
-\r
-               subtopSizer->Add(progressionBox, 0, wxGROW | wxALL, 3);\r
-\r
-       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
-\r
-       // assign top and fit it\r
-    panel->SetSizer(topSizer);\r
-    topSizer->Fit(panel);\r
-\r
-    return panel;\r
-}\r
-\r
-wxPanel* OPJEncoderDialog::CreatePart1_2SettingsPage(wxWindow* parent)\r
-{\r
-    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
-\r
-       // top sizer\r
-    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
-\r
-       // add some space\r
-       //topSizer->AddSpacer(5);\r
-\r
-               // sub top sizer\r
-               wxFlexGridSizer *subtopSizer = new wxFlexGridSizer(2, 3, 3);\r
-                       \r
-                       // resilience settings, column\r
-                       wxStaticBox* resilBox = new wxStaticBox(panel, wxID_ANY, wxT("Error resilience"));\r
-                       wxBoxSizer* resilSizer = new wxStaticBoxSizer(resilBox, wxVERTICAL);\r
-\r
-                               // resil2 sizer, row\r
-                               wxBoxSizer* resil2Sizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // SOP check box\r
-                               resil2Sizer->Add(\r
-                                       m_sopCheck = new wxCheckBox(panel, OPJENCO_ENABLESOP, wxT("SOP"),\r
-                                               wxDefaultPosition, wxDefaultSize),\r
-                                               0, wxGROW | wxALL, 3);\r
-                               m_sopCheck->SetValue(wxGetApp().m_enablesop);\r
-\r
-                               // EPH check box\r
-                               resil2Sizer->Add(\r
-                                       m_ephCheck = new wxCheckBox(panel, OPJENCO_ENABLEEPH, wxT("EPH"),\r
-                                               wxDefaultPosition, wxDefaultSize),\r
-                                               0, wxGROW | wxALL, 3);\r
-                               m_ephCheck->SetValue(wxGetApp().m_enableeph);\r
-\r
-                       resilSizer->Add(resil2Sizer, 0, wxGROW | wxALL, 3);\r
-\r
-                       // separation\r
-                       resilSizer->Add(new wxStaticLine(panel, wxID_ANY), 0, wxEXPAND | wxLEFT | wxRIGHT, 3);\r
-\r
-                               // resil3 sizer, row\r
-                               wxFlexGridSizer* resil3Sizer = new wxFlexGridSizer(3, 3, 3);\r
-\r
-                               // BYPASS check box\r
-                               resil3Sizer->Add(\r
-                                       m_enablebypassCheck = new wxCheckBox(panel, OPJENCO_ENABLEBYPASS, wxT("BYPASS"),\r
-                                       wxDefaultPosition, wxDefaultSize),\r
-                                       0, wxGROW | wxALL, 3);\r
-                               m_enablebypassCheck->SetValue(wxGetApp().m_enablebypass);\r
-\r
-                               // RESET check box\r
-                               resil3Sizer->Add(\r
-                                       m_enableresetCheck = new wxCheckBox(panel, OPJENCO_ENABLERESET, wxT("RESET"),\r
-                                       wxDefaultPosition, wxDefaultSize),\r
-                                       0, wxGROW | wxALL, 3);\r
-                               m_enableresetCheck->SetValue(wxGetApp().m_enablereset);\r
-\r
-                               // RESTART check box\r
-                               resil3Sizer->Add(\r
-                                       m_enablerestartCheck = new wxCheckBox(panel, OPJENCO_ENABLERESTART, wxT("RESTART"),\r
-                                       wxDefaultPosition, wxDefaultSize),\r
-                                       0, wxGROW | wxALL, 3);\r
-                               m_enablerestartCheck->SetValue(wxGetApp().m_enablerestart);\r
-\r
-                               // VSC check box\r
-                               resil3Sizer->Add(\r
-                                       m_enablevscCheck = new wxCheckBox(panel, OPJENCO_ENABLEVSC, wxT("VSC"),\r
-                                       wxDefaultPosition, wxDefaultSize),\r
-                                       0, wxGROW | wxALL, 3);\r
-                               m_enablevscCheck->SetValue(wxGetApp().m_enablevsc);\r
-\r
-                               // ERTERM check box\r
-                               resil3Sizer->Add(\r
-                                       m_enableertermCheck = new wxCheckBox(panel, OPJENCO_ENABLEERTERM, wxT("ERTERM"),\r
-                                       wxDefaultPosition, wxDefaultSize),\r
-                                       0, wxGROW | wxALL, 3);\r
-                               m_enableertermCheck->SetValue(wxGetApp().m_enableerterm);\r
-\r
-                               // SEGMARK check box\r
-                               resil3Sizer->Add(\r
-                                       m_enablesegmarkCheck = new wxCheckBox(panel, OPJENCO_ENABLESEGMARK, wxT("SEGMARK"),\r
-                                       wxDefaultPosition, wxDefaultSize),\r
-                                       0, wxGROW | wxALL, 3);\r
-                               m_enablesegmarkCheck->SetValue(wxGetApp().m_enablesegmark);\r
-\r
-                       resilSizer->Add(resil3Sizer, 0, wxGROW | wxALL, 3);\r
-\r
-               subtopSizer->Add(resilSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                       // ROI settings, column\r
-                       wxStaticBox* roiBox = new wxStaticBox(panel, wxID_ANY, wxT("Region Of Interest"));\r
-                       wxBoxSizer* roiSizer = new wxStaticBoxSizer(roiBox, wxVERTICAL);\r
-\r
-                               // component number sizer, row\r
-                               wxBoxSizer* roicompSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               roicompSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Component:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                               // add some horizontal space\r
-                               roicompSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               roicompSizer->Add(\r
-                                       /*m_layerCtrl =*/ new wxSpinCtrl(panel, OPJENCO_ROICOMP,\r
-                                                               wxT("0"),\r
-                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
-                                                               wxSP_ARROW_KEYS,\r
-                                                               0, 256, 0),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                       roiSizer->Add(roicompSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                               // upshift sizer, row\r
-                               wxBoxSizer* roishiftSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               roishiftSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Upshift:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                               // add some horizontal space\r
-                               roishiftSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               roishiftSizer->Add(\r
-                                       /*m_layerCtrl =*/ new wxSpinCtrl(panel, OPJENCO_ROISHIFT,\r
-                                                               wxT("0"),\r
-                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
-                                                               wxSP_ARROW_KEYS,\r
-                                                               0, 37, 0),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                       roiSizer->Add(roishiftSizer, 0, wxGROW | wxALL, 3);\r
-\r
-               subtopSizer->Add(roiSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                       // POC settings, column\r
-                       wxStaticBox* pocBox = new wxStaticBox(panel, wxID_ANY, wxT("POC"));\r
-                       wxBoxSizer* pocSizer = new wxStaticBoxSizer(pocBox, wxVERTICAL);\r
-\r
-                       // POC check box\r
-                       pocSizer->Add(\r
-                               m_enablepocCheck = new wxCheckBox(panel, OPJENCO_ENABLEPOC, wxT("Enabled (tn=rs,cs,le,re,ce,pr)"),\r
-                               wxDefaultPosition, wxDefaultSize),\r
-                               0, wxGROW | wxALL, 3);\r
-                       m_enablepocCheck->SetValue(wxGetApp().m_enablepoc);\r
-\r
-                               // POC sizer, row\r
-                               wxBoxSizer* pocspecSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               pocspecSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Changes:")),\r
-                                                               0, wxALL | wxALIGN_TOP, 3);\r
-\r
-                               // add some horizontal space\r
-                               pocspecSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               pocspecSizer->Add(\r
-                                       m_pocCtrl = new wxTextCtrl(panel, OPJENCO_POCSPEC,\r
-                                                               wxGetApp().m_poc,\r
-                                                               wxDefaultPosition, wxSize(140, 60),\r
-                                                               wxTE_LEFT | wxTE_MULTILINE),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-                               m_pocCtrl->Enable(wxGetApp().m_enablepoc);\r
-\r
-                       pocSizer->Add(pocspecSizer, 0, wxGROW | wxALL, 3);\r
-\r
-               subtopSizer->Add(pocSizer, 0, wxGROW | wxALL, 3);\r
-                       \r
-                       // Comment settings, column\r
-                       wxStaticBox* commentBox = new wxStaticBox(panel, wxID_ANY, wxT("Comment"));\r
-                       wxBoxSizer* commentSizer = new wxStaticBoxSizer(commentBox, wxVERTICAL);\r
-\r
-                       // commenting check box\r
-                       commentSizer->Add(\r
-                               m_enablecommCheck = new wxCheckBox(panel, OPJENCO_ENABLECOMM, wxT("Enabled (empty to reset)"),\r
-                               wxDefaultPosition, wxDefaultSize),\r
-                               0, wxGROW | wxALL, 3);\r
-                       m_enablecommCheck->SetValue(wxGetApp().m_enablecomm);\r
-\r
-                       // add some horizontal space\r
-                       commentSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                       // add the value control\r
-                       commentSizer->Add(\r
-                               m_commentCtrl = new wxTextCtrl(panel, OPJENCO_COMMENTTEXT,\r
-                                                       wxGetApp().m_comment,\r
-                                                       wxDefaultPosition, wxSize(wxDefaultCoord, 60),\r
-                                                       wxTE_LEFT | wxTE_MULTILINE),\r
-                               0, wxGROW | wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-                       m_commentCtrl->Enable(wxGetApp().m_enablecomm);\r
-\r
-               subtopSizer->Add(commentSizer, 0, wxGROW | wxALL, 3);\r
-\r
-                       // Index file settings, column\r
-                       wxStaticBox* indexBox = new wxStaticBox(panel, wxID_ANY, wxT("Indexing"));\r
-                       wxBoxSizer* indexSizer = new wxStaticBoxSizer(indexBox, wxVERTICAL);\r
-\r
-                       // indexing check box\r
-                       indexSizer->Add(\r
-                               m_enableidxCheck = new wxCheckBox(panel, OPJENCO_ENABLEINDEX, wxT("Enabled"),\r
-                               wxDefaultPosition, wxDefaultSize),\r
-                               0, wxGROW | wxALL, 3);\r
-                       m_enableidxCheck->SetValue(wxGetApp().m_enableidx);\r
-\r
-                               // index file sizer, row\r
-                               wxBoxSizer* indexnameSizer = new wxBoxSizer(wxHORIZONTAL);\r
-\r
-                               // add some text\r
-                               indexnameSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&File name:")),\r
-                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
-\r
-                               // add some horizontal space\r
-                               indexnameSizer->Add(3, 3, 1, wxALL, 0);\r
-\r
-                               // add the value control\r
-                               indexnameSizer->Add(\r
-                                       m_indexCtrl = new wxTextCtrl(panel, OPJENCO_INDEXNAME,\r
-                                                               wxGetApp().m_index,\r
-                                                               wxDefaultPosition, wxSize(120, wxDefaultCoord),\r
-                                                               wxTE_LEFT),\r
-                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
-                               m_indexCtrl->Enable(wxGetApp().m_enableidx);\r
-\r
-                       indexSizer->Add(indexnameSizer, 0, wxGROW | wxALL, 3);\r
-\r
-               subtopSizer->Add(indexSizer, 0, wxGROW | wxALL, 3);\r
-\r
-       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
-\r
-       // assign top and fit it\r
-    panel->SetSizer(topSizer);\r
-    topSizer->Fit(panel);\r
-\r
-    return panel;\r
-}\r
-\r
-void OPJEncoderDialog::OnEnableComm(wxCommandEvent& event)\r
-{\r
-       if (event.IsChecked()) {\r
-               wxLogMessage(wxT("Comment enabled"));\r
-               m_commentCtrl->Enable(true);\r
-       } else {\r
-               wxLogMessage(wxT("Comment disabled"));\r
-               m_commentCtrl->Enable(false);\r
-       }\r
-\r
-}\r
-\r
-void OPJEncoderDialog::OnEnableIdx(wxCommandEvent& event)\r
-{\r
-       if (event.IsChecked()) {\r
-               wxLogMessage(wxT("Index enabled"));\r
-               m_indexCtrl->Enable(true);\r
-       } else {\r
-               wxLogMessage(wxT("Index disabled"));\r
-               m_indexCtrl->Enable(false);\r
-       }\r
-\r
-}\r
-\r
-void OPJEncoderDialog::OnEnablePoc(wxCommandEvent& event)\r
-{\r
-       if (event.IsChecked()) {\r
-               wxLogMessage(wxT("POC enabled"));\r
-               m_pocCtrl->Enable(true);\r
-       } else {\r
-               wxLogMessage(wxT("POC disabled"));\r
-               m_pocCtrl->Enable(false);\r
-       }\r
-\r
-}\r
-\r
-void OPJEncoderDialog::OnRadioQualityRate(wxCommandEvent& event)\r
-{\r
-       if (event.GetId() == OPJENCO_QUALITYRADIO) {\r
-               wxLogMessage(wxT("Quality selected"));\r
-               m_rateCtrl->Enable(false);\r
-               m_qualityCtrl->Enable(true);\r
-       } else {\r
-               wxLogMessage(wxT("Rate selected"));\r
-               m_rateCtrl->Enable(true);\r
-               m_qualityCtrl->Enable(false);\r
-       }\r
-}\r
-\r
-#ifdef USE_JPWL\r
-void OPJEncoderDialog::OnEnableJPWL(wxCommandEvent& event)\r
-{\r
-       int specno;\r
-\r
-       if (event.IsChecked()) {\r
-               wxLogMessage(wxT("JPWL enabled"));\r
-               for (specno = 0; specno < MYJPWL_MAX_NO_TILESPECS; specno++) {\r
-                       m_hprotChoice[specno]->Enable(true);\r
-                       m_htileCtrl[specno]->Enable(true);\r
-                       m_pprotChoice[specno]->Enable(true);\r
-                       m_ptileCtrl[specno]->Enable(true);\r
-                       m_ppackCtrl[specno]->Enable(true);\r
-                       m_sensiChoice[specno]->Enable(true);\r
-                       m_stileCtrl[specno]->Enable(true);\r
-               }\r
-               OnHprotSelect(event);\r
-               OnPprotSelect(event);\r
-               OnSensiSelect(event);\r
-       } else {\r
-               wxLogMessage(wxT("JPWL disabled"));\r
-               for (specno = 0; specno < MYJPWL_MAX_NO_TILESPECS; specno++) {\r
-                       m_hprotChoice[specno]->Enable(false);\r
-                       m_htileCtrl[specno]->Enable(false);\r
-                       m_pprotChoice[specno]->Enable(false);\r
-                       m_ptileCtrl[specno]->Enable(false);\r
-                       m_ppackCtrl[specno]->Enable(false);\r
-                       m_sensiChoice[specno]->Enable(false);\r
-                       m_stileCtrl[specno]->Enable(false);\r
-               }\r
-       }\r
-\r
-}\r
-\r
-void OPJEncoderDialog::OnHprotSelect(wxCommandEvent& event)\r
-{\r
-       int specno;\r
-\r
-       // deactivate properly\r
-       for (specno = MYJPWL_MAX_NO_TILESPECS - 1; specno >= 0; specno--) {\r
-               if (!m_hprotChoice[specno]->GetSelection()) {\r
-                       m_hprotChoice[specno]->Enable(false);\r
-                       m_htileCtrl[specno]->Enable(false);\r
-               } else\r
-                       break;\r
-       }\r
-       if (specno < (MYJPWL_MAX_NO_TILESPECS - 1)) {\r
-               m_hprotChoice[specno + 1]->Enable(true);\r
-               m_htileCtrl[specno + 1]->Enable(true);\r
-       }\r
-\r
-       //wxLogMessage(wxT("hprot changed: %d"), specno);\r
-}\r
-\r
-void OPJEncoderDialog::OnPprotSelect(wxCommandEvent& event)\r
-{\r
-       int specno;\r
-\r
-       // deactivate properly\r
-       for (specno = MYJPWL_MAX_NO_TILESPECS - 1; specno >= 0; specno--) {\r
-               if (!m_pprotChoice[specno]->GetSelection()) {\r
-                       m_pprotChoice[specno]->Enable(false);\r
-                       m_ptileCtrl[specno]->Enable(false);\r
-                       m_ppackCtrl[specno]->Enable(false);\r
-               } else\r
-                       break;\r
-       }\r
-       if (specno < (MYJPWL_MAX_NO_TILESPECS - 1)) {\r
-               m_pprotChoice[specno + 1]->Enable(true);\r
-               m_ptileCtrl[specno + 1]->Enable(true);\r
-               m_ppackCtrl[specno + 1]->Enable(true);\r
-       }\r
-\r
-       //wxLogMessage(wxT("pprot changed: %d"), specno);\r
-}\r
-\r
-void OPJEncoderDialog::OnSensiSelect(wxCommandEvent& event)\r
-{\r
-       int specno;\r
-\r
-       // deactivate properly\r
-       for (specno = MYJPWL_MAX_NO_TILESPECS - 1; specno >= 0; specno--) {\r
-               if (!m_sensiChoice[specno]->GetSelection()) {\r
-                       m_sensiChoice[specno]->Enable(false);\r
-                       m_stileCtrl[specno]->Enable(false);\r
-               } else\r
-                       break;\r
-       }\r
-       if (specno < (MYJPWL_MAX_NO_TILESPECS - 1)) {\r
-               m_sensiChoice[specno + 1]->Enable(true);\r
-               m_stileCtrl[specno + 1]->Enable(true);\r
-       }\r
-\r
-       //wxLogMessage(wxT("sprot changed: %d"), specno);\r
-}\r
-\r
-\r
-#endif // USE_JPWL\r
-\r
diff --git a/OPJViewer/source/OPJThreads.cpp b/OPJViewer/source/OPJThreads.cpp
deleted file mode 100644 (file)
index 3c93ee2..0000000
+++ /dev/null
@@ -1,1268 +0,0 @@
-/*\r
- * Copyright (c) 2007, Digital Signal Processing Laboratory, Universita'� degli studi di Perugia (UPG), Italy\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-#include "OPJViewer.h"\r
-\r
-\r
-/////////////////////////////////////////////////////////////////////\r
-// Encoding thread class\r
-/////////////////////////////////////////////////////////////////////\r
-\r
-OPJEncoThread::OPJEncoThread(OPJCanvas *canvas)\r
-        : wxThread()\r
-{\r
-    m_count = 0;\r
-    m_canvas = canvas;\r
-}\r
-\r
-void OPJEncoThread::WriteText(const wxString& text)\r
-{\r
-    wxString msg;\r
-\r
-    // before doing any GUI calls we must ensure that this thread is the only\r
-    // one doing it!\r
-\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiEnter();\r
-#endif // __WXGTK__\r
-\r
-    msg << text;\r
-    m_canvas->WriteText(msg);\r
-\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiLeave();\r
-#endif // __WXGTK__\r
-}\r
-\r
-void OPJEncoThread::OnExit()\r
-{\r
-    wxCriticalSectionLocker locker(wxGetApp().m_enco_critsect);\r
-\r
-    wxArrayThread& ethreads = wxGetApp().m_enco_threads;\r
-    ethreads.Remove(this);\r
-\r
-    if (ethreads.IsEmpty() )\r
-    {\r
-        // signal the main thread that there are no more threads left if it is\r
-        // waiting for us\r
-        if (wxGetApp().m_enco_waitingUntilAllDone) {\r
-            wxGetApp().m_enco_waitingUntilAllDone = false;\r
-            wxGetApp().m_enco_semAllDone.Post();\r
-        }\r
-    }\r
-}\r
-\r
-void *OPJEncoThread::Entry()\r
-{\r
-    wxString text;\r
-\r
-       srand(GetId());\r
-       //int m_countnum = rand() % 9;\r
-    //text.Printf(wxT("Deco thread 0x%lx started (priority = %u, time = %d)."),\r
-    //            GetId(), GetPriority(), m_countnum);\r
-    text.Printf(wxT("Enco thread %d started"), m_canvas->m_childframe->m_winnumber);\r
-    WriteText(text);\r
-\r
-       // set handler properties\r
-       wxJPEG2000Handler *jpeg2000handler = (wxJPEG2000Handler *) wxImage::FindHandler(wxBITMAP_TYPE_JPEG2000);\r
-       jpeg2000handler->m_subsampling = wxGetApp().m_subsampling;\r
-       jpeg2000handler->m_origin = wxGetApp().m_origin;\r
-       jpeg2000handler->m_rates = wxGetApp().m_rates;\r
-       jpeg2000handler->m_quality = wxGetApp().m_quality;\r
-       jpeg2000handler->m_enablequality = wxGetApp().m_enablequality;\r
-       jpeg2000handler->m_multicomp = wxGetApp().m_multicomp;\r
-       jpeg2000handler->m_irreversible = wxGetApp().m_irreversible;\r
-       jpeg2000handler->m_resolutions = wxGetApp().m_resolutions;\r
-       jpeg2000handler->m_progression = wxGetApp().m_progression;\r
-       jpeg2000handler->m_cbsize = wxGetApp().m_cbsize;\r
-       jpeg2000handler->m_prsize = wxGetApp().m_prsize;\r
-       jpeg2000handler->m_tsize = wxGetApp().m_tsize;\r
-       jpeg2000handler->m_torigin = wxGetApp().m_torigin;\r
-       jpeg2000handler->m_enablesop = wxGetApp().m_enablesop;\r
-       jpeg2000handler->m_enableeph = wxGetApp().m_enableeph;\r
-       jpeg2000handler->m_enablebypass = wxGetApp().m_enablebypass;\r
-       jpeg2000handler->m_enablerestart = wxGetApp().m_enablerestart;\r
-       jpeg2000handler->m_enablereset = wxGetApp().m_enablereset;\r
-       jpeg2000handler->m_enablesegmark = wxGetApp().m_enablesegmark;\r
-       jpeg2000handler->m_enableerterm = wxGetApp().m_enableerterm;\r
-       jpeg2000handler->m_enablevsc = wxGetApp().m_enablevsc;\r
-       jpeg2000handler->m_enableidx = wxGetApp().m_enableidx;\r
-       jpeg2000handler->m_index = m_canvas->m_savename.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR) + wxGetApp().m_index;\r
-       jpeg2000handler->m_enablecomm = wxGetApp().m_enablecomm;\r
-       jpeg2000handler->m_comment = wxGetApp().m_comment;\r
-       jpeg2000handler->m_enablepoc = wxGetApp().m_enablepoc;\r
-       jpeg2000handler->m_poc = wxGetApp().m_poc;\r
-\r
-       // save the file\r
-       if (!m_canvas->m_image100.SaveFile(m_canvas->m_savename.GetFullPath(), (wxBitmapType) wxBITMAP_TYPE_JPEG2000)) {\r
-               WriteText(wxT("Can't save image"));\r
-               return NULL;\r
-       }\r
-\r
-    text.Printf(wxT("Enco thread %d finished"), m_canvas->m_childframe->m_winnumber);\r
-    WriteText(text);\r
-    return NULL;\r
-}\r
-\r
-\r
-/////////////////////////////////////////////////////////////////////\r
-// Decoding thread class\r
-/////////////////////////////////////////////////////////////////////\r
-OPJDecoThread::OPJDecoThread(OPJCanvas *canvas)\r
-        : wxThread()\r
-{\r
-    m_count = 0;\r
-    m_canvas = canvas;\r
-}\r
-\r
-void OPJDecoThread::WriteText(const wxString& text)\r
-{\r
-    wxString msg;\r
-       \r
-       // we use a fake event and post it for inter-thread gui communication\r
-    wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, OPJFRAME_THREADLOGMSG);\r
-    event.SetInt(-1); \r
-       msg << text;\r
-       event.SetString(msg);\r
-    wxPostEvent(this->m_canvas->m_childframe->m_frame, event);\r
-\r
-/*\r
-    // before doing any GUI calls we must ensure that this thread is the only\r
-    // one doing it!\r
-\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiEnter();\r
-#endif // __WXGTK__\r
-\r
-    msg << text;\r
-    m_canvas->WriteText(msg);\r
-\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiLeave();\r
-#endif // __WXGTK__\r
-*/\r
-}\r
-\r
-void OPJDecoThread::OnExit()\r
-{\r
-    wxCriticalSectionLocker locker(wxGetApp().m_deco_critsect);\r
-\r
-    wxArrayThread& dthreads = wxGetApp().m_deco_threads;\r
-    dthreads.Remove(this);\r
-\r
-    if (dthreads.IsEmpty() )\r
-    {\r
-        // signal the main thread that there are no more threads left if it is\r
-        // waiting for us\r
-        if (wxGetApp().m_deco_waitingUntilAllDone) {\r
-            wxGetApp().m_deco_waitingUntilAllDone = false;\r
-            wxGetApp().m_deco_semAllDone.Post();\r
-        }\r
-    }\r
-}\r
-\r
-void *OPJDecoThread::Entry()\r
-{\r
-\r
-    wxString text;\r
-\r
-       //srand(GetId());\r
-       //int m_countnum = rand() % 9;\r
-    //text.Printf(wxT("Deco thread 0x%lx started (priority = %u, time = %d)."),\r
-    //            GetId(), GetPriority(), m_countnum);\r
-\r
-       // we have started\r
-    text.Printf(wxT("Deco thread %d started"), m_canvas->m_childframe->m_winnumber);\r
-    WriteText(text);\r
-\r
-       // prepare dummy wximage\r
-    wxBitmap bitmap(100, 100);\r
-    wxImage image(100, 100, true); //= bitmap.ConvertToImage();\r
-    image.Destroy();\r
-\r
-       // show image full name\r
-       WriteText(m_canvas->m_fname.GetFullPath());\r
-\r
-       // set handler properties\r
-       wxJPEG2000Handler *jpeg2000handler = (wxJPEG2000Handler *) wxImage::FindHandler(wxBITMAP_TYPE_JPEG2000);\r
-       jpeg2000handler->m_reducefactor = wxGetApp().m_reducefactor;\r
-       jpeg2000handler->m_qualitylayers = wxGetApp().m_qualitylayers;\r
-       jpeg2000handler->m_components = wxGetApp().m_components;\r
-       jpeg2000handler->m_framenum = wxGetApp().m_framenum;\r
-#ifdef USE_JPWL\r
-       jpeg2000handler->m_enablejpwl = wxGetApp().m_enablejpwl;\r
-       jpeg2000handler->m_expcomps = wxGetApp().m_expcomps;\r
-       jpeg2000handler->m_maxtiles = wxGetApp().m_maxtiles;\r
-#endif // USE_JPWL\r
-\r
-#ifdef USE_MXF\r
-       wxMXFHandler *mxfffhandler = (wxMXFHandler *) wxImage::FindHandler(wxBITMAP_TYPE_MXF);\r
-       mxfffhandler->m_reducefactor = wxGetApp().m_reducefactor;\r
-       mxfffhandler->m_qualitylayers = wxGetApp().m_qualitylayers;\r
-       mxfffhandler->m_components = wxGetApp().m_components;\r
-       mxfffhandler->m_framenum = wxGetApp().m_framenum;\r
-       mxfffhandler->m_filename = m_canvas->m_fname;\r
-#ifdef USE_JPWL\r
-       mxfffhandler->m_enablejpwl = wxGetApp().m_enablejpwl;\r
-       mxfffhandler->m_expcomps = wxGetApp().m_expcomps;\r
-       mxfffhandler->m_maxtiles = wxGetApp().m_maxtiles;\r
-#endif // USE_JPWL\r
-#endif // USE_MXF\r
-\r
-       // if decoding is enabled...\r
-       if (wxGetApp().m_enabledeco) {\r
-\r
-               // load the file\r
-               if (!image.LoadFile(m_canvas->m_fname.GetFullPath(), wxBITMAP_TYPE_ANY, 0)) {\r
-                       WriteText(wxT("Can't load image!"));\r
-                       return NULL;\r
-               }\r
-\r
-       } else {\r
-\r
-               // display a warning\r
-               if (!image.Create(300, 5, false)) {\r
-                       WriteText(wxT("Can't create image!"));\r
-                       return NULL;\r
-               }\r
-\r
-       }\r
-\r
-       // assign 100% image\r
-    m_canvas->m_image100 = wxBitmap(image);\r
-\r
-       // signal the frame to refresh the canvas\r
-    wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, OPJFRAME_VIEWFIT);\r
-       event.SetString(wxT("Fit me"));\r
-    event.SetInt(m_canvas->m_childframe->m_winnumber); \r
-    wxPostEvent(m_canvas->m_childframe->m_frame, event);\r
-\r
-       // find a fit-to-width zoom\r
-       /*int zooml, wzooml, hzooml;\r
-       wxSize clientsize = m_canvas->GetClientSize();\r
-       wzooml = (int) floor(100.0 * (double) clientsize.GetWidth() / (double) (2 * OPJ_CANVAS_BORDER + image.GetWidth()));\r
-       hzooml = (int) floor(100.0 * (double) clientsize.GetHeight() / (double) (2 * OPJ_CANVAS_BORDER + image.GetHeight()));\r
-       zooml = wxMin(100, wxMin(wzooml, hzooml));*/\r
-\r
-       // fit to width\r
-#ifndef __WXGTK__\r
-       //m_canvas->m_childframe->m_frame->Rescale(zooml, m_canvas->m_childframe);\r
-#endif // __WXGTK__\r
-\r
-       //m_canvas->m_image = m_canvas->m_image100;\r
-       //m_canvas->Refresh();\r
-       //m_canvas->SetScrollbars(20, 20, (int)(0.5 + (double) image.GetWidth() / 20.0), (int)(0.5 + (double) image.GetHeight() / 20.0));\r
-\r
-    //text.Printf(wxT("Deco thread 0x%lx finished."), GetId());\r
-    text.Printf(wxT("Deco thread %d finished"), m_canvas->m_childframe->m_winnumber);\r
-    WriteText(text);\r
-    return NULL;\r
-\r
-}\r
-\r
-/////////////////////////////////////////////////////////////////////\r
-// Parsing thread class\r
-/////////////////////////////////////////////////////////////////////\r
-\r
-OPJParseThread::OPJParseThread(OPJMarkerTree *tree, wxTreeItemId parentid)\r
-        : wxThread()\r
-{\r
-    m_count = 0;\r
-    m_tree = tree;\r
-       m_parentid = parentid;\r
-}\r
-\r
-void OPJParseThread::WriteText(const wxString& text)\r
-{\r
-    wxString msg;\r
-       \r
-       // we use a fake event and post it for inter-thread gui communication\r
-    wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, OPJFRAME_THREADLOGMSG);\r
-    event.SetInt(-1); \r
-       msg << text;\r
-       event.SetString(msg);\r
-    wxPostEvent(this->m_tree->m_childframe->m_frame, event);\r
-\r
-/*    // before doing any GUI calls we must ensure that this thread is the only\r
-    // one doing it!\r
-\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiEnter();\r
-#endif // __WXGTK\r
-\r
-    msg << text;\r
-    m_tree->WriteText(msg);\r
-\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiLeave();\r
-#endif // __WXGTK*/\r
-}\r
-\r
-void OPJParseThread::OnExit()\r
-{\r
-    wxCriticalSectionLocker locker(wxGetApp().m_parse_critsect);\r
-\r
-    wxArrayThread& threads = wxGetApp().m_parse_threads;\r
-    threads.Remove(this);\r
-\r
-    if (threads.IsEmpty()) {\r
-        // signal the main thread that there are no more threads left if it is\r
-        // waiting for us\r
-        if (wxGetApp().m_parse_waitingUntilAllDone) {\r
-            wxGetApp().m_parse_waitingUntilAllDone = false;\r
-            wxGetApp().m_parse_semAllDone.Post();\r
-        }\r
-    }\r
-}\r
-\r
-void *OPJParseThread::Entry()\r
-{\r
-\r
-       printf("Entering\n\n");\r
-\r
-    wxString text;\r
-\r
-       srand(GetId());\r
-       int m_countnum = rand() % 9;\r
-    text.Printf(wxT("Parse thread 0x%lx started (priority = %u, time = %d)."),\r
-            GetId(), GetPriority(), m_countnum);\r
-    WriteText(text);\r
-    LoadFile(m_tree->m_fname);\r
-    text.Printf(wxT("Parse thread 0x%lx finished."), GetId());\r
-    WriteText(text);\r
-\r
-\r
-    //wxLogMessage(wxT("Entering\n")); //test wxLog thread safeness\r
-\r
-       //wxBusyCursor wait;\r
-       //wxBusyInfo wait(wxT("Decoding image ..."));\r
-\r
-\r
-    /*for ( m_count = 0; m_count < m_countnum; m_count++ )\r
-    {\r
-        // check if we were asked to exit\r
-        if ( TestDestroy() )\r
-            break;\r
-\r
-        text.Printf(wxT("[%u] Parse thread 0x%lx here."), m_count, GetId());\r
-        WriteText(text);\r
-\r
-        // wxSleep() can't be called from non-GUI thread!\r
-        wxThread::Sleep(10);\r
-    }*/\r
-\r
-    // wxLogMessage(text); -- test wxLog thread safeness\r
-\r
-       printf("Exiting\n\n");\r
-\r
-    return NULL;\r
-}\r
-\r
-\r
-///////////////////////////////////////////\r
-// Parsing hread and related\r
-///////////////////////////////////////////\r
-\r
-#if USE_GENERIC_TREECTRL\r
-BEGIN_EVENT_TABLE(OPJMarkerTree, wxGenericTreeCtrl)\r
-#else\r
-BEGIN_EVENT_TABLE(OPJMarkerTree, wxTreeCtrl)\r
-#endif\r
-    /*EVT_TREE_BEGIN_DRAG(TreeTest_Ctrl, OPJMarkerTree::OnBeginDrag)\r
-    EVT_TREE_BEGIN_RDRAG(TreeTest_Ctrl, OPJMarkerTree::OnBeginRDrag)\r
-    EVT_TREE_END_DRAG(TreeTest_Ctrl, OPJMarkerTree::OnEndDrag)*/\r
-    /*EVT_TREE_BEGIN_LABEL_EDIT(TreeTest_Ctrl, OPJMarkerTree::OnBeginLabelEdit)\r
-    EVT_TREE_END_LABEL_EDIT(TreeTest_Ctrl, OPJMarkerTree::OnEndLabelEdit)*/\r
-    /*EVT_TREE_DELETE_ITEM(TreeTest_Ctrl, OPJMarkerTree::OnDeleteItem)*/\r
-#if 0       // there are so many of those that logging them causes flicker\r
-    /*EVT_TREE_GET_INFO(TreeTest_Ctrl, OPJMarkerTree::OnGetInfo)*/\r
-#endif\r
-    /*EVT_TREE_SET_INFO(TreeTest_Ctrl, OPJMarkerTree::OnSetInfo)\r
-    EVT_TREE_ITEM_EXPANDED(TreeTest_Ctrl, OPJMarkerTree::OnItemExpanded)*/\r
-    EVT_TREE_ITEM_EXPANDING(TreeTest_Ctrl, OPJMarkerTree::OnItemExpanding)\r
-    /*EVT_TREE_ITEM_COLLAPSED(TreeTest_Ctrl, OPJMarkerTree::OnItemCollapsed)\r
-    EVT_TREE_ITEM_COLLAPSING(TreeTest_Ctrl, OPJMarkerTree::OnItemCollapsing)*/\r
-\r
-    EVT_TREE_SEL_CHANGED(TreeTest_Ctrl, OPJMarkerTree::OnSelChanged)\r
-    /*EVT_TREE_SEL_CHANGING(TreeTest_Ctrl, OPJMarkerTree::OnSelChanging)*/\r
-    /*EVT_TREE_KEY_DOWN(TreeTest_Ctrl, OPJMarkerTree::OnTreeKeyDown)*/\r
-    /*EVT_TREE_ITEM_ACTIVATED(TreeTest_Ctrl, OPJMarkerTree::OnItemActivated)*/\r
-\r
-    // so many differents ways to handle right mouse button clicks...\r
-    /*EVT_CONTEXT_MENU(OPJMarkerTree::OnContextMenu)*/\r
-    // EVT_TREE_ITEM_MENU is the preferred event for creating context menus\r
-    // on a tree control, because it includes the point of the click or item,\r
-    // meaning that no additional placement calculations are required.\r
-    EVT_TREE_ITEM_MENU(TreeTest_Ctrl, OPJMarkerTree::OnItemMenu)\r
-    /*EVT_TREE_ITEM_RIGHT_CLICK(TreeTest_Ctrl, OPJMarkerTree::OnItemRClick)*/\r
-\r
-    /*EVT_RIGHT_DOWN(OPJMarkerTree::OnRMouseDown)\r
-    EVT_RIGHT_UP(OPJMarkerTree::OnRMouseUp)\r
-    EVT_RIGHT_DCLICK(OPJMarkerTree::OnRMouseDClick)*/\r
-END_EVENT_TABLE()\r
-\r
-// OPJMarkerTree implementation\r
-#if USE_GENERIC_TREECTRL\r
-IMPLEMENT_DYNAMIC_CLASS(OPJMarkerTree, wxGenericTreeCtrl)\r
-#else\r
-IMPLEMENT_DYNAMIC_CLASS(OPJMarkerTree, wxTreeCtrl)\r
-#endif\r
-\r
-OPJMarkerTree::OPJMarkerTree(wxWindow *parent, OPJChildFrame *subframe, wxFileName fname, wxString name, const wxWindowID id,\r
-           const wxPoint& pos, const wxSize& size, long style)\r
-          : wxTreeCtrl(parent, id, pos, size, style)\r
-{\r
-    m_reverseSort = false;\r
-       m_fname = fname;\r
-\r
-       m_peektextCtrl = ((OPJFrame *) (parent->GetParent()->GetParent()))->m_textCtrlbrowse;\r
-    CreateImageList();\r
-\r
-    // Add some items to the tree\r
-    //AddTestItemsToTree(5, 5);\r
-    int image = wxGetApp().ShowImages() ? OPJMarkerTree::TreeCtrlIcon_Folder : -1;\r
-    wxTreeItemId rootId = AddRoot(name,\r
-                                  image, image,\r
-                                  new OPJMarkerData(name));\r
-\r
-    OPJParseThread *pthread = CreateParseThread(0x00, subframe);\r
-    if (pthread->Run() != wxTHREAD_NO_ERROR)\r
-        wxLogMessage(wxT("Can't start parse thread!"));\r
-    else\r
-               wxLogMessage(wxT("New parse thread started."));\r
-\r
-       m_childframe = subframe;\r
-}\r
-\r
-void OPJMarkerTree::CreateImageList(int size)\r
-{\r
-    if (size == -1) {\r
-        SetImageList(NULL);\r
-        return;\r
-    }\r
-    if (size == 0)\r
-        size = m_imageSize;\r
-    else\r
-        m_imageSize = size;\r
-\r
-    // Make an image list containing small icons\r
-    wxImageList *images = new wxImageList(size, size, true);\r
-\r
-    // should correspond to TreeCtrlIcon_xxx enum\r
-    wxBusyCursor wait;\r
-    wxIcon icons[5];\r
-    icons[0] = wxIcon(icon1_xpm);\r
-    icons[1] = wxIcon(icon2_xpm);\r
-    icons[2] = wxIcon(icon3_xpm);\r
-    icons[3] = wxIcon(icon4_xpm);\r
-    icons[4] = wxIcon(icon5_xpm);\r
-\r
-    int sizeOrig = icons[0].GetWidth();\r
-    for (size_t i = 0; i < WXSIZEOF(icons); i++) {\r
-        if (size == sizeOrig) {\r
-            images->Add(icons[i]);\r
-        } else {\r
-            images->Add(wxBitmap(wxBitmap(icons[i]).ConvertToImage().Rescale(size, size)));\r
-        }\r
-    }\r
-\r
-    AssignImageList(images);\r
-}\r
-\r
-#if USE_GENERIC_TREECTRL || !defined(__WXMSW__)\r
-void OPJMarkerTree::CreateButtonsImageList(int size)\r
-{\r
-    if ( size == -1 ) {\r
-        SetButtonsImageList(NULL);\r
-        return;\r
-    }\r
-\r
-    // Make an image list containing small icons\r
-    wxImageList *images = new wxImageList(size, size, true);\r
-\r
-    // should correspond to TreeCtrlIcon_xxx enum\r
-    wxBusyCursor wait;\r
-    wxIcon icons[4];\r
-    icons[0] = wxIcon(icon3_xpm);   // closed\r
-    icons[1] = wxIcon(icon3_xpm);   // closed, selected\r
-    icons[2] = wxIcon(icon5_xpm);   // open\r
-    icons[3] = wxIcon(icon5_xpm);   // open, selected\r
-\r
-    for ( size_t i = 0; i < WXSIZEOF(icons); i++ ) {\r
-        int sizeOrig = icons[i].GetWidth();\r
-        if ( size == sizeOrig ) {\r
-            images->Add(icons[i]);\r
-        } else {\r
-            images->Add(wxBitmap(wxBitmap(icons[i]).ConvertToImage().Rescale(size, size)));\r
-        }\r
-    }\r
-\r
-    AssignButtonsImageList(images);\r
-#else\r
-void OPJMarkerTree::CreateButtonsImageList(int WXUNUSED(size))\r
-{\r
-#endif\r
-}\r
-\r
-void OPJParseThread::LoadFile(wxFileName fname)\r
-{\r
-       wxTreeItemId rootid;\r
-\r
-       // this is the root node\r
-       int image = wxGetApp().ShowImages() ? m_tree->TreeCtrlIcon_Folder : -1;\r
-\r
-       if (this->m_parentid) {\r
-               // leaf of a tree\r
-               rootid = m_parentid;\r
-               m_tree->SetItemText(rootid, wxT("Parsing..."));\r
-\r
-       } else {\r
-\r
-               // delete the existing tree hierarchy\r
-               m_tree->DeleteAllItems();\r
-\r
-               // new tree\r
-               rootid = m_tree->AddRoot(wxT("Parsing..."),\r
-                       image,\r
-                       image,\r
-                       new OPJMarkerData(fname.GetFullPath())\r
-                       );\r
-               //m_tree->SetItemFont(rootid, *wxITALIC_FONT);\r
-               m_tree->SetItemBold(rootid);\r
-       }\r
-\r
-       // open the file\r
-       wxFile m_file(fname.GetFullPath().c_str(), wxFile::read);\r
-\r
-       // parsing enabled?\r
-       if (wxGetApp().m_enableparse) {\r
-\r
-               // what is the extension?\r
-               if ((fname.GetExt() == wxT("j2k")) || (fname.GetExt() == wxT("j2c"))) {\r
-\r
-                       // parse the file\r
-                       ParseJ2KFile(&m_file, 0, m_file.Length(), rootid);\r
-\r
-               } else if ((fname.GetExt() == wxT("jp2")) || (fname.GetExt() == wxT("mj2"))) {\r
-\r
-                       // parse the file\r
-                       if (this->m_parentid) {\r
-                               //WriteText(wxT("Only a subsection of jp2"));\r
-                               OPJMarkerData *data = (OPJMarkerData *) m_tree->GetItemData(rootid);\r
-                               ParseJ2KFile(&m_file, data->m_start, data->m_length, rootid);\r
-                               m_tree->Expand(rootid);\r
-\r
-                       } else {\r
-                               // as usual\r
-                               ParseJP2File(&m_file, 0, m_file.Length(), rootid);\r
-                       }\r
-\r
-               } else {\r
-\r
-                       // unknown extension\r
-                       WriteText(wxT("Unknown file format!"));\r
-\r
-               }\r
-\r
-       }\r
-\r
-       // this is the root node\r
-       if (this->m_parentid)\r
-               m_tree->SetItemText(rootid, wxT("Codestream"));\r
-       else\r
-               //m_tree->SetItemText(rootid, wxString::Format(wxT("%s (%d B)"), fname.GetFullName(), m_file.Length()));\r
-               m_tree->SetItemText(rootid, fname.GetFullName());\r
-\r
-       // close the file\r
-       m_file.Close();\r
-\r
-       WriteText(wxT("Parsing finished!"));\r
-}\r
-\r
-/*int OPJMarkerTree::OnCompareItems(const wxTreeItemId& item1,\r
-                               const wxTreeItemId& item2)\r
-{\r
-    if ( m_reverseSort )\r
-    {\r
-        // just exchange 1st and 2nd items\r
-        return wxTreeCtrl::OnCompareItems(item2, item1);\r
-    }\r
-    else\r
-    {\r
-        return wxTreeCtrl::OnCompareItems(item1, item2);\r
-    }\r
-}*/\r
-\r
-/*void OPJMarkerTree::AddItemsRecursively(const wxTreeItemId& idParent,\r
-                                     size_t numChildren,\r
-                                     size_t depth,\r
-                                     size_t folder)\r
-{\r
-    if ( depth > 0 )\r
-    {\r
-        bool hasChildren = depth > 1;\r
-\r
-        wxString str;\r
-        for ( size_t n = 0; n < numChildren; n++ )\r
-        {\r
-            // at depth 1 elements won't have any more children\r
-            if ( hasChildren )\r
-                str.Printf(wxT("%s child %u"), wxT("Folder"), unsigned(n + 1));\r
-            else\r
-                str.Printf(wxT("%s child %u.%u"), wxT("File"), unsigned(folder), unsigned(n + 1));\r
-\r
-            // here we pass to AppendItem() normal and selected item images (we\r
-            // suppose that selected image follows the normal one in the enum)\r
-            int image, imageSel;\r
-            if ( wxGetApp().ShowImages() )\r
-            {\r
-                image = depth == 1 ? TreeCtrlIcon_File : TreeCtrlIcon_Folder;\r
-                imageSel = image + 1;\r
-            }\r
-            else\r
-            {\r
-                image = imageSel = -1;\r
-            }\r
-            wxTreeItemId id = AppendItem(idParent, str, image, imageSel,\r
-                                         new OPJMarkerData(str));\r
-\r
-            // and now we also set the expanded one (only for the folders)\r
-            if ( hasChildren && wxGetApp().ShowImages() )\r
-            {\r
-                SetItemImage(id, TreeCtrlIcon_FolderOpened,\r
-                             wxTreeItemIcon_Expanded);\r
-            }\r
-\r
-            // remember the last child for OnEnsureVisible()\r
-            if ( !hasChildren && n == numChildren - 1 )\r
-            {\r
-                m_lastItem = id;\r
-            }\r
-\r
-            AddItemsRecursively(id, numChildren, depth - 1, n + 1);\r
-        }\r
-    }\r
-    //else: done!\r
-}*/\r
-\r
-/*void OPJMarkerTree::AddTestItemsToTree(size_t numChildren,\r
-                                    size_t depth)\r
-{\r
-    int image = wxGetApp().ShowImages() ? OPJMarkerTree::TreeCtrlIcon_Folder : -1;\r
-    wxTreeItemId rootId = AddRoot(wxT("Root"),\r
-                                  image, image,\r
-                                  new OPJMarkerData(wxT("Root item")));\r
-    if ( image != -1 )\r
-    {\r
-        SetItemImage(rootId, TreeCtrlIcon_FolderOpened, wxTreeItemIcon_Expanded);\r
-    }\r
-\r
-    AddItemsRecursively(rootId, numChildren, depth, 0);\r
-\r
-    // set some colours/fonts for testing\r
-    SetItemFont(rootId, *wxITALIC_FONT);\r
-\r
-    wxTreeItemIdValue cookie;\r
-    wxTreeItemId id = GetFirstChild(rootId, cookie);\r
-    SetItemTextColour(id, *wxBLUE);\r
-\r
-    id = GetNextChild(rootId, cookie);\r
-    id = GetNextChild(rootId, cookie);\r
-    SetItemTextColour(id, *wxRED);\r
-    SetItemBackgroundColour(id, *wxLIGHT_GREY);\r
-}*/\r
-\r
-/*void OPJMarkerTree::GetItemsRecursively(const wxTreeItemId& idParent,\r
-                                     wxTreeItemIdValue cookie)\r
-{\r
-    wxTreeItemId id;\r
-\r
-    if ( !cookie )\r
-        id = GetFirstChild(idParent, cookie);\r
-    else\r
-        id = GetNextChild(idParent, cookie);\r
-\r
-    if ( !id.IsOk() )\r
-        return;\r
-\r
-    wxString text = GetItemText(id);\r
-    wxLogMessage(text);\r
-\r
-    if (ItemHasChildren(id))\r
-        GetItemsRecursively(id);\r
-\r
-    GetItemsRecursively(idParent, cookie);\r
-}*/\r
-\r
-/*void OPJMarkerTree::DoToggleIcon(const wxTreeItemId& item)\r
-{\r
-    int image = (GetItemImage(item) == TreeCtrlIcon_Folder)\r
-                    ? TreeCtrlIcon_File\r
-                    : TreeCtrlIcon_Folder;\r
-    SetItemImage(item, image, wxTreeItemIcon_Normal);\r
-\r
-    image = (GetItemImage(item) == TreeCtrlIcon_FolderSelected)\r
-                    ? TreeCtrlIcon_FileSelected\r
-                    : TreeCtrlIcon_FolderSelected;\r
-    SetItemImage(item, image, wxTreeItemIcon_Selected);\r
-}*/\r
-\r
-void OPJMarkerTree::LogEvent(const wxChar *name, const wxTreeEvent& event)\r
-{\r
-    wxTreeItemId item = event.GetItem();\r
-    wxString text;\r
-    if ( item.IsOk() )\r
-        text << wxT('"') << GetItemText(item).c_str() << wxT('"');\r
-    else\r
-        text = wxT("invalid item");\r
-    wxLogMessage(wxT("%s(%s)"), name, text.c_str());\r
-}\r
-\r
-OPJParseThread *OPJMarkerTree::CreateParseThread(wxTreeItemId parentid, OPJChildFrame *subframe)\r
-{\r
-    OPJParseThread *pthread = new OPJParseThread(this, parentid);\r
-\r
-    if (pthread->Create() != wxTHREAD_NO_ERROR)\r
-               wxLogError(wxT("Can't create parse thread!"));\r
-\r
-    wxCriticalSectionLocker enter(wxGetApp().m_parse_critsect);\r
-    wxGetApp().m_parse_threads.Add(pthread);\r
-\r
-    return pthread;\r
-}\r
-\r
-\r
-/*// avoid repetition\r
-#define TREE_EVENT_HANDLER(name)                                 \\r
-void OPJMarkerTree::name(wxTreeEvent& event)                        \\r
-{                                                                \\r
-    LogEvent(_T(#name), event);                                  \\r
-    SetLastItem(wxTreeItemId());                                 \\r
-    event.Skip();                                                \\r
-}*/\r
-\r
-/*TREE_EVENT_HANDLER(OnBeginRDrag)*/\r
-/*TREE_EVENT_HANDLER(OnDeleteItem)*/\r
-/*TREE_EVENT_HANDLER(OnGetInfo)\r
-TREE_EVENT_HANDLER(OnSetInfo)*/\r
-/*TREE_EVENT_HANDLER(OnItemExpanded)\r
-TREE_EVENT_HANDLER(OnItemExpanding)*/\r
-/*TREE_EVENT_HANDLER(OnItemCollapsed)*/\r
-/*TREE_EVENT_HANDLER(OnSelChanged)\r
-TREE_EVENT_HANDLER(OnSelChanging)*/\r
-\r
-/*#undef TREE_EVENT_HANDLER*/\r
-\r
-void OPJMarkerTree::OnItemExpanding(wxTreeEvent& event)\r
-{\r
-       wxTreeItemId item = event.GetItem();\r
-       OPJMarkerData* data = (OPJMarkerData *) GetItemData(item);\r
-       wxString text;\r
-\r
-       if (item.IsOk())\r
-               text << wxT('"') << GetItemText(item).c_str() << wxT('"');\r
-       else\r
-               text = wxT("invalid item");\r
-\r
-       if (wxStrcmp(data->GetDesc1(), wxT("INFO-CSTREAM")))\r
-               return;\r
-\r
-       wxLogMessage(wxT("Expanding... (%s -> %s, %s, %d, %d)"),\r
-               text.c_str(), data->GetDesc1(), data->GetDesc2(),\r
-               data->m_start, data->m_length);\r
-\r
-       // the codestream box is being asked for expansion\r
-       wxTreeItemIdValue cookie;\r
-       if (!GetFirstChild(item, cookie).IsOk()) {\r
-               OPJParseThread *pthread = CreateParseThread(item);\r
-               if (pthread->Run() != wxTHREAD_NO_ERROR)\r
-                       wxLogMessage(wxT("Can't start parse thread!"));\r
-               else\r
-                       wxLogMessage(wxT("New parse thread started."));\r
-       }\r
-}\r
-\r
-void OPJMarkerTree::OnSelChanged(wxTreeEvent& event)\r
-{\r
-       int bunch_linesize = 16;\r
-       int bunch_numlines = 7;\r
-\r
-       wxTreeItemId item = event.GetItem();\r
-       OPJMarkerData* data = (OPJMarkerData *) GetItemData(item);\r
-       wxString text;\r
-       int l, c, pos = 0, pre_pos;\r
-\r
-       m_peektextCtrl->Clear();\r
-\r
-       /*text << wxString::Format(wxT("Selected... (%s -> %s, %s, %d, %d)"),\r
-               text.c_str(), data->GetDesc1(), data->GetDesc2(),\r
-               data->m_start, data->m_length) << wxT("\n");*/\r
-\r
-       // open the file and browse a little\r
-       wxFile *fp = new wxFile(m_fname.GetFullPath().c_str(), wxFile::read);\r
-\r
-       // go to position claimed\r
-       fp->Seek(data->m_start, wxFromStart);\r
-\r
-       // read a bunch\r
-       int max_read = wxMin(wxFileOffset(bunch_linesize * bunch_numlines), data->m_length - data->m_start + 1);\r
-       if (data->m_desc == wxT("MARK (65380)")) {\r
-               /*wxLogMessage(data->m_desc);*/\r
-               max_read = data->m_length - data->m_start + 1;\r
-               bunch_numlines = (int) ceil((float) max_read / (float) bunch_linesize);\r
-       }\r
-       unsigned char *buffer = new unsigned char[bunch_linesize * bunch_numlines];\r
-       fp->Read(buffer, max_read);\r
-\r
-       // write the file data between start and stop\r
-       pos = 0;\r
-       for (l = 0; l < bunch_numlines; l++) {\r
-\r
-               text << wxString::Format(wxT("%010d:"), data->m_start + pos);\r
-\r
-               pre_pos = pos;\r
-\r
-               // add hex browsing text\r
-               for (c = 0; c < bunch_linesize; c++) {\r
-\r
-                       if (!(c % 8))\r
-                               text << wxT(" ");\r
-\r
-                       if (pos < max_read) {\r
-                               text << wxString::Format(wxT("%02X "), buffer[pos]);\r
-                       } else\r
-                               text << wxT("   ");\r
-                       pos++;\r
-               }\r
-\r
-               text << wxT("    ");\r
-\r
-               // add char browsing text\r
-               for (c = 0; c < bunch_linesize; c++) {\r
-\r
-                       if (pre_pos < max_read) {\r
-                               if ((buffer[pre_pos] == '\n') ||\r
-                                       (buffer[pre_pos] == '\t') ||\r
-                                       (buffer[pre_pos] == '\0') ||\r
-                                       (buffer[pre_pos] == 0x0D) ||\r
-                                       (buffer[pre_pos] == 0x0B))\r
-                                       buffer[pre_pos] = ' ';\r
-                               text << wxString::FromAscii((char) buffer[pre_pos]) << wxT(".");\r
-                       } else\r
-                               text << wxT("  ");\r
-                       pre_pos++;\r
-               }\r
-\r
-               text << wxT("\n");\r
-\r
-       }\r
-\r
-       // close the file\r
-       fp->Close();\r
-\r
-       m_peektextCtrl->WriteText(text);\r
-\r
-       delete buffer;\r
-}\r
-\r
-/*void LogKeyEvent(const wxChar *name, const wxKeyEvent& event)\r
-{\r
-    wxString key;\r
-    long keycode = event.GetKeyCode();\r
-    {\r
-        switch ( keycode )\r
-        {\r
-            case WXK_BACK: key = wxT("BACK"); break;\r
-            case WXK_TAB: key = wxT("TAB"); break;\r
-            case WXK_RETURN: key = wxT("RETURN"); break;\r
-            case WXK_ESCAPE: key = wxT("ESCAPE"); break;\r
-            case WXK_SPACE: key = wxT("SPACE"); break;\r
-            case WXK_DELETE: key = wxT("DELETE"); break;\r
-            case WXK_START: key = wxT("START"); break;\r
-            case WXK_LBUTTON: key = wxT("LBUTTON"); break;\r
-            case WXK_RBUTTON: key = wxT("RBUTTON"); break;\r
-            case WXK_CANCEL: key = wxT("CANCEL"); break;\r
-            case WXK_MBUTTON: key = wxT("MBUTTON"); break;\r
-            case WXK_CLEAR: key = wxT("CLEAR"); break;\r
-            case WXK_SHIFT: key = wxT("SHIFT"); break;\r
-            case WXK_ALT: key = wxT("ALT"); break;\r
-            case WXK_CONTROL: key = wxT("CONTROL"); break;\r
-            case WXK_MENU: key = wxT("MENU"); break;\r
-            case WXK_PAUSE: key = wxT("PAUSE"); break;\r
-            case WXK_CAPITAL: key = wxT("CAPITAL"); break;\r
-            case WXK_END: key = wxT("END"); break;\r
-            case WXK_HOME: key = wxT("HOME"); break;\r
-            case WXK_LEFT: key = wxT("LEFT"); break;\r
-            case WXK_UP: key = wxT("UP"); break;\r
-            case WXK_RIGHT: key = wxT("RIGHT"); break;\r
-            case WXK_DOWN: key = wxT("DOWN"); break;\r
-            case WXK_SELECT: key = wxT("SELECT"); break;\r
-            case WXK_PRINT: key = wxT("PRINT"); break;\r
-            case WXK_EXECUTE: key = wxT("EXECUTE"); break;\r
-            case WXK_SNAPSHOT: key = wxT("SNAPSHOT"); break;\r
-            case WXK_INSERT: key = wxT("INSERT"); break;\r
-            case WXK_HELP: key = wxT("HELP"); break;\r
-            case WXK_NUMPAD0: key = wxT("NUMPAD0"); break;\r
-            case WXK_NUMPAD1: key = wxT("NUMPAD1"); break;\r
-            case WXK_NUMPAD2: key = wxT("NUMPAD2"); break;\r
-            case WXK_NUMPAD3: key = wxT("NUMPAD3"); break;\r
-            case WXK_NUMPAD4: key = wxT("NUMPAD4"); break;\r
-            case WXK_NUMPAD5: key = wxT("NUMPAD5"); break;\r
-            case WXK_NUMPAD6: key = wxT("NUMPAD6"); break;\r
-            case WXK_NUMPAD7: key = wxT("NUMPAD7"); break;\r
-            case WXK_NUMPAD8: key = wxT("NUMPAD8"); break;\r
-            case WXK_NUMPAD9: key = wxT("NUMPAD9"); break;\r
-            case WXK_MULTIPLY: key = wxT("MULTIPLY"); break;\r
-            case WXK_ADD: key = wxT("ADD"); break;\r
-            case WXK_SEPARATOR: key = wxT("SEPARATOR"); break;\r
-            case WXK_SUBTRACT: key = wxT("SUBTRACT"); break;\r
-            case WXK_DECIMAL: key = wxT("DECIMAL"); break;\r
-            case WXK_DIVIDE: key = wxT("DIVIDE"); break;\r
-            case WXK_F1: key = wxT("F1"); break;\r
-            case WXK_F2: key = wxT("F2"); break;\r
-            case WXK_F3: key = wxT("F3"); break;\r
-            case WXK_F4: key = wxT("F4"); break;\r
-            case WXK_F5: key = wxT("F5"); break;\r
-            case WXK_F6: key = wxT("F6"); break;\r
-            case WXK_F7: key = wxT("F7"); break;\r
-            case WXK_F8: key = wxT("F8"); break;\r
-            case WXK_F9: key = wxT("F9"); break;\r
-            case WXK_F10: key = wxT("F10"); break;\r
-            case WXK_F11: key = wxT("F11"); break;\r
-            case WXK_F12: key = wxT("F12"); break;\r
-            case WXK_F13: key = wxT("F13"); break;\r
-            case WXK_F14: key = wxT("F14"); break;\r
-            case WXK_F15: key = wxT("F15"); break;\r
-            case WXK_F16: key = wxT("F16"); break;\r
-            case WXK_F17: key = wxT("F17"); break;\r
-            case WXK_F18: key = wxT("F18"); break;\r
-            case WXK_F19: key = wxT("F19"); break;\r
-            case WXK_F20: key = wxT("F20"); break;\r
-            case WXK_F21: key = wxT("F21"); break;\r
-            case WXK_F22: key = wxT("F22"); break;\r
-            case WXK_F23: key = wxT("F23"); break;\r
-            case WXK_F24: key = wxT("F24"); break;\r
-            case WXK_NUMLOCK: key = wxT("NUMLOCK"); break;\r
-            case WXK_SCROLL: key = wxT("SCROLL"); break;\r
-            case WXK_PAGEUP: key = wxT("PAGEUP"); break;\r
-            case WXK_PAGEDOWN: key = wxT("PAGEDOWN"); break;\r
-            case WXK_NUMPAD_SPACE: key = wxT("NUMPAD_SPACE"); break;\r
-            case WXK_NUMPAD_TAB: key = wxT("NUMPAD_TAB"); break;\r
-            case WXK_NUMPAD_ENTER: key = wxT("NUMPAD_ENTER"); break;\r
-            case WXK_NUMPAD_F1: key = wxT("NUMPAD_F1"); break;\r
-            case WXK_NUMPAD_F2: key = wxT("NUMPAD_F2"); break;\r
-            case WXK_NUMPAD_F3: key = wxT("NUMPAD_F3"); break;\r
-            case WXK_NUMPAD_F4: key = wxT("NUMPAD_F4"); break;\r
-            case WXK_NUMPAD_HOME: key = wxT("NUMPAD_HOME"); break;\r
-            case WXK_NUMPAD_LEFT: key = wxT("NUMPAD_LEFT"); break;\r
-            case WXK_NUMPAD_UP: key = wxT("NUMPAD_UP"); break;\r
-            case WXK_NUMPAD_RIGHT: key = wxT("NUMPAD_RIGHT"); break;\r
-            case WXK_NUMPAD_DOWN: key = wxT("NUMPAD_DOWN"); break;\r
-            case WXK_NUMPAD_PAGEUP: key = wxT("NUMPAD_PAGEUP"); break;\r
-            case WXK_NUMPAD_PAGEDOWN: key = wxT("NUMPAD_PAGEDOWN"); break;\r
-            case WXK_NUMPAD_END: key = wxT("NUMPAD_END"); break;\r
-            case WXK_NUMPAD_BEGIN: key = wxT("NUMPAD_BEGIN"); break;\r
-            case WXK_NUMPAD_INSERT: key = wxT("NUMPAD_INSERT"); break;\r
-            case WXK_NUMPAD_DELETE: key = wxT("NUMPAD_DELETE"); break;\r
-            case WXK_NUMPAD_EQUAL: key = wxT("NUMPAD_EQUAL"); break;\r
-            case WXK_NUMPAD_MULTIPLY: key = wxT("NUMPAD_MULTIPLY"); break;\r
-            case WXK_NUMPAD_ADD: key = wxT("NUMPAD_ADD"); break;\r
-            case WXK_NUMPAD_SEPARATOR: key = wxT("NUMPAD_SEPARATOR"); break;\r
-            case WXK_NUMPAD_SUBTRACT: key = wxT("NUMPAD_SUBTRACT"); break;\r
-            case WXK_NUMPAD_DECIMAL: key = wxT("NUMPAD_DECIMAL"); break;\r
-\r
-            default:\r
-            {\r
-               if ( keycode < 128 && wxIsprint((int)keycode) )\r
-                   key.Printf(wxT("'%c'"), (char)keycode);\r
-               else if ( keycode > 0 && keycode < 27 )\r
-                   key.Printf(_("Ctrl-%c"), wxT('A') + keycode - 1);\r
-               else\r
-                   key.Printf(wxT("unknown (%ld)"), keycode);\r
-            }\r
-        }\r
-    }\r
-\r
-    wxLogMessage(wxT("%s event: %s (flags = %c%c%c%c)"),\r
-                  name,\r
-                  key.c_str(),\r
-                  event.ControlDown() ? wxT('C') : wxT('-'),\r
-                  event.AltDown() ? wxT('A') : wxT('-'),\r
-                  event.ShiftDown() ? wxT('S') : wxT('-'),\r
-                  event.MetaDown() ? wxT('M') : wxT('-'));\r
-}\r
-\r
-void OPJMarkerTree::OnTreeKeyDown(wxTreeEvent& event)\r
-{\r
-    LogKeyEvent(wxT("Tree key down "), event.GetKeyEvent());\r
-\r
-    event.Skip();\r
-}*/\r
-\r
-/*void OPJMarkerTree::OnBeginDrag(wxTreeEvent& event)\r
-{\r
-    // need to explicitly allow drag\r
-    if ( event.GetItem() != GetRootItem() )\r
-    {\r
-        m_draggedItem = event.GetItem();\r
-\r
-        wxLogMessage(wxT("OnBeginDrag: started dragging %s"),\r
-                     GetItemText(m_draggedItem).c_str());\r
-\r
-        event.Allow();\r
-    }\r
-    else\r
-    {\r
-        wxLogMessage(wxT("OnBeginDrag: this item can't be dragged."));\r
-    }\r
-}\r
-\r
-void OPJMarkerTree::OnEndDrag(wxTreeEvent& event)\r
-{\r
-    wxTreeItemId itemSrc = m_draggedItem,\r
-                 itemDst = event.GetItem();\r
-    m_draggedItem = (wxTreeItemId)0l;\r
-\r
-    // where to copy the item?\r
-    if ( itemDst.IsOk() && !ItemHasChildren(itemDst) )\r
-    {\r
-        // copy to the parent then\r
-        itemDst = GetItemParent(itemDst);\r
-    }\r
-\r
-    if ( !itemDst.IsOk() )\r
-    {\r
-        wxLogMessage(wxT("OnEndDrag: can't drop here."));\r
-\r
-        return;\r
-    }\r
-\r
-    wxString text = GetItemText(itemSrc);\r
-    wxLogMessage(wxT("OnEndDrag: '%s' copied to '%s'."),\r
-                 text.c_str(), GetItemText(itemDst).c_str());\r
-\r
-    // just do append here - we could also insert it just before/after the item\r
-    // on which it was dropped, but this requires slightly more work... we also\r
-    // completely ignore the client data and icon of the old item but could\r
-    // copy them as well.\r
-    //\r
-    // Finally, we only copy one item here but we might copy the entire tree if\r
-    // we were dragging a folder.\r
-    int image = wxGetApp().ShowImages() ? TreeCtrlIcon_File : -1;\r
-    AppendItem(itemDst, text, image);\r
-}*/\r
-\r
-/*void OPJMarkerTree::OnBeginLabelEdit(wxTreeEvent& event)\r
-{\r
-    wxLogMessage(wxT("OnBeginLabelEdit"));\r
-\r
-    // for testing, prevent this item's label editing\r
-    wxTreeItemId itemId = event.GetItem();\r
-    if ( IsTestItem(itemId) )\r
-    {\r
-        wxMessageBox(wxT("You can't edit this item."));\r
-\r
-        event.Veto();\r
-    }\r
-    else if ( itemId == GetRootItem() )\r
-    {\r
-        // test that it is possible to change the text of the item being edited\r
-        SetItemText(itemId, _T("Editing root item"));\r
-    }\r
-}\r
-\r
-void OPJMarkerTree::OnEndLabelEdit(wxTreeEvent& event)\r
-{\r
-    wxLogMessage(wxT("OnEndLabelEdit"));\r
-\r
-    // don't allow anything except letters in the labels\r
-    if ( !event.GetLabel().IsWord() )\r
-    {\r
-        wxMessageBox(wxT("The new label should be a single word."));\r
-\r
-        event.Veto();\r
-    }\r
-}*/\r
-\r
-/*void OPJMarkerTree::OnItemCollapsing(wxTreeEvent& event)\r
-{\r
-    wxLogMessage(wxT("OnItemCollapsing"));\r
-\r
-    // for testing, prevent the user from collapsing the first child folder\r
-    wxTreeItemId itemId = event.GetItem();\r
-    if ( IsTestItem(itemId) )\r
-    {\r
-        wxMessageBox(wxT("You can't collapse this item."));\r
-\r
-        event.Veto();\r
-    }\r
-}*/\r
-\r
-/*void OPJMarkerTree::OnItemActivated(wxTreeEvent& event)\r
-{\r
-    // show some info about this item\r
-    wxTreeItemId itemId = event.GetItem();\r
-    OPJMarkerData *item = (OPJMarkerData *)GetItemData(itemId);\r
-\r
-    if ( item != NULL )\r
-    {\r
-        item->ShowInfo(this);\r
-    }\r
-\r
-    wxLogMessage(wxT("OnItemActivated"));\r
-}*/\r
-\r
-void OPJMarkerTree::OnItemMenu(wxTreeEvent& event)\r
-{\r
-    /*wxTreeItemId itemId = event.GetItem();\r
-    OPJMarkerData *item = itemId.IsOk() ? (OPJMarkerData *)GetItemData(itemId)\r
-                                         : NULL;\r
-\r
-    wxLogMessage(wxT("OnItemMenu for item \"%s\""), item ? item->GetDesc()\r
-                                                         : _T(""));*/\r
-\r
-       //wxLogMessage(wxT("EEEEEEEEEE"));\r
-\r
-    //event.Skip();\r
-}\r
-\r
-/*void OPJMarkerTree::OnContextMenu(wxContextMenuEvent& event)\r
-{\r
-    wxPoint pt = event.GetPosition();\r
-    wxTreeItemId item;\r
-    wxLogMessage(wxT("OnContextMenu at screen coords (%i, %i)"), pt.x, pt.y);\r
-\r
-    // check if event was generated by keyboard (MSW-specific?)\r
-    if ( pt.x == -1 && pt.y == -1 ) //(this is how MSW indicates it)\r
-    {\r
-        if ( !HasFlag(wxTR_MULTIPLE) )\r
-            item = GetSelection();\r
-\r
-        // attempt to guess where to show the menu\r
-        if ( item.IsOk() )\r
-        {\r
-            // if an item was clicked, show menu to the right of it\r
-            wxRect rect;\r
-            GetBoundingRect(item, rect, true );// only the label\r
-            pt = wxPoint(rect.GetRight(), rect.GetTop());\r
-        }\r
-        else\r
-        {\r
-            pt = wxPoint(0, 0);\r
-        }\r
-    }\r
-    else // event was generated by mouse, use supplied coords\r
-    {\r
-        pt = ScreenToClient(pt);\r
-        item = HitTest(pt);\r
-    }\r
-\r
-    ShowMenu(item, pt);\r
-}*/\r
-\r
-/*void OPJMarkerTree::ShowMenu(wxTreeItemId id, const wxPoint& pt)\r
-{\r
-    wxString title;\r
-    if ( id.IsOk() )\r
-    {\r
-        title << wxT("Menu for ") << GetItemText(id);\r
-    }\r
-    else\r
-    {\r
-        title = wxT("Menu for no particular item");\r
-    }\r
-\r
-#if wxUSE_MENUS\r
-    wxMenu menu(title);\r
-    menu.Append(TreeTest_About, wxT("&About..."));\r
-    menu.AppendSeparator();\r
-    menu.Append(TreeTest_Highlight, wxT("&Highlight item"));\r
-    menu.Append(TreeTest_Dump, wxT("&Dump"));\r
-\r
-    PopupMenu(&menu, pt);\r
-#endif // wxUSE_MENUS\r
-}*/\r
-\r
-/*void OPJMarkerTree::OnItemRClick(wxTreeEvent& event)\r
-{\r
-    wxTreeItemId itemId = event.GetItem();\r
-    OPJMarkerData *item = itemId.IsOk() ? (OPJMarkerData *)GetItemData(itemId)\r
-                                         : NULL;\r
-\r
-    wxLogMessage(wxT("Item \"%s\" right clicked"), item ? item->GetDesc()\r
-                                                        : _T(""));\r
-\r
-    event.Skip();\r
-}*/\r
-\r
-/*\r
-void OPJMarkerTree::OnRMouseDown(wxMouseEvent& event)\r
-{\r
-    wxLogMessage(wxT("Right mouse button down"));\r
-\r
-    event.Skip();\r
-}\r
-\r
-void OPJMarkerTree::OnRMouseUp(wxMouseEvent& event)\r
-{\r
-    wxLogMessage(wxT("Right mouse button up"));\r
-\r
-    event.Skip();\r
-}\r
-\r
-void OPJMarkerTree::OnRMouseDClick(wxMouseEvent& event)\r
-{\r
-    wxTreeItemId id = HitTest(event.GetPosition());\r
-    if ( !id )\r
-        wxLogMessage(wxT("No item under mouse"));\r
-    else\r
-    {\r
-        OPJMarkerData *item = (OPJMarkerData *)GetItemData(id);\r
-        if ( item )\r
-            wxLogMessage(wxT("Item '%s' under mouse"), item->GetDesc());\r
-    }\r
-\r
-    event.Skip();\r
-}\r
-*/\r
-\r
-static inline const wxChar *Bool2String(bool b)\r
-{\r
-    return b ? wxT("") : wxT("not ");\r
-}\r
-\r
-void OPJMarkerData::ShowInfo(wxTreeCtrl *tree)\r
-{\r
-    wxLogMessage(wxT("Item '%s': %sselected, %sexpanded, %sbold,\n")\r
-                 wxT("%u children (%u immediately under this item)."),\r
-                 m_desc.c_str(),\r
-                 Bool2String(tree->IsSelected(GetId())),\r
-                 Bool2String(tree->IsExpanded(GetId())),\r
-                 Bool2String(tree->IsBold(GetId())),\r
-                 unsigned(tree->GetChildrenCount(GetId())),\r
-                 unsigned(tree->GetChildrenCount(GetId(), false)));\r
-}\r
-\r
-\r
diff --git a/OPJViewer/source/OPJViewer.cpp b/OPJViewer/source/OPJViewer.cpp
deleted file mode 100644 (file)
index 8f2c86e..0000000
+++ /dev/null
@@ -1,1664 +0,0 @@
-/*\r
- * Copyright (c) 2007, Digital Signal Processing Laboratory, Universita' degli studi di Perugia (UPG), Italy\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        sashtest.cpp\r
-// Purpose:     Layout/sash sample\r
-// Author:      Julian Smart\r
-// Modified by:\r
-// Created:     04/01/98\r
-// RCS-ID:      $Id: sashtest.cpp,v 1.18 2005/08/23 15:54:35 ABX Exp $\r
-// Copyright:   (c) Julian Smart\r
-// Licence:     wxWindows license\r
-/////////////////////////////////////////////////////////////////////////////\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        treetest.cpp\r
-// Purpose:     wxTreeCtrl sample\r
-// Author:      Julian Smart\r
-// Modified by:\r
-// Created:     04/01/98\r
-// RCS-ID:      $Id: treetest.cpp,v 1.110 2006/11/04 11:26:51 VZ Exp $\r
-// Copyright:   (c) Julian Smart\r
-// Licence:     wxWindows license\r
-/////////////////////////////////////////////////////////////////////////////\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        dialogs.cpp\r
-// Purpose:     Common dialogs demo\r
-// Author:      Julian Smart\r
-// Modified by: ABX (2004) - adjustements for conditional building + new menu\r
-// Created:     04/01/98\r
-// RCS-ID:      $Id: dialogs.cpp,v 1.163 2006/11/04 10:57:24 VZ Exp $\r
-// Copyright:   (c) Julian Smart\r
-// Licence:     wxWindows license\r
-/////////////////////////////////////////////////////////////////////////////\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        thread.cpp\r
-// Purpose:     wxWidgets thread sample\r
-// Author:      Guilhem Lavaux, Vadim Zeitlin\r
-// Modified by:\r
-// Created:     06/16/98\r
-// RCS-ID:      $Id: thread.cpp,v 1.26 2006/10/02 05:36:28 PC Exp $\r
-// Copyright:   (c) 1998-2002 wxWidgets team\r
-// Licence:     wxWindows license\r
-/////////////////////////////////////////////////////////////////////////////\r
-///////////////////////////////////////////////////////////////////////////////\r
-// Name:        samples/image/image.cpp\r
-// Purpose:     sample showing operations with wxImage\r
-// Author:      Robert Roebling\r
-// Modified by:\r
-// Created:     1998\r
-// RCS-ID:      $Id: image.cpp,v 1.120 2006/12/06 17:13:11 VZ Exp $\r
-// Copyright:   (c) 1998-2005 Robert Roebling\r
-// License:     wxWindows licence\r
-///////////////////////////////////////////////////////////////////////////////\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        samples/console/console.cpp\r
-// Purpose:     A sample console (as opposed to GUI) program using wxWidgets\r
-// Author:      Vadim Zeitlin\r
-// Modified by:\r
-// Created:     04.10.99\r
-// RCS-ID:      $Id: console.cpp,v 1.206 2006/11/12 19:55:19 VZ Exp $\r
-// Copyright:   (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>\r
-// Licence:     wxWindows license\r
-/////////////////////////////////////////////////////////////////////////////\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        samples/notebook/notebook.cpp\r
-// Purpose:     a sample demonstrating notebook usage\r
-// Author:      Julian Smart\r
-// Modified by: Dimitri Schoolwerth\r
-// Created:     26/10/98\r
-// RCS-ID:      $Id: notebook.cpp,v 1.49 2006/11/04 18:24:07 RR Exp $\r
-// Copyright:   (c) 1998-2002 wxWidgets team\r
-// License:     wxWindows license\r
-/////////////////////////////////////////////////////////////////////////////\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        dialogs.cpp\r
-// Purpose:     Common dialogs demo\r
-// Author:      Julian Smart\r
-// Modified by: ABX (2004) - adjustements for conditional building + new menu\r
-// Created:     04/01/98\r
-// RCS-ID:      $Id: dialogs.cpp,v 1.163 2006/11/04 10:57:24 VZ Exp $\r
-// Copyright:   (c) Julian Smart\r
-// Licence:     wxWindows license\r
-/////////////////////////////////////////////////////////////////////////////\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        dnd.cpp\r
-// Purpose:     Drag and drop sample\r
-// Author:      Vadim Zeitlin\r
-// Modified by:\r
-// Created:     04/01/98\r
-// RCS-ID:      $Id: dnd.cpp,v 1.107 2006/10/30 20:23:41 VZ Exp $\r
-// Copyright:\r
-// Licence:     wxWindows licence\r
-/////////////////////////////////////////////////////////////////////////////\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        test.cpp\r
-// Purpose:     wxHtml testing example\r
-/////////////////////////////////////////////////////////////////////////////\r
-\r
-\r
-#include "OPJViewer.h"\r
-\r
-IMPLEMENT_APP(OPJViewerApp)\r
-\r
-// For drawing lines in a canvas\r
-long xpos = -1;\r
-long ypos = -1;\r
-\r
-int winNumber = 1;\r
-\r
-// Initialise this in OnInit, not statically\r
-bool OPJViewerApp::OnInit(void)\r
-{\r
-       int n;\r
-#if wxUSE_UNICODE\r
-\r
-    wxChar **wxArgv = new wxChar *[argc + 1];\r
-\r
-    for (n = 0; n < argc; n++ ) {\r
-        wxMB2WXbuf warg = wxConvertMB2WX((char *) argv[n]);\r
-        wxArgv[n] = wxStrdup(warg);\r
-    }\r
-\r
-    wxArgv[n] = NULL;\r
-\r
-#else // !wxUSE_UNICODE\r
-\r
-    #define wxArgv argv\r
-\r
-#endif // wxUSE_UNICODE/!wxUSE_UNICODE\r
-\r
-#if wxUSE_CMDLINE_PARSER\r
-\r
-    static const wxCmdLineEntryDesc cmdLineDesc[] =\r
-    {\r
-        { wxCMD_LINE_SWITCH, _T("h"), _T("help"), _T("show this help message"),\r
-            wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },\r
-\r
-        { wxCMD_LINE_PARAM,  NULL, NULL, _T("input file"),\r
-            wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE },\r
-\r
-        { wxCMD_LINE_NONE }\r
-    };\r
-\r
-    wxCmdLineParser parser(cmdLineDesc, argc, wxArgv);\r
-\r
-    switch (parser.Parse()) {\r
-    case -1:\r
-        wxLogMessage(wxT("Help was given, terminating."));\r
-        break;\r
-\r
-    case 0:\r
-        ShowCmdLine(parser);\r
-        break;\r
-\r
-    default:\r
-        wxLogMessage(wxT("Syntax error detected."));\r
-        break;\r
-    }\r
-\r
-#endif // wxUSE_CMDLINE_PARSER\r
-\r
-    //wxInitAllImageHandlers();\r
-#if wxUSE_LIBJPEG\r
-  wxImage::AddHandler( new wxJPEGHandler );\r
-#endif\r
-#if wxUSE_LIBOPENJPEG\r
-  wxImage::AddHandler( new wxJPEG2000Handler );\r
-#endif\r
-#if USE_MXF\r
-  wxImage::AddHandler( new wxMXFHandler );\r
-#endif // USE_MXF\r
-#if OPJ_MANYFORMATS\r
-  wxImage::AddHandler( new wxBMPHandler );\r
-  wxImage::AddHandler( new wxPNGHandler );\r
-  wxImage::AddHandler( new wxGIFHandler );\r
-  wxImage::AddHandler( new wxPNMHandler );\r
-  wxImage::AddHandler( new wxTIFFHandler );\r
-#endif\r
-    // we use a XPM image in our HTML page\r
-    wxImage::AddHandler(new wxXPMHandler);\r
-\r
-       // memory file system\r
-    wxFileSystem::AddHandler(new wxMemoryFSHandler);\r
-\r
-#ifdef OPJ_INICONFIG\r
-       //load decoding engine parameters\r
-       OPJconfig = new wxConfig(OPJ_APPLICATION, OPJ_APPLICATION_VENDOR);\r
-\r
-       OPJconfig->Read(wxT("decode/enabledeco"), &m_enabledeco, (bool) true);\r
-       OPJconfig->Read(wxT("decode/enableparse"), &m_enableparse, (bool) true);\r
-       OPJconfig->Read(wxT("decode/resizemethod"), &m_resizemethod, (long) 0);\r
-       OPJconfig->Read(wxT("decode/xxxreducefactor"), &m_reducefactor, (long) 0);\r
-       OPJconfig->Read(wxT("decode/xxxqualitylayers"), &m_qualitylayers, (long) 0);\r
-       OPJconfig->Read(wxT("decode/xxxcomponents"), &m_components, (long) 0);\r
-       OPJconfig->Read(wxT("decode/xxxframenum"), &m_framenum, (long) 0);\r
-#ifdef USE_JPWL\r
-       OPJconfig->Read(wxT("decode/enablejpwl"), &m_enablejpwl, (bool) true);\r
-       OPJconfig->Read(wxT("decode/expcomps"), &m_expcomps, (long) JPWL_EXPECTED_COMPONENTS);\r
-       OPJconfig->Read(wxT("decode/maxtiles"), &m_maxtiles, (long) JPWL_MAXIMUM_TILES);\r
-#endif // USE_JPWL\r
-\r
-       OPJconfig->Write(wxT("teststring"), wxT("This is a test value"));\r
-       OPJconfig->Write(wxT("testbool"), (bool) true);\r
-       OPJconfig->Write(wxT("testlong"), (long) 245);\r
-\r
-       OPJconfig->Read(wxT("showtoolbar"), &m_showtoolbar, (bool) true);\r
-       OPJconfig->Read(wxT("showbrowser"), &m_showbrowser, (bool) true);\r
-       OPJconfig->Read(wxT("showpeeker"), &m_showpeeker, (bool) true);\r
-       OPJconfig->Read(wxT("browserwidth"), &m_browserwidth, (long) OPJ_BROWSER_WIDTH);\r
-       OPJconfig->Read(wxT("peekerheight"), &m_peekerheight, (long) OPJ_PEEKER_HEIGHT);\r
-       OPJconfig->Read(wxT("framewidth"), &m_framewidth, (long) OPJ_FRAME_WIDTH);\r
-       OPJconfig->Read(wxT("frameheight"), &m_frameheight, (long) OPJ_FRAME_HEIGHT);\r
-\r
-       // load encoding engine parameters\r
-       OPJconfig->Read(wxT("encode/subsampling"), &m_subsampling, (wxString) wxT("1,1"));\r
-       OPJconfig->Read(wxT("encode/origin"), &m_origin, (wxString) wxT("0,0"));\r
-       OPJconfig->Read(wxT("encode/rates"), &m_rates, (wxString) wxT("20,10,5"));\r
-       OPJconfig->Read(wxT("encode/quality"), &m_quality, (wxString) wxT("30,35,40"));\r
-       OPJconfig->Read(wxT("encode/enablequality"), &m_enablequality, (bool) false);\r
-       OPJconfig->Read(wxT("encode/multicomp"), &m_multicomp, (bool) false);   \r
-       OPJconfig->Read(wxT("encode/irreversible"), &m_irreversible, (bool) false);     \r
-       OPJconfig->Read(wxT("encode/resolutions"), &m_resolutions, (int) 6);    \r
-       OPJconfig->Read(wxT("encode/progression"), &m_progression, (int) 0);    \r
-       OPJconfig->Read(wxT("encode/cbsize"), &m_cbsize, (wxString) wxT("32,32"));\r
-       OPJconfig->Read(wxT("encode/prsize"), &m_prsize, (wxString) wxT("[128,128],[128,128]"));\r
-       OPJconfig->Read(wxT("encode/tsize"), &m_tsize, (wxString) wxT(""));\r
-       OPJconfig->Read(wxT("encode/torigin"), &m_torigin, (wxString) wxT("0,0"));\r
-       OPJconfig->Read(wxT("encode/enablesop"), &m_enablesop, (bool) false);   \r
-       OPJconfig->Read(wxT("encode/enableeph"), &m_enableeph, (bool) false);   \r
-       OPJconfig->Read(wxT("encode/enablebypass"), &m_enablebypass, (bool) false);     \r
-       OPJconfig->Read(wxT("encode/enablereset"), &m_enablereset, (bool) false);       \r
-       OPJconfig->Read(wxT("encode/enablerestart"), &m_enablerestart, (bool) false);   \r
-       OPJconfig->Read(wxT("encode/enablevsc"), &m_enablevsc, (bool) false);   \r
-       OPJconfig->Read(wxT("encode/enableerterm"), &m_enableerterm, (bool) false);     \r
-       OPJconfig->Read(wxT("encode/enablesegmark"), &m_enablesegmark, (bool) false);   \r
-       OPJconfig->Read(wxT("encode/enablecomm"), &m_enablecomm, (bool) true);  \r
-       OPJconfig->Read(wxT("encode/enablepoc"), &m_enablepoc, (bool) false);   \r
-       OPJconfig->Read(wxT("encode/comment"), &m_comment, (wxString) wxT(""));\r
-       OPJconfig->Read(wxT("encode/poc"), &m_poc, (wxString) wxT("T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL"));\r
-       OPJconfig->Read(wxT("encode/enableidx"), &m_enableidx, (bool) false);   \r
-       OPJconfig->Read(wxT("encode/index"), &m_index, (wxString) wxT("index.txt"));\r
-#ifdef USE_JPWL\r
-       OPJconfig->Read(wxT("encode/enablejpwl"), &m_enablejpwle, (bool) true);\r
-       for (n = 0; n < MYJPWL_MAX_NO_TILESPECS; n++) {\r
-               OPJconfig->Read(wxT("encode/jpwl/hprotsel") + wxString::Format(wxT("%02d"), n), &m_hprotsel[n], 0);\r
-               OPJconfig->Read(wxT("encode/jpwl/htileval") + wxString::Format(wxT("%02d"), n), &m_htileval[n], 0);\r
-               OPJconfig->Read(wxT("encode/jpwl/pprotsel") + wxString::Format(wxT("%02d"), n), &m_pprotsel[n], 0);\r
-               OPJconfig->Read(wxT("encode/jpwl/ptileval") + wxString::Format(wxT("%02d"), n), &m_ptileval[n], 0);\r
-               OPJconfig->Read(wxT("encode/jpwl/ppackval") + wxString::Format(wxT("%02d"), n), &m_ppackval[n], 0);\r
-               OPJconfig->Read(wxT("encode/jpwl/sensisel") + wxString::Format(wxT("%02d"), n), &m_sensisel[n], 0);\r
-               OPJconfig->Read(wxT("encode/jpwl/stileval") + wxString::Format(wxT("%02d"), n), &m_stileval[n], 0);\r
-       }\r
-#endif // USE_JPWL\r
-\r
-#else\r
-       // set decoding engine parameters\r
-       m_enabledeco = true;\r
-       m_enableparse = true;\r
-       m_resizemethod = 0;\r
-       m_reducefactor = 0;\r
-       m_qualitylayers = 0;\r
-       m_components = 0;\r
-       m_framenum = 0;\r
-#ifdef USE_JPWL\r
-       m_enablejpwl = true;\r
-       m_expcomps = JPWL_EXPECTED_COMPONENTS;\r
-       m_maxtiles = JPWL_MAXIMUM_TILES;\r
-#endif // USE_JPWL\r
-       m_showtoolbar = true;\r
-       m_showbrowser = true;\r
-       m_showpeeker = true;\r
-       m_browserwidth = OPJ_BROWSER_WIDTH;\r
-       m_peekerheight = OPJ_PEEKER_HEIGHT;\r
-       m_framewidth = OPJ_FRAME_WIDTH;\r
-       m_frameheight = OPJ_FRAME_HEIGHT;\r
-\r
-       // set encoding engine parameters\r
-       m_subsampling = wxT("1,1");\r
-       m_origin = wxT("0,0");\r
-       m_rates = wxT("20,10,5");\r
-       m_quality = wxT("30,35,40");\r
-       m_enablequality = false;\r
-       m_multicomp = false;\r
-       m_irreversible = false;\r
-       m_resolutions = 6;\r
-       m_progression = 0;\r
-       m_cbsize= wxT("32,32");\r
-       m_prsize= wxT("[128,128],[128,128]");\r
-       m_tsize = wxT("");\r
-       m_torigin = wxT("0,0");\r
-       m_enablesop = false;\r
-       m_enableeph = false;\r
-       m_enablebypass = false;\r
-       m_enablereset = false;\r
-       m_enablerestart = false;\r
-       m_enablevsc = false;\r
-       m_enableerterm = false;\r
-       m_enablesegmark = false;\r
-       m_enableidx = false;\r
-       m_index = wxT("index.txt");\r
-       m_enablecomm = true;\r
-       m_comment = wxT("");\r
-       m_enablepoc = false;\r
-       m_poc = wxT("T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL");\r
-#ifdef USE_JPWL\r
-       m_enablejpwle = true;\r
-       for (n = 0; n < MYJPWL_MAX_NO_TILESPECS; n++) {\r
-               m_hprotsel[n] = 0;\r
-               m_htileval[n] = 0;\r
-               m_pprotsel[n] = 0;\r
-               m_ptileval[n] = 0;\r
-               m_sensisel[n] = 0;\r
-               m_stileval[n] = 0;\r
-       }\r
-#endif // USE_JPWL\r
-\r
-#endif // OPJ_INICONFIG\r
-\r
-       if (m_comment == wxT("")) {\r
-#if defined __WXMSW__\r
-               m_comment = wxT("Created by OPJViewer Win32 - OpenJPEG  version ");\r
-#elif defined __WXGTK__\r
-               m_comment = wxT("Created by OPJViewer Lin32 - OpenJPEG version ");\r
-#else\r
-               m_comment = wxT("Created by OPJViewer - OpenJPEG version ");\r
-#endif\r
-\r
-#ifdef USE_JPWL\r
-               m_comment += wxString::Format(wxT("%s with JPWL"), (char *) opj_version());\r
-#else\r
-               m_comment += wxString::Format(wxT("%s"), (char *) opj_version());\r
-#endif\r
-       }\r
-\r
-       // Create the main frame window\r
-  OPJFrame *frame = new OPJFrame(NULL, wxID_ANY, OPJ_APPLICATION_TITLEBAR,\r
-                                         wxDefaultPosition, wxSize(wxGetApp().m_framewidth, wxGetApp().m_frameheight),\r
-                      wxDEFAULT_FRAME_STYLE | wxNO_FULL_REPAINT_ON_RESIZE |\r
-                      wxHSCROLL | wxVSCROLL);\r
-\r
-  // Give it an icon (this is ignored in MDI mode: uses resources)\r
-#ifdef __WXMSW__\r
-  frame->SetIcon(wxIcon(wxT("OPJViewer16")));\r
-#endif\r
-\r
-  frame->Show(true);\r
-\r
-  SetTopWindow(frame);\r
-\r
-       // if there are files on the command line, open them\r
-       if (!(m_filelist.IsEmpty())) {\r
-               //wxLogMessage(wxT("Habemus files!!!"));\r
-               wxArrayString paths, filenames;\r
-               for (unsigned int f = 0; f < wxGetApp().m_filelist.GetCount(); f++) {\r
-                       paths.Add(wxFileName(wxGetApp().m_filelist[f]).GetFullPath());\r
-                       filenames.Add(wxFileName(wxGetApp().m_filelist[f]).GetFullName());\r
-               }\r
-               //wxLogMessage(paths[0]);\r
-               frame->OpenFiles(paths, filenames);\r
-       }\r
-\r
-  return true;\r
-}\r
-\r
-int OPJViewerApp::OnExit()\r
-{\r
-       int n;\r
-\r
-#ifdef OPJ_INICONFIG\r
-       OPJconfig->Write(wxT("decode/enabledeco"), m_enabledeco);\r
-       OPJconfig->Write(wxT("decode/enableparse"), m_enableparse);\r
-       OPJconfig->Write(wxT("decode/resizemethod"), m_resizemethod);\r
-       OPJconfig->Write(wxT("decode/reducefactor"), m_reducefactor);\r
-       OPJconfig->Write(wxT("decode/qualitylayers"), m_qualitylayers);\r
-       OPJconfig->Write(wxT("decode/components"), m_components);\r
-       OPJconfig->Write(wxT("decode/framenum"), m_framenum);\r
-#ifdef USE_JPWL\r
-       OPJconfig->Write(wxT("decode/enablejpwl"), m_enablejpwl);\r
-       OPJconfig->Write(wxT("decode/expcomps"), m_expcomps);\r
-       OPJconfig->Write(wxT("decode/maxtiles"), m_maxtiles);\r
-#endif // USE_JPWL\r
-       OPJconfig->Write(wxT("showtoolbar"), m_showtoolbar);\r
-       OPJconfig->Write(wxT("showbrowser"), m_showbrowser);\r
-       OPJconfig->Write(wxT("showpeeker"), m_showpeeker);\r
-       OPJconfig->Write(wxT("browserwidth"), m_browserwidth);\r
-       OPJconfig->Write(wxT("peekerheight"), m_peekerheight);\r
-       OPJconfig->Write(wxT("framewidth"), m_framewidth);\r
-       OPJconfig->Write(wxT("frameheight"), m_frameheight);\r
-\r
-       OPJconfig->Write(wxT("encode/subsampling"), m_subsampling);\r
-       OPJconfig->Write(wxT("encode/origin"), m_origin);\r
-       OPJconfig->Write(wxT("encode/rates"), m_rates);\r
-       OPJconfig->Write(wxT("encode/quality"), m_quality);\r
-       OPJconfig->Write(wxT("encode/enablequality"), m_enablequality);\r
-       OPJconfig->Write(wxT("encode/multicomp"), m_multicomp);\r
-       OPJconfig->Write(wxT("encode/irreversible"), m_irreversible);\r
-       OPJconfig->Write(wxT("encode/resolutions"), m_resolutions);\r
-       OPJconfig->Write(wxT("encode/progression"), m_progression);\r
-       OPJconfig->Write(wxT("encode/cbsize"), m_cbsize);\r
-       OPJconfig->Write(wxT("encode/prsize"), m_prsize);\r
-       OPJconfig->Write(wxT("encode/tiles"), m_tsize);\r
-       OPJconfig->Write(wxT("encode/torigin"), m_torigin);\r
-       OPJconfig->Write(wxT("encode/enablesop"), m_enablesop);\r
-       OPJconfig->Write(wxT("encode/enableeph"), m_enableeph);\r
-       OPJconfig->Write(wxT("encode/enablebypass"), m_enablebypass);\r
-       OPJconfig->Write(wxT("encode/enablereset"), m_enablereset);\r
-       OPJconfig->Write(wxT("encode/enablerestart"), m_enablerestart);\r
-       OPJconfig->Write(wxT("encode/enablevsc"), m_enablevsc);\r
-       OPJconfig->Write(wxT("encode/enableerterm"), m_enableerterm);\r
-       OPJconfig->Write(wxT("encode/enablesegmark"), m_enablesegmark);\r
-       OPJconfig->Write(wxT("encode/enableidx"), m_enableidx);\r
-       OPJconfig->Write(wxT("encode/index"), m_index);\r
-       OPJconfig->Write(wxT("encode/enablecomm"), m_enablecomm);\r
-       OPJconfig->Write(wxT("encode/comment"), m_comment);\r
-       OPJconfig->Write(wxT("encode/enablepoc"), m_enablepoc);\r
-       OPJconfig->Write(wxT("encode/poc"), m_poc);\r
-#ifdef USE_JPWL\r
-       OPJconfig->Write(wxT("encode/enablejpwl"), m_enablejpwle);\r
-       for (n = 0; n < MYJPWL_MAX_NO_TILESPECS; n++) {\r
-               OPJconfig->Write(wxT("encode/jpwl/hprotsel") + wxString::Format(wxT("%02d"), n), m_hprotsel[n]);\r
-               OPJconfig->Write(wxT("encode/jpwl/htileval") + wxString::Format(wxT("%02d"), n), m_htileval[n]);\r
-               OPJconfig->Write(wxT("encode/jpwl/pprotsel") + wxString::Format(wxT("%02d"), n), m_pprotsel[n]);\r
-               OPJconfig->Write(wxT("encode/jpwl/ptileval") + wxString::Format(wxT("%02d"), n), m_ptileval[n]);\r
-               OPJconfig->Write(wxT("encode/jpwl/ppackval") + wxString::Format(wxT("%02d"), n), m_ppackval[n]);\r
-               OPJconfig->Write(wxT("encode/jpwl/sensisel") + wxString::Format(wxT("%02d"), n), m_sensisel[n]);\r
-               OPJconfig->Write(wxT("encode/jpwl/stileval") + wxString::Format(wxT("%02d"), n), m_stileval[n]);\r
-       }\r
-#endif // USE_JPWL\r
-\r
-#endif // OPJ_INICONFIG\r
-\r
-       return 1;\r
-}\r
-\r
-void OPJViewerApp::ShowCmdLine(const wxCmdLineParser& parser)\r
-{\r
-    wxString s = wxT("Command line parsed successfully:\nInput files: ");\r
-\r
-    size_t count = parser.GetParamCount();\r
-    for (size_t param = 0; param < count; param++) {\r
-        s << parser.GetParam(param) << ';';\r
-               m_filelist.Add(parser.GetParam(param));\r
-    }\r
-\r
-    //wxLogMessage(s);\r
-}\r
-\r
-// OPJFrame events\r
-\r
-// Event class for sending text messages between worker and GUI threads\r
-BEGIN_EVENT_TABLE(OPJFrame, wxMDIParentFrame)\r
-    EVT_MENU(OPJFRAME_HELPABOUT, OPJFrame::OnAbout)\r
-    EVT_MENU(OPJFRAME_FILEOPEN, OPJFrame::OnFileOpen)\r
-    EVT_MENU(OPJFRAME_FILESAVEAS, OPJFrame::OnFileSaveAs)\r
-    EVT_MENU(OPJFRAME_MEMORYOPEN, OPJFrame::OnMemoryOpen)\r
-    EVT_SIZE(OPJFrame::OnSize)\r
-    EVT_MENU(OPJFRAME_FILEEXIT, OPJFrame::OnQuit)\r
-    EVT_MENU(OPJFRAME_FILECLOSE, OPJFrame::OnClose)\r
-    EVT_MENU(OPJFRAME_VIEWZOOM, OPJFrame::OnZoom)\r
-    EVT_MENU(OPJFRAME_VIEWFIT, OPJFrame::OnFit)\r
-    EVT_MENU(OPJFRAME_VIEWRELOAD, OPJFrame::OnReload)\r
-    EVT_MENU(OPJFRAME_VIEWPREVFRAME, OPJFrame::OnPrevFrame)\r
-    EVT_MENU(OPJFRAME_VIEWHOMEFRAME, OPJFrame::OnHomeFrame)\r
-    EVT_MENU(OPJFRAME_VIEWNEXTFRAME, OPJFrame::OnNextFrame)\r
-    EVT_MENU(OPJFRAME_VIEWLESSLAYERS, OPJFrame::OnLessLayers)\r
-    EVT_MENU(OPJFRAME_VIEWALLLAYERS, OPJFrame::OnAllLayers)\r
-    EVT_MENU(OPJFRAME_VIEWMORELAYERS, OPJFrame::OnMoreLayers)\r
-    EVT_MENU(OPJFRAME_VIEWLESSRES, OPJFrame::OnLessRes)\r
-    EVT_MENU(OPJFRAME_VIEWFULLRES, OPJFrame::OnFullRes)\r
-    EVT_MENU(OPJFRAME_VIEWMORERES, OPJFrame::OnMoreRes)\r
-    EVT_MENU(OPJFRAME_VIEWPREVCOMP, OPJFrame::OnPrevComp)\r
-    EVT_MENU(OPJFRAME_VIEWALLCOMPS, OPJFrame::OnAllComps)\r
-    EVT_MENU(OPJFRAME_VIEWNEXTCOMP, OPJFrame::OnNextComp)\r
-    EVT_MENU(OPJFRAME_FILETOGGLEB, OPJFrame::OnToggleBrowser)\r
-    EVT_MENU(OPJFRAME_FILETOGGLEP, OPJFrame::OnTogglePeeker)\r
-    EVT_MENU(OPJFRAME_FILETOGGLET, OPJFrame::OnToggleToolbar)\r
-    EVT_MENU(OPJFRAME_SETSENCO, OPJFrame::OnSetsEnco)\r
-    EVT_MENU(OPJFRAME_SETSDECO, OPJFrame::OnSetsDeco)\r
-    EVT_SASH_DRAGGED_RANGE(OPJFRAME_BROWSEWIN, OPJFRAME_LOGWIN, OPJFrame::OnSashDrag)\r
-    EVT_NOTEBOOK_PAGE_CHANGED(LEFT_NOTEBOOK_ID, OPJFrame::OnNotebook)\r
-    EVT_MENU(OPJFRAME_THREADLOGMSG, OPJFrame::OnThreadLogmsg)\r
-END_EVENT_TABLE()\r
-\r
-// this is the frame constructor\r
-OPJFrame::OPJFrame(wxWindow *parent, const wxWindowID id, const wxString& title,\r
-                                  const wxPoint& pos, const wxSize& size, const long style)\r
-               : wxMDIParentFrame(parent, id, title, pos, size, style)\r
-{\r
-       // file menu and its items\r
-       wxMenu *file_menu = new wxMenu;\r
-\r
-       file_menu->Append(OPJFRAME_FILEOPEN, wxT("&Open\tCtrl+O"));\r
-       file_menu->SetHelpString(OPJFRAME_FILEOPEN, wxT("Open one or more files"));\r
-\r
-       file_menu->Append(OPJFRAME_MEMORYOPEN, wxT("&Memory\tCtrl+M"));\r
-       file_menu->SetHelpString(OPJFRAME_MEMORYOPEN, wxT("Open a memory buffer"));\r
-\r
-       file_menu->Append(OPJFRAME_FILECLOSE, wxT("&Close\tCtrl+C"));\r
-       file_menu->SetHelpString(OPJFRAME_FILECLOSE, wxT("Close current image"));\r
-\r
-       file_menu->AppendSeparator();\r
-\r
-       file_menu->Append(OPJFRAME_FILESAVEAS, wxT("&Save as\tCtrl+S"));\r
-       file_menu->SetHelpString(OPJFRAME_FILESAVEAS, wxT("Save the current image"));\r
-       //file_menu->Enable(OPJFRAME_FILESAVEAS, false);\r
-\r
-       file_menu->AppendSeparator();\r
-\r
-       file_menu->Append(OPJFRAME_FILETOGGLEB, wxT("Toggle &browser\tCtrl+B"));\r
-       file_menu->SetHelpString(OPJFRAME_FILETOGGLEB, wxT("Toggle the left browsing pane"));\r
-\r
-       file_menu->Append(OPJFRAME_FILETOGGLEP, wxT("Toggle &peeker\tCtrl+P"));\r
-       file_menu->SetHelpString(OPJFRAME_FILETOGGLEP, wxT("Toggle the bottom peeking pane"));\r
-\r
-       file_menu->Append(OPJFRAME_FILETOGGLET, wxT("Toggle &toolbar\tCtrl+T"));\r
-       file_menu->SetHelpString(OPJFRAME_FILETOGGLET, wxT("Toggle the toolbar"));\r
-\r
-       file_menu->AppendSeparator();\r
-\r
-       file_menu->Append(OPJFRAME_FILEEXIT, wxT("&Exit\tCtrl+Q"));\r
-       file_menu->SetHelpString(OPJFRAME_FILEEXIT, wxT("Quit this program"));\r
-\r
-       // view menu and its items\r
-       wxMenu *view_menu = new wxMenu;\r
-\r
-       view_menu->Append(OPJFRAME_VIEWZOOM, wxT("&Zoom\tCtrl+Z"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWZOOM, wxT("Rescale the image"));\r
-\r
-       view_menu->Append(OPJFRAME_VIEWFIT, wxT("Zoom to &fit\tCtrl+F"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWFIT, wxT("Fit the image in canvas"));\r
-\r
-       view_menu->Append(OPJFRAME_VIEWRELOAD, wxT("&Reload image\tCtrl+R"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWRELOAD, wxT("Reload the current image"));\r
-\r
-       view_menu->AppendSeparator();\r
-\r
-       view_menu->Append(OPJFRAME_VIEWPREVFRAME, wxT("&Prev frame\tLeft"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWPREVFRAME, wxT("View previous frame"));\r
-\r
-       view_menu->Append(OPJFRAME_VIEWHOMEFRAME, wxT("&Start frame\tHome"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWHOMEFRAME, wxT("View starting frame"));\r
-\r
-       view_menu->Append(OPJFRAME_VIEWNEXTFRAME, wxT("&Next frame\tRight"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWNEXTFRAME, wxT("View next frame"));\r
-\r
-       view_menu->AppendSeparator();\r
-\r
-       view_menu->Append(OPJFRAME_VIEWLESSLAYERS, wxT("&Less layers\t-"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWLESSLAYERS, wxT("Remove a layer"));\r
-\r
-       view_menu->Append(OPJFRAME_VIEWALLLAYERS, wxT("&All layers\t0"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWALLLAYERS, wxT("Show all layers"));\r
-\r
-       view_menu->Append(OPJFRAME_VIEWMORELAYERS, wxT("&More layers\t+"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWMORELAYERS, wxT("Add a layer"));\r
-\r
-       view_menu->AppendSeparator();\r
-\r
-       view_menu->Append(OPJFRAME_VIEWLESSRES, wxT("&Less resolution\t<"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWLESSRES, wxT("Reduce the resolution"));\r
-\r
-       view_menu->Append(OPJFRAME_VIEWFULLRES, wxT("&Full resolution\tf"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWFULLRES, wxT("Full resolution"));\r
-\r
-       view_menu->Append(OPJFRAME_VIEWMORERES, wxT("&More resolution\t>"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWMORERES, wxT("Increase the resolution"));\r
-\r
-       view_menu->AppendSeparator();\r
-\r
-       view_menu->Append(OPJFRAME_VIEWPREVCOMP, wxT("&Prev component\tDown"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWPREVCOMP, wxT("View previous component"));\r
-\r
-       view_menu->Append(OPJFRAME_VIEWALLCOMPS, wxT("&All components\ta"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWALLCOMPS, wxT("View all components"));\r
-\r
-       view_menu->Append(OPJFRAME_VIEWNEXTCOMP, wxT("&Next component\tUp"));\r
-       view_menu->SetHelpString(OPJFRAME_VIEWNEXTCOMP, wxT("View next component"));\r
-\r
-\r
-       // settings menu and its items\r
-       wxMenu *sets_menu = new wxMenu;\r
-\r
-       sets_menu->Append(OPJFRAME_SETSENCO, wxT("&Encoder\tCtrl+E"));\r
-       sets_menu->SetHelpString(OPJFRAME_SETSENCO, wxT("Encoder settings"));\r
-\r
-       sets_menu->Append(OPJFRAME_SETSDECO, wxT("&Decoder\tCtrl+D"));\r
-       sets_menu->SetHelpString(OPJFRAME_SETSDECO, wxT("Decoder settings"));\r
-\r
-       // help menu and its items\r
-       wxMenu *help_menu = new wxMenu;\r
-\r
-       help_menu->Append(OPJFRAME_HELPABOUT, wxT("&About\tF1"));\r
-       help_menu->SetHelpString(OPJFRAME_HELPABOUT, wxT("Basic info on the program"));\r
-\r
-       // the whole menubar\r
-       wxMenuBar *menu_bar = new wxMenuBar;\r
-       menu_bar->Append(file_menu, wxT("&File"));\r
-       menu_bar->Append(view_menu, wxT("&View"));\r
-       menu_bar->Append(sets_menu, wxT("&Settings"));\r
-       menu_bar->Append(help_menu, wxT("&Help"));\r
-\r
-       // Associate the menu bar with the frame\r
-       SetMenuBar(menu_bar);\r
-\r
-       // the status bar\r
-       CreateStatusBar();\r
-\r
-       // the toolbar\r
-       tool_bar = new wxToolBar(this, OPJFRAME_TOOLBAR,\r
-                                                               wxDefaultPosition, wxDefaultSize,\r
-                                                               wxTB_HORIZONTAL | wxNO_BORDER);\r
-       wxBitmap bmpOpen = wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR,\r
-                                                                                               wxDefaultSize);\r
-       wxBitmap bmpSaveAs = wxArtProvider::GetBitmap(wxART_FILE_SAVE_AS, wxART_TOOLBAR,\r
-                                                                                               wxDefaultSize);\r
-       wxBitmap bmpZoom = wxArtProvider::GetBitmap(wxART_FIND, wxART_TOOLBAR,\r
-                                                                                               wxDefaultSize);\r
-       wxBitmap bmpFit = wxArtProvider::GetBitmap(wxART_FIND_AND_REPLACE, wxART_TOOLBAR,\r
-                                                                                               wxDefaultSize);\r
-       wxBitmap bmpReload = wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE, wxART_TOOLBAR,\r
-                                                                                               wxDefaultSize);\r
-       wxBitmap bmpDecosettings = wxArtProvider::GetBitmap(wxART_REPORT_VIEW, wxART_TOOLBAR,\r
-                                                                                               wxDefaultSize);\r
-       wxBitmap bmpEncosettings = wxArtProvider::GetBitmap(wxART_LIST_VIEW, wxART_TOOLBAR,\r
-                                                                                               wxDefaultSize);\r
-       wxBitmap bmpPrevframe = wxArtProvider::GetBitmap(wxART_GO_BACK, wxART_TOOLBAR,\r
-                                                                                               wxDefaultSize);\r
-       wxBitmap bmpHomeframe = wxArtProvider::GetBitmap(wxART_GO_HOME, wxART_TOOLBAR,\r
-                                                                                               wxDefaultSize);\r
-       wxBitmap bmpNextframe = wxArtProvider::GetBitmap(wxART_GO_FORWARD, wxART_TOOLBAR,\r
-                                                                                               wxDefaultSize);\r
-       wxBitmap bmpLesslayers = bmpPrevframe;\r
-       wxBitmap bmpAlllayers = wxArtProvider::GetBitmap(wxART_GO_TO_PARENT, wxART_TOOLBAR,\r
-                                                                                               wxDefaultSize);\r
-       wxBitmap bmpMorelayers = bmpNextframe;\r
-       wxBitmap bmpLessres = bmpPrevframe;\r
-       wxBitmap bmpFullres = wxArtProvider::GetBitmap(wxART_GO_TO_PARENT, wxART_TOOLBAR,\r
-                                                                                               wxDefaultSize);\r
-       wxBitmap bmpMoreres = bmpNextframe;\r
-       wxBitmap bmpPrevcomp = bmpPrevframe;\r
-       wxBitmap bmpAllcomps = wxArtProvider::GetBitmap(wxART_GO_TO_PARENT, wxART_TOOLBAR,\r
-                                                                                               wxDefaultSize);\r
-       wxBitmap bmpNextcomp = bmpNextframe;\r
-\r
-       tool_bar->AddTool(OPJFRAME_FILEOPEN, bmpOpen, wxT("Open"));\r
-       tool_bar->AddTool(OPJFRAME_FILESAVEAS, bmpSaveAs, wxT("Save as "));\r
-       //tool_bar->EnableTool(OPJFRAME_FILESAVEAS, false);\r
-       tool_bar->AddSeparator();\r
-       tool_bar->AddTool(OPJFRAME_VIEWZOOM, bmpZoom, wxT("Zoom"));\r
-       tool_bar->AddTool(OPJFRAME_VIEWFIT, bmpFit, wxT("Zoom to fit"));\r
-       tool_bar->AddTool(OPJFRAME_VIEWRELOAD, bmpReload, wxT("Reload"));\r
-       tool_bar->AddSeparator();\r
-       tool_bar->AddTool(OPJFRAME_SETSDECO, bmpDecosettings, wxT("Decoder settings"));\r
-       tool_bar->AddTool(OPJFRAME_SETSENCO, bmpEncosettings, wxT("Encoder settings"));\r
-       tool_bar->AddSeparator();\r
-       tool_bar->AddTool(OPJFRAME_VIEWPREVFRAME, bmpPrevframe, wxT("Previous frame"));\r
-       tool_bar->AddTool(OPJFRAME_VIEWHOMEFRAME, bmpHomeframe, wxT("Starting frame"));\r
-       tool_bar->AddTool(OPJFRAME_VIEWNEXTFRAME, bmpNextframe, wxT("Next frame"));\r
-       tool_bar->AddSeparator();\r
-       tool_bar->AddTool(OPJFRAME_VIEWLESSLAYERS, bmpLesslayers, wxT("Remove a layer"));\r
-       tool_bar->AddTool(OPJFRAME_VIEWALLLAYERS, bmpAlllayers, wxT("Show all layers"));\r
-       tool_bar->AddTool(OPJFRAME_VIEWMORELAYERS, bmpMorelayers, wxT("Add a layer"));\r
-       tool_bar->AddSeparator();\r
-       tool_bar->AddTool(OPJFRAME_VIEWLESSRES, bmpLessres, wxT("Reduce the resolution"));\r
-       tool_bar->AddTool(OPJFRAME_VIEWFULLRES, bmpFullres, wxT("Full resolution"));\r
-       tool_bar->AddTool(OPJFRAME_VIEWMORERES, bmpMoreres, wxT("Increase the resolution"));\r
-       tool_bar->AddSeparator();\r
-       tool_bar->AddTool(OPJFRAME_VIEWPREVCOMP, bmpPrevcomp, wxT("Previous component"));\r
-       tool_bar->AddTool(OPJFRAME_VIEWALLCOMPS, bmpAllcomps, wxT("All components"));\r
-       tool_bar->AddTool(OPJFRAME_VIEWNEXTCOMP, bmpNextcomp, wxT("Next component"));\r
-       tool_bar->Realize();\r
-       \r
-       // associate the toolbar with the frame\r
-       SetToolBar(tool_bar);\r
-\r
-       // show the toolbar?\r
-       if (!wxGetApp().m_showtoolbar)\r
-               tool_bar->Show(false);\r
-       else\r
-               tool_bar->Show(true);\r
-\r
-       // the logging window\r
-       loggingWindow = new wxSashLayoutWindow(this, OPJFRAME_LOGWIN,\r
-                                                                                       wxDefaultPosition, wxSize(400, wxGetApp().m_peekerheight),\r
-                                                                                       wxNO_BORDER | wxSW_3D | wxCLIP_CHILDREN\r
-                                                                                       );\r
-       loggingWindow->SetDefaultSize(wxSize(1000, wxGetApp().m_peekerheight));\r
-       loggingWindow->SetOrientation(wxLAYOUT_HORIZONTAL);\r
-       loggingWindow->SetAlignment(wxLAYOUT_BOTTOM);\r
-       //loggingWindow->SetBackgroundColour(wxColour(0, 0, 255));\r
-       loggingWindow->SetSashVisible(wxSASH_TOP, true);\r
-\r
-       // show the logging?\r
-       if (!wxGetApp().m_showpeeker)\r
-               loggingWindow->Show(false);\r
-       else\r
-               loggingWindow->Show(true);\r
-\r
-       // create the bottom notebook\r
-       m_bookCtrlbottom = new wxNotebook(loggingWindow, BOTTOM_NOTEBOOK_ID,\r
-                                                               wxDefaultPosition, wxDefaultSize,\r
-                                                               wxBK_LEFT);\r
-\r
-       // create the text control of the logger\r
-       m_textCtrl = new wxTextCtrl(m_bookCtrlbottom, wxID_ANY, wxT(""),\r
-                                                               wxDefaultPosition, wxDefaultSize,\r
-                                                               wxTE_MULTILINE | wxSUNKEN_BORDER | wxTE_READONLY\r
-                                                               );\r
-       m_textCtrl->SetValue(_T("Logging window\n"));\r
-\r
-       // add it to the notebook\r
-       m_bookCtrlbottom->AddPage(m_textCtrl, wxT("Log"));\r
-\r
-       // create the text control of the browser\r
-       m_textCtrlbrowse = new wxTextCtrl(m_bookCtrlbottom, wxID_ANY, wxT(""),\r
-                                                               wxDefaultPosition, wxDefaultSize,\r
-                                                               wxTE_MULTILINE | wxSUNKEN_BORDER | wxTE_READONLY | wxTE_RICH\r
-                                                               );\r
-       wxFont *browsefont = new wxFont(wxNORMAL_FONT->GetPointSize(),\r
-               wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);\r
-    m_textCtrlbrowse->SetDefaultStyle(wxTextAttr(wxNullColour, wxNullColour, *browsefont));\r
-       m_textCtrlbrowse->AppendText(wxT("Browsing window\n"));\r
-\r
-       // add it the notebook\r
-       m_bookCtrlbottom->AddPage(m_textCtrlbrowse, wxT("Peek"), false);\r
-\r
-       // the browser window\r
-       markerTreeWindow = new wxSashLayoutWindow(this, OPJFRAME_BROWSEWIN,\r
-                                                                                         wxDefaultPosition, wxSize(wxGetApp().m_browserwidth, 30),\r
-                                                                                         wxNO_BORDER | wxSW_3D | wxCLIP_CHILDREN\r
-                                                                                         );\r
-       markerTreeWindow->SetDefaultSize(wxSize(wxGetApp().m_browserwidth, 1000));\r
-       markerTreeWindow->SetOrientation(wxLAYOUT_VERTICAL);\r
-       markerTreeWindow->SetAlignment(wxLAYOUT_LEFT);\r
-       //markerTreeWindow->SetBackgroundColour(wxColour(0, 255, 0));\r
-       markerTreeWindow->SetSashVisible(wxSASH_RIGHT, true);\r
-       markerTreeWindow->SetExtraBorderSize(0);\r
-\r
-       // create the browser notebook\r
-       m_bookCtrl = new wxNotebook(markerTreeWindow, LEFT_NOTEBOOK_ID,\r
-                                                               wxDefaultPosition, wxDefaultSize,\r
-                                                               wxBK_TOP);\r
-\r
-       // show the browser?\r
-       if (!wxGetApp().m_showbrowser)\r
-               markerTreeWindow->Show(false);\r
-       else\r
-               markerTreeWindow->Show(true);\r
-\r
-#ifdef __WXMOTIF__\r
-       // For some reason, we get a memcpy crash in wxLogStream::DoLogStream\r
-       // on gcc/wxMotif, if we use wxLogTextCtl. Maybe it's just gcc?\r
-       delete wxLog::SetActiveTarget(new wxLogStderr);\r
-#else\r
-       // set our text control as the log target\r
-       wxLogTextCtrl *logWindow = new wxLogTextCtrl(m_textCtrl);\r
-       delete wxLog::SetActiveTarget(logWindow);\r
-#endif\r
-\r
-       // associate drop targets with the controls\r
-       SetDropTarget(new OPJDnDFile(this));\r
-\r
-}\r
-\r
-// this is the frame destructor\r
-OPJFrame::~OPJFrame(void)\r
-{\r
-       // save size settings\r
-       GetSize(&(wxGetApp().m_framewidth), &(wxGetApp().m_frameheight));\r
-\r
-       // delete all possible things\r
-       delete m_bookCtrl;\r
-       m_bookCtrl = NULL;\r
-\r
-       delete markerTreeWindow;\r
-       markerTreeWindow = NULL;\r
-\r
-       delete m_textCtrl;\r
-       m_textCtrl = NULL;\r
-\r
-       delete m_bookCtrlbottom;\r
-       m_bookCtrlbottom = NULL;\r
-\r
-       delete loggingWindow;\r
-       loggingWindow = NULL;\r
-}\r
-\r
-void OPJFrame::OnNotebook(wxNotebookEvent& event)\r
-{\r
-       int sel = event.GetSelection();\r
-       long childnum;\r
-\r
-       m_bookCtrl->GetPageText(sel).ToLong(&childnum);\r
-\r
-       if (m_childhash[childnum])\r
-               m_childhash[childnum]->Activate();\r
-\r
-       //wxLogMessage(wxT("Selection changed (now %d --> %d)"), childnum, m_childhash[childnum]->m_winnumber);\r
-\r
-}\r
-\r
-\r
-void OPJFrame::Resize(int number)\r
-{\r
-       wxSize size = GetClientSize();\r
-}\r
-\r
-void OPJFrame::OnSetsEnco(wxCommandEvent& event)\r
-{\r
-       int n;\r
-\r
-    OPJEncoderDialog dialog(this, event.GetId());\r
-\r
-    if (dialog.ShowModal() == wxID_OK) {\r
-\r
-               // load settings\r
-               wxGetApp().m_subsampling = dialog.m_subsamplingCtrl->GetValue();\r
-               wxGetApp().m_origin = dialog.m_originCtrl->GetValue();\r
-               wxGetApp().m_rates = dialog.m_rateCtrl->GetValue();\r
-               wxGetApp().m_quality = dialog.m_qualityCtrl->GetValue();\r
-               wxGetApp().m_enablequality = dialog.m_qualityRadio->GetValue();\r
-               wxGetApp().m_multicomp = dialog.m_mctCheck->GetValue();\r
-               wxGetApp().m_irreversible = dialog.m_irrevCheck->GetValue();\r
-               wxGetApp().m_resolutions = dialog.m_resolutionsCtrl->GetValue();\r
-               wxGetApp().m_cbsize = dialog.m_cbsizeCtrl->GetValue();\r
-               wxGetApp().m_prsize = dialog.m_prsizeCtrl->GetValue();\r
-               wxGetApp().m_tsize = dialog.m_tsizeCtrl->GetValue();\r
-               wxGetApp().m_torigin = dialog.m_toriginCtrl->GetValue();\r
-               wxGetApp().m_progression = dialog.progressionBox->GetSelection();\r
-               wxGetApp().m_enablesop = dialog.m_sopCheck->GetValue();\r
-               wxGetApp().m_enableeph = dialog.m_ephCheck->GetValue();\r
-               wxGetApp().m_enablebypass = dialog.m_enablebypassCheck->GetValue();\r
-               wxGetApp().m_enablereset = dialog.m_enableresetCheck->GetValue();\r
-               wxGetApp().m_enablerestart = dialog.m_enablerestartCheck->GetValue();\r
-               wxGetApp().m_enablevsc = dialog.m_enablevscCheck->GetValue();\r
-               wxGetApp().m_enableerterm = dialog.m_enableertermCheck->GetValue();\r
-               wxGetApp().m_enablesegmark = dialog.m_enablesegmarkCheck->GetValue();\r
-               wxGetApp().m_enableidx = dialog.m_enableidxCheck->GetValue();\r
-               wxGetApp().m_index = dialog.m_indexCtrl->GetValue();\r
-               wxGetApp().m_enablecomm = dialog.m_enablecommCheck->GetValue();\r
-               wxGetApp().m_comment = dialog.m_commentCtrl->GetValue();\r
-               wxGetApp().m_enablepoc = dialog.m_enablepocCheck->GetValue();\r
-               wxGetApp().m_poc = dialog.m_pocCtrl->GetValue();\r
-#ifdef USE_JPWL\r
-               wxGetApp().m_enablejpwle = dialog.m_enablejpwlCheck->GetValue();\r
-               for (n = 0; n < MYJPWL_MAX_NO_TILESPECS; n++) {\r
-                       wxGetApp().m_hprotsel[n] = dialog.m_hprotChoice[n]->GetSelection();\r
-                       wxGetApp().m_htileval[n] = dialog.m_htileCtrl[n]->GetValue();\r
-                       wxGetApp().m_pprotsel[n] = dialog.m_pprotChoice[n]->GetSelection();\r
-                       wxGetApp().m_ptileval[n] = dialog.m_ptileCtrl[n]->GetValue();\r
-                       wxGetApp().m_ppackval[n] = dialog.m_ppackCtrl[n]->GetValue();\r
-                       wxGetApp().m_sensisel[n] = dialog.m_sensiChoice[n]->GetSelection();\r
-                       wxGetApp().m_stileval[n] = dialog.m_stileCtrl[n]->GetValue();\r
-               }\r
-#endif // USE_JPWL\r
-       };\r
-}\r
-\r
-void OPJFrame::OnSetsDeco(wxCommandEvent& event)\r
-{\r
-    OPJDecoderDialog dialog(this, event.GetId());\r
-\r
-    if (dialog.ShowModal() == wxID_OK) {\r
-\r
-               // load settings\r
-               wxGetApp().m_enabledeco = dialog.m_enabledecoCheck->GetValue();\r
-               wxGetApp().m_enableparse = dialog.m_enableparseCheck->GetValue();\r
-               wxGetApp().m_resizemethod = dialog.m_resizeBox->GetSelection() - 1;\r
-               wxGetApp().m_reducefactor = dialog.m_reduceCtrl->GetValue();\r
-               wxGetApp().m_qualitylayers = dialog.m_layerCtrl->GetValue();\r
-               wxGetApp().m_components = dialog.m_numcompsCtrl->GetValue();\r
-               wxGetApp().m_framenum = dialog.m_framenumCtrl->GetValue();\r
-#ifdef USE_JPWL\r
-               wxGetApp().m_enablejpwl = dialog.m_enablejpwlCheck->GetValue();\r
-               wxGetApp().m_expcomps = dialog.m_expcompsCtrl->GetValue();\r
-               wxGetApp().m_maxtiles = dialog.m_maxtilesCtrl->GetValue();\r
-#endif // USE_JPWL\r
-\r
-       };\r
-}\r
-\r
-void OPJFrame::OnQuit(wxCommandEvent& WXUNUSED(event))\r
-{\r
-       Close(true);\r
-}\r
-\r
-void OPJFrame::OnClose(wxCommandEvent& WXUNUSED(event))\r
-{\r
-       // current frame\r
-       OPJChildFrame *currframe = (OPJChildFrame *) GetActiveChild();\r
-\r
-       if (!currframe)\r
-               return;\r
-\r
-       wxCloseEvent e;\r
-       currframe->OnClose(e);\r
-}\r
-\r
-void OPJFrame::OnFit(wxCommandEvent& event)\r
-{\r
-       OPJChildFrame *currchild;\r
-       wxString eventstring = event.GetString();\r
-\r
-       //wxLogMessage(wxT("OnFit:%d:%s"), event.GetInt(), eventstring);\r
-\r
-       // current child\r
-       if (event.GetInt() >= 1) {\r
-               currchild = m_childhash[event.GetInt()];\r
-       } else {\r
-               currchild = (OPJChildFrame *) GetActiveChild();\r
-       }\r
-\r
-       // problems\r
-       if (!currchild)\r
-               return;\r
-\r
-       // current canvas\r
-       OPJCanvas *currcanvas = currchild->m_canvas;\r
-\r
-       // find a fit-to-width zoom\r
-       /*int zooml, wzooml, hzooml;\r
-       wxSize clientsize = currcanvas->GetClientSize();\r
-       wzooml = (int) ceil(100.0 * (double) (clientsize.GetWidth() - 2 * OPJ_CANVAS_BORDER) / (double) (currcanvas->m_image100.GetWidth()));\r
-       hzooml = (int) ceil(100.0 * (double) (clientsize.GetHeight() - 2 * OPJ_CANVAS_BORDER) / (double) (currcanvas->m_image100.GetHeight()));\r
-       zooml = wxMin(100, wxMin(wzooml, hzooml));*/\r
-\r
-       // fit to width\r
-       Rescale(-1, currchild);\r
-}\r
-\r
-void OPJFrame::OnZoom(wxCommandEvent& WXUNUSED(event))\r
-{\r
-       // current frame\r
-       OPJChildFrame *currframe = (OPJChildFrame *) GetActiveChild();\r
-\r
-       if (!currframe)\r
-               return;\r
-\r
-       // get the preferred zoom\r
-       long zooml = wxGetNumberFromUser(wxT("Choose a scale between 5% and 300%"),\r
-               wxT("Zoom (%)"),\r
-               wxT("Image scale"),\r
-               currframe->m_canvas->m_zooml, 5, 300, NULL, wxDefaultPosition);\r
-\r
-       // rescale current frame image if necessary\r
-       if (zooml >= 5) {\r
-               Rescale(zooml, currframe);\r
-               wxLogMessage(wxT("zoom to %d%%"), zooml);\r
-       }\r
-}\r
-\r
-void OPJFrame::Rescale(int zooml, OPJChildFrame *currframe)\r
-{\r
-       wxImage new_image = currframe->m_canvas->m_image100.ConvertToImage();\r
-\r
-       // resizing enabled?\r
-       if (wxGetApp().m_resizemethod == -1) {\r
-\r
-               zooml = 100;\r
-\r
-       } else {\r
-\r
-               if (zooml < 0) {\r
-                       // find a fit-to-width zoom\r
-                       int wzooml, hzooml;\r
-                       //wxSize clientsize = currframe->m_canvas->GetClientSize();\r
-                       wxSize clientsize = currframe->m_frame->GetActiveChild()->GetClientSize();\r
-                       wzooml = (int) floor(100.0 * (double) clientsize.GetWidth() / (double) (2 * OPJ_CANVAS_BORDER + currframe->m_canvas->m_image100.GetWidth()));\r
-                       hzooml = (int) floor(100.0 * (double) clientsize.GetHeight() / (double) (2 * OPJ_CANVAS_BORDER + currframe->m_canvas->m_image100.GetHeight()));\r
-                       zooml = wxMin(100, wxMin(wzooml, hzooml));\r
-               }\r
-       }\r
-\r
-       if (zooml != 100)\r
-               new_image.Rescale((int) ((double) zooml * (double) new_image.GetWidth() / 100.0),\r
-                       (int) ((double) zooml * (double) new_image.GetHeight() / 100.0),\r
-                       wxGetApp().m_resizemethod ? wxIMAGE_QUALITY_HIGH : wxIMAGE_QUALITY_NORMAL);\r
-       currframe->m_canvas->m_image = wxBitmap(new_image);\r
-       currframe->m_canvas->SetScrollbars(20,\r
-                                                                               20,\r
-                                                                               (int)(0.5 + (double) new_image.GetWidth() / 20.0),\r
-                                                                               (int)(0.5 + (double) new_image.GetHeight() / 20.0)\r
-                                                                               );\r
-\r
-       currframe->m_canvas->Refresh();\r
-\r
-       wxLogMessage(wxT("Rescale said %d%%"), zooml);\r
-\r
-       // update zoom\r
-       currframe->m_canvas->m_zooml = zooml;\r
-}\r
-\r
-\r
-void OPJFrame::OnReload(wxCommandEvent& event)\r
-{\r
-       OPJChildFrame *currframe = (OPJChildFrame *) GetActiveChild();\r
-\r
-       if (currframe) {\r
-               OPJDecoThread *dthread = currframe->m_canvas->CreateDecoThread();\r
-\r
-               if (dthread->Run() != wxTHREAD_NO_ERROR)\r
-                       wxLogMessage(wxT("Can't start deco thread!"));\r
-               else\r
-                       wxLogMessage(wxT("New deco thread started."));\r
-\r
-               currframe->m_canvas->Refresh();\r
-\r
-               // update zoom\r
-               //currframe->m_canvas->m_zooml = zooml;\r
-       }\r
-}\r
-\r
-void OPJFrame::OnPrevFrame(wxCommandEvent& event)\r
-{\r
-       if (--wxGetApp().m_framenum < 0)\r
-               wxGetApp().m_framenum = 0;\r
-\r
-       wxCommandEvent e;\r
-       OnReload(e);\r
-}\r
-\r
-void OPJFrame::OnHomeFrame(wxCommandEvent& event)\r
-{\r
-       wxGetApp().m_framenum = 0;\r
-\r
-       wxCommandEvent e;\r
-       OnReload(e);\r
-}\r
-\r
-void OPJFrame::OnNextFrame(wxCommandEvent& event)\r
-{\r
-       ++wxGetApp().m_framenum;\r
-\r
-       wxCommandEvent e;\r
-       OnReload(e);\r
-}\r
-\r
-void OPJFrame::OnLessLayers(wxCommandEvent& event)\r
-{\r
-       if (--wxGetApp().m_qualitylayers < 1)\r
-               wxGetApp().m_qualitylayers = 1;\r
-\r
-       wxCommandEvent e;\r
-       OnReload(e);\r
-}\r
-\r
-void OPJFrame::OnAllLayers(wxCommandEvent& event)\r
-{\r
-       wxGetApp().m_qualitylayers = 0;\r
-\r
-       wxCommandEvent e;\r
-       OnReload(e);\r
-}\r
-\r
-void OPJFrame::OnMoreLayers(wxCommandEvent& event)\r
-{\r
-       ++wxGetApp().m_qualitylayers;\r
-\r
-       wxCommandEvent e;\r
-       OnReload(e);\r
-}\r
-\r
-void OPJFrame::OnLessRes(wxCommandEvent& event)\r
-{\r
-       ++wxGetApp().m_reducefactor;\r
-\r
-       wxCommandEvent e;\r
-       OnReload(e);\r
-}\r
-\r
-void OPJFrame::OnFullRes(wxCommandEvent& event)\r
-{\r
-       wxGetApp().m_reducefactor = 0;\r
-\r
-       wxCommandEvent e;\r
-       OnReload(e);\r
-}\r
-\r
-void OPJFrame::OnMoreRes(wxCommandEvent& event)\r
-{\r
-       if (--wxGetApp().m_reducefactor < 0)\r
-               wxGetApp().m_reducefactor = 0;\r
-\r
-       wxCommandEvent e;\r
-       OnReload(e);\r
-}\r
-\r
-void OPJFrame::OnPrevComp(wxCommandEvent& event)\r
-{\r
-       if (--wxGetApp().m_components < 1)\r
-               wxGetApp().m_components = 1;\r
-\r
-       wxCommandEvent e;\r
-       OnReload(e);\r
-}\r
-\r
-void OPJFrame::OnAllComps(wxCommandEvent& event)\r
-{\r
-       wxGetApp().m_components = 0;\r
-\r
-       wxCommandEvent e;\r
-       OnReload(e);\r
-}\r
-\r
-void OPJFrame::OnNextComp(wxCommandEvent& event)\r
-{\r
-       ++wxGetApp().m_components;\r
-\r
-       wxCommandEvent e;\r
-       OnReload(e);\r
-}\r
-\r
-void OPJFrame::OnToggleBrowser(wxCommandEvent& WXUNUSED(event))\r
-{\r
-    if (markerTreeWindow->IsShown())\r
-        markerTreeWindow->Show(false);\r
-    else\r
-        markerTreeWindow->Show(true);\r
-\r
-    wxLayoutAlgorithm layout;\r
-    layout.LayoutMDIFrame(this);\r
-\r
-       wxGetApp().m_showbrowser = markerTreeWindow->IsShown();\r
-\r
-    // Leaves bits of itself behind sometimes\r
-    GetClientWindow()->Refresh();\r
-}\r
-\r
-void OPJFrame::OnTogglePeeker(wxCommandEvent& WXUNUSED(event))\r
-{\r
-    if (loggingWindow->IsShown())\r
-        loggingWindow->Show(false);\r
-    else\r
-        loggingWindow->Show(true);\r
-\r
-    wxLayoutAlgorithm layout;\r
-    layout.LayoutMDIFrame(this);\r
-\r
-       wxGetApp().m_showpeeker = loggingWindow->IsShown();\r
-\r
-    // Leaves bits of itself behind sometimes\r
-    GetClientWindow()->Refresh();\r
-}\r
-\r
-void OPJFrame::OnToggleToolbar(wxCommandEvent& WXUNUSED(event))\r
-{\r
-    if (tool_bar->IsShown())\r
-        tool_bar->Show(false);\r
-    else\r
-        tool_bar->Show(true);\r
-\r
-    wxLayoutAlgorithm layout;\r
-    layout.LayoutMDIFrame(this);\r
-\r
-       wxGetApp().m_showtoolbar = tool_bar->IsShown();\r
-\r
-    // Leaves bits of itself behind sometimes\r
-    GetClientWindow()->Refresh();\r
-}\r
-\r
-void OPJFrame::OnSashDrag(wxSashEvent& event)\r
-{\r
-       int wid, hei;\r
-\r
-    if (event.GetDragStatus() == wxSASH_STATUS_OUT_OF_RANGE)\r
-        return;\r
-\r
-    switch (event.GetId()) {\r
-               case OPJFRAME_BROWSEWIN:\r
-               {\r
-                       markerTreeWindow->SetDefaultSize(wxSize(event.GetDragRect().width, 1000));\r
-                       break;\r
-               }\r
-               case OPJFRAME_LOGWIN:\r
-               {\r
-                       loggingWindow->SetDefaultSize(wxSize(1000, event.GetDragRect().height));\r
-                       break;\r
-               }\r
-    }\r
-\r
-    wxLayoutAlgorithm layout;\r
-    layout.LayoutMDIFrame(this);\r
-\r
-    // Leaves bits of itself behind sometimes\r
-    GetClientWindow()->Refresh();\r
-\r
-       // update dimensions\r
-       markerTreeWindow->GetSize(&wid, &hei);\r
-       wxGetApp().m_browserwidth = wid;\r
-\r
-       loggingWindow->GetSize(&wid, &hei);\r
-       wxGetApp().m_peekerheight = hei;\r
-\r
-}\r
-\r
-void OPJFrame::OnThreadLogmsg(wxCommandEvent& event)\r
-{\r
-#if 1\r
-    wxLogMessage(wxT("Frame got message from worker thread: %d"), event.GetInt());\r
-    wxLogMessage(event.GetString());\r
-#else\r
-    int n = event.GetInt();\r
-    if ( n == -1 )\r
-    {\r
-        m_dlgProgress->Destroy();\r
-        m_dlgProgress = (wxProgressDialog *)NULL;\r
-\r
-        // the dialog is aborted because the event came from another thread, so\r
-        // we may need to wake up the main event loop for the dialog to be\r
-        // really closed\r
-        wxWakeUpIdle();\r
-    }\r
-    else\r
-    {\r
-        if ( !m_dlgProgress->Update(n) )\r
-        {\r
-            wxCriticalSectionLocker lock(m_critsectWork);\r
-\r
-            m_cancelled = true;\r
-        }\r
-    }\r
-#endif\r
-}\r
-\r
-\r
-// physically save the file\r
-void OPJFrame::SaveFile(wxArrayString paths, wxArrayString filenames)\r
-{\r
-       size_t count = paths.GetCount();\r
-       wxString msg, s;\r
-\r
-       if (wxFile::Exists(paths[0].c_str())) {\r
-\r
-               s.Printf(wxT("File %s already exists. Do you want to overwrite it?\n"), filenames[0].c_str());\r
-               wxMessageDialog dialog3(this, s, _T("File exists"), wxYES_NO);\r
-               if (dialog3.ShowModal() == wxID_NO)\r
-                       return;\r
-       }\r
-\r
-       /*s.Printf(_T("File %d: %s (%s)\n"), (int)0, paths[0].c_str(), filenames[0].c_str());\r
-       msg += s;\r
-\r
-       wxMessageDialog dialog2(this, msg, _T("Selected files"));\r
-       dialog2.ShowModal();*/\r
-\r
-       if (!GetActiveChild())\r
-               return;\r
-\r
-       ((OPJChildFrame *) GetActiveChild())->m_canvas->m_savename = paths[0];\r
-\r
-       OPJEncoThread *ethread = ((OPJChildFrame *) GetActiveChild())->m_canvas->CreateEncoThread();\r
-\r
-    if (ethread->Run() != wxTHREAD_NO_ERROR)\r
-        wxLogMessage(wxT("Can't start enco thread!"));\r
-    else\r
-               wxLogMessage(wxT("New enco thread started."));\r
-\r
-\r
-}\r
-\r
-// physically open the files\r
-void OPJFrame::OpenFiles(wxArrayString paths, wxArrayString filenames)\r
-{\r
-\r
-       size_t count = paths.GetCount();\r
-       for (size_t n = 0; n < count; n++) {\r
-\r
-               wxString msg, s;\r
-               s.Printf(_T("File %d: %s (%s)\n"), (int)n, paths[n].c_str(), filenames[n].c_str());\r
-\r
-               msg += s;\r
-\r
-               /*wxMessageDialog dialog2(this, msg, _T("Selected files"));\r
-               dialog2.ShowModal();*/\r
-\r
-               // Make another frame, containing a canvas\r
-               OPJChildFrame *subframe = new OPJChildFrame(this,\r
-                                                                                                       paths[n],\r
-                                                                                                       winNumber,\r
-                                                                                                       wxT("Canvas Frame"),\r
-                                                                                                       wxDefaultPosition, wxSize(300, 300),\r
-                                                                                                       wxDEFAULT_FRAME_STYLE | wxNO_FULL_REPAINT_ON_RESIZE\r
-                                                                                                       );\r
-               m_childhash[winNumber] = subframe;\r
-\r
-               // create own marker tree\r
-               m_treehash[winNumber] = new OPJMarkerTree(m_bookCtrl, subframe, paths[n], wxT("Parsing..."), TreeTest_Ctrl,\r
-                                                                                                 wxDefaultPosition, wxDefaultSize,\r
-                                                                                                 wxTR_DEFAULT_STYLE | wxSUNKEN_BORDER\r
-                                                                                                 );\r
-\r
-               m_bookCtrl->AddPage(m_treehash[winNumber], wxString::Format(wxT("%u"), winNumber), false);\r
-\r
-               for (unsigned int p = 0; p < m_bookCtrl->GetPageCount(); p++) {\r
-                       if (m_bookCtrl->GetPageText(p) == wxString::Format(wxT("%u"), winNumber)) {\r
-                               m_bookCtrl->ChangeSelection(p);\r
-                               break;\r
-                       }\r
-               }\r
-\r
-               winNumber++;\r
-       }\r
-}\r
-\r
-void OPJFrame::OnFileOpen(wxCommandEvent& WXUNUSED(event))\r
-{\r
-    wxString wildcards =\r
-#ifdef __WXMOTIF__\r
-       wxT("JPEG 2000 files (*.jp2,*.j2k,*.j2c,*.mj2)|*.*j*2*");\r
-#else\r
-#if wxUSE_LIBOPENJPEG\r
-       wxT("JPEG 2000 files (*.jp2,*.j2k,*.j2c,*.mj2)|*.jp2;*.j2k;*.j2c;*.mj2")\r
-#endif\r
-#if USE_MXF\r
-       wxT("|MXF JPEG 2000 video (*.mxf)|*.mxf")\r
-#endif // USE_MXF\r
-#if wxUSE_LIBJPEG\r
-               wxT("|JPEG files (*.jpg)|*.jpg")\r
-#endif\r
-#if OPJ_MANYFORMATS\r
-               wxT("|BMP files (*.bmp)|*.bmp")\r
-               wxT("|PNG files (*.png)|*.png")\r
-               wxT("|GIF files (*.gif)|*.gif")\r
-               wxT("|PNM files (*.pnm)|*.pnm")\r
-               wxT("|TIFF files (*.tif,*.tiff)|*.tif*")\r
-#endif\r
-               wxT("|All files|*");\r
-#endif\r
-    wxFileDialog dialog(this, _T("Open image file(s)"),\r
-                        wxEmptyString, wxEmptyString, wildcards,\r
-                        wxFD_OPEN|wxFD_MULTIPLE);\r
-\r
-    if (dialog.ShowModal() == wxID_OK) {\r
-        wxArrayString paths, filenames;\r
-\r
-        dialog.GetPaths(paths);\r
-        dialog.GetFilenames(filenames);\r
-\r
-               OpenFiles(paths, filenames);\r
-    }\r
-\r
-}\r
-\r
-void OPJFrame::OnFileSaveAs(wxCommandEvent& WXUNUSED(event))\r
-{\r
-    wxString wildcards =\r
-#ifdef wxUSE_LIBOPENJPEG\r
-#ifdef __WXMOTIF__\r
-       wxT("JPEG 2000 codestream (*.j2k)|*.*j*2*");\r
-#else\r
-       wxT("JPEG 2000 codestream (*.j2k)|*.j2k")\r
-       wxT("|JPEG 2000 file format (*.jp2)|*.jp2");\r
-#endif\r
-#endif\r
-\r
-    wxFileDialog dialog(this, _T("Save image file"),\r
-                        wxEmptyString, wxEmptyString, wildcards,\r
-                        wxFD_SAVE);\r
-\r
-    if (dialog.ShowModal() == wxID_OK) {\r
-        wxArrayString paths, filenames;\r
-\r
-        dialog.GetPaths(paths);\r
-        dialog.GetFilenames(filenames);\r
-\r
-               SaveFile(paths, filenames);\r
-    }\r
-\r
-\r
-}\r
-\r
-void OPJFrame::OnMemoryOpen(wxCommandEvent& WXUNUSED(event))\r
-{\r
-       // do nothing\r
-       return;\r
-       \r
-       wxTextEntryDialog dialog(this, wxT("Memory HEX address range: start_address-stop_address"),\r
-                                                       wxT("Decode a memory buffer"),\r
-                                                       wxT("0x-0x"),\r
-                                                       wxOK | wxCANCEL | wxCENTRE,\r
-                                                       wxDefaultPosition);\r
-\r
-       if (dialog.ShowModal() == wxID_OK) {\r
-\r
-       }\r
-\r
-}\r
-\r
-BEGIN_EVENT_TABLE(OPJCanvas, wxScrolledWindow)\r
-    EVT_MOUSE_EVENTS(OPJCanvas::OnEvent)\r
-    EVT_MENU(OPJCANVAS_THREADSIGNAL, OPJCanvas::OnThreadSignal)\r
-END_EVENT_TABLE()\r
-\r
-// Define a constructor for my canvas\r
-OPJCanvas::OPJCanvas(wxFileName fname, wxWindow *parent, const wxPoint& pos, const wxSize& size)\r
-        : wxScrolledWindow(parent, wxID_ANY, pos, size,\r
-                           wxSUNKEN_BORDER | wxNO_FULL_REPAINT_ON_RESIZE)\r
-{\r
-    SetBackgroundColour(OPJ_CANVAS_COLOUR);\r
-\r
-       m_fname = fname;\r
-       m_childframe = (OPJChildFrame *) parent;\r
-       // 100% zoom\r
-       m_zooml = 100;\r
-\r
-\r
-    OPJDecoThread *dthread = CreateDecoThread();\r
-\r
-    if (dthread->Run() != wxTHREAD_NO_ERROR)\r
-        wxLogMessage(wxT("Can't start deco thread!"));\r
-    else\r
-               wxLogMessage(wxT("New deco thread started."));\r
-\r
-       // 100% zoom\r
-       //m_zooml = 100;\r
-\r
-}\r
-\r
-OPJDecoThread *OPJCanvas::CreateDecoThread(void)\r
-{\r
-    OPJDecoThread *dthread = new OPJDecoThread(this);\r
-\r
-    if (dthread->Create() != wxTHREAD_NO_ERROR)\r
-               wxLogError(wxT("Can't create deco thread!"));\r
-\r
-    wxCriticalSectionLocker enter(wxGetApp().m_deco_critsect);\r
-    wxGetApp().m_deco_threads.Add(dthread);\r
-\r
-    return dthread;\r
-}\r
-\r
-OPJEncoThread *OPJCanvas::CreateEncoThread(void)\r
-{\r
-    OPJEncoThread *ethread = new OPJEncoThread(this);\r
-\r
-    if (ethread->Create() != wxTHREAD_NO_ERROR)\r
-               wxLogError(wxT("Can't create enco thread!"));\r
-\r
-    wxCriticalSectionLocker enter(wxGetApp().m_enco_critsect);\r
-    wxGetApp().m_enco_threads.Add(ethread);\r
-\r
-    return ethread;\r
-}\r
-\r
-#define activeoverlay 0\r
-// Define the repainting behaviour\r
-void OPJCanvas::OnDraw(wxDC& dc)\r
-{\r
-       if (m_image.Ok()) {\r
-               dc.DrawBitmap(m_image, OPJ_CANVAS_BORDER, OPJ_CANVAS_BORDER);\r
-\r
-               if (activeoverlay) {\r
-                       dc.SetPen(*wxRED_PEN);\r
-                       dc.SetBrush(*wxTRANSPARENT_BRUSH);\r
-                       //int tw, th;\r
-                       dc.DrawRectangle(OPJ_CANVAS_BORDER, OPJ_CANVAS_BORDER,\r
-                               (unsigned long int) (0.5 + (double) m_zooml * (double) m_childframe->m_twidth / 100.0),\r
-                               (unsigned long int) (0.5 + (double) m_zooml * (double) m_childframe->m_theight / 100.0));\r
-               }\r
-\r
-       } else {\r
-               dc.SetFont(*wxSWISS_FONT);\r
-               dc.SetPen(*wxBLACK_PEN);\r
-#ifdef __WXGTK__\r
-               dc.DrawText(_T("Decoding image, please wait... (press \"Zoom to Fit\" to show the image)"), 40, 50);\r
-#else\r
-               dc.DrawText(_T("Decoding image, please wait..."), 40, 50);\r
-#endif\r
-       }\r
-}\r
-\r
-// This implements a tiny doodling program! Drag the mouse using\r
-// the left button.\r
-void OPJCanvas::OnEvent(wxMouseEvent& event)\r
-{\r
-#if USE_PENCIL_ON_CANVAS\r
-  wxClientDC dc(this);\r
-  PrepareDC(dc);\r
-\r
-  wxPoint pt(event.GetLogicalPosition(dc));\r
-\r
-  if ((xpos > -1) && (ypos > -1) && event.Dragging()) {\r
-    dc.SetPen(*wxRED_PEN);\r
-    dc.DrawLine(xpos, ypos, pt.x, pt.y);\r
-  }\r
-  xpos = pt.x;\r
-  ypos = pt.y;\r
-#endif\r
-}\r
-\r
-void OPJFrame::OnSize(wxSizeEvent& WXUNUSED(event))\r
-{\r
-    wxLayoutAlgorithm layout;\r
-    layout.LayoutMDIFrame(this);\r
-}\r
-\r
-void OPJCanvas::OnThreadSignal(wxCommandEvent& event)\r
-{\r
-#if 1\r
-    wxLogMessage(wxT("Canvas got signal from deco thread: %d"), event.GetInt());\r
-    wxLogMessage(event.GetString());\r
-#else\r
-    int n = event.GetInt();\r
-    if ( n == -1 )\r
-    {\r
-        m_dlgProgress->Destroy();\r
-        m_dlgProgress = (wxProgressDialog *)NULL;\r
-\r
-        // the dialog is aborted because the event came from another thread, so\r
-        // we may need to wake up the main event loop for the dialog to be\r
-        // really closed\r
-        wxWakeUpIdle();\r
-    }\r
-    else\r
-    {\r
-        if ( !m_dlgProgress->Update(n) )\r
-        {\r
-            wxCriticalSectionLocker lock(m_critsectWork);\r
-\r
-            m_cancelled = true;\r
-        }\r
-    }\r
-#endif\r
-}\r
-\r
-\r
-// Note that OPJFRAME_FILEOPEN and OPJFRAME_HELPABOUT commands get passed\r
-// to the parent window for processing, so no need to\r
-// duplicate event handlers here.\r
-\r
-BEGIN_EVENT_TABLE(OPJChildFrame, wxMDIChildFrame)\r
-  /*EVT_MENU(SASHTEST_CHILD_QUIT, OPJChildFrame::OnQuit)*/\r
-  EVT_CLOSE(OPJChildFrame::OnClose)\r
-  EVT_SET_FOCUS(OPJChildFrame::OnGotFocus)\r
-  EVT_KILL_FOCUS(OPJChildFrame::OnLostFocus)\r
-END_EVENT_TABLE()\r
-\r
-OPJChildFrame::OPJChildFrame(OPJFrame *parent, wxFileName fname, int winnumber, const wxString& title, const wxPoint& pos, const wxSize& size,\r
-const long style):\r
-  wxMDIChildFrame(parent, wxID_ANY, title, pos, size, style)\r
-{\r
-       m_frame = (OPJFrame  *) parent;\r
-       m_canvas = NULL;\r
-       //my_children.Append(this);\r
-       m_fname = fname;\r
-       m_winnumber = winnumber;\r
-       SetTitle(wxString::Format(_T("%d: "), m_winnumber) + m_fname.GetFullName());\r
-\r
-         // Give it an icon (this is ignored in MDI mode: uses resources)\r
-#ifdef __WXMSW__\r
-       SetIcon(wxIcon(wxT("OPJChild16")));\r
-#endif\r
-\r
-       // Give it a status line\r
-       /*CreateStatusBar();*/\r
-\r
-       int width, height;\r
-       GetClientSize(&width, &height);\r
-\r
-       OPJCanvas *canvas = new OPJCanvas(fname, this, wxPoint(0, 0), wxSize(width, height));\r
-#if USE_PENCIL_ON_CANVAS\r
-       canvas->SetCursor(wxCursor(wxCURSOR_PENCIL));\r
-#endif\r
-       m_canvas = canvas;\r
-\r
-       // Give it scrollbars\r
-       canvas->SetScrollbars(20, 20, 5, 5);\r
-\r
-       Show(true);\r
-       Maximize(true);\r
-\r
-       /*wxLogError(wxString::Format(wxT("Created tree %d (0x%x)"), m_winnumber, m_frame->m_treehash[m_winnumber]));*/\r
-\r
-}\r
-\r
-OPJChildFrame::~OPJChildFrame(void)\r
-{\r
-  //my_children.DeleteObject(this);\r
-}\r
-\r
-\r
-void OPJChildFrame::OnClose(wxCloseEvent& event)\r
-{\r
-       for (unsigned int p = 0; p < m_frame->m_bookCtrl->GetPageCount(); p++) {\r
-               if (m_frame->m_bookCtrl->GetPageText(p) == wxString::Format(wxT("%u"), m_winnumber)) {\r
-                       m_frame->m_bookCtrl->DeletePage(p);\r
-                       break;\r
-               }\r
-       }\r
-       Destroy();\r
-\r
-       wxLogMessage(wxT("Closed: %d"), m_winnumber);\r
-}\r
-\r
-void OPJChildFrame::OnActivate(wxActivateEvent& event)\r
-{\r
-  /*if (event.GetActive() && m_canvas)\r
-    m_canvas->SetFocus();*/\r
-}\r
-\r
-void OPJChildFrame::OnGotFocus(wxFocusEvent& event)\r
-{\r
-       // we need to check if the notebook is being destroyed or not\r
-       if (!m_frame->m_bookCtrl)\r
-               return;\r
-\r
-       for (unsigned int p = 0; p < m_frame->m_bookCtrl->GetPageCount(); p++) {\r
-\r
-               if (m_frame->m_bookCtrl->GetPageText(p) == wxString::Format(wxT("%u"), m_winnumber)) {\r
-                       m_frame->m_bookCtrl->ChangeSelection(p);\r
-                       break;\r
-               }\r
-\r
-       }\r
-\r
-       //wxLogMessage(wxT("Got focus: %d (%x)"), m_winnumber, event.GetWindow());\r
-}\r
-\r
-void OPJChildFrame::OnLostFocus(wxFocusEvent& event)\r
-{\r
-       //wxLogMessage(wxT("Lost focus: %d (%x)"), m_winnumber, event.GetWindow());\r
-}\r
-\r
-\r
-////////////////////////////////\r
-// drag and drop \r
-////////////////////////////////\r
-\r
-bool OPJDnDFile::OnDropFiles(wxCoord, wxCoord, const wxArrayString& filenames)\r
-{\r
-    /*size_t nFiles = filenames.GetCount();\r
-    wxString str;\r
-    str.Printf( _T("%d files dropped\n"), (int)nFiles);\r
-    for ( size_t n = 0; n < nFiles; n++ ) {\r
-        str << filenames[n] << wxT("\n");\r
-    }\r
-    wxLogMessage(str);*/\r
-       m_pOwner->OpenFiles(filenames, filenames);\r
-\r
-    return true;\r
-}\r
-\r
diff --git a/OPJViewer/source/OPJViewer.h b/OPJViewer/source/OPJViewer.h
deleted file mode 100644 (file)
index 3574dac..0000000
+++ /dev/null
@@ -1,811 +0,0 @@
-/*\r
- * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        sashtest.h\r
-// Purpose:     Layout window/sash sample\r
-// Author:      Julian Smart\r
-// Modified by:\r
-// Created:     04/01/98\r
-// RCS-ID:      $Id: sashtest.h,v 1.5 2005/06/02 12:04:24 JS Exp $\r
-// Copyright:   (c) Julian Smart\r
-// Licence:     wxWindows license\r
-/////////////////////////////////////////////////////////////////////////////\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        treectrl.h\r
-// Purpose:     wxTreeCtrl sample\r
-// Author:      Julian Smart\r
-// Modified by:\r
-// Created:     04/01/98\r
-// RCS-ID:      $Id: treetest.h,v 1.50 2006/11/04 11:26:51 VZ Exp $\r
-// Copyright:   (c) Julian Smart\r
-// Licence:     wxWindows license\r
-/////////////////////////////////////////////////////////////////////////////\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        dialogs.h\r
-// Purpose:     Common dialogs demo\r
-// Author:      Julian Smart\r
-// Modified by: ABX (2004) - adjustementd for conditional building\r
-// Created:     04/01/98\r
-// RCS-ID:      $Id: dialogs.h,v 1.50 2006/10/08 14:12:59 VZ Exp $\r
-// Copyright:   (c) Julian Smart\r
-// Licence:     wxWindows license\r
-/////////////////////////////////////////////////////////////////////////////\r
-\r
-#ifndef __OPJ_VIEWER_H__\r
-#define __OPJ_VIEWER_H__\r
-\r
-// For compilers that support precompilation, includes "wx/wx.h".\r
-#include "wx/wxprec.h"\r
-\r
-#ifdef __BORLANDC__\r
-#pragma hdrstop\r
-#endif\r
-\r
-#ifndef WX_PRECOMP\r
-#include "wx/wx.h"\r
-#include "wx/mdi.h"\r
-#endif\r
-\r
-#include "wx/toolbar.h"\r
-#include "wx/laywin.h"\r
-#include "wx/treectrl.h"\r
-\r
-#include "icon1.xpm"\r
-#include "icon2.xpm"\r
-#include "icon3.xpm"\r
-#include "icon4.xpm"\r
-#include "icon5.xpm"\r
-\r
-#include "wx/filedlg.h"\r
-#include "wx/toolbar.h"\r
-#include <wx/filename.h>\r
-#include <wx/busyinfo.h>\r
-#include <wx/cmdline.h>\r
-#include <wx/file.h>\r
-#include "wx/notebook.h"\r
-#include <wx/numdlg.h>\r
-\r
-#include "wx/propdlg.h"\r
-#include "wx/spinctrl.h"\r
-\r
-#include <wx/dnd.h>\r
-#include "wx/wxhtml.h"\r
-#include "wx/statline.h"\r
-#include <wx/fs_mem.h>\r
-\r
-#include <wx/imaglist.h>\r
-\r
-#include "wx/toolbar.h"\r
-#include "wx/artprov.h"\r
-\r
-#include "libopenjpeg/openjpeg.h"\r
-\r
-//#include "imagj2k.h"\r
-//#include "imagjp2.h"\r
-//#include "imagmj2.h"\r
-#include "imagjpeg2000.h"\r
-#ifdef USE_MXF\r
-#include "imagmxf.h"\r
-#endif // USE_MXF\r
-\r
-#ifdef __WXMSW__\r
-typedef unsigned __int64 int8byte;\r
-#endif // __WXMSW__\r
-\r
-#ifdef __WXGTK__\r
-typedef unsigned long long int8byte;\r
-#endif // __WXGTK__\r
-\r
-#define USE_GENERIC_TREECTRL 0\r
-#define USE_PENCIL_ON_CANVAS 0\r
-\r
-#if USE_GENERIC_TREECTRL\r
-#include "wx/generic/treectlg.h"\r
-#ifndef wxTreeCtrl\r
-#define wxTreeCtrl wxGenericTreeCtrl\r
-#define sm_classwxTreeCtrl sm_classwxGenericTreeCtrl\r
-#endif\r
-#endif\r
-\r
-#define OPJ_APPLICATION             wxT("OPJViewer")\r
-#define OPJ_APPLICATION_NAME           wxT("OpenJPEG Viewer")\r
-#define OPJ_APPLICATION_VERSION                wxT("0.4 beta")\r
-#define OPJ_APPLICATION_TITLEBAR       OPJ_APPLICATION_NAME wxT(" ") OPJ_APPLICATION_VERSION\r
-#define OPJ_APPLICATION_COPYRIGHT      wxT("(C) 2007-2008, Giuseppe Baruffa")\r
-#define OPJ_APPLICATION_VENDOR      wxT("OpenJPEG")\r
-\r
-#ifdef __WXMSW__\r
-#define OPJ_APPLICATION_PLATFORM    wxT("Windows")\r
-#endif\r
-\r
-#ifdef __WXGTK__\r
-#define OPJ_APPLICATION_PLATFORM    wxT("Linux")\r
-#endif\r
-\r
-#define OPJ_FRAME_WIDTH   800\r
-#define OPJ_FRAME_HEIGHT  600\r
-\r
-#define OPJ_BROWSER_WIDTH 300\r
-#define OPJ_PEEKER_HEIGHT 130\r
-\r
-#define OPJ_CANVAS_BORDER 10\r
-#define OPJ_CANVAS_COLOUR *wxWHITE\r
-\r
-\r
-\r
-#ifdef USE_JPWL\r
-\r
-//#define MYJPWL_MAX_NO_TILESPECS JPWL_MAX_NO_TILESPECS\r
-#define MYJPWL_MAX_NO_TILESPECS 4\r
-\r
-#endif // USE_JPWL\r
-\r
-\r
-class OPJDecoThread;\r
-class OPJEncoThread;\r
-class OPJParseThread;\r
-WX_DEFINE_ARRAY_PTR(wxThread *, wxArrayThread);\r
-class OPJChildFrame;\r
-\r
-//////////////////////////////////\r
-// this is our main application //\r
-//////////////////////////////////\r
-class OPJViewerApp: public wxApp\r
-{\r
-       // public methods and variables\r
-       public:\r
-\r
-               // class constructor\r
-               OPJViewerApp() { m_showImages = true; m_showButtons = false; }\r
-\r
-               // other methods\r
-               bool OnInit(void);\r
-               int OnExit(void);\r
-               void SetShowImages(bool show) { m_showImages = show; }\r
-               bool ShowImages() const { return m_showImages; }\r
-               void ShowCmdLine(const wxCmdLineParser& parser);\r
-\r
-               // all the threads currently alive - as soon as the thread terminates, it's\r
-               // removed from the array\r
-               wxArrayThread m_deco_threads, m_parse_threads, m_enco_threads;\r
-\r
-               // crit section protects access to all of the arrays below\r
-               wxCriticalSection m_deco_critsect, m_parse_critsect, m_enco_critsect;\r
-\r
-               // semaphore used to wait for the threads to exit, see OPJFrame::OnQuit()\r
-               wxSemaphore m_deco_semAllDone, m_parse_semAllDone, m_enco_semAllDone;\r
-\r
-               // the last exiting thread should post to m_semAllDone if this is true\r
-               // (protected by the same m_critsect)\r
-               bool m_deco_waitingUntilAllDone, m_parse_waitingUntilAllDone, m_enco_waitingUntilAllDone;\r
-\r
-               // the list of all filenames written in the command line\r
-               wxArrayString m_filelist;\r
-\r
-               // displaying engine parameters\r
-               int m_resizemethod;\r
-\r
-               // decoding engine parameters\r
-               bool m_enabledeco, m_enableparse;\r
-               int m_reducefactor, m_qualitylayers, m_components, m_framenum;\r
-#ifdef USE_JPWL\r
-               bool m_enablejpwl, m_enablejpwle;\r
-               int m_expcomps, m_maxtiles;\r
-               int m_framewidth, m_frameheight;\r
-#endif // USE_JPWL\r
-\r
-               // encoding engine parameters\r
-               wxString m_subsampling, m_origin, m_rates, m_comment, m_index, m_quality;\r
-               wxString m_cbsize, m_prsize, m_tsize, m_torigin, m_poc;\r
-               bool m_enablecomm, m_enableidx, m_multicomp, m_irreversible, m_enablesop, m_enableeph;\r
-               bool m_enablebypass, m_enablereset, m_enablerestart, m_enablevsc, m_enableerterm;\r
-               bool m_enablesegmark, m_enablepoc;\r
-               bool m_enablequality;\r
-               int m_resolutions, m_progression;\r
-#ifdef USE_JPWL\r
-               int m_hprotsel[MYJPWL_MAX_NO_TILESPECS], m_pprotsel[MYJPWL_MAX_NO_TILESPECS];\r
-               int m_htileval[MYJPWL_MAX_NO_TILESPECS], m_ptileval[MYJPWL_MAX_NO_TILESPECS],\r
-                       m_ppackval[MYJPWL_MAX_NO_TILESPECS];\r
-               int m_sensisel[MYJPWL_MAX_NO_TILESPECS], m_stileval[MYJPWL_MAX_NO_TILESPECS];\r
-#endif // USE_JPWL\r
-\r
-               // some layout settings\r
-               bool m_showtoolbar, m_showbrowser, m_showpeeker;\r
-               int m_browserwidth, m_peekerheight;\r
-\r
-               // application configuration\r
-               wxConfig *OPJconfig; \r
-\r
-       // private methods and variables\r
-       private:\r
-               bool m_showImages, m_showButtons;\r
-\r
-};\r
-\r
-DECLARE_APP(OPJViewerApp)\r
-\r
-///////////////////////////////////////////\r
-// this canvas is used to draw the image //\r
-///////////////////////////////////////////\r
-class OPJCanvas: public wxScrolledWindow\r
-{\r
-       // public methods and variables\r
-       public:\r
-\r
-               // class constructor\r
-               OPJCanvas(wxFileName fname, wxWindow *parent, const wxPoint& pos, const wxSize& size);\r
-\r
-               virtual void OnDraw(wxDC& dc);\r
-               void OnEvent(wxMouseEvent& event);\r
-               void WriteText(const wxString& text) {\r
-#ifndef __WXGTK__ \r
-                       wxMutexGuiEnter();\r
-#endif //__WXGTK__\r
-                       wxLogMessage(text);\r
-#ifndef __WXGTK__ \r
-                       wxMutexGuiLeave();\r
-#endif //__WXGTK__\r
-               }\r
-\r
-               void OnThreadSignal(wxCommandEvent& event);\r
-\r
-               OPJDecoThread *CreateDecoThread(void);\r
-               OPJEncoThread *CreateEncoThread(void);\r
-\r
-\r
-               OPJChildFrame *m_childframe;\r
-\r
-               wxBitmap  m_image, m_image100;\r
-               wxFileName m_fname, m_savename;\r
-               long m_zooml;\r
-\r
-       DECLARE_EVENT_TABLE()\r
-};\r
-\r
-///////////////////////////////////////////////////\r
-// the data associated to each tree leaf or node //\r
-///////////////////////////////////////////////////\r
-class OPJMarkerData : public wxTreeItemData\r
-{\r
-       // public methods and variables\r
-       public:\r
-\r
-               // class constructor\r
-               OPJMarkerData(const wxString& desc, const wxString& fname = wxT(""), wxFileOffset start = 0, wxFileOffset length = 0) : m_desc(desc), m_filestring(fname) { m_start = start; m_length = length; }\r
-\r
-               void ShowInfo(wxTreeCtrl *tree);\r
-               const wxChar *GetDesc1() const { return m_desc.c_str(); }\r
-               const wxChar *GetDesc2() const { return m_filestring.c_str(); }\r
-               wxFileOffset m_start, m_length;\r
-               wxString m_desc;\r
-\r
-       // private methods and variables\r
-       private:\r
-               wxString m_filestring;\r
-};\r
-\r
-\r
-class OPJMarkerTree : public wxTreeCtrl\r
-{\r
-public:\r
-    enum\r
-    {\r
-        TreeCtrlIcon_File,\r
-        TreeCtrlIcon_FileSelected,\r
-        TreeCtrlIcon_Folder,\r
-        TreeCtrlIcon_FolderSelected,\r
-        TreeCtrlIcon_FolderOpened\r
-    };\r
-\r
-    OPJMarkerTree() { };\r
-    OPJMarkerTree(wxWindow *parent, OPJChildFrame *subframe, wxFileName fname, wxString name, const wxWindowID id,\r
-               const wxPoint& pos, const wxSize& size,\r
-               long style);\r
-    virtual ~OPJMarkerTree(){};\r
-       OPJParseThread *CreateParseThread(wxTreeItemId parentid = 0x00, OPJChildFrame *subframe = NULL);\r
-    void WriteText(const wxString& text) { wxMutexGuiEnter(); wxLogMessage(text); wxMutexGuiLeave(); }\r
-\r
-       wxFileName m_fname;\r
-       wxTextCtrl *m_peektextCtrl;\r
-       OPJChildFrame *m_childframe;\r
-\r
-    /*void OnBeginDrag(wxTreeEvent& event);\r
-    void OnBeginRDrag(wxTreeEvent& event);\r
-    void OnEndDrag(wxTreeEvent& event);*/\r
-    /*void OnBeginLabelEdit(wxTreeEvent& event);\r
-    void OnEndLabelEdit(wxTreeEvent& event);*/\r
-    /*void OnDeleteItem(wxTreeEvent& event);*/\r
-    /*void OnContextMenu(wxContextMenuEvent& event);*/\r
-    void OnItemMenu(wxTreeEvent& event);\r
-    /*void OnGetInfo(wxTreeEvent& event);\r
-    void OnSetInfo(wxTreeEvent& event);*/\r
-    /*void OnItemExpanded(wxTreeEvent& event);*/\r
-    void OnItemExpanding(wxTreeEvent& event);\r
-    /*void OnItemCollapsed(wxTreeEvent& event);\r
-    void OnItemCollapsing(wxTreeEvent& event);*/\r
-    void OnSelChanged(wxTreeEvent& event);\r
-    /*void OnSelChanging(wxTreeEvent& event);*/\r
-    /*void OnTreeKeyDown(wxTreeEvent& event);*/\r
-    /*void OnItemActivated(wxTreeEvent& event);*/\r
-    /*void OnItemRClick(wxTreeEvent& event);*/\r
-    /*void OnRMouseDown(wxMouseEvent& event);\r
-    void OnRMouseUp(wxMouseEvent& event);\r
-    void OnRMouseDClick(wxMouseEvent& event);*/\r
-    /*void GetItemsRecursively(const wxTreeItemId& idParent,\r
-                             wxTreeItemIdValue cookie = 0);*/\r
-\r
-    void CreateImageList(int size = 16);\r
-    void CreateButtonsImageList(int size = 11);\r
-\r
-    /*void AddTestItemsToTree(size_t numChildren, size_t depth);*/\r
-    /*void DoSortChildren(const wxTreeItemId& item, bool reverse = false)\r
-        { m_reverseSort = reverse; wxTreeCtrl::SortChildren(item); }*/\r
-    /*void DoEnsureVisible() { if (m_lastItem.IsOk()) EnsureVisible(m_lastItem); }*/\r
-    /*void DoToggleIcon(const wxTreeItemId& item);*/\r
-    /*void ShowMenu(wxTreeItemId id, const wxPoint& pt);*/\r
-\r
-    int ImageSize(void) const { return m_imageSize; }\r
-\r
-    void SetLastItem(wxTreeItemId id) { m_lastItem = id; }\r
-\r
-protected:\r
-    /*virtual int OnCompareItems(const wxTreeItemId& i1, const wxTreeItemId& i2);*/\r
-\r
-    // is this the test item which we use in several event handlers?\r
-    /*bool IsTestItem(const wxTreeItemId& item)\r
-    {\r
-        // the test item is the first child folder\r
-        return GetItemParent(item) == GetRootItem() && !GetPrevSibling(item);\r
-    }*/\r
-\r
-private:\r
-    /*void AddItemsRecursively(const wxTreeItemId& idParent,\r
-                             size_t nChildren,\r
-                             size_t depth,\r
-                             size_t folder);*/\r
-\r
-    void LogEvent(const wxChar *name, const wxTreeEvent& event);\r
-\r
-    int          m_imageSize;               // current size of images\r
-    bool         m_reverseSort;             // flag for OnCompareItems\r
-    wxTreeItemId m_lastItem,                // for OnEnsureVisible()\r
-                 m_draggedItem;             // item being dragged right now\r
-\r
-    // NB: due to an ugly wxMSW hack you _must_ use DECLARE_DYNAMIC_CLASS()\r
-    //     if you want your overloaded OnCompareItems() to be called.\r
-    //     OTOH, if you don't want it you may omit the next line - this will\r
-    //     make default (alphabetical) sorting much faster under wxMSW.\r
-    DECLARE_DYNAMIC_CLASS(OPJMarkerTree)\r
-    DECLARE_EVENT_TABLE()\r
-};\r
-\r
-// this hash map stores all the trees of currently opened images, with an integer key\r
-WX_DECLARE_HASH_MAP(int, OPJMarkerTree*, wxIntegerHash, wxIntegerEqual, OPJMarkerTreeHash);\r
-\r
-// this hash map stores all the children of currently opened images, with an integer key\r
-WX_DECLARE_HASH_MAP(int, OPJChildFrame*, wxIntegerHash, wxIntegerEqual, OPJChildFrameHash);\r
-\r
-// Define a new frame\r
-class OPJFrame: public wxMDIParentFrame\r
-{\r
-  public:\r
-\r
-    OPJFrame(wxWindow *parent, const wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, const long style);\r
-\r
-    ~OPJFrame(void);\r
-       void OnSize(wxSizeEvent& WXUNUSED(event));\r
-    void OnAbout(wxCommandEvent& WXUNUSED(event));\r
-    void OnFileOpen(wxCommandEvent& WXUNUSED(event));\r
-    void OnFileSaveAs(wxCommandEvent& WXUNUSED(event));\r
-    void OnMemoryOpen(wxCommandEvent& WXUNUSED(event));\r
-    void OnQuit(wxCommandEvent& WXUNUSED(event));\r
-    void OnClose(wxCommandEvent& WXUNUSED(event));\r
-    void OnZoom(wxCommandEvent& WXUNUSED(event));\r
-       void OnFit(wxCommandEvent& event);\r
-       void OnToggleBrowser(wxCommandEvent& WXUNUSED(event));\r
-       void OnTogglePeeker(wxCommandEvent& WXUNUSED(event));\r
-       void OnToggleToolbar(wxCommandEvent& WXUNUSED(event));\r
-       void OnReload(wxCommandEvent& event);\r
-       void OnPrevFrame(wxCommandEvent& event);\r
-       void OnHomeFrame(wxCommandEvent& event);\r
-       void OnNextFrame(wxCommandEvent& event);\r
-       void OnLessLayers(wxCommandEvent& event);\r
-       void OnAllLayers(wxCommandEvent& event);\r
-       void OnMoreLayers(wxCommandEvent& event);\r
-       void OnLessRes(wxCommandEvent& event);\r
-       void OnFullRes(wxCommandEvent& event);\r
-       void OnMoreRes(wxCommandEvent& event);\r
-       void OnPrevComp(wxCommandEvent& event);\r
-       void OnAllComps(wxCommandEvent& event);\r
-       void OnNextComp(wxCommandEvent& event);\r
-       void OnSetsEnco(wxCommandEvent& event);\r
-       void OnSetsDeco(wxCommandEvent& event);\r
-       void OnSashDrag(wxSashEvent& event);\r
-       void OpenFiles(wxArrayString paths, wxArrayString filenames);\r
-       void SaveFile(wxArrayString paths, wxArrayString filenames);\r
-       void OnNotebook(wxNotebookEvent& event);\r
-       void Rescale(int scale, OPJChildFrame *child);\r
-       void OnThreadLogmsg(wxCommandEvent& event);\r
-\r
-       OPJMarkerTreeHash m_treehash;\r
-       OPJChildFrameHash m_childhash;\r
-    wxSashLayoutWindow* markerTreeWindow;\r
-    wxSashLayoutWindow* loggingWindow;\r
-       wxToolBar* tool_bar;\r
-    void Resize(int number);\r
-       wxNotebook *m_bookCtrl;\r
-       wxNotebook *m_bookCtrlbottom;\r
-    wxTextCtrl *m_textCtrlbrowse;\r
-\r
-  private:\r
-    void TogStyle(int id, long flag);\r
-\r
-    void DoSort(bool reverse = false);\r
-\r
-    wxPanel *m_panel;\r
-    wxTextCtrl *m_textCtrl;\r
-\r
-    void DoSetBold(bool bold = true);\r
-\r
-protected:\r
-    wxSashLayoutWindow* m_topWindow;\r
-    wxSashLayoutWindow* m_leftWindow2;\r
-\r
-DECLARE_EVENT_TABLE()\r
-};\r
-\r
-class OPJChildFrame: public wxMDIChildFrame\r
-{\r
-  public:\r
-    OPJCanvas *m_canvas;\r
-    OPJChildFrame(OPJFrame *parent, wxFileName fname, int winnumber, const wxString& title, const wxPoint& pos, const wxSize& size, const long style);\r
-    ~OPJChildFrame(void);\r
-    void OnActivate(wxActivateEvent& event);\r
-       /*void OnQuit(wxCommandEvent& WXUNUSED(event));*/\r
-       void OnClose(wxCloseEvent& event);\r
-       void OnGotFocus(wxFocusEvent& event);\r
-       void OnLostFocus(wxFocusEvent& event);\r
-    OPJFrame *m_frame;\r
-       wxFileName m_fname;\r
-       int m_winnumber;\r
-\r
-       unsigned long  m_twidth, m_theight, m_tx, m_ty;\r
-\r
-       DECLARE_EVENT_TABLE()\r
-};\r
-\r
-// frame and main menu ids\r
-enum {\r
-       OPJFRAME_FILEEXIT = wxID_EXIT,\r
-       OPJFRAME_HELPABOUT = wxID_ABOUT,\r
-       OPJFRAME_FILEOPEN,\r
-       OPJFRAME_MEMORYOPEN,\r
-       OPJFRAME_FILESAVEAS,\r
-       OPJFRAME_FILETOGGLEB,\r
-       OPJFRAME_FILETOGGLEP,\r
-       OPJFRAME_FILETOGGLET,\r
-       OPJFRAME_VIEWZOOM,\r
-       OPJFRAME_VIEWFIT,\r
-       OPJFRAME_VIEWRELOAD,\r
-       OPJFRAME_VIEWPREVFRAME,\r
-       OPJFRAME_VIEWHOMEFRAME,\r
-       OPJFRAME_VIEWNEXTFRAME,\r
-       OPJFRAME_VIEWLESSLAYERS,\r
-       OPJFRAME_VIEWALLLAYERS,\r
-       OPJFRAME_VIEWMORELAYERS,\r
-       OPJFRAME_VIEWLESSRES,\r
-       OPJFRAME_VIEWFULLRES,\r
-       OPJFRAME_VIEWMORERES,\r
-       OPJFRAME_VIEWPREVCOMP,\r
-       OPJFRAME_VIEWALLCOMPS,\r
-       OPJFRAME_VIEWNEXTCOMP,\r
-       OPJFRAME_FILECLOSE,\r
-       OPJFRAME_SETSENCO,\r
-       OPJFRAME_SETSDECO,\r
-\r
-       OPJFRAME_BROWSEWIN = 10000,\r
-       OPJFRAME_LOGWIN,\r
-       OPJFRAME_TOOLBAR,\r
-\r
-       OPJFRAME_THREADLOGMSG,\r
-       OPJCANVAS_THREADSIGNAL\r
-};\r
-\r
-\r
-// menu and control ids\r
-enum\r
-{\r
-    TreeTest_Quit = wxID_EXIT,\r
-    TreeTest_About = wxID_ABOUT,\r
-    TreeTest_TogButtons = wxID_HIGHEST,\r
-    TreeTest_TogTwist,\r
-    TreeTest_TogLines,\r
-    TreeTest_TogEdit,\r
-    TreeTest_TogHideRoot,\r
-    TreeTest_TogRootLines,\r
-    TreeTest_TogBorder,\r
-    TreeTest_TogFullHighlight,\r
-    TreeTest_SetFgColour,\r
-    TreeTest_SetBgColour,\r
-    TreeTest_ResetStyle,\r
-    TreeTest_Highlight,\r
-    TreeTest_Dump,\r
-    TreeTest_DumpSelected,\r
-    TreeTest_Count,\r
-    TreeTest_CountRec,\r
-    TreeTest_Sort,\r
-    TreeTest_SortRev,\r
-    TreeTest_SetBold,\r
-    TreeTest_ClearBold,\r
-    TreeTest_Rename,\r
-    TreeTest_Delete,\r
-    TreeTest_DeleteChildren,\r
-    TreeTest_DeleteAll,\r
-    TreeTest_Recreate,\r
-    TreeTest_ToggleImages,\r
-    TreeTest_ToggleButtons,\r
-    TreeTest_SetImageSize,\r
-    TreeTest_ToggleSel,\r
-    TreeTest_CollapseAndReset,\r
-    TreeTest_EnsureVisible,\r
-    TreeTest_AddItem,\r
-    TreeTest_InsertItem,\r
-    TreeTest_IncIndent,\r
-    TreeTest_DecIndent,\r
-    TreeTest_IncSpacing,\r
-    TreeTest_DecSpacing,\r
-    TreeTest_ToggleIcon,\r
-    TreeTest_Select,\r
-    TreeTest_Unselect,\r
-    TreeTest_SelectRoot,\r
-    TreeTest_Ctrl = 1000,\r
-       BOTTOM_NOTEBOOK_ID,\r
-       LEFT_NOTEBOOK_ID\r
-};\r
-\r
-class OPJEncoThread : public wxThread\r
-{\r
-public:\r
-    OPJEncoThread(OPJCanvas *canvas);\r
-\r
-    // thread execution starts here\r
-    virtual void *Entry();\r
-\r
-    // called when the thread exits - whether it terminates normally or is\r
-    // stopped with Delete() (but not when it is Kill()ed!)\r
-    virtual void OnExit();\r
-\r
-    // write something to the text control\r
-    void WriteText(const wxString& text);\r
-\r
-public:\r
-    unsigned m_count;\r
-    OPJCanvas *m_canvas;\r
-};\r
-\r
-class OPJDecoThread : public wxThread\r
-{\r
-public:\r
-    OPJDecoThread(OPJCanvas *canvas);\r
-\r
-    // thread execution starts here\r
-    virtual void *Entry();\r
-\r
-    // called when the thread exits - whether it terminates normally or is\r
-    // stopped with Delete() (but not when it is Kill()ed!)\r
-    virtual void OnExit();\r
-\r
-    // write something to the text control\r
-    void WriteText(const wxString& text);\r
-\r
-public:\r
-    unsigned m_count;\r
-    OPJCanvas *m_canvas;\r
-};\r
-\r
-class OPJParseThread : public wxThread\r
-{\r
-public:\r
-    OPJParseThread(OPJMarkerTree *tree, wxTreeItemId parentid = 0x00);\r
-\r
-    // thread execution starts here\r
-    virtual void *Entry();\r
-\r
-    // called when the thread exits - whether it terminates normally or is\r
-    // stopped with Delete() (but not when it is Kill()ed!)\r
-    virtual void OnExit();\r
-\r
-    // write something to the text control\r
-    void WriteText(const wxString& text);\r
-       void LoadFile(wxFileName fname);\r
-       void ParseJ2KFile(wxFile *m_file, wxFileOffset offset, wxFileOffset length, wxTreeItemId parentid);\r
-       void ParseJP2File(wxFile *fileid, wxFileOffset filepoint, wxFileOffset filelimit, wxTreeItemId parentid);\r
-\r
-    unsigned m_count;\r
-    OPJMarkerTree *m_tree;\r
-       wxTreeItemId m_parentid;\r
-\r
-private:\r
-       int jpeg2000parse(wxFile *fileid, wxFileOffset filepoint, wxFileOffset filelimit,\r
-                       wxTreeItemId parentid, int level, char *scansign, unsigned long int *scanpoint);\r
-       int box_handler_function(int boxtype, wxFile *fileid, wxFileOffset filepoint, wxFileOffset filelimit,\r
-                       wxTreeItemId parentid, int level, char *scansign, unsigned long int *scanpoint);\r
-\r
-};\r
-\r
-\r
-// Drag and drop files target\r
-class OPJDnDFile: public wxFileDropTarget\r
-{\r
-public:\r
-    OPJDnDFile(OPJFrame *pOwner) { m_pOwner = pOwner; }\r
-    virtual bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames);\r
-\r
-private:\r
-    OPJFrame *m_pOwner;\r
-};\r
-\r
-\r
-\r
-// Property sheet dialog: encoder\r
-class OPJEncoderDialog: public wxPropertySheetDialog\r
-{\r
-DECLARE_CLASS(OPJEncoderDialog)\r
-public:\r
-    OPJEncoderDialog(wxWindow* parent, int dialogType);\r
-    ~OPJEncoderDialog();\r
-\r
-       wxBookCtrlBase* m_settingsNotebook;\r
-\r
-    wxPanel* CreateMainSettingsPage(wxWindow* parent);\r
-    wxPanel* CreatePart1_1SettingsPage(wxWindow* parent);\r
-    wxPanel* CreatePart1_2SettingsPage(wxWindow* parent);\r
-/*    wxPanel* CreatePart3SettingsPage(wxWindow* parent);*/\r
-       void OnEnableComm(wxCommandEvent& event);\r
-       void OnEnableIdx(wxCommandEvent& event);\r
-       void OnEnablePoc(wxCommandEvent& event);\r
-       void OnRadioQualityRate(wxCommandEvent& event);\r
-#ifdef USE_JPWL\r
-       void OnEnableJPWL(wxCommandEvent& event);\r
-       wxPanel* CreatePart11SettingsPage(wxWindow* parent);\r
-       /*wxCheckBox *m_enablejpwlCheck;*/\r
-       wxChoice *m_hprotChoice[MYJPWL_MAX_NO_TILESPECS];\r
-       wxSpinCtrl *m_htileCtrl[MYJPWL_MAX_NO_TILESPECS];\r
-       wxChoice *m_pprotChoice[MYJPWL_MAX_NO_TILESPECS];\r
-       wxSpinCtrl *m_ptileCtrl[MYJPWL_MAX_NO_TILESPECS];\r
-       wxSpinCtrl *m_ppackCtrl[MYJPWL_MAX_NO_TILESPECS];\r
-       wxChoice *m_sensiChoice[MYJPWL_MAX_NO_TILESPECS];\r
-       wxSpinCtrl *m_stileCtrl[MYJPWL_MAX_NO_TILESPECS];\r
-       void OnHprotSelect(wxCommandEvent& event);\r
-       void OnPprotSelect(wxCommandEvent& event);\r
-       void OnSensiSelect(wxCommandEvent& event);\r
-#endif // USE_JPWL\r
-\r
-       wxTextCtrl *m_subsamplingCtrl, *m_originCtrl, *m_rateCtrl, *m_commentCtrl;\r
-       wxRadioButton *m_rateRadio, *m_qualityRadio;\r
-       wxTextCtrl *m_indexCtrl, *m_qualityCtrl, *m_cbsizeCtrl, *m_prsizeCtrl, *m_pocCtrl;\r
-       wxTextCtrl *m_tsizeCtrl, *m_toriginCtrl;\r
-       wxRadioBox *progressionBox;\r
-       wxCheckBox *m_enablecommCheck, *m_enableidxCheck, *m_mctCheck, *m_irrevCheck;\r
-       wxCheckBox *m_sopCheck, *m_ephCheck, *m_enablebypassCheck, *m_enableresetCheck,\r
-               *m_enablerestartCheck, *m_enablevscCheck, *m_enableertermCheck, *m_enablesegmarkCheck;\r
-       wxCheckBox *m_enablepocCheck, *m_enablejpwlCheck;\r
-       wxSpinCtrl *m_resolutionsCtrl;\r
-\r
-protected:\r
-\r
-    enum {\r
-               OPJENCO_ENABLEJPWL = 100,\r
-               OPJENCO_RATEFACTOR,\r
-               OPJENCO_RATERADIO,\r
-               OPJENCO_QUALITYFACTOR,\r
-               OPJENCO_QUALITYRADIO,\r
-               OPJENCO_RESNUMBER,\r
-               OPJENCO_CODEBLOCKSIZE,\r
-               OPJENCO_PRECINCTSIZE,\r
-               OPJENCO_TILESIZE,\r
-               OPJENCO_PROGRESSION,\r
-               OPJENCO_SUBSAMPLING,\r
-               OPJENCO_ENABLESOP,\r
-               OPJENCO_ENABLEEPH,\r
-               OPJENCO_ENABLEBYPASS,\r
-               OPJENCO_ENABLERESET,\r
-               OPJENCO_ENABLERESTART,\r
-               OPJENCO_ENABLEVSC,\r
-               OPJENCO_ENABLEERTERM,\r
-               OPJENCO_ENABLESEGMARK,\r
-               OPJENCO_ENABLEPOC,\r
-               OPJENCO_ROICOMP,\r
-               OPJENCO_ROISHIFT,\r
-               OPJENCO_IMORIG,\r
-               OPJENCO_TILORIG,\r
-               OPJENCO_ENABLEMCT,\r
-               OPJENCO_ENABLEIRREV,\r
-               OPJENCO_ENABLEINDEX,\r
-               OPJENCO_INDEXNAME,\r
-               OPJENCO_POCSPEC,\r
-               OPJENCO_ENABLECOMM,\r
-               OPJENCO_COMMENTTEXT,\r
-               OPJENCO_HPROT,\r
-               OPJENCO_HTILE,\r
-               OPJENCO_PPROT,\r
-               OPJENCO_PTILE,\r
-               OPJENCO_PPACK,\r
-               OPJENCO_SENSI,\r
-               OPJENCO_STILE\r
-    };\r
-\r
-DECLARE_EVENT_TABLE()\r
-};\r
-\r
-// Property sheet dialog: decoder\r
-class OPJDecoderDialog: public wxPropertySheetDialog\r
-{\r
-DECLARE_CLASS(OPJDecoderDialog)\r
-public:\r
-    OPJDecoderDialog(wxWindow* parent, int dialogType);\r
-    ~OPJDecoderDialog();\r
-\r
-       wxBookCtrlBase* m_settingsNotebook;\r
-       wxCheckBox *m_enabledecoCheck, *m_enableparseCheck;\r
-       wxSpinCtrl *m_reduceCtrl, *m_layerCtrl, *m_numcompsCtrl;\r
-       wxRadioBox* m_resizeBox;\r
-\r
-       void OnEnableDeco(wxCommandEvent& event);\r
-\r
-    wxPanel* CreateMainSettingsPage(wxWindow* parent);\r
-    wxPanel* CreatePart1SettingsPage(wxWindow* parent);\r
-    wxPanel* CreatePart3SettingsPage(wxWindow* parent);\r
-#ifdef USE_JPWL\r
-       void OnEnableJPWL(wxCommandEvent& event);\r
-    wxPanel* CreatePart11SettingsPage(wxWindow* parent);\r
-       wxSpinCtrl *m_expcompsCtrl, *m_framenumCtrl, *m_maxtilesCtrl;\r
-       wxCheckBox *m_enablejpwlCheck;\r
-#endif // USE_JPWL\r
-\r
-\r
-protected:\r
-\r
-    enum {\r
-               OPJDECO_RESMETHOD = 100,\r
-               OPJDECO_REDUCEFACTOR,\r
-               OPJDECO_QUALITYLAYERS,\r
-               OPJDECO_NUMCOMPS,\r
-               OPJDECO_ENABLEDECO,\r
-               OPJDECO_ENABLEPARSE,\r
-               OPJDECO_ENABLEJPWL,\r
-               OPJDECO_EXPCOMPS,\r
-               OPJDECO_MAXTILES,\r
-               OPJDECO_FRAMENUM\r
-    };\r
-\r
-DECLARE_EVENT_TABLE()\r
-};\r
-\r
-#endif //__OPJ_VIEWER_H__\r
-\r
-\r
-\r
diff --git a/OPJViewer/source/OPJViewer.ico b/OPJViewer/source/OPJViewer.ico
deleted file mode 100644 (file)
index 931d5e0..0000000
Binary files a/OPJViewer/source/OPJViewer.ico and /dev/null differ
diff --git a/OPJViewer/source/OPJViewer.rc b/OPJViewer/source/OPJViewer.rc
deleted file mode 100644 (file)
index fb5a5de..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-OPJChild16 ICON OPJChild.ico\r
-OPJViewer16 ICON OPJViewer.ico\r
-#include "wx/msw/wx.rc"
\ No newline at end of file
diff --git a/OPJViewer/source/OPJViewer16.xpm b/OPJViewer/source/OPJViewer16.xpm
deleted file mode 100644 (file)
index 27e522b..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-/* XPM */\r
-static char *OPJViewer16[] = {\r
-/* columns rows colors chars-per-pixel */\r
-"16 16 4 1",\r
-"  c black",\r
-". c #800000",\r
-"X c red",\r
-"o c None",\r
-/* pixels */\r
-"oooooooooooooooo",\r
-"ooo.XXXXoooooooo",\r
-"ooXXoo .Xooooooo",\r
-"o..oooo .ooooooo",\r
-"oX.oooo  ooooooo",\r
-"oX.oooo .ooooooo",\r
-"oXXoooo .ooooooo",\r
-"o.XXoo .oooooooo",\r
-"oo.XXXXooooooooo",\r
-"ooooooooo.Xo .oo",\r
-"ooooooooo X. ooo",\r
-"oooooooooo...ooo",\r
-"oooooooooo XXooo",\r
-"oooooooooo .Xooo",\r
-"oooooooooooooooo",\r
-"oooooooooooooooo"\r
-};\r
diff --git a/OPJViewer/source/about_htm.h b/OPJViewer/source/about_htm.h
deleted file mode 100644 (file)
index c39fdc5..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-wxString htmlaboutpage = wxT(\r
-"<html>"\r
-"<body bgcolor=#FFFFFF>"\r
-"<table cellspacing=7 cellpadding=1 border=0 width=100%>"   \r
-"<tr>"\r
-"<td rowspan=3 valign=top align=center width=70>"\r
-"<img src=\"memory:opj_logo.xpm\"><br><br>" \r
-"</td>"\r
-"<td align=center>"\r
-"<font size=+0 color=#000000><b>" \r
-OPJ_APPLICATION " " OPJ_APPLICATION_VERSION \r
-"</b></font><br>"\r
-"<font size=-1 color=#000000><b>A JPEG 2000 image viewer</b></font><br>"  \r
-"<font size=-2 color=#000000><b>" OPJ_APPLICATION_PLATFORM " version</b></font>"  \r
-"</td>"\r
-"</tr>"\r
-"<tr height=3 valign=center>"  \r
-"<td valign=center  bgcolor=#cc3300></td>"   \r
-"</tr>"\r
-"<tr>"\r
-"<td align=justify>"\r
-"<center><font size=+0 color=#000000><a href=\"http://www.openjpeg.org/\">OpenJPEG</a></font></center>"\r
-"<p><font size=-1 color=#000000>The OpenJPEG library is an open-source JPEG 2000 codec written in C language. "\r
-"In addition to the basic codec, various other features are under development.</font></p><br>"\r
-"<font size=-2 color=red>* Build: ")\r
-#include "build.h"\r
-wxT(", " __DATE__ ", " __TIME__ "</font><br>")\r
-wxT("<font size=-2 color=red>* " wxVERSION_STRING "</font><br>")\r
-wxT("<font size=-2 color=red>* OpenJPEG " OPENJPEG_VERSION " (")\r
-#ifdef USE_JPWL\r
-wxT("<font size=-2 color=green>JPWL</font> ")\r
-#endif // USE_JPWL\r
-#ifdef USE_JPSEC\r
-wxT("<font size=-2 color=green>JPSEC</font> ")\r
-#endif // USE_JPSEC\r
-wxT(")</font><br>")\r
-#ifdef USE_MXF\r
-wxT("<font size=-2 color=red>* MXFLib " MXFLIB_VERSION_MAJOR "." MXFLIB_VERSION_MINOR "." MXFLIB_VERSION_TWEAK " (" MXFLIB_VERSION_BUILD ")</font><br>")\r
-#endif // USE_MXF\r
-wxT("</td>"\r
-"</tr>"\r
-"<tr>"\r
-"<td colspan=2 bgcolor=#CC3300 height=3 valign=center></td>" \r
-"</tr>"\r
-"<tr>"\r
-"<td colspan=2>"\r
-"<font size=-2 color=#444444>OpenJPEG is &copy; 2002-2008 <a href=\"http://www.tele.ucl.ac.be/\">TELE</a> - <a href=\"http://www.uclouvain.be/\">Universite' Catholique de Louvain</a></font><br>"\r
-"<font size=-2 color=#444444>OPJViewer is &copy; 2007-2008 <a href=\"http://dsplab.diei.unipg.it/\">DSPLab</a> - <a href=\"http://www.unipg.it/\">Universita' degli studi di Perugia</a></font>"\r
-"</td>"\r
-"</tr>"\r
-"</table>"\r
-"</body>"\r
-"</html>"\r
-);\r
diff --git a/OPJViewer/source/build.h b/OPJViewer/source/build.h
deleted file mode 100644 (file)
index 9858dff..0000000
+++ /dev/null
@@ -1 +0,0 @@
-wxT("491") \r
diff --git a/OPJViewer/source/icon1.xpm b/OPJViewer/source/icon1.xpm
deleted file mode 100644 (file)
index fbc605b..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-/* XPM */
-static char *icon1_xpm[] = {
-/* columns rows colors chars-per-pixel */
-"32 32 41 1",
-"> c #97C4E7",
-"# c #4381AA",
-"d c #FFFFFF",
-"< c #71B2DE",
-"+ c #538BB1",
-"& c #D1E5F5",
-"q c #63B3DE",
-"6 c #F1F4F7",
-"* c #CAE1F3",
-"y c #7AC4E5",
-"= c #C3DDF1",
-"X c #74A1BD",
-"- c #BCD9EF",
-"5 c #619BC4",
-"3 c #E6EAF1",
-"2 c #4B8EBF",
-"o c #6B97B6",
-". c #4B82A8",
-"  c None",
-"w c #54A6D8",
-"1 c #71A8D1",
-", c #85BBE2",
-"t c #EFF6FC",
-"7 c #DEEDF8",
-"@ c #4388B4",
-"a c #F7FBFD",
-"$ c #D7E0E9",
-"r c #FAFCFE",
-"4 c #DAEAF7",
-"e c #E9F3FA",
-"0 c #76BAE2",
-"% c #7FA6C0",
-"s c #FDFDFE",
-"O c #5896BE",
-"p c #B6D5EE",
-"8 c #87ABC3",
-": c #A5CCEA",
-"9 c #E5F0F9",
-"; c #AFD1EC",
-"i c #F4F9FD",
-"u c #8FB0C3",
-/* pixels */
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"        .XXXooOO++@#$           ",
-"        %&*=-;:>>,<123          ",
-"        %4&*=-;:>>,1>56         ",
-"        %74&*=-;:>>1*>56        ",
-"        89700qqqqwq1e*>X        ",
-"        8e974&*=-;:1re*>8       ",
-"        8te974&*=-;11111#       ",
-"        8tty000qqqqqww>,+       ",
-"        uitte974&*=-p:>>+       ",
-"        uaitte974&*=-p:>O       ",
-"        uaayyyy000qqqqp:O       ",
-"        uraaitte974&*=-po       ",
-"        urraaitte974&*=-o       ",
-"        usryyyyyyy000q*=X       ",
-"        ussrraaitte974&*X       ",
-"        udssrraaitte974&X       ",
-"        uddyyyyyyyyyy074%       ",
-"        udddssrraaitte97%       ",
-"        uddddssrraaitte9%       ",
-"        udddddssrraaitte8       ",
-"        uddddddssrraaitt8       ",
-"        uuuuuuuuuuuuuu88u       ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                "
-};
diff --git a/OPJViewer/source/icon2.xpm b/OPJViewer/source/icon2.xpm
deleted file mode 100644 (file)
index 7ae8c92..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/* XPM */
-static char *icon2_xpm[] = {
-/* columns rows colors chars-per-pixel */
-"32 32 15 1",
-". c Black",
-"O c #97C4E7",
-"$ c #63B3DE",
-"@ c #CAE1F3",
-"; c #7AC4E5",
-"* c #74A1BD",
-"+ c #619BC4",
-"o c #4B8EBF",
-"  c None",
-"% c #54A6D8",
-"= c #FAFCFE",
-"& c #E9F3FA",
-"# c #76BAE2",
-"X c #C00000",
-"- c #87ABC3",
-/* pixels */
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"        .............           ",
-"        .XXXXXXXXXX.o.          ",
-"        .XXXXXXXXXX.O+.         ",
-"        .XXXXXXXXXX.@O+.        ",
-"        .XX##$$$$%$.&@O*        ",
-"        .XXXXXXXXXX.=&@O-       ",
-"        .XXXXXXXXXX......       ",
-"        .XX;###$$$$$%%XX.       ",
-"        .XXXXXXXXXXXXXXX.       ",
-"        .XXXXXXXXXXXXXXX.       ",
-"        .XX;;;;###$$$$XX.       ",
-"        .XXXXXXXXXXXXXXX.       ",
-"        .XXXXXXXXXXXXXXX.       ",
-"        .XX;;;;;;;###$XX.       ",
-"        .XXXXXXXXXXXXXXX.       ",
-"        .XXXXXXXXXXXXXXX.       ",
-"        .XX;;;;;;;;;;#XX.       ",
-"        .XXXXXXXXXXXXXXX.       ",
-"        .XXXXXXXXXXXXXXX.       ",
-"        .XXXXXXXXXXXXXXX.       ",
-"        .XXXXXXXXXXXXXXX.       ",
-"        .................       ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                "
-};
diff --git a/OPJViewer/source/icon3.xpm b/OPJViewer/source/icon3.xpm
deleted file mode 100644 (file)
index 722de6b..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-/* XPM */
-static char *icon3_xpm[] = {
-/* columns rows colors chars-per-pixel */
-"32 32 41 1",
-"6 c #EDF2FB",
-"- c #AAC1E8",
-": c #B9CDED",
-"X c #295193",
-", c #C6D6F0",
-"a c #4A7CCE",
-"u c #779DDB",
-"y c #7FA2DD",
-"$ c #3263B4",
-"5 c #EAF0FA",
-". c #2D59A3",
-"o c #6E96D8",
-"* c #356AC1",
-"r c #F7F9FD",
-"> c #BED0EE",
-"3 c #E1E9F7",
-"7 c #F0F5FC",
-"< c #CBD9F1",
-"2 c #DAE5F6",
-"# c #3161B1",
-"  c None",
-"0 c #FDFEFF",
-"= c #9FB9E5",
-"e c #AEC5EA",
-"t c #89A9DF",
-"q c #98B5E4",
-"p c #5584D1",
-"d c #3A70CA",
-"@ c #305FAC",
-"i c #5D89D3",
-"1 c #D2DFF4",
-"% c #3366B9",
-"9 c #FAFCFE",
-"8 c #F5F8FD",
-"s c #4075CC",
-"O c #638ED5",
-"w c #90AFE2",
-"& c #3467BC",
-"+ c #2F5DA9",
-"; c #B3C8EB",
-"4 c #E5EDF9",
-/* pixels */
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"      ......X                   ",
-"      .oooooO+                  ",
-"      .ooooooo.                 ",
-"      .+@@@##$%%&&&&&****.      ",
-"      .=-;:>,<12345678900.      ",
-"      .q=-;:>,<1234567890.      ",
-"      .wq=-e:>,<12345678r.      ",
-"      .twq=-e:>,<12345678.      ",
-"      .ytwq=-e:>,<1234567.      ",
-"      .uytwq=-e:>,<123456.      ",
-"      .ouytwq=-e:>,<12345.      ",
-"      .Oouytwq=-e;>,<1234.      ",
-"      .iOouytwq=-e;>,<123.      ",
-"      .piOouytwq=-e;>,<12.      ",
-"      .apiOouytwq=-e;>,<1.      ",
-"      .sapiOouytwq=-e;>,<.      ",
-"      .dsapiOouytwq=-e;>,.      ",
-"      ...................#      ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                "
-};
diff --git a/OPJViewer/source/icon4.xpm b/OPJViewer/source/icon4.xpm
deleted file mode 100644 (file)
index a18e1a7..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/* XPM */
-static char *icon4_xpm[] = {
-/* columns rows colors chars-per-pixel */
-"32 32 5 1",
-". c Black",
-"o c #8399B4",
-"X c #8DA0B9",
-"  c None",
-"O c #800000",
-/* pixels */
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"      .......                   ",
-"      .XXXXXo.                  ",
-"      .XXXXXXX.                 ",
-"      ....................      ",
-"      .OOOOOOOOOOOOOOOOOO.      ",
-"      .OOOOOOOOOOOOOOOOOO.      ",
-"      .OOOOOOOOOOOOOOOOOO.      ",
-"      .OOOOOOOOOOOOOOOOOO.      ",
-"      .OOOOOOOOOOOOOOOOOO.      ",
-"      .OOOOOOOOOOOOOOOOOO.      ",
-"      .OOOOOOOOOOOOOOOOOO.      ",
-"      .OOOOOOOOOOOOOOOOOO.      ",
-"      .OOOOOOOOOOOOOOOOOO.      ",
-"      .OOOOOOOOOOOOOOOOOO.      ",
-"      .OOOOOOOOOOOOOOOOOO.      ",
-"      .OOOOOOOOOOOOOOOOOO.      ",
-"      .OOOOOOOOOOOOOOOOOO.      ",
-"      ....................      ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                "
-};
diff --git a/OPJViewer/source/icon5.xpm b/OPJViewer/source/icon5.xpm
deleted file mode 100644 (file)
index 9f63c31..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-/* XPM */
-static char *icon5_xpm[] = {
-/* columns rows colors chars-per-pixel */
-"32 32 41 1",
-"0 c #AAC1E8",
-"q c #B9CDED",
-"X c #295193",
-"e c #C6D6F0",
-"a c #4A7CCE",
-"& c #779DDB",
-"* c #7FA2DD",
-"2 c #EAF0FA",
-"@ c #2D59A3",
-"o c #6E96D8",
-"y c #356AC1",
-"d c #214279",
-"w c #BED0EE",
-"= c #85A7DF",
-"< c #E1E9F7",
-"3 c #F0F5FC",
-"s c #CBD9F1",
-", c #DAE5F6",
-"7 c #3161B1",
-"  c None",
-". c #274D8B",
-"6 c #FDFEFF",
-"i c #E7EEF9",
-"9 c #9FB9E5",
-"- c #89A9DF",
-"8 c #98B5E4",
-"$ c #5584D1",
-"+ c #3569BF",
-"% c #305FAC",
-"O c #5D89D3",
-"> c #D2DFF4",
-"p c #3366B9",
-"5 c #FAFCFE",
-"4 c #F5F8FD",
-"t c #4075CC",
-"u c #638ED5",
-"r c #CEDCF2",
-"; c #90AFE2",
-"# c #2F5DA9",
-": c #B3C8EB",
-"1 c #E5EDF9",
-/* pixels */
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"     ......X                    ",
-"     XoooooO.                   ",
-"     Xoooooo+.                  ",
-"     Xooooooo@XXXXXXXXXX#       ",
-"     Xoooooooooooooooooo#       ",
-"     Xoooooooooooooooooo#       ",
-"     Xoo$###################    ",
-"     Xoo%O&*=-;:>,<123445667    ",
-"     XooX890:qwer>,<123445q#    ",
-"     Xoty;890:qwer>,<12344#     ",
-"     Xo%u-;890:qwer>,<i234#     ",
-"     XoX&*-;890:qwer>,<i2r#     ",
-"     Xtpo&*-;890:qwer>,<i#      ",
-"     X%auo&*-;890:qwer>,<#      ",
-"     XX$Ouo&*-;890:qwer>s#      ",
-"     d%a$Ouo&*-;890:qwer#       ",
-"     d+ta$Ouo&*-;890:qwe#       ",
-"     d..................#       ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                ",
-"                                "
-};
diff --git a/OPJViewer/source/imagjpeg2000.cpp b/OPJViewer/source/imagjpeg2000.cpp
deleted file mode 100644 (file)
index 66e1146..0000000
+++ /dev/null
@@ -1,1464 +0,0 @@
-/*\r
- * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        imagjpeg2000.cpp\r
-// Purpose:     wxImage JPEG 2000 family file format handler\r
-// Author:      Giuseppe Baruffa - based on imagjpeg.cpp, Vaclav Slavik\r
-// RCS-ID:      $Id: imagjpeg2000.cpp,v 0.00 2008/01/31 10:58:00 MW Exp $\r
-// Copyright:   (c) Giuseppe Baruffa\r
-// Licence:     wxWindows licence\r
-/////////////////////////////////////////////////////////////////////////////\r
-\r
-// For compilers that support precompilation, includes "wx.h".\r
-#include "wx/wxprec.h"\r
-\r
-#ifdef __BORLANDC__\r
-    #pragma hdrstop\r
-#endif\r
-\r
-#if wxUSE_IMAGE && wxUSE_LIBOPENJPEG\r
-\r
-#include "imagjpeg2000.h"\r
-\r
-#ifndef WX_PRECOMP\r
-    #include "wx/log.h"\r
-    #include "wx/app.h"\r
-    #include "wx/intl.h"\r
-    #include "wx/bitmap.h"\r
-    #include "wx/module.h"\r
-#endif\r
-\r
-#include "libopenjpeg/openjpeg.h"\r
-\r
-#include "wx/filefn.h"\r
-#include "wx/wfstream.h"\r
-\r
-// ----------------------------------------------------------------------------\r
-// types\r
-// ----------------------------------------------------------------------------\r
-\r
-\r
-//-----------------------------------------------------------------------------\r
-// wxJPEG2000Handler\r
-//-----------------------------------------------------------------------------\r
-\r
-IMPLEMENT_DYNAMIC_CLASS(wxJPEG2000Handler,wxImageHandler)\r
-\r
-#if wxUSE_STREAMS\r
-\r
-//------------- JPEG 2000 Data Source Manager\r
-\r
-#define J2K_CFMT 0\r
-#define JP2_CFMT 1\r
-#define JPT_CFMT 2\r
-#define MJ2_CFMT 3\r
-#define PXM_DFMT 0\r
-#define PGX_DFMT 1\r
-#define BMP_DFMT 2\r
-#define YUV_DFMT 3\r
-\r
-#define MAX_MESSAGE_LEN 200\r
-\r
-/* check file type */\r
-int\r
-jpeg2000familytype(unsigned char *hdr, int hdr_len)\r
-{\r
-       // check length\r
-    if (hdr_len < 24)\r
-        return -1;\r
-\r
-       // check format\r
-       if (hdr[0] == 0x00 &&\r
-                       hdr[1] == 0x00 &&\r
-                       hdr[2] == 0x00 &&\r
-                       hdr[3] == 0x0C &&\r
-                       hdr[4] == 0x6A &&\r
-                       hdr[5] == 0x50 &&\r
-                       hdr[6] == 0x20 &&\r
-                       hdr[7] == 0x20 &&\r
-                       hdr[20] == 0x6A &&\r
-                       hdr[21] == 0x70 &&\r
-                       hdr[22] == 0x32)\r
-               // JP2 file format\r
-               return JP2_CFMT;\r
-       else if (hdr[0] == 0x00 &&\r
-                       hdr[1] == 0x00 &&\r
-                       hdr[2] == 0x00 &&\r
-                       hdr[3] == 0x0C &&\r
-                       hdr[4] == 0x6A &&\r
-                       hdr[5] == 0x50 &&\r
-                       hdr[6] == 0x20 &&\r
-                       hdr[7] == 0x20 &&\r
-                       hdr[20] == 0x6D &&\r
-                       hdr[21] == 0x6A &&\r
-                       hdr[22] == 0x70 &&\r
-                       hdr[23] == 0x32)\r
-               // MJ2 file format\r
-               return MJ2_CFMT;\r
-       else if (hdr[0] == 0xFF &&\r
-                       hdr[1] == 0x4F)\r
-               // J2K file format\r
-               return J2K_CFMT;\r
-       else\r
-               // unknown format\r
-               return -1;\r
-\r
-}\r
-\r
-/* we have to use this to avoid GUI-noGUI threads crashing */\r
-void printevent(const char *msg)\r
-{\r
-#ifndef __WXGTK__ \r
-       wxMutexGuiEnter();\r
-#endif /* __WXGTK__ */\r
-       wxLogMessage(wxT("%s"), msg);\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiLeave();\r
-#endif /* __WXGTK__ */\r
-}\r
-\r
-/* sample error callback expecting a FILE* client object */\r
-void jpeg2000_error_callback(const char *msg, void *client_data) {\r
-       char mess[MAX_MESSAGE_LEN + 20];\r
-       int message_len = strlen(msg);\r
-\r
-       if (message_len > MAX_MESSAGE_LEN)\r
-               message_len = MAX_MESSAGE_LEN;\r
-       \r
-       if (msg[message_len - 1] == '\n')\r
-               message_len--;\r
-\r
-       sprintf(mess, "[ERROR] %.*s", message_len, msg);\r
-       printevent(mess);\r
-}\r
-\r
-/* sample warning callback expecting a FILE* client object */\r
-void jpeg2000_warning_callback(const char *msg, void *client_data) {\r
-       char mess[MAX_MESSAGE_LEN + 20];\r
-       int message_len = strlen(msg);\r
-\r
-       if (message_len > MAX_MESSAGE_LEN)\r
-               message_len = MAX_MESSAGE_LEN;\r
-       \r
-       if (msg[message_len - 1] == '\n')\r
-               message_len--;\r
-\r
-       sprintf(mess, "[WARNING] %.*s", message_len, msg);\r
-       printevent(mess);\r
-}\r
-\r
-/* sample debug callback expecting no client object */\r
-void jpeg2000_info_callback(const char *msg, void *client_data) {\r
-       char mess[MAX_MESSAGE_LEN + 20];\r
-       int message_len = strlen(msg);\r
-\r
-       if (message_len > MAX_MESSAGE_LEN)\r
-               message_len = MAX_MESSAGE_LEN;\r
-       \r
-       if (msg[message_len - 1] == '\n')\r
-               message_len--;\r
-\r
-       sprintf(mess, "[INFO] %.*s", message_len, msg);\r
-       printevent(mess);\r
-}\r
-\r
-/* macro functions */\r
-/* From little endian to big endian, 2 and 4 bytes */\r
-#define        BYTE_SWAP2(X)   ((X & 0x00FF) << 8) | ((X & 0xFF00) >> 8)\r
-#define        BYTE_SWAP4(X)   ((X & 0x000000FF) << 24) | ((X & 0x0000FF00) << 8) | ((X & 0x00FF0000) >> 8) | ((X & 0xFF000000) >> 24)\r
-\r
-#ifdef __WXGTK__\r
-#define        BYTE_SWAP8(X)   ((X & 0x00000000000000FFULL) << 56) | ((X & 0x000000000000FF00ULL) << 40) | \\r
-                        ((X & 0x0000000000FF0000ULL) << 24) | ((X & 0x00000000FF000000ULL) << 8) | \\r
-                                               ((X & 0x000000FF00000000ULL) >> 8)  | ((X & 0x0000FF0000000000ULL) >> 24) | \\r
-                                               ((X & 0x00FF000000000000ULL) >> 40) | ((X & 0xFF00000000000000ULL) >> 56)\r
-#else\r
-#define        BYTE_SWAP8(X)   ((X & 0x00000000000000FF) << 56) | ((X & 0x000000000000FF00) << 40) | \\r
-                        ((X & 0x0000000000FF0000) << 24) | ((X & 0x00000000FF000000) << 8) | \\r
-                                               ((X & 0x000000FF00000000) >> 8)  | ((X & 0x0000FF0000000000) >> 24) | \\r
-                                               ((X & 0x00FF000000000000) >> 40) | ((X & 0xFF00000000000000) >> 56)\r
-#endif\r
-\r
-/* From codestream to int values */\r
-#define STREAM_TO_UINT32(C, P) (((unsigned long int) (C)[(P) + 0] << 24) + \\r
-                                                               ((unsigned long int) (C)[(P) + 1] << 16) + \\r
-                                                               ((unsigned long int) (C)[(P) + 2] << 8) + \\r
-                                                               ((unsigned long int) (C)[(P) + 3] << 0))\r
-\r
-#define STREAM_TO_UINT16(C, P) (((unsigned long int) (C)[(P) + 0] << 8) + \\r
-                                                               ((unsigned long int) (C)[(P) + 1] << 0))\r
-\r
-/* defines */\r
-#define SHORT_DESCR_LEN        32\r
-#define LONG_DESCR_LEN         256\r
-\r
-/* enumeration for file formats */\r
-#define JPEG2000FILENUM              4\r
-typedef enum {\r
-\r
-        JP2_FILE,\r
-        J2K_FILE,\r
-               MJ2_FILE,\r
-               UNK_FILE\r
-\r
-} jpeg2000filetype;\r
-\r
-/* enumeration for the box types */\r
-#define JPEG2000BOXNUM                23\r
-typedef enum {\r
-\r
-                       FILE_BOX,\r
-                       JP_BOX,\r
-                       FTYP_BOX,\r
-                       JP2H_BOX,\r
-                       IHDR_BOX,\r
-                       COLR_BOX,\r
-                       JP2C_BOX,\r
-                       JP2I_BOX,\r
-                       XML_BOX,\r
-                       UUID_BOX,\r
-                       UINF_BOX,\r
-                       MOOV_BOX,\r
-                       MVHD_BOX,\r
-                       TRAK_BOX,\r
-                       TKHD_BOX,\r
-                       MDIA_BOX,\r
-                       MINF_BOX,\r
-                       STBL_BOX,\r
-                       STSD_BOX,\r
-                       MJP2_BOX,\r
-                       MDAT_BOX,\r
-                       ANY_BOX,\r
-                       UNK_BOX\r
-\r
-} jpeg2000boxtype;\r
-\r
-/* jpeg2000 family box signatures */\r
-#define FILE_SIGN           ""\r
-#define JP_SIGN             "jP\040\040"\r
-#define FTYP_SIGN           "ftyp"\r
-#define JP2H_SIGN           "jp2h"\r
-#define IHDR_SIGN           "ihdr"\r
-#define COLR_SIGN           "colr"\r
-#define JP2C_SIGN           "jp2c"\r
-#define JP2I_SIGN           "jp2i"\r
-#define XML_SIGN            "xml\040"\r
-#define UUID_SIGN           "uuid"\r
-#define UINF_SIGN           "uinf"\r
-#define MOOV_SIGN           "moov"\r
-#define MVHD_SIGN           "mvhd"\r
-#define TRAK_SIGN           "trak"\r
-#define TKHD_SIGN           "tkhd"\r
-#define MDIA_SIGN           "mdia"\r
-#define MINF_SIGN           "minf"\r
-#define VMHD_SIGN           "vmhd"\r
-#define STBL_SIGN           "stbl"\r
-#define STSD_SIGN           "stsd"\r
-#define MJP2_SIGN           "mjp2"\r
-#define MDAT_SIGN           "mdat"\r
-#define ANY_SIGN                       ""\r
-#define UNK_SIGN            ""\r
-\r
-/* the box structure itself */\r
-struct jpeg2000boxdef {\r
-\r
-        char                  value[5];                 /* hexadecimal value/string*/\r
-               char                  name[SHORT_DESCR_LEN];    /* short description       */\r
-               char                  descr[LONG_DESCR_LEN];    /* long  description       */\r
-               int                   sbox;                     /* is it a superbox?       */\r
-               int                   req[JPEG2000FILENUM];     /* mandatory box           */\r
-               jpeg2000boxtype       ins;                      /* contained in box...     */\r
-\r
-};\r
-\r
-/* the possible boxes */\r
-struct jpeg2000boxdef jpeg2000box[] =\r
-{\r
-/* sign */     {FILE_SIGN,\r
-/* short */    "placeholder for nothing",\r
-/* long */     "Nothing to say",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {JP_SIGN,\r
-/* short */    "JPEG 2000 Signature box",\r
-/* long */     "This box uniquely identifies the file as being part of the JPEG 2000 family of files",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {FTYP_SIGN,\r
-/* short */    "File Type box",\r
-/* long */     "This box specifies file type, version and compatibility information, including specifying if this file "\r
-                       "is a conforming JP2 file or if it can be read by a conforming JP2 reader",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {JP2H_SIGN,\r
-/* short */    "JP2 Header box",\r
-/* long */     "This box contains a series of boxes that contain header-type information about the file",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {IHDR_SIGN,\r
-/* short */    "Image Header box",\r
-/* long */     "This box specifies the size of the image and other related fields",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      JP2H_BOX},\r
-\r
-/* sign */     {COLR_SIGN,\r
-/* short */    "Colour Specification box",\r
-/* long */     "This box specifies the colourspace of the image",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      JP2H_BOX},\r
-\r
-/* sign */     {JP2C_SIGN,\r
-/* short */    "Contiguous Codestream box",\r
-/* long */     "This box contains the codestream as defined by Annex A",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {JP2I_SIGN,\r
-/* short */    "Intellectual Property box",\r
-/* long */     "This box contains intellectual property information about the image",\r
-/* sbox */     0,\r
-/* req */      {0, 0, 0},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {XML_SIGN,\r
-/* short */    "XML box",\r
-/* long */     "This box provides a tool by which vendors can add XML formatted information to a JP2 file",\r
-/* sbox */     0,\r
-/* req */      {0, 0, 0},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {UUID_SIGN,\r
-/* short */    "UUID box",\r
-/* long */     "This box provides a tool by which vendors can add additional information to a file "\r
-                       "without risking conflict with other vendors",\r
-/* sbox */     0,\r
-/* req */      {0, 0, 0},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {UINF_SIGN,\r
-/* short */    "UUID Info box",\r
-/* long */     "This box provides a tool by which a vendor may provide access to additional information associated with a UUID",\r
-/* sbox */     0,\r
-/* req */      {0, 0, 0},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {MOOV_SIGN,\r
-/* short */    "Movie box",\r
-/* long */     "This box contains the media data. In video tracks, this box would contain JPEG2000 video frames",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {MVHD_SIGN,\r
-/* short */    "Movie Header box",\r
-/* long */     "This box defines overall information which is media-independent, and relevant to the entire presentation "\r
-                       "considered as a whole",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MOOV_BOX},\r
-\r
-/* sign */     {TRAK_SIGN,\r
-/* short */    "Track box",\r
-/* long */     "This is a container box for a single track of a presentation. A presentation may consist of one or more tracks",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MOOV_BOX},\r
-\r
-/* sign */     {TKHD_SIGN,\r
-/* short */    "Track Header box",\r
-/* long */     "This box specifies the characteristics of a single track. Exactly one Track Header Box is contained in a track",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      TRAK_BOX},\r
-\r
-/* sign */     {MDIA_SIGN,\r
-/* short */    "Media box",\r
-/* long */     "The media declaration container contains all the objects which declare information about the media data "\r
-                       "within a track",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      TRAK_BOX},\r
-\r
-/* sign */     {MINF_SIGN,\r
-/* short */    "Media Information box",\r
-/* long */     "This box contains all the objects which declare characteristic information of the media in the track",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MDIA_BOX},\r
-\r
-/* sign */     {STBL_SIGN,\r
-/* short */    "Sample Table box",\r
-/* long */     "The sample table contains all the time and data indexing of the media samples in a track",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MINF_BOX},\r
-\r
-/* sign */     {STSD_SIGN,\r
-/* short */    "Sample Description box",\r
-/* long */     "The sample description table gives detailed information about the coding type used, and any initialization "\r
-                       "information needed for that coding",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MINF_BOX},\r
-\r
-/* sign */     {MJP2_SIGN,\r
-/* short */    "MJP2 Sample Description box",\r
-/* long */     "The MJP2 sample description table gives detailed information about the coding type used, and any initialization "\r
-                       "information needed for that coding",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MINF_BOX},\r
-\r
-/* sign */     {MDAT_SIGN,\r
-/* short */    "Media Data box",\r
-/* long */     "The meta-data for a presentation is stored in the single Movie Box which occurs at the top-level of a file",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {ANY_SIGN,\r
-/* short */    "Any box",\r
-/* long */     "All the existing boxes",\r
-/* sbox */     0,\r
-/* req */      {0, 0, 0},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {UNK_SIGN,\r
-/* short */    "Unknown Type box",\r
-/* long */     "The signature is not recognised to be that of an existing box",\r
-/* sbox */     0,\r
-/* req */      {0, 0, 0},\r
-/* ins */      ANY_BOX}\r
-\r
-};\r
-\r
-/* declaration */\r
-int\r
-jpeg2000_box_handler_function(jpeg2000boxtype boxtype, wxInputStream& stream, unsigned long int filepoint,\r
-                                                         unsigned long int filelimit, int level, char *scansign,\r
-                                                         unsigned long int *scanpoint);\r
-\r
-#ifdef __WXMSW__\r
-typedef unsigned __int64 int8byte;\r
-#endif // __WXMSW__\r
-\r
-#ifdef __WXGTK__\r
-typedef unsigned long long int8byte;\r
-#endif // __WXGTK__\r
-\r
-/* internal mini-search for a box signature */\r
-int\r
-jpeg2000_file_parse(wxInputStream& stream, unsigned long int filepoint, unsigned long int filelimit, int level,\r
-                                       char *scansign, unsigned long int *scanpoint)\r
-{\r
-       unsigned long int       LBox = 0x00000000;\r
-       char                    TBox[5] = "\0\0\0\0";\r
-       int8byte                XLBox = 0x0000000000000000;\r
-       unsigned long int       box_length = 0;\r
-       int                     last_box = 0, box_num = 0;\r
-       int                     box_type = ANY_BOX;\r
-       unsigned char           fourbytes[4];\r
-       int                     box_number = 0;\r
-\r
-       /* cycle all over the file */\r
-       box_num = 0;\r
-       last_box = 0;\r
-       while (!last_box) {\r
-\r
-               /* do not exceed file limit */\r
-               if (filepoint >= filelimit)\r
-                       return (0);\r
-\r
-               /* seek on file */\r
-               if (stream.SeekI(filepoint, wxFromStart) == wxInvalidOffset)\r
-                       return (-1);\r
-\r
-               /* read the mandatory LBox, 4 bytes */\r
-               if (!stream.Read(fourbytes, 4)) {\r
-                       wxLogError(wxT("Problem reading LBox from the file (file ended?)"));\r
-                       return -1;\r
-               };\r
-               LBox = STREAM_TO_UINT32(fourbytes, 0);\r
-\r
-               /* read the mandatory TBox, 4 bytes */\r
-               if (!stream.Read(TBox, 4)) {\r
-                       wxLogError(wxT("Problem reading TBox from the file (file ended?)"));\r
-                       return -1;\r
-               };\r
-\r
-               /* look if scansign is got */\r
-               if ((scansign != NULL) && (memcmp(TBox, scansign, 4) == 0)) {\r
-                       /* hack/exploit */\r
-                       // stop as soon as you find the level-th codebox\r
-                       if (box_number == level) {\r
-                               memcpy(scansign, "    ", 4);\r
-                               *scanpoint = filepoint;\r
-                               return (0);\r
-                       } else\r
-                               box_number++;\r
-\r
-               };\r
-\r
-               /* determine the box type */\r
-               for (box_type = JP_BOX; box_type < UNK_BOX; box_type++)\r
-                       if (memcmp(TBox, jpeg2000box[box_type].value, 4) == 0)\r
-                               break;  \r
-\r
-               /* read the optional XLBox, 8 bytes */\r
-               if (LBox == 1) {\r
-\r
-                       if (!stream.Read(&XLBox, 8)) {\r
-                               wxLogError(wxT("Problem reading XLBox from the file (file ended?)"));\r
-                               return -1;\r
-                       };\r
-                       box_length = (unsigned long int) BYTE_SWAP8(XLBox);\r
-\r
-               } else if (LBox == 0x00000000) {\r
-\r
-                       /* last box in file */\r
-                       last_box = 1; \r
-                       box_length = filelimit - filepoint;\r
-\r
-               } else\r
-\r
-                       box_length = LBox;\r
-\r
-\r
-               /* go deep in the box */\r
-               jpeg2000_box_handler_function((jpeg2000boxtype) box_type,\r
-                       stream, (LBox == 1) ? (filepoint + 16) : (filepoint + 8),\r
-                       filepoint + box_length, level, scansign, scanpoint);\r
-\r
-               /* if it's a superbox go inside it */\r
-               if (jpeg2000box[box_type].sbox)\r
-                       jpeg2000_file_parse(stream, (LBox == 1) ? (filepoint + 16) : (filepoint + 8), filepoint + box_length,\r
-                               level, scansign, scanpoint);\r
-\r
-               /* increment box number and filepoint*/\r
-               box_num++;\r
-               filepoint += box_length;\r
-\r
-       };\r
-\r
-       /* all good */\r
-       return (0);\r
-}\r
-\r
-// search first contiguos codestream box in an mj2 file\r
-unsigned long int\r
-searchjpeg2000c(wxInputStream& stream, unsigned long int fsize, int number)\r
-{\r
-       char scansign[] = "jp2c";\r
-       unsigned long int scanpoint = 0L;\r
-\r
-       wxLogMessage(wxT("Searching jp2c box... "));\r
-\r
-       /* do the parsing */\r
-       if (jpeg2000_file_parse(stream, 0, fsize, number, scansign, &scanpoint) < 0)            \r
-               wxLogMessage(wxT("Unrecoverable error during JPEG 2000 box parsing: stopping"));\r
-\r
-       if (strcmp(scansign, "    "))\r
-               wxLogMessage(wxT("Box not found"));\r
-       else {\r
-\r
-               wxLogMessage(wxString::Format(wxT("Box found at byte %d"), scanpoint));\r
-\r
-       };\r
-\r
-       return (scanpoint);\r
-}\r
-\r
-// search the jp2h box in the file\r
-unsigned long int\r
-searchjpeg2000headerbox(wxInputStream& stream, unsigned long int fsize)\r
-{\r
-       char scansign[] = "jp2h";\r
-       unsigned long int scanpoint = 0L;\r
-\r
-       wxLogMessage(wxT("Searching jp2h box... "));\r
-\r
-       /* do the parsing */\r
-       if (jpeg2000_file_parse(stream, 0, fsize, 0, scansign, &scanpoint) < 0)         \r
-               wxLogMessage(wxT("Unrecoverable error during JPEG 2000 box parsing: stopping"));\r
-\r
-       if (strcmp(scansign, "    "))\r
-               wxLogMessage(wxT("Box not found"));\r
-       else\r
-               wxLogMessage(wxString::Format(wxT("Box found at byte %d"), scanpoint));\r
-\r
-       return (scanpoint);\r
-}\r
-\r
-/* handling functions */\r
-#define ITEM_PER_ROW   10\r
-\r
-/* Box handler function */\r
-int\r
-jpeg2000_box_handler_function(jpeg2000boxtype boxtype, wxInputStream& stream, unsigned long int filepoint,\r
-                                                         unsigned long int filelimit, int level,\r
-                                                         char *scansign, unsigned long int *scanpoint)\r
-{\r
-       switch (boxtype) {\r
-\r
-       /* Sample Description box */\r
-       case (STSD_BOX):\r
-               jpeg2000_file_parse(stream, filepoint + 8, filelimit, level, scansign, scanpoint);\r
-               break;\r
-\r
-       /* MJP2 Sample Description box */\r
-       case (MJP2_BOX):\r
-               jpeg2000_file_parse(stream, filepoint + 78, filelimit, level, scansign, scanpoint);\r
-               break;\r
-               \r
-       /* not yet implemented */\r
-       default:\r
-               break;\r
-\r
-       };\r
-\r
-       return (0);\r
-}\r
-\r
-// the jP and ftyp parts of the header\r
-#define jpeg2000headSIZE       32\r
-unsigned char jpeg2000head[jpeg2000headSIZE] = {\r
-               0x00, 0x00, 0x00, 0x0C,  'j',  'P',  ' ',  ' ',\r
-               0x0D, 0x0A, 0x87, 0x0A, 0x00, 0x00, 0x00, 0x14,\r
-                'f',  't',  'y',  'p',  'j',  'p',  '2',  ' ',\r
-               0x00, 0x00, 0x00, 0x00,  'j',  'p',  '2',  ' '                  \r
-};\r
-\r
-/////////////////////////////////////////////////\r
-/////////////////////////////////////////////////\r
-\r
-// load the jpeg2000 file format\r
-bool wxJPEG2000Handler::LoadFile(wxImage *image, wxInputStream& stream, bool verbose, int index)\r
-{\r
-       opj_dparameters_t parameters;   /* decompression parameters */\r
-       opj_event_mgr_t event_mgr;              /* event manager */\r
-       opj_image_t *opjimage = NULL;\r
-       unsigned char *src = NULL;\r
-    unsigned char *ptr;\r
-       int file_length, jp2c_point, jp2h_point;\r
-       unsigned long int jp2hboxlen, jp2cboxlen;\r
-       opj_codestream_info_t cstr_info;  /* Codestream information structure */\r
-    unsigned char hdr[24];\r
-       int jpfamform;\r
-\r
-       // destroy the image\r
-    image->Destroy();\r
-\r
-       /* read the beginning of the file to check the type */ \r
-    if (!stream.Read(hdr, WXSIZEOF(hdr)))\r
-        return false;\r
-       if ((jpfamform = jpeg2000familytype(hdr, WXSIZEOF(hdr))) < 0)\r
-               return false;\r
-       stream.SeekI(0, wxFromStart);\r
-\r
-       /* handle to a decompressor */\r
-       opj_dinfo_t* dinfo = NULL;      \r
-       opj_cio_t *cio = NULL;\r
-\r
-       /* configure the event callbacks */\r
-       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));\r
-       event_mgr.error_handler = jpeg2000_error_callback;\r
-       event_mgr.warning_handler = jpeg2000_warning_callback;\r
-       event_mgr.info_handler = jpeg2000_info_callback;\r
-\r
-       /* set decoding parameters to default values */\r
-       opj_set_default_decoder_parameters(&parameters);\r
-\r
-       /* prepare parameters */\r
-       strncpy(parameters.infile, "", sizeof(parameters.infile) - 1);\r
-       strncpy(parameters.outfile, "", sizeof(parameters.outfile) - 1);\r
-       parameters.decod_format = jpfamform;\r
-       parameters.cod_format = BMP_DFMT;\r
-       if (m_reducefactor)\r
-               parameters.cp_reduce = m_reducefactor;\r
-       if (m_qualitylayers)\r
-               parameters.cp_layer = m_qualitylayers;\r
-       /*if (n_components)\r
-               parameters. = n_components;*/\r
-\r
-       /* JPWL only */\r
-#ifdef USE_JPWL\r
-       parameters.jpwl_exp_comps = m_expcomps;\r
-       parameters.jpwl_max_tiles = m_maxtiles;\r
-       parameters.jpwl_correct = m_enablejpwl;\r
-#endif /* USE_JPWL */\r
-\r
-       /* get a decoder handle */\r
-       if (jpfamform == JP2_CFMT || jpfamform == MJ2_CFMT)\r
-               dinfo = opj_create_decompress(CODEC_JP2);\r
-       else if (jpfamform == J2K_CFMT)\r
-               dinfo = opj_create_decompress(CODEC_J2K);\r
-       else\r
-               return false;\r
-\r
-       /* find length of the stream */\r
-       stream.SeekI(0, wxFromEnd);\r
-       file_length = (int) stream.TellI();\r
-\r
-       /* it's a movie */\r
-       if (jpfamform == MJ2_CFMT) {\r
-               /* search for the first codestream box and the movie header box  */\r
-               jp2c_point = searchjpeg2000c(stream, file_length, m_framenum);\r
-               jp2h_point = searchjpeg2000headerbox(stream, file_length);\r
-\r
-               // read the jp2h box and store it\r
-               stream.SeekI(jp2h_point, wxFromStart);\r
-               stream.Read(&jp2hboxlen, sizeof(unsigned long int));\r
-               jp2hboxlen = BYTE_SWAP4(jp2hboxlen);\r
-\r
-               // read the jp2c box and store it\r
-               stream.SeekI(jp2c_point, wxFromStart);\r
-               stream.Read(&jp2cboxlen, sizeof(unsigned long int));\r
-               jp2cboxlen = BYTE_SWAP4(jp2cboxlen);\r
-\r
-               // malloc memory source\r
-               src = (unsigned char *) malloc(jpeg2000headSIZE + jp2hboxlen + jp2cboxlen);\r
-\r
-               // copy the jP and ftyp\r
-               memcpy(src, jpeg2000head, jpeg2000headSIZE);\r
-\r
-               // copy the jp2h\r
-               stream.SeekI(jp2h_point, wxFromStart);\r
-               stream.Read(&src[jpeg2000headSIZE], jp2hboxlen);\r
-\r
-               // copy the jp2c\r
-               stream.SeekI(jp2c_point, wxFromStart);\r
-               stream.Read(&src[jpeg2000headSIZE + jp2hboxlen], jp2cboxlen);\r
-       } else  if (jpfamform == JP2_CFMT || jpfamform == J2K_CFMT) {\r
-               /* It's a plain image */\r
-               /* get data */\r
-               stream.SeekI(0, wxFromStart);\r
-               src = (unsigned char *) malloc(file_length);\r
-               stream.Read(src, file_length);\r
-       } else\r
-               return false;\r
-\r
-       /* catch events using our callbacks and give a local context */\r
-       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);\r
-\r
-       /* setup the decoder decoding parameters using user parameters */\r
-       opj_setup_decoder(dinfo, &parameters);\r
-\r
-       /* open a byte stream */\r
-       if (jpfamform == MJ2_CFMT)\r
-               cio = opj_cio_open((opj_common_ptr)dinfo, src, jpeg2000headSIZE + jp2hboxlen + jp2cboxlen);\r
-       else if (jpfamform == JP2_CFMT || jpfamform == J2K_CFMT)\r
-               cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);\r
-       else {\r
-               free(src);\r
-               return false;\r
-       }\r
-\r
-       /* decode the stream and fill the image structure */\r
-       opjimage = opj_decode_with_info(dinfo, cio, &cstr_info);\r
-       if (!opjimage) {\r
-               wxMutexGuiEnter();\r
-               wxLogError(wxT("JPEG 2000 failed to decode image!"));\r
-               wxMutexGuiLeave();\r
-               opj_destroy_decompress(dinfo);\r
-               opj_cio_close(cio);\r
-               free(src);\r
-               return false;\r
-       }\r
-\r
-       /* close the byte stream */\r
-       opj_cio_close(cio);\r
-\r
-       /*\r
-\r
-       - At this point, we have the structure "opjimage" that is filled with decompressed\r
-         data, as processed by the OpenJPEG decompression engine\r
-\r
-       - We need to fill the class "image" with the proper pixel sample values\r
-\r
-       */\r
-       {\r
-               int shiftbpp;\r
-               int c, tempcomps;\r
-\r
-               // check components number\r
-               if (m_components > opjimage->numcomps)\r
-                       m_components = opjimage->numcomps;\r
-\r
-               // check image depth (only on the first one, for now)\r
-               if (m_components)\r
-                       shiftbpp = opjimage->comps[m_components - 1].prec - 8;\r
-               else\r
-                       shiftbpp = opjimage->comps[0].prec - 8;\r
-\r
-               // prepare image size\r
-               if (m_components)\r
-                       image->Create(opjimage->comps[m_components - 1].w, opjimage->comps[m_components - 1].h, true);\r
-               else\r
-                       image->Create(opjimage->comps[0].w, opjimage->comps[0].h, true);\r
-\r
-               // access image raw data\r
-               image->SetMask(false);\r
-               ptr = image->GetData();\r
-\r
-               // workaround for components different from 1 or 3\r
-               if ((opjimage->numcomps != 1) && (opjimage->numcomps != 3)) {\r
-#ifndef __WXGTK__ \r
-                       wxMutexGuiEnter();\r
-#endif /* __WXGTK__ */\r
-                       wxLogMessage(wxT("JPEG2000: weird number of components"));\r
-#ifndef __WXGTK__ \r
-                       wxMutexGuiLeave();\r
-#endif /* __WXGTK__ */\r
-                       tempcomps = 1;\r
-               } else\r
-                       tempcomps = opjimage->numcomps;\r
-\r
-               // workaround for subsampled components\r
-               for (c = 1; c < tempcomps; c++) {\r
-                       if ((opjimage->comps[c].w != opjimage->comps[c - 1].w) || (opjimage->comps[c].h != opjimage->comps[c - 1].h)) {\r
-                               tempcomps = 1;\r
-                               break;\r
-                       }\r
-               }\r
-\r
-               // workaround for different precision components\r
-               for (c = 1; c < tempcomps; c++) {\r
-                       if (opjimage->comps[c].bpp != opjimage->comps[c - 1].bpp) {\r
-                               tempcomps = 1;\r
-                               break;\r
-                       }\r
-               }\r
-\r
-               // only one component selected\r
-               if (m_components)\r
-                       tempcomps = 1;\r
-\r
-               // RGB color picture\r
-               if (tempcomps == 3) {\r
-                       int row, col;\r
-                       int *r = opjimage->comps[0].data;\r
-                       int *g = opjimage->comps[1].data;\r
-                       int *b = opjimage->comps[2].data;\r
-                       if (shiftbpp > 0) {\r
-                               for (row = 0; row < opjimage->comps[0].h; row++) {\r
-                                       for (col = 0; col < opjimage->comps[0].w; col++) {\r
-                                               \r
-                                               *(ptr++) = (*(r++)) >> shiftbpp;\r
-                                               *(ptr++) = (*(g++)) >> shiftbpp;\r
-                                               *(ptr++) = (*(b++)) >> shiftbpp;\r
-\r
-                                       }\r
-                               }\r
-\r
-                       } else if (shiftbpp < 0) {\r
-                               for (row = 0; row < opjimage->comps[0].h; row++) {\r
-                                       for (col = 0; col < opjimage->comps[0].w; col++) {\r
-                                               \r
-                                               *(ptr++) = (*(r++)) << -shiftbpp;\r
-                                               *(ptr++) = (*(g++)) << -shiftbpp;\r
-                                               *(ptr++) = (*(b++)) << -shiftbpp;\r
-\r
-                                       }\r
-                               }\r
-                               \r
-                       } else {\r
-                               for (row = 0; row < opjimage->comps[0].h; row++) {\r
-                                       for (col = 0; col < opjimage->comps[0].w; col++) {\r
-\r
-                                               *(ptr++) = *(r++);\r
-                                               *(ptr++) = *(g++);\r
-                                               *(ptr++) = *(b++);\r
-                                       \r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               // B/W picture\r
-               if (tempcomps == 1) {\r
-                       int row, col;\r
-                       int selcomp;\r
-\r
-                       if (m_components)\r
-                               selcomp = m_components - 1;\r
-                       else\r
-                               selcomp = 0;\r
-\r
-                       int *y = opjimage->comps[selcomp].data;\r
-                       if (shiftbpp > 0) {\r
-                               for (row = 0; row < opjimage->comps[selcomp].h; row++) {\r
-                                       for (col = 0; col < opjimage->comps[selcomp].w; col++) {\r
-                                               \r
-                                               *(ptr++) = (*(y)) >> shiftbpp;\r
-                                               *(ptr++) = (*(y)) >> shiftbpp;\r
-                                               *(ptr++) = (*(y++)) >> shiftbpp;\r
-\r
-                                       }\r
-                               }\r
-                       } else if (shiftbpp < 0) {\r
-                               for (row = 0; row < opjimage->comps[selcomp].h; row++) {\r
-                                       for (col = 0; col < opjimage->comps[selcomp].w; col++) {\r
-                                               \r
-                                               *(ptr++) = (*(y)) << -shiftbpp;\r
-                                               *(ptr++) = (*(y)) << -shiftbpp;\r
-                                               *(ptr++) = (*(y++)) << -shiftbpp;\r
-\r
-                                       }\r
-                               }\r
-                       } else {\r
-                               for (row = 0; row < opjimage->comps[selcomp].h; row++) {\r
-                                       for (col = 0; col < opjimage->comps[selcomp].w; col++) {\r
-                                               \r
-                                               *(ptr++) = *(y);\r
-                                               *(ptr++) = *(y);\r
-                                               *(ptr++) = *(y++);\r
-\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-       }\r
-\r
-    wxMutexGuiEnter();\r
-    wxLogMessage(wxT("JPEG 2000 image loaded."));\r
-    wxMutexGuiLeave();\r
-\r
-       /* close openjpeg structs */\r
-       opj_destroy_decompress(dinfo);\r
-       opj_image_destroy(opjimage);\r
-       free(src);\r
-\r
-       if (!image->Ok())\r
-               return false;\r
-       else\r
-               return true;\r
-\r
-}\r
-\r
-#define CINEMA_24_CS 1302083   /* Codestream length for 24fps */\r
-#define CINEMA_48_CS 651041            /* Codestream length for 48fps */\r
-#define COMP_24_CS 1041666             /* Maximum size per color component for 2K & 4K @ 24fps */\r
-#define COMP_48_CS 520833              /* Maximum size per color component for 2K @ 48fps */\r
-\r
-// save the j2k codestream\r
-bool wxJPEG2000Handler::SaveFile( wxImage *wimage, wxOutputStream& stream, bool verbose )\r
-{\r
-        opj_cparameters_t parameters;  /* compression parameters */\r
-        opj_event_mgr_t event_mgr;             /* event manager */\r
-        opj_image_t *oimage = NULL;\r
-        opj_image_cmptparm_t *cmptparm;        \r
-        opj_cio_t *cio = NULL;\r
-        opj_codestream_info_t cstr_info;\r
-        int codestream_length;\r
-        bool bSuccess;\r
-        int i;\r
-        char indexfilename[OPJ_PATH_LEN] = ""; /* index file name */\r
-\r
-        /*\r
-        configure the event callbacks (not required)\r
-        setting of each callback is optionnal\r
-        */\r
-        memset(&event_mgr, 0, sizeof(opj_event_mgr_t));\r
-        event_mgr.error_handler = jpeg2000_error_callback;\r
-        event_mgr.warning_handler = jpeg2000_warning_callback;\r
-        event_mgr.info_handler = jpeg2000_info_callback;\r
-\r
-        /* set encoding parameters to default values */\r
-        opj_set_default_encoder_parameters(&parameters);\r
-\r
-        /* load parameters */\r
-        parameters.cp_cinema = OFF;\r
-\r
-        /* subsampling */\r
-        if (sscanf(m_subsampling.ToAscii(), "%d,%d", &(parameters.subsampling_dx), &(parameters.subsampling_dy)) != 2) {\r
-                wxLogError(wxT("Wrong sub-sampling encoder setting: dx,dy"));\r
-                return false;\r
-        }\r
-\r
-        /* compression rates */\r
-        if ((m_rates != wxT("")) && (!m_enablequality)) {\r
-                const char *s1 = m_rates.ToAscii();\r
-                wxLogMessage(wxT("rates %s"), s1);\r
-                while (sscanf(s1, "%f", &(parameters.tcp_rates[parameters.tcp_numlayers])) == 1) {\r
-                        parameters.tcp_numlayers++;\r
-                        while (*s1 && *s1 != ',') {\r
-                                s1++;\r
-                        }\r
-                        if (!*s1)\r
-                                break;\r
-                        s1++;\r
-                }\r
-                wxLogMessage(wxT("%d layers"), parameters.tcp_numlayers);\r
-                parameters.cp_disto_alloc = 1;\r
-        }\r
-\r
-        /* image quality, dB */\r
-        if ((m_quality != wxT("")) && (m_enablequality)) {\r
-                const char *s2 = m_quality.ToAscii();\r
-                wxLogMessage(wxT("qualities %s"), s2);\r
-                while (sscanf(s2, "%f", &parameters.tcp_distoratio[parameters.tcp_numlayers]) == 1) {\r
-                        parameters.tcp_numlayers++;\r
-                        while (*s2 && *s2 != ',') {\r
-                                s2++;\r
-                        }\r
-                        if (!*s2)\r
-                                break;\r
-                        s2++;\r
-                }\r
-                wxLogMessage(wxT("%d layers"), parameters.tcp_numlayers);\r
-                parameters.cp_fixed_quality = 1;\r
-        }\r
-\r
-        /* image origin */\r
-        if (sscanf(m_origin.ToAscii(), "%d,%d", &parameters.image_offset_x0, &parameters.image_offset_y0) != 2) {\r
-                wxLogError(wxT("bad coordinate of the image origin: x0,y0"));\r
-                return false;\r
-        }\r
-                                \r
-        /* Create comment for codestream */\r
-        if(m_enablecomm) {\r
-                parameters.cp_comment = (char *) malloc(strlen(m_comment.ToAscii()) + 1);\r
-                if(parameters.cp_comment) {\r
-                        strcpy(parameters.cp_comment, m_comment.ToAscii());\r
-                }\r
-        } else {\r
-                parameters.cp_comment = NULL;\r
-        }\r
-\r
-        /* indexing file */\r
-        if (m_enableidx) {\r
-                strncpy(indexfilename, m_index.ToAscii(), OPJ_PATH_LEN);\r
-                wxLogMessage(wxT("index file is %s"), indexfilename);\r
-        }\r
-\r
-        /* if no rate entered, lossless by default */\r
-        if (parameters.tcp_numlayers == 0) {\r
-                parameters.tcp_rates[0] = 0;   /* MOD antonin : losslessbug */\r
-                parameters.tcp_numlayers++;\r
-                parameters.cp_disto_alloc = 1;\r
-        }\r
-\r
-        /* irreversible transform */\r
-        parameters.irreversible = (m_irreversible == true) ? 1 : 0;\r
-\r
-        /* resolutions */\r
-        parameters.numresolution = m_resolutions;\r
-\r
-        /* codeblocks size */\r
-        if (m_cbsize != wxT("")) {\r
-                int cblockw_init = 0, cblockh_init = 0;\r
-                sscanf(m_cbsize.ToAscii(), "%d,%d", &cblockw_init, &cblockh_init);\r
-                if (cblockw_init * cblockh_init > 4096 || cblockw_init > 1024 || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {\r
-                        wxLogError(wxT("!! Size of code_block error !! Restrictions:\n  width*height<=4096\n  4<=width,height<= 1024"));\r
-                        return false;\r
-                }\r
-                parameters.cblockw_init = cblockw_init;\r
-                parameters.cblockh_init = cblockh_init;\r
-        }\r
-\r
-        /* precincts size */\r
-        if (m_prsize != wxT("")) {\r
-                char sep;\r
-                int res_spec = 0;\r
-                char *s = (char *) m_prsize.c_str();\r
-                do {\r
-                        sep = 0;\r
-                        sscanf(s, "[%d,%d]%c", &parameters.prcw_init[res_spec], &parameters.prch_init[res_spec], &sep);\r
-                        parameters.csty |= 0x01;\r
-                        res_spec++;\r
-                        s = strpbrk(s, "]") + 2;\r
-                } while (sep == ',');\r
-                parameters.res_spec = res_spec;\r
-        }\r
-\r
-        /* tiles */\r
-        if (m_tsize != wxT("")) {\r
-                sscanf(m_tsize.ToAscii(), "%d,%d", &parameters.cp_tdx, &parameters.cp_tdy);\r
-                parameters.tile_size_on = true;\r
-        }\r
-\r
-        /* tile origin */\r
-        if (sscanf(m_torigin.ToAscii(), "%d,%d", &parameters.cp_tx0, &parameters.cp_ty0) != 2) {\r
-                wxLogError(wxT("tile offset setting error: X0,Y0"));\r
-                return false;\r
-        }\r
-\r
-        /* use SOP */\r
-        if (m_enablesop)\r
-                parameters.csty |= 0x02;\r
-\r
-        /* use EPH */\r
-        if (m_enableeph)\r
-                parameters.csty |= 0x04;\r
-\r
-        /* multiple component transform */\r
-        if (m_multicomp)\r
-                parameters.tcp_mct = 1;\r
-        else\r
-                parameters.tcp_mct = 0;\r
-\r
-        /* mode switch */\r
-        parameters.mode = (m_enablebypass ? 1 : 0) + (m_enablereset ? 2 : 0)\r
-                + (m_enablerestart ? 4 : 0) + (m_enablevsc ? 8 : 0)\r
-                + (m_enableerterm ? 16 : 0) + (m_enablesegmark ? 32 : 0);\r
-\r
-        /* progression order */\r
-        switch (m_progression) {\r
-\r
-                /* LRCP */\r
-        case 0:\r
-                parameters.prog_order = LRCP;\r
-                break;\r
-\r
-                /* RLCP */\r
-        case 1:\r
-                parameters.prog_order = RLCP;\r
-                break;\r
-\r
-                /* RPCL */\r
-        case 2:\r
-                parameters.prog_order = RPCL;\r
-                break;\r
-\r
-                /* PCRL */\r
-        case 3:\r
-                parameters.prog_order = PCRL;\r
-                break;\r
-\r
-                /* CPRL */\r
-        case 4:\r
-                parameters.prog_order = CPRL;\r
-                break;\r
-\r
-                /* DCI2K24 */\r
-        case 5:\r
-                parameters.cp_cinema = CINEMA2K_24;\r
-                parameters.cp_rsiz = CINEMA2K;\r
-                break;\r
-\r
-                /* DCI2K48 */\r
-        case 6:\r
-                parameters.cp_cinema = CINEMA2K_48;\r
-                parameters.cp_rsiz = CINEMA2K;\r
-                break;\r
-\r
-                /* DCI4K */\r
-        case 7:\r
-                parameters.cp_cinema = CINEMA4K_24;\r
-                parameters.cp_rsiz = CINEMA4K;\r
-                break;\r
-\r
-        default:\r
-                break;\r
-        }\r
-\r
-        /* check cinema */\r
-        if (parameters.cp_cinema) {\r
-\r
-                /* set up */\r
-                parameters.tile_size_on = false;\r
-                parameters.cp_tdx=1;\r
-                parameters.cp_tdy=1;\r
-                \r
-                /*Tile part*/\r
-                parameters.tp_flag = 'C';\r
-                parameters.tp_on = 1;\r
-\r
-                /*Tile and Image shall be at (0,0)*/\r
-                parameters.cp_tx0 = 0;\r
-                parameters.cp_ty0 = 0;\r
-                parameters.image_offset_x0 = 0;\r
-                parameters.image_offset_y0 = 0;\r
-\r
-                /*Codeblock size= 32*32*/\r
-                parameters.cblockw_init = 32;  \r
-                parameters.cblockh_init = 32;\r
-                parameters.csty |= 0x01;\r
-\r
-                /*The progression order shall be CPRL*/\r
-                parameters.prog_order = CPRL;\r
-\r
-                /* No ROI */\r
-                parameters.roi_compno = -1;\r
-\r
-                parameters.subsampling_dx = 1;\r
-                parameters.subsampling_dy = 1;\r
-\r
-                /* 9-7 transform */\r
-                parameters.irreversible = 1;\r
-\r
-        }                              \r
-\r
-        /* convert wx image into opj image */\r
-        cmptparm = (opj_image_cmptparm_t*) malloc(3 * sizeof(opj_image_cmptparm_t));\r
-\r
-        /* initialize opj image components */  \r
-        memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));\r
-        for(i = 0; i < 3; i++) {               \r
-                cmptparm[i].prec = 8;\r
-                cmptparm[i].bpp = 8;\r
-                cmptparm[i].sgnd = false;\r
-                cmptparm[i].dx = parameters.subsampling_dx;\r
-                cmptparm[i].dy = parameters.subsampling_dy;\r
-                cmptparm[i].w = wimage->GetWidth();\r
-                cmptparm[i].h = wimage->GetHeight();\r
-        }\r
-\r
-        /* create the image */\r
-        oimage = opj_image_create(3, &cmptparm[0], CLRSPC_SRGB);\r
-        if(!oimage) {\r
-                if (cmptparm)\r
-                        free(cmptparm);\r
-                return false;\r
-        }\r
-\r
-        /* set image offset and reference grid */\r
-        oimage->x0 = parameters.image_offset_x0;\r
-        oimage->y0 = parameters.image_offset_y0;\r
-        oimage->x1 = parameters.image_offset_x0 + (wimage->GetWidth() - 1) * 1 + 1;\r
-        oimage->y1 = parameters.image_offset_y0 + (wimage->GetHeight() - 1) * 1 + 1;\r
-\r
-        /* load image data */\r
-        unsigned char *value = wimage->GetData(); \r
-        int area = wimage->GetWidth() * wimage->GetHeight();\r
-        for (i = 0; i < area; i++) {\r
-                        oimage->comps[0].data[i] = *(value++);\r
-                        oimage->comps[1].data[i] = *(value++);\r
-                        oimage->comps[2].data[i] = *(value++);\r
-        }\r
-\r
-        /* check cinema again */\r
-        if (parameters.cp_cinema) {\r
-                int i;\r
-                float temp_rate;\r
-                opj_poc_t *POC = NULL;\r
-\r
-                switch (parameters.cp_cinema) {\r
-\r
-                case CINEMA2K_24:\r
-                case CINEMA2K_48:\r
-                        if (parameters.numresolution > 6) {\r
-                                parameters.numresolution = 6;\r
-                        }\r
-                        if (!((oimage->comps[0].w == 2048) | (oimage->comps[0].h == 1080))) {\r
-                                wxLogWarning(wxT("Image coordinates %d x %d is not 2K compliant. JPEG Digital Cinema Profile-3 "\r
-                                        "(2K profile) compliance requires that at least one of coordinates match 2048 x 1080"),\r
-                                        oimage->comps[0].w, oimage->comps[0].h);\r
-                                parameters.cp_rsiz = STD_RSIZ;\r
-                        }\r
-                break;\r
-                \r
-                case CINEMA4K_24:\r
-                        if (parameters.numresolution < 1) {\r
-                                        parameters.numresolution = 1;\r
-                        } else if (parameters.numresolution > 7) {\r
-                                        parameters.numresolution = 7;\r
-                        }\r
-                        if (!((oimage->comps[0].w == 4096) | (oimage->comps[0].h == 2160))) {\r
-                                wxLogWarning(wxT("Image coordinates %d x %d is not 4K compliant. JPEG Digital Cinema Profile-4" \r
-                                        "(4K profile) compliance requires that at least one of coordinates match 4096 x 2160"),\r
-                                        oimage->comps[0].w, oimage->comps[0].h);\r
-                                parameters.cp_rsiz = STD_RSIZ;\r
-                        }\r
-                        parameters.POC[0].tile  = 1; \r
-                        parameters.POC[0].resno0  = 0; \r
-                        parameters.POC[0].compno0 = 0;\r
-                        parameters.POC[0].layno1  = 1;\r
-                        parameters.POC[0].resno1  = parameters.numresolution - 1;\r
-                        parameters.POC[0].compno1 = 3;\r
-                        parameters.POC[0].prg1 = CPRL;\r
-                        parameters.POC[1].tile  = 1;\r
-                        parameters.POC[1].resno0  = parameters.numresolution - 1; \r
-                        parameters.POC[1].compno0 = 0;\r
-                        parameters.POC[1].layno1  = 1;\r
-                        parameters.POC[1].resno1  = parameters.numresolution;\r
-                        parameters.POC[1].compno1 = 3;\r
-                        parameters.POC[1].prg1 = CPRL;\r
-                        parameters.numpocs = 2;\r
-                        break;\r
-                }\r
-\r
-                switch (parameters.cp_cinema) {\r
-                case CINEMA2K_24:\r
-                case CINEMA4K_24:\r
-                        for (i = 0 ; i < parameters.tcp_numlayers; i++) {\r
-                                temp_rate = 0;\r
-                                if (parameters.tcp_rates[i] == 0) {\r
-                                        parameters.tcp_rates[0] = ((float) (oimage->numcomps * oimage->comps[0].w * oimage->comps[0].h * oimage->comps[0].prec)) / \r
-                                        (CINEMA_24_CS * 8 * oimage->comps[0].dx * oimage->comps[0].dy);\r
-                                }else{\r
-                                        temp_rate = ((float) (oimage->numcomps * oimage->comps[0].w * oimage->comps[0].h * oimage->comps[0].prec)) / \r
-                                                (parameters.tcp_rates[i] * 8 * oimage->comps[0].dx * oimage->comps[0].dy);\r
-                                        if (temp_rate > CINEMA_24_CS ) {\r
-                                                parameters.tcp_rates[i]= ((float) (oimage->numcomps * oimage->comps[0].w * oimage->comps[0].h * oimage->comps[0].prec)) / \r
-                                                (CINEMA_24_CS * 8 * oimage->comps[0].dx * oimage->comps[0].dy);\r
-                                        } else {\r
-                                                /* do nothing */\r
-                                        }\r
-                                }\r
-                        }\r
-                        parameters.max_comp_size = COMP_24_CS;\r
-                        break;\r
-                        \r
-                case CINEMA2K_48:\r
-                        for (i = 0; i < parameters.tcp_numlayers; i++) {\r
-                                temp_rate = 0 ;\r
-                                if (parameters.tcp_rates[i] == 0) {\r
-                                        parameters.tcp_rates[0] = ((float) (oimage->numcomps * oimage->comps[0].w * oimage->comps[0].h * oimage->comps[0].prec)) / \r
-                                        (CINEMA_48_CS * 8 * oimage->comps[0].dx * oimage->comps[0].dy);\r
-                                }else{\r
-                                        temp_rate =((float) (oimage->numcomps * oimage->comps[0].w * oimage->comps[0].h * oimage->comps[0].prec)) / \r
-                                                (parameters.tcp_rates[i] * 8 * oimage->comps[0].dx * oimage->comps[0].dy);\r
-                                        if (temp_rate > CINEMA_48_CS ){\r
-                                                parameters.tcp_rates[0]= ((float) (oimage->numcomps * oimage->comps[0].w * oimage->comps[0].h * oimage->comps[0].prec)) / \r
-                                                (CINEMA_48_CS * 8 * oimage->comps[0].dx * oimage->comps[0].dy);\r
-                                        }else{\r
-                                                /* do nothing */\r
-                                        }\r
-                                }\r
-                        }\r
-                        parameters.max_comp_size = COMP_48_CS;\r
-                        break;\r
-                }\r
-\r
-                parameters.cp_disto_alloc = 1;\r
-        }\r
-        \r
-        /* get a J2K compressor handle */\r
-        opj_cinfo_t* cinfo = opj_create_compress(CODEC_J2K);\r
-\r
-        /* catch events using our callbacks and give a local context */\r
-        opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);\r
-\r
-        /* setup the encoder parameters using the current image and user parameters */\r
-        opj_setup_encoder(cinfo, &parameters, oimage);\r
-\r
-        /* open a byte stream for writing */\r
-        /* allocate memory for all tiles */\r
-        cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);\r
-\r
-        /* encode the image */\r
-        bSuccess = opj_encode_with_info(cinfo, cio, oimage, &cstr_info);\r
-        if (!bSuccess) {\r
-\r
-                opj_cio_close(cio);\r
-                opj_destroy_compress(cinfo);\r
-                opj_image_destroy(oimage);\r
-                if (cmptparm)\r
-                        free(cmptparm);\r
-                if(parameters.cp_comment)\r
-                        free(parameters.cp_comment);\r
-                if(parameters.cp_matrice)\r
-                        free(parameters.cp_matrice);\r
-\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiEnter();\r
-#endif /* __WXGTK__ */\r
-\r
-                wxLogError(wxT("failed to encode image"));\r
-\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiLeave();\r
-#endif /* __WXGTK__ */\r
-\r
-                return false;\r
-        }\r
-        codestream_length = cio_tell(cio);\r
-        wxLogMessage(wxT("Codestream: %d bytes"), codestream_length);\r
-\r
-        /* write the buffer to stream */\r
-        stream.Write(cio->buffer, codestream_length);\r
-\r
-        /* close and free the byte stream */\r
-        opj_cio_close(cio);\r
-\r
-        /* Write the index to disk */\r
-        if (*indexfilename) {\r
-                if (write_index_file(&cstr_info, indexfilename)) {\r
-                        wxLogError(wxT("Failed to output index file"));\r
-                }\r
-        }\r
-\r
-        /* free remaining compression structures */\r
-        opj_destroy_compress(cinfo);\r
-\r
-        /* free image data */\r
-        opj_image_destroy(oimage);\r
-\r
-        if (cmptparm)\r
-                free(cmptparm);\r
-        if(parameters.cp_comment)\r
-                free(parameters.cp_comment);\r
-        if(parameters.cp_matrice)\r
-                free(parameters.cp_matrice);\r
-\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiEnter();\r
-#endif /* __WXGTK__ */\r
-\r
-    wxLogMessage(wxT("J2K: Image encoded!"));\r
-\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiLeave();\r
-#endif /* __WXGTK__ */\r
-\r
-    return true;\r
-}\r
-\r
-#ifdef __VISUALC__\r
-    #pragma warning(default:4611)\r
-#endif /* VC++ */\r
-\r
-// recognize the JPEG 2000 family starting box or the 0xFF4F JPEG 2000 SOC marker\r
-bool wxJPEG2000Handler::DoCanRead(wxInputStream& stream)\r
-{\r
-    unsigned char hdr[24];\r
-       int jpfamform;\r
-\r
-    if ( !stream.Read(hdr, WXSIZEOF(hdr)) )\r
-        return false;\r
-\r
-       jpfamform = jpeg2000familytype(hdr, WXSIZEOF(hdr));\r
-\r
-       return ((jpfamform == JP2_CFMT) || (jpfamform == MJ2_CFMT) || (jpfamform == J2K_CFMT));\r
-}\r
-\r
-#endif   // wxUSE_STREAMS\r
-\r
-#endif   // wxUSE_LIBOPENJPEG\r
diff --git a/OPJViewer/source/imagjpeg2000.h b/OPJViewer/source/imagjpeg2000.h
deleted file mode 100644 (file)
index 2fea20a..0000000
+++ /dev/null
@@ -1,177 +0,0 @@
-/*\r
- * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        imagalljpeg2000.h\r
-// Purpose:     wxImage JPEG 2000 family file format handler\r
-// Author:      G. Baruffa - based on imagjpeg.h, Vaclav Slavik\r
-// RCS-ID:      $Id: imagalljpeg2000.h,v 0.0 2008/01/31 11:22:00 VZ Exp $\r
-// Copyright:   (c) Giuseppe Baruffa\r
-// Licence:     wxWindows licence\r
-/////////////////////////////////////////////////////////////////////////////\r
-\r
-#ifndef _WX_IMAGJPEG2000_H_\r
-#define _WX_IMAGJPEG2000_H_\r
-\r
-#include "wx/defs.h"\r
-\r
-//-----------------------------------------------------------------------------\r
-// wxJPEG2000Handler\r
-//-----------------------------------------------------------------------------\r
-\r
-#if wxUSE_LIBOPENJPEG\r
-\r
-#include "wx/image.h"\r
-#include "libopenjpeg/openjpeg.h"\r
-#include "codec/index.h"\r
-\r
-#define wxBITMAP_TYPE_JPEG2000 50\r
-\r
-class WXDLLEXPORT wxJPEG2000Handler: public wxImageHandler\r
-{\r
-public:\r
-    inline wxJPEG2000Handler()\r
-    {\r
-        m_name = wxT("JPEG 2000 family file format");\r
-        m_extension = wxT("mj2");\r
-        m_type = wxBITMAP_TYPE_JPEG2000;\r
-        m_mime = wxT("image/mj2");\r
-\r
-               /* decoding */\r
-               m_reducefactor = 0;\r
-               m_qualitylayers = 0;\r
-               m_components = 0;\r
-#ifdef USE_JPWL\r
-               m_enablejpwl = true;\r
-               m_expcomps = JPWL_EXPECTED_COMPONENTS;\r
-               m_maxtiles = JPWL_MAXIMUM_TILES;\r
-#endif // USE_JPWL\r
-\r
-               /* encoding */\r
-               m_subsampling = wxT("1,1");\r
-               m_origin = wxT("0,0");\r
-               m_rates = wxT("20,10,5");\r
-               m_quality = wxT("30,35,40");\r
-               m_enablequality = false;\r
-               m_multicomp = false;\r
-               m_irreversible = false;\r
-               m_resolutions = 6;\r
-               m_progression = 0;\r
-               m_cbsize = wxT("32,32");\r
-               m_prsize = wxT("[128,128],[128,128]");\r
-               m_tsize = wxT("");\r
-               m_torigin = wxT("0,0");\r
-               /*m_progression\r
-               m_resilience*/\r
-               m_enablesop = false;\r
-               m_enableeph = false;\r
-               m_enablereset = false;\r
-               m_enablesegmark = false;\r
-               m_enablevsc = false;\r
-               m_enablerestart = false;\r
-               m_enableerterm = false;\r
-               m_enablebypass = false;\r
-               /*m_roicompo\r
-               m_roiup\r
-               m_indexfname*/\r
-               m_enableidx = false;\r
-               m_index = wxT("index.txt");\r
-               m_enablepoc = false;\r
-               m_poc = wxT("T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL");\r
-               m_enablecomm = true;\r
-\r
-#if defined __WXMSW__\r
-               m_comment = wxT("Created by OPJViewer Win32 - OpenJPEG  version ");\r
-#elif defined __WXGTK__\r
-               m_comment = wxT("Created by OPJViewer Lin32 - OpenJPEG version ");\r
-#else\r
-               m_comment = wxT("Created by OPJViewer - OpenJPEG version ");\r
-#endif\r
-\r
-#ifdef USE_JPWL\r
-               m_comment += wxString::Format(wxT("%s with JPWL"), (char *) opj_version());\r
-#else\r
-               m_comment += wxString::Format(wxT("%s"), (char *) opj_version());\r
-#endif\r
-\r
-    }\r
-\r
-       // decoding engine parameters\r
-       int m_reducefactor, m_qualitylayers, m_components, m_framenum;\r
-#ifdef USE_JPWL\r
-       bool m_enablejpwl;\r
-       int m_expcomps, m_maxtiles;\r
-#endif // USE_JPWL\r
-\r
-       // encoding engine parameters\r
-       wxString m_subsampling;\r
-       wxString m_origin;\r
-       wxString m_rates;\r
-       wxString m_quality;\r
-       bool m_enablequality;\r
-       bool m_multicomp;\r
-       bool m_irreversible;\r
-       int m_resolutions;\r
-       int m_progression;\r
-       wxString m_cbsize;\r
-       wxString m_prsize;\r
-       wxString m_tsize;\r
-       wxString m_torigin;\r
-       /*m_progression\r
-       m_resilience*/\r
-       bool m_enablesop;\r
-       bool m_enableeph;\r
-       bool m_enablebypass;\r
-       bool m_enableerterm;\r
-       bool m_enablerestart;\r
-       bool m_enablereset;\r
-       bool m_enablesegmark;\r
-       bool m_enablevsc;\r
-       /*m_roicompo\r
-       m_roiup\r
-       m_indexfname*/\r
-       bool m_enableidx;\r
-       wxString m_index;\r
-       bool m_enablecomm;\r
-       wxString m_comment;\r
-       bool m_enablepoc;\r
-       wxString m_poc;\r
-\r
-#if wxUSE_STREAMS\r
-    virtual bool LoadFile(wxImage *image, wxInputStream& stream, bool verbose=true, int index=-1);\r
-    virtual bool SaveFile(wxImage *image, wxOutputStream& stream, bool verbose=true);\r
-protected:\r
-    virtual bool DoCanRead(wxInputStream& stream);\r
-#endif\r
-\r
-private:\r
-       OPJ_PROG_ORDER give_progression(char progression[4]);\r
-    DECLARE_DYNAMIC_CLASS(wxJPEG2000Handler)\r
-};\r
-\r
-#endif // wxUSE_LIBOPENJPEG\r
-\r
-#endif // _WX_IMAGJPEG2000_H_\r
-\r
diff --git a/OPJViewer/source/imagmxf.cpp b/OPJViewer/source/imagmxf.cpp
deleted file mode 100644 (file)
index 99d0b93..0000000
+++ /dev/null
@@ -1,502 +0,0 @@
-/*\r
- * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        imagmxf.cpp\r
-// Purpose:     wxImage MXF (Material eXchange Format) JPEG 2000 file format handler\r
-// Author:      Giuseppe Baruffa - based on imagjpeg.cpp, Vaclav Slavik\r
-// RCS-ID:      $Id: imagmxf.cpp,v 0.00 2007/11/19 17:00:00 MW Exp $\r
-// Copyright:   (c) Giuseppe Baruffa\r
-// Licence:     wxWindows licence\r
-/////////////////////////////////////////////////////////////////////////////\r
-\r
-#ifdef USE_MXF\r
-\r
-#include "mxflib/mxflib.h"\r
-using namespace mxflib;\r
-\r
-namespace\r
-{\r
-       //! Structure holding information about the essence in each body stream\r
-       struct EssenceInfo\r
-       {\r
-               UMIDPtr PackageID;\r
-               PackagePtr Package;\r
-               MDObjectPtr Descriptor;\r
-       };\r
-       //! Map of EssenceInfo structures indexed by BodySID\r
-       typedef std::map<UInt32, EssenceInfo> EssenceInfoMap;\r
-\r
-       //! The map of essence info for this file\r
-       EssenceInfoMap EssenceLookup;\r
-};\r
-\r
-//! Build an EssenceInfoMap for the essence in a given file\r
-/*! \return True if al OK, else false\r
- */\r
-bool BuildEssenceInfo(MXFFilePtr &File, EssenceInfoMap &EssenceLookup);\r
-\r
-// For compilers that support precompilation, includes "wx.h".\r
-#include "wx/wxprec.h"\r
-\r
-#ifdef __BORLANDC__\r
-    #pragma hdrstop\r
-#endif\r
-\r
-#if wxUSE_IMAGE && wxUSE_LIBOPENJPEG\r
-\r
-#include "imagmxf.h"\r
-\r
-#ifndef WX_PRECOMP\r
-    #include "wx/log.h"\r
-    #include "wx/app.h"\r
-    #include "wx/intl.h"\r
-    #include "wx/bitmap.h"\r
-    #include "wx/module.h"\r
-#endif\r
-\r
-\r
-#include "libopenjpeg/openjpeg.h"\r
-\r
-\r
-#include "wx/filefn.h"\r
-#include "wx/wfstream.h"\r
-\r
-// ----------------------------------------------------------------------------\r
-// types\r
-// ----------------------------------------------------------------------------\r
-\r
-\r
-//-----------------------------------------------------------------------------\r
-// wxMXFHandler\r
-//-----------------------------------------------------------------------------\r
-\r
-IMPLEMENT_DYNAMIC_CLASS(wxMXFHandler,wxImageHandler)\r
-\r
-#if wxUSE_STREAMS\r
-\r
-#include <stdarg.h>\r
-#define MAX_MESSAGE_LEN 200\r
-\r
-//------------- MXF Manager\r
-\r
-// Debug and error messages\r
-\r
-//! Display a warning message\r
-void mxflib::warning(const char *Fmt, ...)\r
-{\r
-       char msg[MAX_MESSAGE_LEN];\r
-       va_list args;\r
-\r
-       va_start(args, Fmt);\r
-       _vsnprintf(msg, MAX_MESSAGE_LEN, Fmt, args);\r
-       va_end(args);\r
-\r
-       int message_len = strlen(msg) - 1;\r
-       if (msg[message_len] != '\n')\r
-               message_len = MAX_MESSAGE_LEN;\r
-#ifndef __WXGTK__ \r
-               wxMutexGuiEnter();\r
-#endif /* __WXGTK__ */\r
-       wxLogMessage(wxT("[WARNING_MXF] %.*s"), message_len, msg);\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiLeave();\r
-#endif /* __WXGTK__ */\r
-}\r
-\r
-//! Display an error message\r
-void mxflib::error(const char *Fmt, ...)\r
-{\r
-       char msg[MAX_MESSAGE_LEN];\r
-       va_list args;\r
-\r
-       va_start(args, Fmt);\r
-       _vsnprintf(msg, MAX_MESSAGE_LEN, Fmt, args);\r
-       va_end(args);\r
-\r
-       int message_len = strlen(msg) - 1;\r
-       if (msg[message_len] != '\n')\r
-               message_len = MAX_MESSAGE_LEN;\r
-#ifndef __WXGTK__ \r
-               wxMutexGuiEnter();\r
-#endif /* __WXGTK__ */\r
-       wxLogMessage(wxT("[ERROR_MXF] %.*s"), message_len, msg);\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiLeave();\r
-#endif /* __WXGTK__ */\r
-}\r
-\r
-//! Display an error message\r
-void mxflib::debug(const char *Fmt, ...)\r
-{\r
-       char msg[MAX_MESSAGE_LEN];\r
-       va_list args;\r
-\r
-       va_start(args, Fmt);\r
-       _vsnprintf(msg, MAX_MESSAGE_LEN, Fmt, args);\r
-       va_end(args);\r
-\r
-       int message_len = strlen(msg) - 1;\r
-       if (msg[message_len] != '\n')\r
-               message_len = MAX_MESSAGE_LEN;\r
-#ifndef __WXGTK__ \r
-               wxMutexGuiEnter();\r
-#endif /* __WXGTK__ */\r
-       wxLogMessage(wxT("[DEBUG_MXF] %.*s"), message_len, msg);\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiLeave();\r
-#endif /* __WXGTK__ */\r
-}\r
-\r
-\r
-\r
-//------------- JPEG 2000 Data Source Manager\r
-\r
-#define J2K_CFMT 0\r
-#define JP2_CFMT 1\r
-#define JPT_CFMT 2\r
-#define MJ2_CFMT 3\r
-#define PXM_DFMT 0\r
-#define PGX_DFMT 1\r
-#define BMP_DFMT 2\r
-#define YUV_DFMT 3\r
-\r
-/* sample error callback expecting a FILE* client object */\r
-void mxf_error_callback(const char *msg, void *client_data) {\r
-       int message_len = strlen(msg) - 1;\r
-       if (msg[message_len] != '\n')\r
-               message_len = MAX_MESSAGE_LEN;\r
-#ifndef __WXGTK__ \r
-               wxMutexGuiEnter();\r
-#endif /* __WXGTK__ */\r
-       wxLogMessage(wxT("[ERROR] %.*s"), message_len, msg);\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiLeave();\r
-#endif /* __WXGTK__ */\r
-}\r
-\r
-/* sample warning callback expecting a FILE* client object */\r
-void mxf_warning_callback(const char *msg, void *client_data) {\r
-       int message_len = strlen(msg) - 1;\r
-       if (msg[message_len] != '\n')\r
-               message_len = MAX_MESSAGE_LEN;\r
-#ifndef __WXGTK__ \r
-               wxMutexGuiEnter();\r
-#endif /* __WXGTK__ */\r
-       wxLogMessage(wxT("[WARNING] %.*s"), message_len, msg);\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiLeave();\r
-#endif /* __WXGTK__ */\r
-}\r
-\r
-/* sample debug callback expecting no client object */\r
-void mxf_info_callback(const char *msg, void *client_data) {\r
-       int message_len = strlen(msg) - 1;\r
-       if (msg[message_len] != '\n')\r
-               message_len = MAX_MESSAGE_LEN;\r
-#ifndef __WXGTK__ \r
-               wxMutexGuiEnter();\r
-#endif /* __WXGTK__ */\r
-       wxLogMessage(wxT("[INFO] %.*s"), message_len, msg);\r
-#ifndef __WXGTK__ \r
-    wxMutexGuiLeave();\r
-#endif /* __WXGTK__ */\r
-}\r
-\r
-\r
-/////////////////////////////////////////////////\r
-/////////////////////////////////////////////////\r
-\r
-// load the mxf file format\r
-bool wxMXFHandler::LoadFile(wxImage *image, wxInputStream& stream, bool verbose, int index)\r
-{\r
-       opj_dparameters_t parameters;   /* decompression parameters */\r
-       opj_event_mgr_t event_mgr;              /* event manager */\r
-       opj_image_t *opjimage = NULL;\r
-       unsigned char *src = NULL;\r
-    unsigned char *ptr;\r
-       int file_length, j2k_point, j2k_len;\r
-       opj_codestream_info_t cstr_info;  /* Codestream information structure */\r
-       \r
-       // simply display the version of the library\r
-       wxLogMessage(wxT("Version of MXF: %s   "), wxString::FromAscii(LibraryVersion().c_str()));\r
-       //wxLogMessage(wxT("MXF file name: %s"), m_filename.GetFullPath());\r
-\r
-       // open MXF file\r
-       MXFFilePtr TestFile = new MXFFile;\r
-       if (! TestFile->Open(m_filename.GetFullPath().c_str(), true))\r
-       {\r
-               wxLogError(wxT("Could not find %s"), m_filename.GetFullPath().c_str());\r
-               return false;\r
-       } else\r
-               wxLogMessage(wxT("Found %s"), m_filename.GetFullPath().c_str());\r
-\r
-       // Get the size\r
-       TestFile->SeekEnd();\r
-       wxLogMessage(wxT("Size is %d bytes"), TestFile->Tell());\r
-       TestFile->Seek(0);\r
-\r
-       // essence information\r
-       //BuildEssenceInfo(TestFile, EssenceLookup);\r
-\r
-       // close MXF file\r
-       TestFile->Close();\r
-\r
-       return false;\r
-       \r
-       // destroy the image\r
-    image->Destroy();\r
-\r
-       /* handle to a decompressor */\r
-       opj_dinfo_t* dinfo = NULL;      \r
-       opj_cio_t *cio = NULL;\r
-\r
-       /* configure the event callbacks (not required) */\r
-       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));\r
-       event_mgr.error_handler = mxf_error_callback;\r
-       event_mgr.warning_handler = mxf_warning_callback;\r
-       event_mgr.info_handler = mxf_info_callback;\r
-\r
-       /* set decoding parameters to default values */\r
-       opj_set_default_decoder_parameters(&parameters);\r
-\r
-       /* prepare parameters */\r
-       strncpy(parameters.infile, "", sizeof(parameters.infile)-1);\r
-       strncpy(parameters.outfile, "", sizeof(parameters.outfile)-1);\r
-       parameters.decod_format = J2K_CFMT;\r
-       parameters.cod_format = BMP_DFMT;\r
-       if (m_reducefactor)\r
-               parameters.cp_reduce = m_reducefactor;\r
-       if (m_qualitylayers)\r
-               parameters.cp_layer = m_qualitylayers;\r
-       /*if (n_components)\r
-               parameters. = n_components;*/\r
-\r
-       /* JPWL only */\r
-#ifdef USE_JPWL\r
-       parameters.jpwl_exp_comps = m_expcomps;\r
-       parameters.jpwl_max_tiles = m_maxtiles;\r
-       parameters.jpwl_correct = m_enablejpwl;\r
-#endif /* USE_JPWL */\r
-\r
-       /* get a decoder handle */\r
-       dinfo = opj_create_decompress(CODEC_J2K);\r
-\r
-       /* find length of the stream */\r
-       stream.SeekI(0, wxFromEnd);\r
-       file_length = (int) stream.TellI();\r
-\r
-       /* search for the m_framenum codestream position and length  */\r
-       //jp2c_point = searchjp2c(stream, file_length, m_framenum);\r
-       //jp2c_len = searchjp2c(stream, file_length, m_framenum);\r
-       j2k_point = 0;\r
-       j2k_len = 10;\r
-\r
-       // malloc memory source\r
-    src = (unsigned char *) malloc(j2k_len);\r
-\r
-       // copy the jp2c\r
-       stream.SeekI(j2k_point, wxFromStart);\r
-       stream.Read(src, j2k_len);\r
-\r
-       /* catch events using our callbacks and give a local context */\r
-       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);\r
-\r
-       /* setup the decoder decoding parameters using user parameters */\r
-       opj_setup_decoder(dinfo, &parameters);\r
-\r
-       /* open a byte stream */\r
-       cio = opj_cio_open((opj_common_ptr)dinfo, src, j2k_len);\r
-\r
-       /* decode the stream and fill the image structure */\r
-       opjimage = opj_decode_with_info(dinfo, cio, &cstr_info);\r
-       if (!opjimage) {\r
-               wxMutexGuiEnter();\r
-               wxLogError(wxT("MXF: failed to decode image!"));\r
-               wxMutexGuiLeave();\r
-               opj_destroy_decompress(dinfo);\r
-               opj_cio_close(cio);\r
-               free(src);\r
-               return false;\r
-       }\r
-\r
-       /* close the byte stream */\r
-       opj_cio_close(cio);\r
-\r
-       /* common rendering method */\r
-#include "imagjpeg2000.cpp"\r
-\r
-    wxMutexGuiEnter();\r
-    wxLogMessage(wxT("MXF: image loaded."));\r
-    wxMutexGuiLeave();\r
-\r
-       /* close openjpeg structs */\r
-       opj_destroy_decompress(dinfo);\r
-       opj_image_destroy(opjimage);\r
-       free(src);\r
-\r
-       if (!image->Ok())\r
-               return false;\r
-       else\r
-               return true;\r
-\r
-}\r
-\r
-// save the mxf file format\r
-bool wxMXFHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )\r
-{\r
-    wxLogError(wxT("MXF: Couldn't save movie -> not implemented."));\r
-    return false;\r
-}\r
-\r
-#ifdef __VISUALC__\r
-    #pragma warning(default:4611)\r
-#endif /* VC++ */\r
-\r
-// recognize the MXF JPEG 2000 starting box\r
-bool wxMXFHandler::DoCanRead( wxInputStream& stream )\r
-{\r
-    unsigned char hdr[4];\r
-\r
-    if ( !stream.Read(hdr, WXSIZEOF(hdr)) )\r
-        return false;\r
-\r
-    return (hdr[0] == 0x06 &&\r
-                       hdr[1] == 0x0E &&\r
-                       hdr[2] == 0x2B &&\r
-                       hdr[3] == 0x34);\r
-}\r
-\r
-//! Build an EssenceInfoMap for the essence in a given file\r
-/*! \return True if al OK, else false\r
- */\r
-bool BuildEssenceInfo(MXFFilePtr &File, EssenceInfoMap &EssenceLookup)\r
-{\r
-       // Empty any old data\r
-       EssenceLookup.clear();\r
-\r
-       // Get the master metadata set (or the header if we must)\r
-       PartitionPtr MasterPartition = File->ReadMasterPartition();\r
-       if(!MasterPartition)\r
-       {\r
-               File->Seek(0);\r
-               MasterPartition = File->ReadPartition();\r
-               warning("File %s does not contain a cloased copy of header metadata - using the open copy in the file header\n", File->Name.c_str());\r
-       }\r
-\r
-       if(!MasterPartition) \r
-       {\r
-               error("Could not read header metadata from file %s\n", File->Name.c_str());\r
-               return false;\r
-       }\r
-\r
-       // Read and parse the metadata\r
-       MasterPartition->ReadMetadata();\r
-       MetadataPtr HMeta = MasterPartition->ParseMetadata();\r
-       \r
-       if(!HMeta) \r
-       {\r
-               error("Could not read header metadata from file %s\n", File->Name.c_str());\r
-               return false;\r
-       }\r
-\r
-       /* Scan the Essence container data sets to get PackageID to BodySID mapping */\r
-       MDObjectPtr ECDSet = HMeta[ContentStorage_UL];\r
-       if(ECDSet) ECDSet = ECDSet->GetLink();\r
-       if(ECDSet) ECDSet = ECDSet[EssenceContainerDataBatch_UL];\r
-       if(!ECDSet)\r
-       {\r
-               error("Header metadata in file %s does not contain an EssenceContainerData set\n", File->Name.c_str());\r
-               return false;\r
-       }\r
-\r
-       MDObject::iterator it = ECDSet->begin();\r
-       while(it != ECDSet->end())\r
-       {\r
-               MDObjectPtr ThisECDSet = (*it).second->GetLink();\r
-               MDObjectPtr PackageID;\r
-               if(ThisECDSet) PackageID = ThisECDSet->Child(LinkedPackageUID_UL);\r
-               if(PackageID)\r
-               {\r
-                       EssenceInfo NewEI;\r
-                       NewEI.PackageID = new UMID(PackageID->PutData()->Data);\r
-\r
-                       // Inset the basic essence info - but not if this is external essence (BodySID == 0)\r
-                       UInt32 BodySID = ThisECDSet->GetUInt(BodySID_UL);\r
-                       if(BodySID) EssenceLookup[BodySID] = NewEI;\r
-               }\r
-               it++;\r
-       }\r
-\r
-       /* Now find the other items for the essence lookup map */\r
-       if(EssenceLookup.size())\r
-       {\r
-               PackageList::iterator it = HMeta->Packages.begin();\r
-               while(it != HMeta->Packages.end())\r
-               {\r
-                       // Only Source Packages are of interest\r
-                       if((*it)->IsA(SourcePackage_UL))\r
-                       {\r
-                               MDObjectPtr Descriptor = (*it)->Child(Descriptor_UL);\r
-                               if(Descriptor) Descriptor = Descriptor->GetLink();\r
-\r
-                               if(Descriptor)\r
-                               {\r
-                                       MDObjectPtr PackageID = (*it)->Child(PackageUID_UL);\r
-                                       if(PackageID)\r
-                                       {\r
-                                               UMIDPtr TheID = new UMID(PackageID->PutData()->Data);\r
-                                               \r
-                                               /* Now do a lookup in the essence lookup map (it will need to be done the long way here */\r
-                                               EssenceInfoMap::iterator EL_it = EssenceLookup.begin();\r
-                                               while(EL_it != EssenceLookup.end())\r
-                                               {\r
-                                                       if((*((*EL_it).second.PackageID)) == (*TheID))\r
-                                                       {\r
-                                                               // If found, set the missing items and stop searching\r
-                                                               (*EL_it).second.Package = (*it);\r
-                                                               (*EL_it).second.Descriptor = Descriptor;\r
-                                                               break;\r
-                                                       }\r
-                                                       EL_it++;\r
-                                               }\r
-                                       }\r
-                               }\r
-                       }\r
-\r
-                       it++;\r
-               }\r
-       }\r
-\r
-       return true;\r
-}\r
-\r
-\r
-#endif   // wxUSE_STREAMS\r
-\r
-#endif   // wxUSE_LIBOPENJPEG\r
-\r
-#endif // USE_MXF\r
-\r
diff --git a/OPJViewer/source/imagmxf.h b/OPJViewer/source/imagmxf.h
deleted file mode 100644 (file)
index c87a4cb..0000000
+++ /dev/null
@@ -1,99 +0,0 @@
-/*\r
- * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-/////////////////////////////////////////////////////////////////////////////\r
-// Name:        imagmxf.h\r
-// Purpose:     wxImage MXF (Material eXchange Format) JPEG 2000 file format handler\r
-// Author:      G. Baruffa - based on imagjpeg.h, Vaclav Slavik\r
-// RCS-ID:      $Id: imagmj2.h,v 0.0 2007/11/19 17:00:00 VZ Exp $\r
-// Copyright:   (c) Giuseppe Baruffa\r
-// Licence:     wxWindows licence\r
-/////////////////////////////////////////////////////////////////////////////\r
-\r
-#ifndef _WX_IMAGMXF_H_\r
-#define _WX_IMAGMXF_H_\r
-\r
-#ifdef USE_MXF\r
-\r
-#include "wx/defs.h"\r
-#include "wx/filename.h"\r
-\r
-//-----------------------------------------------------------------------------\r
-// wxMXFHandler\r
-//-----------------------------------------------------------------------------\r
-\r
-#if wxUSE_LIBOPENJPEG\r
-\r
-#include "wx/image.h"\r
-#include "libopenjpeg/openjpeg.h"\r
-\r
-#define wxBITMAP_TYPE_MXF      51\r
-\r
-class WXDLLEXPORT wxMXFHandler: public wxImageHandler\r
-{\r
-public:\r
-    inline wxMXFHandler()\r
-    {\r
-        m_name = wxT("MXF JPEG 2000 file format");\r
-        m_extension = wxT("mxf");\r
-        m_type = wxBITMAP_TYPE_MXF;\r
-        m_mime = wxT("image/mxf");\r
-\r
-               m_reducefactor = 0;\r
-               m_qualitylayers = 0;\r
-               m_components = 0;\r
-               m_filename = wxT("");\r
-#ifdef USE_JPWL\r
-               m_enablejpwl = true;\r
-               m_expcomps = JPWL_EXPECTED_COMPONENTS;\r
-               m_maxtiles = JPWL_MAXIMUM_TILES;\r
-#endif // USE_JPWL\r
-    }\r
-\r
-               // decoding engine parameters\r
-               int m_reducefactor, m_qualitylayers, m_components, m_framenum;\r
-               wxFileName m_filename;\r
-#ifdef USE_JPWL\r
-               bool m_enablejpwl;\r
-               int m_expcomps, m_maxtiles;\r
-#endif // USE_JPWL\r
-\r
-#if wxUSE_STREAMS\r
-    virtual bool LoadFile( wxImage *image, wxInputStream& stream, bool verbose=true, int index=-1 );\r
-    virtual bool SaveFile( wxImage *image, wxOutputStream& stream, bool verbose=true );\r
-protected:\r
-    virtual bool DoCanRead( wxInputStream& stream );\r
-#endif\r
-\r
-private:\r
-    DECLARE_DYNAMIC_CLASS(wxMXFHandler)\r
-};\r
-\r
-#endif // wxUSE_LIBOPENJPEG\r
-\r
-#endif // USE_MXF\r
-\r
-#endif // _WX_IMAGMXF_H_\r
-\r
diff --git a/OPJViewer/source/license.txt b/OPJViewer/source/license.txt
deleted file mode 100644 (file)
index 81d6b34..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
-Copyright (c) 2002-2007, Professor Benoit Macq\r
-Copyright (c) 2001-2003, David Janssens\r
-Copyright (c) 2002-2003, Yannick Verschueren\r
-Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe\r
-Copyright (c) 2005, Herve Drolon, FreeImage Team\r
-Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
-All rights reserved.\r
-\r
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditionsare met:\r
-1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\r
-2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\r
-\r
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/OPJViewer/source/opj_logo.xpm b/OPJViewer/source/opj_logo.xpm
deleted file mode 100644 (file)
index c64d0a7..0000000
+++ /dev/null
@@ -1,285 +0,0 @@
-/* XPM */
-static char *opj_logo[] = {
-/* columns rows colors chars-per-pixel */
-"90 61 218 2",
-"   c #BE3D12",
-".  c #BF461D",
-"X  c #AD5435",
-"o  c #B64925",
-"O  c #B54E2B",
-"+  c #BC4620",
-"@  c #BB4B25",
-"#  c #BC4E29",
-"$  c #B5502F",
-"%  c #BD512C",
-"&  c #B45334",
-"*  c #B35638",
-"=  c #B45B3D",
-"-  c #BB5533",
-";  c #BE5937",
-":  c #BC5C3D",
-">  c #9C766A",
-",  c #AD5D42",
-"<  c #B55F41",
-"1  c #BA5E40",
-"2  c #A7634D",
-"3  c #A76C57",
-"4  c #AA6750",
-"5  c #AC6B56",
-"6  c #AA6E5A",
-"7  c #A4705E",
-"8  c #B46045",
-"9  c #B1644B",
-"0  c #BD6244",
-"q  c #B96448",
-"w  c #BC694D",
-"e  c #B36B53",
-"r  c #B26E58",
-"t  c #BB6C52",
-"y  c #B2725D",
-"u  c #BD7056",
-"i  c #BB745C",
-"p  c #A67566",
-"a  c #A57B6D",
-"s  c #AE7562",
-"d  c #AB7867",
-"f  c #AA7C6C",
-"g  c #A07E73",
-"h  c #AA7F71",
-"j  c #B37661",
-"k  c #B47863",
-"l  c #B27D6B",
-"z  c #BB7863",
-"x  c #BA7E69",
-"c  c #C73605",
-"v  c #C63A0B",
-"b  c #CB3300",
-"n  c #CA3807",
-"m  c #C93A0A",
-"M  c #C43E11",
-"N  c #C93E10",
-"B  c #C44115",
-"V  c #C3441A",
-"C  c #C4481E",
-"Z  c #CA4113",
-"A  c #C94519",
-"S  c #CB481C",
-"D  c #C24A23",
-"F  c #C24F28",
-"G  c #CD4D23",
-"H  c #C4522D",
-"J  c #CB532B",
-"K  c #C25632",
-"L  c #C35936",
-"P  c #C25C3B",
-"I  c #C85630",
-"U  c #CB5933",
-"Y  c #CB5E3A",
-"T  c #D05026",
-"R  c #CC613D",
-"E  c #C26343",
-"W  c #C46748",
-"Q  c #C1694C",
-"!  c #CD6744",
-"~  c #CA6C4D",
-"^  c #C37155",
-"/  c #C4755B",
-"(  c #CB7356",
-")  c #C8765B",
-"_  c #D06D4C",
-"`  c #D07253",
-"'  c #D47B5E",
-"]  c #C37B63",
-"[  c #C27E68",
-"{  c #C97F68",
-"}  c #A68175",
-"|  c #A48479",
-" . c #AD8172",
-".. c #AD8578",
-"X. c #AB897D",
-"o. c #B1806F",
-"O. c #BA816F",
-"+. c #B38373",
-"@. c #B58778",
-"#. c #B3897B",
-"$. c #BA8472",
-"%. c #BB8C7C",
-"&. c #C2816B",
-"*. c #CD846C",
-"=. c #C38470",
-"-. c #C38976",
-";. c #C38D7B",
-":. c #CC8973",
-">. c #CF8F7A",
-",. c #CB907D",
-"<. c #D1937F",
-"1. c #948E8C",
-"2. c #9D8C86",
-"3. c #9D8F89",
-"4. c #96908E",
-"5. c #9C918D",
-"6. c #949392",
-"7. c #9B9492",
-"8. c #9D9997",
-"9. c #9D9C9C",
-"0. c #A38B83",
-"q. c #AA8D83",
-"w. c #A4918B",
-"e. c #AC9087",
-"r. c #AB938C",
-"t. c #A49590",
-"y. c #A29996",
-"u. c #A19D9C",
-"i. c #AA9790",
-"p. c #AC9994",
-"a. c #AC9E99",
-"s. c #B18D81",
-"d. c #B59084",
-"f. c #B49389",
-"g. c #BA9184",
-"h. c #B89589",
-"j. c #BA988D",
-"k. c #B29B93",
-"l. c #BC9C92",
-"z. c #ACA19D",
-"x. c #B1A19D",
-"c. c #BCA39B",
-"v. c #A3A3A3",
-"b. c #ABA5A3",
-"n. c #AEA9A7",
-"m. c #ABABAA",
-"M. c #B3A5A1",
-"N. c #B3A9A6",
-"B. c #B3ADAA",
-"V. c #B9A6A0",
-"C. c #B9AAA5",
-"Z. c #BAADA9",
-"A. c #B4B0AF",
-"S. c #BAB0AD",
-"D. c #B4B3B3",
-"F. c #BAB5B3",
-"G. c #BDB8B6",
-"H. c #BBBBBB",
-"J. c #C39384",
-"K. c #C0978A",
-"L. c #C2998B",
-"P. c #CA9483",
-"I. c #CD9A8A",
-"U. c #C19D92",
-"Y. c #D69B89",
-"T. c #DB9680",
-"R. c #C2A095",
-"E. c #C4A69C",
-"W. c #CCA193",
-"Q. c #C8A599",
-"!. c #CBA99D",
-"~. c #C6AEA6",
-"^. c #CCACA2",
-"/. c #CBB2AB",
-"(. c #C3B8B5",
-"). c #C2BDBC",
-"_. c #C9B9B3",
-"`. c #D3ADA0",
-"'. c #D3B4A9",
-"]. c #DCB2A4",
-"[. c #DEB6A8",
-"{. c #D1BFB9",
-"}. c #D9BEB5",
-"|. c #C5C0BE",
-" X c #CDC0BC",
-".X c #D2C1BB",
-"XX c #DDC3BB",
-"oX c #E0C5BC",
-"OX c #E0C8BF",
-"+X c #C2C2C2",
-"@X c #CBC4C2",
-"#X c #CDC8C6",
-"$X c #CCCBCB",
-"%X c #D2C6C2",
-"&X c #D1CECD",
-"*X c #DDC8C1",
-"=X c #DECFCA",
-"-X c #D9D1CE",
-";X c #D3D3D3",
-":X c #D9D5D4",
-">X c #DED9D7",
-",X c #DBDBDB",
-"<X c #E1CAC3",
-"1X c #E2CFC8",
-"2X c #E1D3CE",
-"3X c #E2D5D0",
-"4X c #E5D8D3",
-"5X c #E4DDDB",
-"6X c #E8DBD6",
-"7X c #EADEDA",
-"8X c #E6E0DE",
-"9X c #EBE0DC",
-"0X c #E4E4E4",
-"qX c #E8E2E0",
-"wX c #EBEBEB",
-"eX c #F0EAE8",
-"rX c #F3F3F3",
-"tX c #FEFEFE",
-/* pixels */
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXrXrXtXrXrXrXrXrXrXrXtXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXrXtXrXrXrXwXwXrXwXrXrXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXrXrXrXwXwX0X0XqX0X0X0X0XwXwXwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXrXtXrXwXwX2X[.[.].].].].].1XwXrXwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXrXrXrXwX0X0XL.J b b b b b b b J '.0X0XwXwXrXrXrXrXrXrXrXrXrXrXtXrXrXrXtXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXtXtXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXrXrXwX0XXXt m b m B V N b b v >.;X0XwXwXwXwXrXwXwXrXrXrXrXtXrXtXrXrXrXwXrXrXrXrXrXrXrXrXrXrXrXwXrXrXwXrXrXrXtXtXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXrXrXrX0X,X'.S b b P l.z.M.k.w n b b g.;X,X,X,X0X0X0X0X0XwXwXwXwXwXwXwXwXwX0X0X0XwX0X0XwXwXwXwX0X0X0X0X0X0XwXwXwXwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXrXrXrXwX0X:XT.m b A ] G.D.D.m.$.m b b $.$X&X.X}.XX>XOX}.oXXX<X0X0XwXwXwX0X2XXXoXXXoXOX5X0XwX0X1XoXXX5X*X}.}.oX<XqXrXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXrXrXwX0X,XL.b b D M.H.D.D.D.D.m.L b b W H.Z.# b Y / m b b b Z P.:X:X:X$X:.Z b b b b n :.;X;X;XR b A &.Z b b b b *.wXwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXrXwX0X:X$.b b E B.H.H.D.D.D.D.P b b E H.V.. b U L v v n b b ( #X;X$X~.Y b m N m b b ! {.&X#XI b C R v v n b b ! 0XwXrXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXrXwX0X:X!.A b Z F.H.H.H.H.H.D.m.L b b e b.+.b b V k i.r.t n b b s.H.x v b L q.b.p.D b b t F.$.n b M l a.M.y b b A :X0XwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXrXwX0X:XL.m b D H.).H.+XH.H.H.D.H b b 6 v.j b b - a.A.m.@.m b b h D.< b b w z.b.b.P b b q B.z b b @ B.D.m...v b G :X,XwXwXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXwX0X,X&X/ b b , D.H.+X+X+X+XH.f.B b b 5.8.M b M w.v.v.v.r.D b b h l v b b M     V v b b q u.X b n @.v.m.v.j b b Q &X,X0XwXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXwX0X,X$X^ b b , H.H.+X+XH.H.H.s.N b n 7.7.v b B 8.v.v.v.w.M b b g r b b b n n n b b b b e y.O b n X.m.v.n.e b b u &X,X0XrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXrX0X,X$X/ b b + F.H.H.H.+XH.d.b b M | 8.> c b @ 9.v.9.u., b b - 3.& b b 7 1.1.4.4.4.6.7.9.w.m b + t.v.m.p.D b b K.;X,X0XwXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXwX0X,X$X-.b b b i D.H.G.H.J.N b b = 9.9.5 c b B 7.9.v.y.b b m f 4.O b b 3 6.6.6.g 9 4 h u.h b b - b.m.m.s.b b N ~.;X,X0XwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXwX0X,X;XE.G b b I z ] ] ] W n b H l 9.8.9 b b m e 6 r e b b # 0.y.< b b O 6 p 6 < # ; q.v.t b b 0 n.A.A.+.b b H _.;X,XwXwXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXwXwX,X;X#Xf.b b b b b b b b b - a.v.v.w.@ b b v b b b b b @ b.m.v.w.M b b b b b b v ..m.n.A b n g.H.H.H.4 b b [ &X,X0XwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXwXwX0X:X$XZ.Q H v n b m B H E x n.m.m.q.B b v < . v N + E z m.m.m.b.e - M m v M - t k.D.m.; # - V.H.+XH.s # # K.:X,X0XwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXrXwXwX,X,X$X+XG.Z.Z.B.C.S.F.H.H.H.D.D.j b b q v.b.a.n.B.H.H.+X+X+XH.H.D.Z.C.Z.Z.F.H.H.+X+XH.).H.$X&X&X;X$X#X#X:X,X0XwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXrXrXwX0X,X;X#X+X+X+XH.H.+X+X+XH.H.H.D.e b n i n.m.D.H.H.+X#X$X$X+X+X+X+XH.H.H.H.+X+X+X$X&X&X&X$X;X;X;X:X;X:X,X,X0XwXwXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXrXrXwXwX,X,X;X;X$X$X$X;X;X&X;X$X#X+XF b v s.H.H.+X$X&X;X;X,X,X,X;X:X;X;X;X;X;X;X:X,X,X,X0X,X0X,X0X0X0X0X0X0X0XwXwXrXtXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXrXtXrXwXwX0X,X:X;X;X;X;X;X:X;X;X;X$X+XC b B k.+X+X$X$X;X,X,X0X0X0X0X0X;X,X,X,X,X,X,X,X,X0X0X0X0X0X0XwX0X0X0XwXwXrXrXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXrXrXrXrXwXwXwX0X0X0X0X0X0X0X,X,X:X^.^.!.$X$X;X,X,X0XwXwXwXwXwXwXwXwX0X0X0X0XwXwXwXwXwXwXrXrXwXrXrXrXrXrXrXrXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXrXrXrXrXwXwXwXwX0XwXwXwX0X0X,X:X;X$X&X&X;X,X,X0XwXwXwXrXrXrXrXrXwXwXwXwXwXwXwXrXrXrXwXrXrXrXrXrXrXrXrXrXrXtXrXtXtXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXrXrXrXrXrXrXrXrXrXwXwXwXwX0X,X0X0X0XwXwXrXrXrXrXrXrXrXrXrXrXrXrXrXrXwXrXrXrXrXrXtXrXrXrXtXrXrXrXrXrXrXrXrXrXtXtXtXrXrXtXtXtXtXrXrXtXrXrXtXrXtXrXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXrXtXtXrXtXrXrXrXrXrXrXwXwXwX0XwX0XwXwXwXrXrXrXtXtXrXrXrXrXrXrXrXrXwXrXwXrXwXwXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXtXrXrXtXtXrXrXrXrXrXrXrXrXrXrXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXwXrXrXrXrXrXrXtXrXtXrXrXrXrXrXwXwXwXwXwX0X0XwX0XwXwXwXwXwXwXwXrXwXwXwX0X0X0X0XwX0XwXwXrXrXrXwXrXwXwXwX0XwX0XwXwXwXrXrXrXrXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXrXrXrXrXrXtXtXrXrXtXrXrXeX7X7X9XwXwXwX5X3X3X3X2X2X2X5X0XwXwXwXwXwX8X3X3X2X2X2X2X2X3X6X6X7XwXwXwXwXwXwX7X1XXXOXOX1X8XwXwXrXrXrXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXtXtXrXrXrXwXT.T T :.,X,X-X` G G G G G G U _ J.-X,X,X,X[ G G G G G G G G G G _ >XwX0X,X&XI.R N b b b m ! `.5XwXrXrXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXtXtXrXtXrXrXrXwX0X' b b ] >X,X%XJ b b b b b b b b Q {.:X;X:Xq b b b b b b b b b b Y >X0X,X-X'.^ n b b b b b m *.1XwXwXrXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrX0X0X%XL b b L.@X+X-.b b M L L L D b b b M V.+X(.N b b D H H H H H U U W.;X&X^.H b b n W -.-.W n b b J &XwXrXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXwXwX0X XF b b U.+X+X[ b b D z z j P v b b N U.H.S.m b m E Q t ^ ) / ) ) /.$X$X;.m b n A %.H.H.J.N b b N .XwXwXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXwXwX,X:X!.m b L N.D.m.* b b y v.v.v.v.p.n b M f.m.w b b D u.v.m.m.D.G.H.H.+X).g.b b B j.F.D.D.D.D.l.; F I /.0XwXrXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXwX,X:XU.n b E B.A.n.$ b b s v.9.v.v.r.n n M r.b.1 b b D u.v.m.m.D.D.H.H.).H.k b b # M.G.D.D.D.D.Z.t w u _.0XwXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXwXwX,X;X$XJ b m h b.v.i.m b M a 5.5.2.p M b c < 8.2.+ b b M o o o o # % j G.H.g.m b A M.D.D.D.B.M.M.M.M.Z.(.:X0XwXrXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXrXrXwX,X,X&X(.n b M 0.v.v.s b b b b b n b b c b M u.v.g M b b b b b b b b b i G.D.0 b b 8 D.D.H.G.P n b b n b U :X,XwXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXrXwX0X,X;X$XV.n b M w.v.9.< b b b b b b b b c H r 9.v.a n b   * < < w w Q Q g.D.B.: b b r D.D.D.m.C b b b b b ) ;X0XwXrXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXrX6XP.=.K.;X#X+Xx n b D v.u.7.. b b M D . D & 2 q.b.b.v.v.< b b X 6.9.9.b.m.D.D.D.D.n.# b b f D.D.D.b.= 1 * N b n !.;X,XwXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXrXrXwX<X~ P x $X+XH.z b b - v.v.3.M b b < r r r k 0.a.m.m.m.v.# b b , 6.9.v.m.D.D.D.H.D.z.O b b s D.D.D.N.f l 9 v b M ~.;X,XwXrXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXrXwX0XY.n b e H.H.V.F b b p b.v.h v b v v.m.A.D.H.+X+X+XH.D.p.b b m p 9.v.m.D.D.H.H.H.D.N.- b b - m.A.D.A.m.a.B b b - (.:X0XwXrXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXwXwX0XY.n b ; Z.C.$.A b v 0.m.m.l n b M m.D.D.H.+X#X+X+XH.H.r.b b m < d l l l $.;.J.V.H.B.w b b C @.s.a.k.#.j n b b : ).:X,XwXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXwXwX0X'.N b b A B n b n z m.D.B.0 b b 9 H.H.+X$X;X:X;X$X$X+Xl b b b b b b b b b b b s.H.H.B.H b b b n Z Z b b V n b ] $X:X0XwXrXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXwX0X,X.XR b b b b b A P d.D.D.C.H b b j H.$X$X;X:X,X,X;X;X+X/ b b b b b b b b b b b a.H.H.D.u G b b b b b B H : v m ;.$X,XwXwXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXwXwX,X:X Xg.j 5 y s.C.H.H.+X+X|.E.Q.Q. X;X;X,X0XwXwX0X0X,X;X/.U.j.h.g.f.h.j.U.U.U.!.$X$X+X+XH.Z.g.y 4 6 l x.D.A.l.~.#X,X0XwXrXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXwX0X:X$XG.k.e.f.B.H.H.+X$X$X$X#X$X$X;X;X,X0XwXwXwXwX0X0X;X$X+XH.D.D.D.F.H.+X+X#X&X$X;X$X$X+X+XA.r.X.e.a.H.H.H.+X+X;X,X0XwXrXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXwX,X,X$X&X$X$X$X$X;X;X,X,X,X,X,X,X0XwXwXwXrXtXrXrXwXwX0X,X;X$X$X+X$X$X$X;X;X:X,X,X,X,X,X;X$X&X#X#X$X$X$X$X$X;X,X,X0XwXrXrXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXwXwX0X,X:X;X;X$X;X;X:X,X,X0X0X,X0X0X0XwXwXwXrXrXtXrXrXwXwX0X;X;X$X&X$X$X&X:X,X,X,X,X0X,X,X:X;X;X$X$X$X$X$X;X:X,X,X0XwXwXrXrXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXrXwXwXwX0X0X0X0X0X0XwXwXwXwXwXwXwXwXrXwXrXtXtXrXtXtXrXrXrXwX0X0X0X0X,X,X0X0X0X0XwXwXwXwXwXwX0X0X0X,X,X,X,X0X0XwXwXwXrXtXrXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXrXwXwX0X0X0X0X0XwXwXwXrXwXrXrXrXrXrXtXrXtXtXtXtXrXrXrXwXwXwX0X0X0X0X0X0X0XwXwXwXwXwXwXwXwXwX0X0X0X0XwXwXwXwXwXrXrXrXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXrXrXrXrXrXrXrXrXrXrXtXtXrXtXtXrXtXtXtXtXtXtXtXrXtXrXtXrXrXrXrXwXwXrXrXrXrXrXrXrXtXrXrXrXrXrXrXrXwXrXrXrXrXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXrXrXrXrXrXrXtXtXrXtXrXtXrXrXtXtXtXtXtXtXtXtXtXtXtXrXrXrXrXrXrXrXrXrXrXrXtXtXrXtXrXrXtXrXrXrXrXrXrXrXrXtXrXrXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
-"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX"
-};
diff --git a/OPJViewer/source/readmeafter.txt b/OPJViewer/source/readmeafter.txt
deleted file mode 100644 (file)
index d5e8fb9..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-This viewer is conceived to open and display information and image content of J2K, JP2,\r
-and MJ2 files.\r
-The viewer application interface is divided into three main panels:\r
-- a browsing pane;\r
-- a viewing pane;\r
-- a log/peek pane.\r
-\r
-The browsing pane will present the markers or boxes hierarchy, with position (byte number where marker/box starts and stops) and length information (i.e., inner length as signalled by marker/box and total length, with marker/box sign included), in the following form:\r
-\r
-filename\r
-|\r
-|_ #000: Marker/Box short name (Hex code)\r
-|  |\r
-|  |_ *** Marker/Box long name ***\r
-|  |_ startbyte > stopbyte, inner_length + marker/box sign length (total length)\r
-|  |_ Additional info, depending on the marker/box type\r
-|  |_ ...\r
-|\r
-|_ #001: Marker/Box short name (Hex code)\r
-|  |\r
-|  |_ ...\r
-|\r
-...\r
-\r
-\r
-The viewing pane will display the decoded image contained in the JPEG 2000 file.\r
-It should display correctly images as large as 4000x2000, provided that a couple of GB of RAM are available. Nothing is known about the display of larger sizes: let us know if you manage to get it working.\r
-\r
-\r
-The log/peek pane is shared among two different subpanels:\r
-\r
-- the log panel will report a lot of debugging info coming out from the wx GUI as well as from the openjpeg library\r
-- the peek pane tries to give a peek on the codestream/file portion which is currently selected in the browsing pane. It shows both hex and ascii values corresponding to the marker/box section. \r
-\r
diff --git a/OPJViewer/source/readmebefore.txt b/OPJViewer/source/readmebefore.txt
deleted file mode 100644 (file)
index c5e1ed8..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-What is OpenJPEG ?\r
-==================\r
-The OpenJPEG library is an open-source JPEG 2000 codec written in C language. It has been developed in order to promote the use of JPEG 2000, the new still-image compression standard from the Joint Photographic Experts Group (JPEG). In addition to the basic codec, various other features are under development, among them the JP2 and MJ2 (Motion JPEG 2000) file formats, an indexing tool useful for the JPIP protocol, JPWL-tools for error-resilience, a Java-viewer for j2k-images, ... \r
-\r
-Who can use the library ?\r
-=========================\r
-Anybody. As the OpenJPEG library is released under the BSD license, anybody can use or modify the library, even for commercial applications. The only restriction is to retain the copyright in the sources or the binaries documentation.\r
-\r
-Who is developing the library ?\r
-===============================\r
-The library is developed by the Communications and Remote Sensing Lab (TELE), in the Universit� Catholique de Louvain (UCL). The JPWL module is developped and maintained by the Digital Signal Processing Lab (DSPLab) of the University of Perugia, Italy (UNIPG). As our purpose is to make OpenJPEG really useful for those interested in the image compression field, any feedback/advices are obviously welcome ! We will do our best to handle them quickly. 
\ No newline at end of file
diff --git a/OPJViewer/source/wxj2kparser.cpp b/OPJViewer/source/wxj2kparser.cpp
deleted file mode 100644 (file)
index 600fd65..0000000
+++ /dev/null
@@ -1,1465 +0,0 @@
-/*\r
- * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-#include "OPJViewer.h"\r
-\r
-/* From little endian to big endian, 2 bytes */\r
-#define        BYTE_SWAP2(X)   ((X & 0x00FF) << 8) | ((X & 0xFF00) >> 8)\r
-#define        BYTE_SWAP4(X)   ((X & 0x000000FF) << 24) | ((X & 0x0000FF00) << 8) | ((X & 0x00FF0000) >> 8) | ((X & 0xFF000000) >> 24)\r
-\r
-/* From codestream to int values */\r
-#define STREAM_TO_UINT32(C, P) (((unsigned long int) (C)[(P) + 0] << 24) + \\r
-                                                               ((unsigned long int) (C)[(P) + 1] << 16) + \\r
-                                                               ((unsigned long int) (C)[(P) + 2] << 8) + \\r
-                                                               ((unsigned long int) (C)[(P) + 3] << 0))\r
-\r
-#define STREAM_TO_UINT16(C, P) (((unsigned long int) (C)[(P) + 0] << 8) + \\r
-                                                               ((unsigned long int) (C)[(P) + 1] << 0))\r
-\r
-\r
-/* Markers values */\r
-#define J2KMARK_NUM 24\r
-enum {\r
-       SOC_VAL = 0xFF4F,\r
-       SOT_VAL = 0xFF90,\r
-       SOD_VAL = 0xFF93,\r
-       EOC_VAL = 0xFFD9,\r
-       SIZ_VAL = 0xFF51,\r
-       COD_VAL = 0xFF52,\r
-       COC_VAL = 0xFF53,\r
-       RGN_VAL = 0xFF5E,\r
-       QCD_VAL = 0xFF5C,\r
-       QCC_VAL = 0xFF5D,\r
-       POD_VAL = 0xFF5F,\r
-       TLM_VAL = 0xFF55,\r
-       PLM_VAL = 0xFF57,\r
-       PLT_VAL = 0xFF58,\r
-       PPM_VAL = 0xFF60,\r
-       PPT_VAL = 0xFF61,\r
-       SOP_VAL = 0xFF91,\r
-       EPH_VAL = 0xFF92,\r
-       COM_VAL = 0xFF64\r
-#ifdef USE_JPWL\r
-       , EPB_VAL       = 0xFF66,\r
-       ESD_VAL = 0xFF67,\r
-       EPC_VAL = 0xFF68,\r
-       RED_VAL = 0xFF69\r
-       /*, EPB_VAL = 0xFF96,\r
-       ESD_VAL = 0xFF98,\r
-       EPC_VAL = 0xFF97,\r
-       RED_VAL = 0xFF99*/\r
-#endif // USE_JPWL\r
-#ifdef USE_JPSEC\r
-       , SEC_VAL = 0xFF65\r
-#endif // USE_JPSEC\r
-};\r
-\r
-// All the markers in one vector\r
-unsigned short int marker_val[] = {\r
-       SOC_VAL, SOT_VAL, SOD_VAL, EOC_VAL,\r
-       SIZ_VAL,\r
-       COD_VAL, COC_VAL, RGN_VAL, QCD_VAL, QCC_VAL, POD_VAL,\r
-       TLM_VAL, PLM_VAL, PLT_VAL, PPM_VAL, PPT_VAL,\r
-       SOP_VAL, EPH_VAL,\r
-       COM_VAL\r
-#ifdef USE_JPWL\r
-       , EPB_VAL, ESD_VAL, EPC_VAL, RED_VAL\r
-#endif // USE_JPWL\r
-#ifdef USE_JPSEC\r
-       , SEC_VAL\r
-#endif // USE_JPSEC\r
-};\r
-\r
-// Marker names\r
-char *marker_name[] = {\r
-       "SOC", "SOT", "SOD", "EOC",\r
-       "SIZ",\r
-       "COD", "COC", "RGN", "QCD", "QCC", "POD",\r
-       "TLM", "PLM", "PLT", "PPM", "PPT",\r
-       "SOP", "EPH",\r
-       "COM"\r
-#ifdef USE_JPWL\r
-       , "EPB", "ESD", "EPC", "RED"\r
-#endif // USE_JPWL\r
-#ifdef USE_JPSEC\r
-       , "SEC"\r
-#endif // USE_JPSEC\r
-};\r
-\r
-// Marker descriptions\r
-char *marker_descr[] = {\r
-       "Start of codestream", "Start of tile-part", "Start of data", "End of codestream",\r
-       "Image and tile size",\r
-       "Coding style default", "Coding style component", "Region-of-interest", "Quantization default",\r
-       "Quantization component", "Progression order change, default",\r
-       "Tile-part lengths, main header", "Packet length, main header", "Packets length, tile-part header",\r
-       "Packed packet headers, main header", "Packed packet headers, tile-part header",\r
-       "Start of packet", "End of packet header",\r
-       "Comment and extension"\r
-#ifdef USE_JPWL\r
-       , "Error Protection Block", "Error Sensitivity Descriptor", "Error Protection Capability",\r
-       "Residual Errors Descriptor"\r
-#endif // USE_JPWL\r
-#ifdef USE_JPSEC\r
-       , "Main security marker"\r
-#endif // USE_JPSEC\r
-};\r
-\r
-void OPJParseThread::ParseJ2KFile(wxFile *m_file, wxFileOffset offset, wxFileOffset length, wxTreeItemId parentid)\r
-{\r
-       unsigned short int csiz = 0;\r
-\r
-       // check if the file is opened\r
-       if (m_file->IsOpened())\r
-               WriteText(wxT("File OK"));\r
-       else\r
-               return;\r
-\r
-       // position at the beginning\r
-       m_file->Seek(offset, wxFromStart);\r
-\r
-       // navigate the file\r
-       int m, inside_sod = 0, inside_sop = 0;\r
-       int nmarks = 0, maxmarks = 10000;\r
-       unsigned char onebyte[1];\r
-       unsigned char twobytes[2], firstbyte, secondbyte;\r
-       unsigned char fourbytes[4];\r
-       unsigned short int currmark;\r
-       unsigned short int currlen;\r
-       int lastPsot = 0, lastsotpos = 0;\r
-\r
-       WriteText(wxT("Start search..."));\r
-\r
-// advancing macro\r
-#define OPJ_ADVANCE(A) {offset += A; if (offset < length) m_file->Seek(offset, wxFromStart); else return;}\r
-\r
-       // begin search\r
-       while ((offset < length) && (!m_file->Eof())) {\r
-\r
-               // read one byte\r
-               if (m_file->Read(&firstbyte, 1) != 1)\r
-                       break;\r
-\r
-               // look for 0xFF\r
-               if (firstbyte == 0xFF) {\r
-\r
-                       // it is a possible marker\r
-                       if (m_file->Read(&secondbyte, 1) != 1)\r
-                               break;\r
-                       else\r
-                               currmark = (((unsigned short int) firstbyte) << 8) + (unsigned short int) secondbyte;\r
-\r
-               } else {\r
-\r
-                       // nope, advance by one and search again\r
-                       OPJ_ADVANCE(1);\r
-                       continue;\r
-               }\r
-               \r
-               // search the marker\r
-               for (m = 0; m < J2KMARK_NUM; m++) {\r
-                       if (currmark == marker_val[m])\r
-                               break;\r
-               }\r
-\r
-               // marker not found\r
-               if (m == J2KMARK_NUM) {\r
-                       // nope, advance by one and search again\r
-                       OPJ_ADVANCE(1);\r
-                       continue;\r
-               }\r
-\r
-               // if we are inside SOD, only some markers are allowed\r
-               if (inside_sod) {\r
-\r
-                       // we are inside SOP\r
-                       if (inside_sop) {\r
-\r
-                       }\r
-\r
-                       // randomly marker coincident data\r
-                       if ((currmark != SOT_VAL) &&\r
-                               (currmark != EOC_VAL) &&\r
-                               (currmark != SOP_VAL) &&\r
-                               (currmark != EPH_VAL)) {\r
-                               OPJ_ADVANCE(1);\r
-                               continue;\r
-                       }\r
-\r
-                       // possible SOT?\r
-                       if ((currmark == SOT_VAL)) {\r
-                               // too early SOT\r
-                               if (offset < (lastsotpos + lastPsot)) {\r
-                                       OPJ_ADVANCE(1);\r
-                                       continue;\r
-                               }\r
-                               // we were not in the last tile\r
-                               /*if (lastPsot != 0) {\r
-                                       OPJ_ADVANCE(1);\r
-                                       break;\r
-                               }*/\r
-                       }\r
-               }\r
-\r
-               // beyond this point, the marker MUST BE real\r
-\r
-               // length of current marker segment\r
-               if ((currmark == SOD_VAL) ||\r
-                       (currmark == SOC_VAL) ||\r
-                       (currmark == EOC_VAL) ||\r
-                       (currmark == EPH_VAL))\r
-\r
-                       // zero length markers\r
-                       currlen = 0;\r
-\r
-               else {\r
-\r
-                       // read length field\r
-                       if (m_file->Read(twobytes, 2) != 2)\r
-                               break;\r
-\r
-                       currlen = (((unsigned short int) twobytes[0]) << 8) + (unsigned short int) twobytes[1];\r
-               }\r
-\r
-               // here we pass to AppendItem() normal and selected item images (we\r
-               // suppose that selected image follows the normal one in the enum)\r
-               int image, imageSel;\r
-               image = m_tree->TreeCtrlIcon_Folder;\r
-               imageSel = image + 1;\r
-\r
-               // append the marker\r
-               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                       wxString::Format(wxT("%03d: "), nmarks) +\r
-                       wxString::FromAscii(marker_name[m]) + \r
-                       wxString::Format(wxT(" (0x%04X)"), marker_val[m]),\r
-                       image, imageSel,\r
-                       new OPJMarkerData(wxT("MARK") + wxString::Format(wxT(" (%d)"), marker_val[m]),\r
-                               m_tree->m_fname.GetFullPath(), offset, offset + currlen + 1)\r
-                       );\r
-\r
-               // append some info\r
-               image = m_tree->TreeCtrlIcon_File;\r
-               imageSel = image + 1;\r
-\r
-               // marker name\r
-               wxTreeItemId subcurrid1 = m_tree->AppendItem(currid,\r
-                       wxT("*** ") + wxString::FromAscii(marker_descr[m]) + wxT(" ***"),\r
-                       image, imageSel,\r
-                       new OPJMarkerData(wxT("INFO"))\r
-                       );\r
-               m_tree->SetItemFont(subcurrid1, *wxITALIC_FONT);\r
-\r
-               // position and length\r
-               wxTreeItemId subcurrid2 = m_tree->AppendItem(currid,\r
-                       wxLongLong(offset).ToString() + wxT(" > ") + wxLongLong(offset + currlen + 1).ToString() + \r
-                       wxT(", ") + wxString::Format(wxT("%d + 2 (%d)"), currlen, currlen + 2),\r
-                       image, imageSel,\r
-                       new OPJMarkerData(wxT("INFO"))\r
-                       );\r
-\r
-               // give additional info on markers\r
-               switch (currmark) {\r
-\r
-               /////////\r
-               // SOP //\r
-               /////////\r
-               case SOP_VAL:\r
-                       {\r
-                       // read packet number\r
-                       if (m_file->Read(twobytes, 2) != 2)\r
-                               break;\r
-                       int packnum = STREAM_TO_UINT16(twobytes, 0);\r
-\r
-                       image = m_tree->TreeCtrlIcon_File;\r
-                       imageSel = image + 1;\r
-\r
-                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("Pack. no. %d"), packnum),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-                       inside_sop = 1;\r
-                       };\r
-                       break;\r
-\r
-#ifdef USE_JPWL\r
-               /////////\r
-               // RED //\r
-               /////////\r
-               case RED_VAL:\r
-                       {\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char pred = onebyte[0];\r
-\r
-                       image = m_tree->TreeCtrlIcon_File;\r
-                       imageSel = image + 1;\r
-\r
-                       wxString address[] = {\r
-                               wxT("Packet addressing"),\r
-                               wxT("Byte-range addressing"),\r
-                               wxT("Packet-range addressing"),\r
-                               wxT("Reserved")\r
-                       };\r
-\r
-                       wxTreeItemId subcurrid = m_tree->AppendItem(currid,\r
-                               address[(pred & 0xC0) >> 6],\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       subcurrid = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("%d bytes range"), (((pred & 0x02) >> 1) + 1) * 2),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       subcurrid = m_tree->AppendItem(currid,\r
-                               pred & 0x01 ? wxT("Errors/erasures in codestream") : wxT("Error free codestream"),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       subcurrid = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("Residual corruption level: %d"), (pred & 0x38) >> 3),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       }\r
-                       break;\r
-\r
-               /////////\r
-               // ESD //\r
-               /////////\r
-               case ESD_VAL:\r
-                       {\r
-                       unsigned short int cesd;\r
-                       if (csiz < 257) {\r
-                               if (m_file->Read(onebyte, 1) != 1)\r
-                                       break;\r
-                               cesd = onebyte[0];\r
-                       } else {\r
-                               if (m_file->Read(twobytes, 2) != 2)\r
-                                       break;\r
-                               cesd = STREAM_TO_UINT16(twobytes, 0);\r
-                       }\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char pesd = onebyte[0];\r
-\r
-                       image = m_tree->TreeCtrlIcon_File;\r
-                       imageSel = image + 1;\r
-\r
-                       wxTreeItemId subcurrid = m_tree->AppendItem(currid,\r
-                               pesd & 0x01 ? wxT("Comp. average") : wxString::Format(wxT("Comp. no. %d"), cesd),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       wxString meth[] = {\r
-                               wxT("Relative error sensitivity"),\r
-                               wxT("MSE"),\r
-                               wxT("MSE reduction"),\r
-                               wxT("PSNR"),\r
-                               wxT("PSNR increase"),\r
-                               wxT("MAXERR (absolute peak error)"),\r
-                               wxT("TSE (total squared error)"),\r
-                               wxT("Reserved")\r
-                       };\r
-\r
-                       subcurrid = m_tree->AppendItem(currid,\r
-                               meth[(pesd & 0x38) >> 3],\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       wxString address[] = {\r
-                               wxT("Packet addressing"),\r
-                               wxT("Byte-range addressing"),\r
-                               wxT("Packet-range addressing"),\r
-                               wxT("Reserved")\r
-                       };\r
-\r
-                       subcurrid = m_tree->AppendItem(currid,\r
-                               address[(pesd & 0xC0) >> 6],\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       subcurrid = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("%d bytes/value, %d bytes range"), ((pesd & 0x04) >> 2) + 1, (((pesd & 0x02) >> 1) + 1) * 2),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       }\r
-                       break;\r
-\r
-               /////////\r
-               // EPC //\r
-               /////////\r
-               case EPC_VAL:\r
-                       {\r
-                       if (m_file->Read(twobytes, 2) != 2)\r
-                               break;\r
-                       unsigned short int pcrc = STREAM_TO_UINT16(twobytes, 0);\r
-\r
-                       if (m_file->Read(fourbytes, 4) != 4)\r
-                               break;\r
-                       unsigned long int dl = STREAM_TO_UINT32(fourbytes, 0);\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char pepc = onebyte[0];\r
-\r
-                       image = m_tree->TreeCtrlIcon_File;\r
-                       imageSel = image + 1;\r
-\r
-                       wxTreeItemId subcurrid = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("CRC-16 = 0x%x"), pcrc),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       subcurrid = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("Tot. length = %d"), dl),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       subcurrid = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("%s%s%s%s"),\r
-                                       pepc & 0x10 ? wxT("ESD, ") : wxT(""),\r
-                                       pepc & 0x20 ? wxT("RED, ") : wxT(""),\r
-                                       pepc & 0x40 ? wxT("EPB, ") : wxT(""),\r
-                                       pepc & 0x80 ? wxT("Info") : wxT("")\r
-                                       ),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       }\r
-                       break;\r
-\r
-               /////////\r
-               // EPB //\r
-               /////////\r
-               case EPB_VAL:\r
-                       {\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char depb = onebyte[0];\r
-\r
-                       if (m_file->Read(fourbytes, 4) != 4)\r
-                               break;\r
-                       unsigned long int ldpepb = STREAM_TO_UINT32(fourbytes, 0);\r
-\r
-                       if (m_file->Read(fourbytes, 4) != 4)\r
-                               break;\r
-                       unsigned long int pepb = STREAM_TO_UINT32(fourbytes, 0);\r
-\r
-                       image = m_tree->TreeCtrlIcon_File;\r
-                       imageSel = image + 1;\r
-\r
-                       wxTreeItemId subcurrid = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("No. %d, %slatest, %spacked"),\r
-                                       depb & 0x3F,\r
-                                       depb & 0x40 ? wxT("") : wxT("not "),\r
-                                       depb & 0x80 ? wxT("") : wxT("un")),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       subcurrid = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("%d bytes protected"), ldpepb),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (pepb == 0x00000000)\r
-\r
-                               subcurrid = m_tree->AppendItem(currid,\r
-                                       wxT("Predefined codes"),\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-                       else if ((pepb >= 0x10000000) && (pepb <= 0x1FFFFFFF)) {\r
-\r
-                               wxString text = wxT("CRC code");\r
-                               if (pepb == 0x10000000)\r
-                                       text << wxT(", CCITT (X25) 16 bits");\r
-                               else if (pepb == 0x10000001)\r
-                                       text << wxT(", Ethernet 32 bits");\r
-                               else\r
-                                       text << wxT(", JPWL RA");\r
-                               subcurrid = m_tree->AppendItem(currid,\r
-                                       text,\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-                       } else if ((pepb >= 0x20000000) && (pepb <= 0x2FFFFFFF)) {\r
-\r
-                               wxString text;\r
-                               subcurrid = m_tree->AppendItem(currid,\r
-                                       wxString::Format(wxT("RS code, RS(%d, %d)"),\r
-                                               (pepb & 0x0000FF00) >> 8,\r
-                                               (pepb & 0x000000FF)),\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-                       } else if ((pepb >= 0x30000000) && (pepb <= 0x3FFFFFFE))\r
-\r
-                               subcurrid = m_tree->AppendItem(currid,\r
-                                       wxT("JPWL RA"),\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-                       else if (pepb == 0xFFFFFFFF)\r
-\r
-                               subcurrid = m_tree->AppendItem(currid,\r
-                                       wxT("No method"),\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-                       }\r
-                       break;\r
-#endif // USE_JPWL\r
-\r
-#ifdef USE_JPSEC\r
-               case SEC_VAL:\r
-                       {\r
-\r
-                       }\r
-                       break;\r
-#endif // USE_JPSEC\r
-\r
-               /////////\r
-               // SIZ //\r
-               /////////\r
-               case SIZ_VAL:\r
-                       {\r
-                       int c;\r
-                       \r
-                       if (m_file->Read(twobytes, 2) != 2)\r
-                               break;\r
-                       unsigned short int rsiz = STREAM_TO_UINT16(twobytes, 0);\r
-\r
-                       if (m_file->Read(fourbytes, 4) != 4)\r
-                               break;\r
-                       unsigned long int xsiz = STREAM_TO_UINT32(fourbytes, 0);\r
-\r
-                       if (m_file->Read(fourbytes, 4) != 4)\r
-                               break;\r
-                       unsigned long int ysiz = STREAM_TO_UINT32(fourbytes, 0);\r
-\r
-                       if (m_file->Read(fourbytes, 4) != 4)\r
-                               break;\r
-                       unsigned long int xosiz = STREAM_TO_UINT32(fourbytes, 0);\r
-\r
-                       if (m_file->Read(fourbytes, 4) != 4)\r
-                               break;\r
-                       unsigned long int yosiz = STREAM_TO_UINT32(fourbytes, 0);\r
-\r
-                       if (m_file->Read(fourbytes, 4) != 4)\r
-                               break;\r
-                       unsigned long int xtsiz = STREAM_TO_UINT32(fourbytes, 0);\r
-                       this->m_tree->m_childframe->m_twidth = xtsiz;\r
-\r
-                       if (m_file->Read(fourbytes, 4) != 4)\r
-                               break;\r
-                       unsigned long int ytsiz = STREAM_TO_UINT32(fourbytes, 0);\r
-                       this->m_tree->m_childframe->m_theight = ytsiz;\r
-\r
-                       if (m_file->Read(fourbytes, 4) != 4)\r
-                               break;\r
-                       unsigned long int xtosiz = STREAM_TO_UINT32(fourbytes, 0);\r
-                       this->m_tree->m_childframe->m_tx = xtosiz;\r
-\r
-                       if (m_file->Read(fourbytes, 4) != 4)\r
-                               break;\r
-                       unsigned long int ytosiz = STREAM_TO_UINT32(fourbytes, 0);\r
-                       this->m_tree->m_childframe->m_ty = ytosiz;\r
-\r
-                       if (m_file->Read(twobytes, 2) != 2)\r
-                               break;\r
-                       csiz = STREAM_TO_UINT16(twobytes, 0);\r
-\r
-                       bool equaldepth = true, equalsize = true;\r
-                       unsigned char *ssiz  = new unsigned char(csiz);\r
-                       unsigned char *xrsiz = new unsigned char(csiz);\r
-                       unsigned char *yrsiz = new unsigned char(csiz);\r
-\r
-                       for (c = 0; c < csiz; c++) {\r
-\r
-                               if (m_file->Read(&ssiz[c], 1) != 1)\r
-                                       break;\r
-\r
-                               if (c > 0)\r
-                                       equaldepth = equaldepth && (ssiz[c] == ssiz[c - 1]);\r
-\r
-                               if (m_file->Read(&xrsiz[c], 1) != 1)\r
-                                       break;\r
-\r
-                               if (m_file->Read(&yrsiz[c], 1) != 1)\r
-                                       break;\r
-\r
-                               if (c > 0)\r
-                                       equalsize = equalsize && (xrsiz[c] == xrsiz[c - 1]) && (yrsiz[c] == yrsiz[c - 1]) ;\r
-\r
-                       }\r
-\r
-                       if (equaldepth && equalsize)\r
-                               wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
-                                       wxString::Format(wxT("I: %dx%d (%d, %d), %d c., %d%s bpp"),\r
-                                       xsiz, ysiz,\r
-                                       xosiz, yosiz,\r
-                                       csiz, ((ssiz[0] & 0x7F) + 1),\r
-                                       (ssiz[0] & 0x80) ? wxT("s") : wxT("u")),\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                       else\r
-                               wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
-                                       wxString::Format(wxT("I: %dx%d (%d, %d), %d c."),\r
-                                       xsiz, ysiz,\r
-                                       xosiz, yosiz,\r
-                                       csiz),\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("T: %dx%d (%d, %d)"),\r
-                               xtsiz, ytsiz,\r
-                               xtosiz, ytosiz),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       image = m_tree->TreeCtrlIcon_Folder;\r
-                       imageSel = image + 1;\r
-\r
-                       wxTreeItemId subcurrid4 = m_tree->AppendItem(currid,\r
-                               wxT("Components"),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       image = m_tree->TreeCtrlIcon_File;\r
-                       imageSel = image + 1;\r
-\r
-                       for (c = 0; c < csiz; c++) {\r
-\r
-                               wxTreeItemId subcurrid5 = m_tree->AppendItem(subcurrid4,\r
-                                       wxString::Format(wxT("#%d: %dx%d, %d%s bpp"),\r
-                                       c,\r
-                                       xsiz/xrsiz[c], ysiz/yrsiz[c],\r
-                                       ((ssiz[c] & 0x7F) + 1),\r
-                                       (ssiz[c] & 0x80) ? wxT("s") : wxT("u")),\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-                       }\r
-\r
-                       };\r
-                       break;\r
-\r
-               /////////\r
-               // SOT //\r
-               /////////\r
-               case SOT_VAL:\r
-                       {\r
-                       if (m_file->Read(twobytes, 2) != 2)\r
-                               break;\r
-                       unsigned short int isot = STREAM_TO_UINT16(twobytes, 0);\r
-\r
-                       if (m_file->Read(fourbytes, 4) != 4)\r
-                               break;\r
-                       unsigned long int psot = STREAM_TO_UINT32(fourbytes, 0);\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char tpsot = onebyte[0];\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char tnsot = onebyte[0];\r
-\r
-                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("tile %d, psot = %d, part %d of %d"), isot, psot, tpsot, tnsot),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       lastPsot = psot;\r
-                       lastsotpos = offset;\r
-                       inside_sod = 0;\r
-                       };\r
-                       break;\r
-\r
-               /////////\r
-               // COC //\r
-               /////////\r
-               case COC_VAL:\r
-                       {\r
-                       unsigned short int ccoc;\r
-                       if (csiz < 257) {\r
-                               if (m_file->Read(onebyte, 1) != 1)\r
-                                       break;\r
-                               ccoc = onebyte[0];\r
-                       } else {\r
-                               if (m_file->Read(twobytes, 2) != 2)\r
-                                       break;\r
-                               ccoc = STREAM_TO_UINT16(twobytes, 0);\r
-                       }\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char scoc = onebyte[0];\r
-\r
-                       wxTreeItemId subcurrid = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("Comp. no. %d"), ccoc),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-                       \r
-                       wxString text;\r
-                       if (scoc & 0x01)\r
-                               text << wxT("Partitioned entropy coder");\r
-                       else\r
-                               text << wxT("Unpartitioned entropy coder");\r
-\r
-                       subcurrid = m_tree->AppendItem(currid,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char decomplevs = onebyte[0];\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char cbswidth = onebyte[0];\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char cbsheight = onebyte[0];\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char cbstyle = onebyte[0];\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char transform = onebyte[0];\r
-\r
-                       subcurrid = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("%d levels (%d resolutions)"), decomplevs, decomplevs + 1),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (transform & 0x01)\r
-                               text = wxT("5-3 reversible wavelet");\r
-                       else\r
-                               text = wxT("9-7 irreversible wavelet");\r
-                       subcurrid = m_tree->AppendItem(currid,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       subcurrid = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("Code-blocks: %dx%d"), 1 << ((cbswidth & 0x0F) + 2), 1 << ((cbsheight & 0x0F) + 2)),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       image = m_tree->TreeCtrlIcon_Folder;\r
-                       imageSel = image + 1;\r
-\r
-                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
-                               wxT("Coding styles"),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       image = m_tree->TreeCtrlIcon_File;\r
-                       imageSel = image + 1;\r
-\r
-                       if (cbstyle & 0x01)\r
-                               text = wxT("Selective arithmetic coding bypass");\r
-                       else\r
-                               text = wxT("No selective arithmetic coding bypass");\r
-                       wxTreeItemId subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (cbstyle & 0x02)\r
-                               text = wxT("Reset context probabilities on coding pass boundaries");\r
-                       else\r
-                               text = wxT("No reset of context probabilities on coding pass boundaries");\r
-                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (cbstyle & 0x04)\r
-                               text = wxT("Termination on each coding passs");\r
-                       else\r
-                               text = wxT("No termination on each coding pass");\r
-                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (cbstyle & 0x08)\r
-                               text = wxT("Vertically stripe causal context");\r
-                       else\r
-                               text = wxT("No vertically stripe causal context");\r
-                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (cbstyle & 0x10)\r
-                               text = wxT("Predictable termination");\r
-                       else\r
-                               text = wxT("No predictable termination");\r
-                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (cbstyle & 0x20)\r
-                               text = wxT("Segmentation symbols are used");\r
-                       else\r
-                               text = wxT("No segmentation symbols are used");\r
-                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       }\r
-                       break;\r
-\r
-               /////////\r
-               // COD //\r
-               /////////\r
-               case COD_VAL:\r
-                       {\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char scod = onebyte[0];\r
-\r
-                       wxString text;\r
-\r
-                       if (scod & 0x01)\r
-                               text << wxT("Partitioned entropy coder");\r
-                       else\r
-                               text << wxT("Unpartitioned entropy coder");\r
-\r
-                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       text = wxT("");\r
-                       if (scod & 0x02)\r
-                               text << wxT("Possible SOPs");\r
-                       else\r
-                               text << wxT("No SOPs");\r
-\r
-                       if (scod & 0x04)\r
-                               text << wxT(", possible EPHs");\r
-                       else\r
-                               text << wxT(", no EPHs");\r
-\r
-                       subcurrid3 = m_tree->AppendItem(currid,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char progord = onebyte[0];\r
-\r
-                       if (m_file->Read(twobytes, 2) != 2)\r
-                               break;\r
-                       unsigned short int numlayers = STREAM_TO_UINT16(twobytes, 0);\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char mctransform = onebyte[0];\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char decomplevs = onebyte[0];\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char cbswidth = onebyte[0];\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char cbsheight = onebyte[0];\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char cbstyle = onebyte[0];\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char transform = onebyte[0];\r
-\r
-                       subcurrid3 = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("%d levels (%d resolutions)"), decomplevs, decomplevs + 1),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       text = wxT("");\r
-                       switch (progord) {\r
-                       case (0):\r
-                               text << wxT("LRCP");\r
-                               break;\r
-                       case (1):\r
-                               text << wxT("RLCP");\r
-                               break;\r
-                       case (2):\r
-                               text << wxT("LRCP");\r
-                               break;\r
-                       case (3):\r
-                               text << wxT("RPCL");\r
-                               break;\r
-                       case (4):\r
-                               text << wxT("CPRL");\r
-                               break;\r
-                       default:\r
-                               text << wxT("unknown progression");\r
-                               break;\r
-                       }\r
-                       text << wxString::Format(wxT(", %d layers"), numlayers);\r
-                       if (transform & 0x01)\r
-                               text << wxT(", 5-3 rev.");\r
-                       else\r
-                               text << wxT(", 9-7 irr.");\r
-                       subcurrid3 = m_tree->AppendItem(currid,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       subcurrid3 = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("Code-blocks: %dx%d"), 1 << ((cbswidth & 0x0F) + 2), 1 << ((cbsheight & 0x0F) + 2)),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       switch (mctransform) {\r
-                       case (0):\r
-                               {\r
-                               text = wxT("No MCT");\r
-                               }\r
-                               break;\r
-                       case (1):\r
-                               {\r
-                               text = wxT("Reversible MCT on 0, 1, 2");\r
-                               }\r
-                               break;\r
-                       case (2):\r
-                               {\r
-                               text = wxT("Irreversible MCT on 0, 1, 2");\r
-                               }\r
-                               break;\r
-                       default:\r
-                               {\r
-                               text = wxT("Unknown");\r
-                               }\r
-                               break;\r
-                       };\r
-                       subcurrid3 = m_tree->AppendItem(currid,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-\r
-                       image = m_tree->TreeCtrlIcon_Folder;\r
-                       imageSel = image + 1;\r
-\r
-                       subcurrid3 = m_tree->AppendItem(currid,\r
-                               wxT("Coding styles"),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       image = m_tree->TreeCtrlIcon_File;\r
-                       imageSel = image + 1;\r
-\r
-                       if (cbstyle & 0x01)\r
-                               text = wxT("Selective arithmetic coding bypass");\r
-                       else\r
-                               text = wxT("No selective arithmetic coding bypass");\r
-                       wxTreeItemId subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (cbstyle & 0x02)\r
-                               text = wxT("Reset context probabilities on coding pass boundaries");\r
-                       else\r
-                               text = wxT("No reset of context probabilities on coding pass boundaries");\r
-                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (cbstyle & 0x04)\r
-                               text = wxT("Termination on each coding passs");\r
-                       else\r
-                               text = wxT("No termination on each coding pass");\r
-                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (cbstyle & 0x08)\r
-                               text = wxT("Vertically stripe causal context");\r
-                       else\r
-                               text = wxT("No vertically stripe causal context");\r
-                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (cbstyle & 0x10)\r
-                               text = wxT("Predictable termination");\r
-                       else\r
-                               text = wxT("No predictable termination");\r
-                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (cbstyle & 0x20)\r
-                               text = wxT("Segmentation symbols are used");\r
-                       else\r
-                               text = wxT("No segmentation symbols are used");\r
-                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       };\r
-                       break;\r
-\r
-               /////////\r
-               // QCC //\r
-               /////////\r
-               case QCC_VAL:\r
-                       {\r
-                       unsigned short int cqcc;\r
-                       if (csiz < 257) {\r
-                               if (m_file->Read(onebyte, 1) != 1)\r
-                                       break;\r
-                               cqcc = onebyte[0];\r
-                       } else {\r
-                               if (m_file->Read(twobytes, 2) != 2)\r
-                                       break;\r
-                               cqcc = STREAM_TO_UINT16(twobytes, 0);\r
-                       }\r
-\r
-                       wxTreeItemId subcurrid = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("Comp. no. %d"), cqcc),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-                       \r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char sqcc = onebyte[0];\r
-\r
-                       wxString text;\r
-                       switch (sqcc & 0x1F) {\r
-                       case (0):\r
-                               text = wxT("No quantization");\r
-                               break;\r
-                       case (1):\r
-                               text = wxT("Scalar implicit");\r
-                               break;\r
-                       case (2):\r
-                               text = wxT("Scalar explicit");\r
-                               break;\r
-                       default:\r
-                               text = wxT("Unknown");\r
-                               break;\r
-                       }\r
-                       text << wxString::Format(wxT(", %d guard bits"), (sqcc & 0xE0) >> 5);\r
-                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       }\r
-                       break;\r
-\r
-               /////////\r
-               // QCD //\r
-               /////////\r
-               case QCD_VAL:\r
-                       {\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char sqcd = onebyte[0];\r
-\r
-                       wxString text;\r
-                       switch (sqcd & 0x1F) {\r
-                       case (0):\r
-                               text = wxT("No quantization");\r
-                               break;\r
-                       case (1):\r
-                               text = wxT("Scalar implicit");\r
-                               break;\r
-                       case (2):\r
-                               text = wxT("Scalar explicit");\r
-                               break;\r
-                       default:\r
-                               text = wxT("Unknown");\r
-                               break;\r
-                       }\r
-                       text << wxString::Format(wxT(", %d guard bits"), (sqcd & 0xE0) >> 5);\r
-                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       };\r
-                       break;\r
-\r
-               /////////\r
-               // COM //\r
-               /////////\r
-               case COM_VAL:\r
-                       {\r
-                       #define showlen 25\r
-                       char comment[showlen];\r
-                       wxString comments;\r
-\r
-                       if (m_file->Read(twobytes, 2) != 2)\r
-                               break;\r
-                       unsigned short int rcom = STREAM_TO_UINT16(twobytes, 0);\r
-\r
-                       wxString text;\r
-                       if (rcom == 0)\r
-                               text = wxT("Binary values");\r
-                       else if (rcom == 1)\r
-                               text = wxT("ISO 8859-1 (latin-1) values");\r
-                       else if (rcom < 65535)\r
-                               text = wxT("Reserved for registration");\r
-                       else\r
-                               text = wxT("Reserved for extension");\r
-                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
-                               text,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (m_file->Read(comment, showlen) != showlen)\r
-                               break;\r
-                       comments = wxString::FromAscii(comment).Truncate(wxMin(showlen, currlen - 4));\r
-                       if ((currlen - 4) > showlen)\r
-                               comments << wxT("...");\r
-                       subcurrid3 = m_tree->AppendItem(currid,\r
-                               comments,\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-                       };\r
-                       break;\r
-\r
-               /////////\r
-               // TLM //\r
-               /////////\r
-               case TLM_VAL:\r
-                       {\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char ztlm = onebyte[0];\r
-\r
-                       if (m_file->Read(onebyte, 1) != 1)\r
-                               break;\r
-                       unsigned char stlm = onebyte[0];\r
-\r
-                       image = m_tree->TreeCtrlIcon_File;\r
-                       imageSel = image + 1;\r
-\r
-                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("TLM #%d"), ztlm),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       subcurrid3 = m_tree->AppendItem(currid,\r
-                               wxString::Format(wxT("%d bits/index, %d bits/length"),\r
-                               8 * ((stlm & 0x30) >> 4), 16 + 16 * ((stlm & 0x40) >> 6)),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       int n, numparts;\r
-\r
-                       numparts = (currlen - 2) / ( ((stlm & 0x30) >> 4) + 2 + 2 * ((stlm & 0x40) >> 6));\r
-\r
-                       image = m_tree->TreeCtrlIcon_Folder;\r
-                       imageSel = image + 1;\r
-\r
-                       subcurrid3 = m_tree->AppendItem(currid,\r
-                               wxT("Tile parts"),\r
-                               image, imageSel,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       image = m_tree->TreeCtrlIcon_File;\r
-                       imageSel = image + 1;\r
-\r
-                       for (n = 0; n < numparts; n++) {\r
-\r
-                               unsigned short int ttlm;\r
-                               unsigned long int ptlm;\r
-\r
-                               switch (((stlm & 0x30) >> 4)) {\r
-\r
-                               case 0:\r
-                                       ttlm = 0;\r
-                                       break;\r
-\r
-                               case 1:\r
-                                       if (m_file->Read(onebyte, 1) != 1)\r
-                                               break;\r
-                                       ttlm = onebyte[0];\r
-                                       break;\r
-\r
-                               case 2:\r
-                                       if (m_file->Read(twobytes, 2) != 2)\r
-                                               break;\r
-                                       ttlm = STREAM_TO_UINT16(twobytes, 0);\r
-                                       break;\r
-\r
-                               }\r
-\r
-                               switch (((stlm & 0x40) >> 6)) {\r
-\r
-                               case 0:\r
-                                       if (m_file->Read(twobytes, 2) != 2)\r
-                                               break;\r
-                                       ptlm = STREAM_TO_UINT16(twobytes, 0);\r
-                                       break;\r
-\r
-                               case 1:\r
-                                       if (m_file->Read(fourbytes, 4) != 4)\r
-                                               break;\r
-                                       ptlm = STREAM_TO_UINT32(fourbytes, 0);\r
-                                       break;\r
-\r
-                               }\r
-\r
-                               wxTreeItemId subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                                       wxString::Format(wxT("Tile %d: %d bytes"), ttlm, ptlm),\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-                       }\r
-\r
-                       }\r
-                       break;\r
-\r
-               /////////\r
-               // POD //\r
-               /////////\r
-               case POD_VAL:\r
-                       {\r
-                       int n, numchanges;\r
-\r
-                       if (csiz < 257)\r
-                               numchanges = (currlen - 2) / 7;\r
-                       else\r
-                               numchanges = (currlen - 2) / 9;\r
-\r
-                       for (n = 0; n < numchanges; n++) {\r
-\r
-                               image = m_tree->TreeCtrlIcon_Folder;\r
-                               imageSel = image + 1;\r
-\r
-                               wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
-                                       wxString::Format(wxT("Change #%d"), n),\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-                               if (m_file->Read(onebyte, 1) != 1)\r
-                                       break;\r
-                               unsigned char rspod = onebyte[0];\r
-\r
-                               unsigned short int cspod;\r
-                               if (csiz < 257) {\r
-                                       if (m_file->Read(onebyte, 1) != 1)\r
-                                               break;\r
-                                       cspod = onebyte[0];\r
-                               } else {\r
-                                       if (m_file->Read(twobytes, 2) != 2)\r
-                                               break;\r
-                                       cspod = STREAM_TO_UINT16(twobytes, 0);\r
-                               }\r
-\r
-                               if (m_file->Read(twobytes, 2) != 2)\r
-                                       break;\r
-                               unsigned short int lyepod = STREAM_TO_UINT16(twobytes, 0);\r
-\r
-                               if (m_file->Read(onebyte, 1) != 1)\r
-                                       break;\r
-                               unsigned char repod = onebyte[0];\r
-\r
-                               unsigned short int cepod;\r
-                               if (csiz < 257) {\r
-                                       if (m_file->Read(onebyte, 1) != 1)\r
-                                               break;\r
-                                       cepod = onebyte[0];\r
-                               } else {\r
-                                       if (m_file->Read(twobytes, 2) != 2)\r
-                                               break;\r
-                                       cepod = STREAM_TO_UINT16(twobytes, 0);\r
-                               }\r
-\r
-                               if (m_file->Read(onebyte, 1) != 1)\r
-                                       break;\r
-                               unsigned char ppod = onebyte[0];\r
-\r
-                               image = m_tree->TreeCtrlIcon_File;\r
-                               imageSel = image + 1;\r
-\r
-                               wxTreeItemId subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                                       wxString::Format(wxT("%d <= Resolution < %d"), rspod, repod),\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-                               subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                                       wxString::Format(wxT("%d <= Component < %d"), cspod, cepod),\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-                               subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                                       wxString::Format(wxT("0 <= Layer < %d"), lyepod),\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-                               wxString text = wxT("");\r
-                               switch (ppod) {\r
-                               case (0):\r
-                                       text << wxT("LRCP");\r
-                                       break;\r
-                               case (1):\r
-                                       text << wxT("RLCP");\r
-                                       break;\r
-                               case (2):\r
-                                       text << wxT("LRCP");\r
-                                       break;\r
-                               case (3):\r
-                                       text << wxT("RPCL");\r
-                                       break;\r
-                               case (4):\r
-                                       text << wxT("CPRL");\r
-                                       break;\r
-                               default:\r
-                                       text << wxT("unknown progression");\r
-                                       break;\r
-                               }\r
-                               subcurrid4 = m_tree->AppendItem(subcurrid3,\r
-                                       text,\r
-                                       image, imageSel,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                       }\r
-\r
-                       }\r
-                       break;\r
-\r
-               /////////\r
-               // SOD //\r
-               /////////\r
-               case SOD_VAL:\r
-                       {\r
-                       inside_sod = 1;\r
-                       };\r
-                       break;\r
-\r
-               default:\r
-                       break;\r
-                       \r
-               }\r
-                                                               \r
-               // increment number of markers\r
-               if (nmarks++ >= maxmarks) {\r
-                       WriteText(wxT("Maximum amount of markers exceeded"));\r
-                       break;\r
-               }\r
-\r
-               // advance position\r
-               OPJ_ADVANCE(currlen + 2);\r
-       }       \r
-\r
-       WriteText(wxT("Search finished"));\r
-}\r
diff --git a/OPJViewer/source/wxjp2parser.cpp b/OPJViewer/source/wxjp2parser.cpp
deleted file mode 100644 (file)
index 6e89390..0000000
+++ /dev/null
@@ -1,1116 +0,0 @@
-/*\r
- * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-#include "OPJViewer.h"\r
-\r
-/* defines */\r
-#define SHORT_DESCR_LEN        32\r
-#define LONG_DESCR_LEN         256\r
-\r
-/* enumeration for file formats */\r
-#define J2FILENUM              4\r
-typedef enum {\r
-\r
-        JP2_FILE,\r
-        J2K_FILE,\r
-               MJ2_FILE,\r
-               UNK_FILE\r
-\r
-} j2filetype;\r
-\r
-/* enumeration for the box types */\r
-#define j22boxNUM                23\r
-typedef enum {\r
-\r
-                       FILE_BOX,\r
-                       JP_BOX,\r
-                       FTYP_BOX,\r
-                       JP2H_BOX,\r
-                       IHDR_BOX,\r
-                       COLR_BOX,\r
-                       JP2C_BOX,\r
-                       JP2I_BOX,\r
-                       XML_BOX,\r
-                       UUID_BOX,\r
-                       UINF_BOX,\r
-                       MOOV_BOX,\r
-                       MVHD_BOX,\r
-                       TRAK_BOX,\r
-                       TKHD_BOX,\r
-                       MDIA_BOX,\r
-                       MDHD_BOX,\r
-                       HDLR_BOX,\r
-                       MINF_BOX,\r
-                       VMHD_BOX,\r
-                       STBL_BOX,\r
-                       STSD_BOX,\r
-                       STSZ_BOX,\r
-                       MJP2_BOX,\r
-                       MDAT_BOX,\r
-                       ANY_BOX,\r
-                       UNK_BOX\r
-\r
-} j22boxtype;\r
-\r
-/* the box structure itself */\r
-struct boxdef {\r
-\r
-        char                  value[5];                 /* hexadecimal value/string*/\r
-               char                  name[SHORT_DESCR_LEN];    /* short description       */\r
-               char                  descr[LONG_DESCR_LEN];    /* long  description       */\r
-               int                   sbox;                     /* is it a superbox?       */\r
-               int                   req[J2FILENUM];           /* mandatory box           */\r
-               j22boxtype             ins;                      /* contained in box...     */\r
-\r
-};\r
-\r
-\r
-/* jp2 family box signatures */\r
-#define FILE_SIGN           ""\r
-#define JP_SIGN             "jP\040\040"\r
-#define FTYP_SIGN           "ftyp"\r
-#define JP2H_SIGN           "jp2h"\r
-#define IHDR_SIGN           "ihdr"\r
-#define COLR_SIGN           "colr"\r
-#define JP2C_SIGN           "jp2c"\r
-#define JP2I_SIGN           "jp2i"\r
-#define XML_SIGN            "xml\040"\r
-#define UUID_SIGN           "uuid"\r
-#define UINF_SIGN           "uinf"\r
-#define MOOV_SIGN           "moov"\r
-#define MVHD_SIGN           "mvhd"\r
-#define TRAK_SIGN           "trak"\r
-#define TKHD_SIGN           "tkhd"\r
-#define MDIA_SIGN           "mdia"\r
-#define MDHD_SIGN           "mdhd"\r
-#define HDLR_SIGN           "hdlr"\r
-#define MINF_SIGN           "minf"\r
-#define VMHD_SIGN           "vmhd"\r
-#define STBL_SIGN           "stbl"\r
-#define STSD_SIGN           "stsd"\r
-#define STSZ_SIGN           "stsz"\r
-#define MJP2_SIGN           "mjp2"\r
-#define MDAT_SIGN           "mdat"\r
-#define ANY_SIGN                       ""\r
-#define UNK_SIGN            ""\r
-\r
-/* the possible boxes */\r
-struct boxdef j22box[] =\r
-{\r
-/* sign */     {FILE_SIGN,\r
-/* short */    "placeholder for nothing",\r
-/* long */     "Nothing to say",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {JP_SIGN,\r
-/* short */    "JPEG 2000 Signature box",\r
-/* long */     "This box uniquely identifies the file as being part of the JPEG 2000 family of files",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {FTYP_SIGN,\r
-/* short */    "File Type box",\r
-/* long */     "This box specifies file type, version and compatibility information, including specifying if this file "\r
-                       "is a conforming JP2 file or if it can be read by a conforming JP2 reader",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {JP2H_SIGN,\r
-/* short */    "JP2 Header box",\r
-/* long */     "This box contains a series of boxes that contain header-type information about the file",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {IHDR_SIGN,\r
-/* short */    "Image Header box",\r
-/* long */     "This box specifies the size of the image and other related fields",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      JP2H_BOX},\r
-\r
-/* sign */     {COLR_SIGN,\r
-/* short */    "Colour Specification box",\r
-/* long */     "This box specifies the colourspace of the image",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      JP2H_BOX},\r
-\r
-/* sign */     {JP2C_SIGN,\r
-/* short */    "Contiguous Codestream box",\r
-/* long */     "This box contains the codestream as defined by Annex A",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {JP2I_SIGN,\r
-/* short */    "Intellectual Property box",\r
-/* long */     "This box contains intellectual property information about the image",\r
-/* sbox */     0,\r
-/* req */      {0, 0, 0},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {XML_SIGN,\r
-/* short */    "XML box",\r
-/* long */     "This box provides a tool by which vendors can add XML formatted information to a JP2 file",\r
-/* sbox */     0,\r
-/* req */      {0, 0, 0},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {UUID_SIGN,\r
-/* short */    "UUID box",\r
-/* long */     "This box provides a tool by which vendors can add additional information to a file "\r
-                       "without risking conflict with other vendors",\r
-/* sbox */     0,\r
-/* req */      {0, 0, 0},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {UINF_SIGN,\r
-/* short */    "UUID Info box",\r
-/* long */     "This box provides a tool by which a vendor may provide access to additional information associated with a UUID",\r
-/* sbox */     0,\r
-/* req */      {0, 0, 0},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {MOOV_SIGN,\r
-/* short */    "Movie box",\r
-/* long */     "This box contains the media data. In video tracks, this box would contain JPEG2000 video frames",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {MVHD_SIGN,\r
-/* short */    "Movie Header box",\r
-/* long */     "This box defines overall information which is media-independent, and relevant to the entire presentation "\r
-                       "considered as a whole",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MOOV_BOX},\r
-\r
-/* sign */     {TRAK_SIGN,\r
-/* short */    "Track box",\r
-/* long */     "This is a container box for a single track of a presentation. A presentation may consist of one or more tracks",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MOOV_BOX},\r
-\r
-/* sign */     {TKHD_SIGN,\r
-/* short */    "Track Header box",\r
-/* long */     "This box specifies the characteristics of a single track. Exactly one Track Header Box is contained in a track",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      TRAK_BOX},\r
-\r
-/* sign */     {MDIA_SIGN,\r
-/* short */    "Media box",\r
-/* long */     "The media declaration container contains all the objects which declare information about the media data "\r
-                       "within a track",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      TRAK_BOX},\r
-\r
-/* sign */     {MDHD_SIGN,\r
-/* short */    "Media Header box",\r
-/* long */     "The media header declares overall information which is media-independent, and relevant to characteristics "\r
-                       "of the media in a track",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MDIA_BOX},\r
-\r
-/* sign */     {HDLR_SIGN,\r
-/* short */    "Handler Reference box",\r
-/* long */     "This box within a Media Box declares the process by which the media-data in the track may be presented, "\r
-                       "and thus, the nature of the media in a track",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MDIA_BOX},\r
-\r
-/* sign */     {MINF_SIGN,\r
-/* short */    "Media Information box",\r
-/* long */     "This box contains all the objects which declare characteristic information of the media in the track",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MDIA_BOX},\r
-\r
-/* sign */     {VMHD_SIGN,\r
-/* short */    "Video Media Header box",\r
-/* long */     "The video media header contains general presentation information, independent of the coding, for video media",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MINF_BOX},\r
-\r
-/* sign */     {STBL_SIGN,\r
-/* short */    "Sample Table box",\r
-/* long */     "The sample table contains all the time and data indexing of the media samples in a track",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MINF_BOX},\r
-\r
-/* sign */     {STSD_SIGN,\r
-/* short */    "STSD Sample Description box",\r
-/* long */     "The sample description table gives detailed information about the coding type used, and any initialization "\r
-                       "information needed for that coding",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MINF_BOX},\r
-\r
-/* sign */     {STSZ_SIGN,\r
-/* short */    "Sample Size box",\r
-/* long */     "This box contains the sample count and a table giving the size of each sample",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      STBL_BOX},\r
-\r
-/* sign */     {MJP2_SIGN,\r
-/* short */    "MJP2 Sample Description box",\r
-/* long */     "The MJP2 sample description table gives detailed information about the coding type used, and any initialization "\r
-                       "information needed for that coding",\r
-/* sbox */     0,\r
-/* req */      {1, 1, 1},\r
-/* ins */      MINF_BOX},\r
-\r
-/* sign */     {MDAT_SIGN,\r
-/* short */    "Media Data box",\r
-/* long */     "The meta-data for a presentation is stored in the single Movie Box which occurs at the top-level of a file",\r
-/* sbox */     1,\r
-/* req */      {1, 1, 1},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {ANY_SIGN,\r
-/* short */    "Any box",\r
-/* long */     "All the existing boxes",\r
-/* sbox */     0,\r
-/* req */      {0, 0, 0},\r
-/* ins */      FILE_BOX},\r
-\r
-/* sign */     {UNK_SIGN,\r
-/* short */    "Unknown Type box",\r
-/* long */     "The signature is not recognised to be that of an existing box",\r
-/* sbox */     0,\r
-/* req */      {0, 0, 0},\r
-/* ins */      ANY_BOX}\r
-\r
-};\r
-\r
-\r
-/* macro functions */\r
-/* From little endian to big endian, 2 and 4 bytes */\r
-#define        BYTE_SWAP2(X)   ((X & 0x00FF) << 8) | ((X & 0xFF00) >> 8)\r
-#define        BYTE_SWAP4(X)   ((X & 0x000000FF) << 24) | ((X & 0x0000FF00) << 8) | ((X & 0x00FF0000) >> 8) | ((X & 0xFF000000) >> 24)\r
-\r
-#ifdef __WXGTK__\r
-#define        BYTE_SWAP8(X)   ((X & 0x00000000000000FFULL) << 56) | ((X & 0x000000000000FF00ULL) << 40) | \\r
-                        ((X & 0x0000000000FF0000ULL) << 24) | ((X & 0x00000000FF000000ULL) << 8) | \\r
-                                               ((X & 0x000000FF00000000ULL) >> 8)  | ((X & 0x0000FF0000000000ULL) >> 24) | \\r
-                                               ((X & 0x00FF000000000000ULL) >> 40) | ((X & 0xFF00000000000000ULL) >> 56)\r
-#else\r
-#define        BYTE_SWAP8(X)   ((X & 0x00000000000000FF) << 56) | ((X & 0x000000000000FF00) << 40) | \\r
-                        ((X & 0x0000000000FF0000) << 24) | ((X & 0x00000000FF000000) << 8) | \\r
-                                               ((X & 0x000000FF00000000) >> 8)  | ((X & 0x0000FF0000000000) >> 24) | \\r
-                                               ((X & 0x00FF000000000000) >> 40) | ((X & 0xFF00000000000000) >> 56)\r
-#endif\r
-\r
-/* From codestream to int values */\r
-#define STREAM_TO_UINT32(C, P) (((unsigned long int) (C)[(P) + 0] << 24) + \\r
-                                                               ((unsigned long int) (C)[(P) + 1] << 16) + \\r
-                                                               ((unsigned long int) (C)[(P) + 2] << 8) + \\r
-                                                               ((unsigned long int) (C)[(P) + 3] << 0))\r
-\r
-#define STREAM_TO_UINT16(C, P) (((unsigned long int) (C)[(P) + 0] << 8) + \\r
-                                                               ((unsigned long int) (C)[(P) + 1] << 0))\r
-\r
-#define OPJREAD_LONG(F,L,N) { \\r
-                                                       if (F->Read(fourbytes, 4) < 4) { \\r
-                                                               wxLogMessage(wxT("Problem reading " N " from the file (file ended?)")); \\r
-                                                               return -1; \\r
-                                                       }; \\r
-                                                       L = STREAM_TO_UINT32(fourbytes, 0); \\r
-                                                       }\r
-\r
-/* handling functions */\r
-#define ITEM_PER_ROW   10\r
-\r
-//#define indprint     if (0) printf("%.*s", 2 * level + 9, indent), printf\r
-char    indent[] =  "                                                                   "\r
-                                       "                                                                   "\r
-                                       "                                                                   "\r
-                                       "                                                                   ";\r
-\r
-void indprint(wxString printout, int level)\r
-{\r
-       wxLogMessage(/*wxString::Format(wxT("%.*s"), 2 * level + 9, indent) + */printout);\r
-}\r
-\r
-/* Box handler function */\r
-int OPJParseThread::box_handler_function(int boxtype, wxFile *fileid, wxFileOffset filepoint, wxFileOffset filelimit,\r
-                                                wxTreeItemId parentid, int level, char *scansign, unsigned long int *scanpoint)\r
-{\r
-       switch ((j22boxtype) boxtype) {\r
-\r
-\r
-       /* JPEG 2000 Signature box */\r
-       case (JP_BOX): {\r
-\r
-                       unsigned long int checkdata = 0;\r
-                       fileid->Read(&checkdata, sizeof(unsigned long int));\r
-                       checkdata = BYTE_SWAP4(checkdata);\r
-\r
-                       // add info\r
-                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Check data: %X -> %s"), checkdata, (checkdata == 0x0D0A870A) ? wxT("OK") : wxT("KO")),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-               };\r
-               break;\r
-\r
-\r
-       /* JPEG 2000 codestream box */\r
-       case (JP2C_BOX): {\r
-\r
-                       // add info\r
-                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                               wxString(wxT("Codestream")),\r
-                               m_tree->TreeCtrlIcon_Folder, m_tree->TreeCtrlIcon_Folder + 1,\r
-                               new OPJMarkerData(wxT("INFO-CSTREAM"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
-                               );\r
-\r
-                       m_tree->SetItemHasChildren(currid);\r
-\r
-                       // parse the file\r
-                       //ParseJ2KFile(fileid, filepoint, filelimit, currid);\r
-\r
-               };\r
-               break;\r
-\r
-\r
-\r
-\r
-\r
-       /* File Type box */\r
-       case (FTYP_BOX): {\r
-\r
-                       char BR[4], CL[4];\r
-                       unsigned long int MinV, numCL, i;\r
-                       fileid->Read(BR, sizeof(char) * 4);\r
-                       fileid->Read(&MinV, sizeof(unsigned long int));\r
-                       MinV = BYTE_SWAP4(MinV);\r
-                       numCL = (filelimit - fileid->Tell()) / 4;                               \r
-\r
-                       // add info\r
-                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                               wxT("Brand/Minor version: ") +\r
-                               wxString::FromAscii(BR).Truncate(4) +\r
-                               wxString::Format(wxT("/%d"), MinV),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Compatibility list")),\r
-                               m_tree->TreeCtrlIcon_Folder, m_tree->TreeCtrlIcon_Folder + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       for (i = 0; i < numCL; i++) {\r
-                               fileid->Read(CL, sizeof(char) * 4);\r
-                               m_tree->AppendItem(currid,\r
-                                       wxString::FromAscii(CL).Truncate(4),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                       };\r
-                       \r
-               };\r
-               break;\r
-\r
-\r
-\r
-       /* JP2 Header box */\r
-       case (IHDR_BOX): {\r
-\r
-                       unsigned long int height, width;\r
-                       unsigned short int nc;\r
-                       unsigned char bpc, C, UnkC, IPR;\r
-                       fileid->Read(&height, sizeof(unsigned long int));\r
-                       height = BYTE_SWAP4(height);\r
-                       fileid->Read(&width, sizeof(unsigned long int));\r
-                       width = BYTE_SWAP4(width);\r
-                       fileid->Read(&nc, sizeof(unsigned short int));\r
-                       nc = BYTE_SWAP2(nc);\r
-                       fileid->Read(&bpc, sizeof(unsigned char));\r
-                       fileid->Read(&C, sizeof(unsigned char));\r
-                       fileid->Read(&UnkC, sizeof(unsigned char));\r
-                       fileid->Read(&IPR, sizeof(unsigned char));\r
-                       \r
-                       // add info\r
-                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Dimensions: %d x %d x %d @ %d bpc"), width, height, nc, bpc + 1),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Compression type: %d"), C),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Colourspace unknown: %d"), UnkC),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Intellectual Property Rights: %d"), IPR),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-                       \r
-               };\r
-               break;\r
-\r
-\r
-\r
-       /* Colour Specification box */\r
-       case (COLR_BOX): {\r
-\r
-                       unsigned char METH, PREC, APPROX;\r
-                       char methdescr[80], enumcsdescr[80];\r
-                       unsigned long int EnumCS;\r
-                       fileid->Read(&METH, sizeof(unsigned char));\r
-                       switch (METH) {\r
-                       case 1:\r
-                               strcpy(methdescr, "Enumerated Colourspace");\r
-                               break;\r
-                       case 2:\r
-                               strcpy(methdescr, "Restricted ICC profile");\r
-                               break;\r
-                       default:\r
-                               strcpy(methdescr, "Unknown");\r
-                               break;\r
-                       };\r
-                       fileid->Read(&PREC, sizeof(unsigned char));\r
-                       fileid->Read(&APPROX, sizeof(unsigned char));\r
-                       if (METH != 2) {\r
-                               fileid->Read(&EnumCS, sizeof(unsigned long int));\r
-                               EnumCS = BYTE_SWAP4(EnumCS);\r
-                               switch (EnumCS) {\r
-                               case 16:\r
-                                       strcpy(enumcsdescr, "sRGB");\r
-                                       break;\r
-                               case 17:\r
-                                       strcpy(enumcsdescr, "greyscale");\r
-                                       break;\r
-                               case 18:\r
-                                       strcpy(enumcsdescr, "sYCC");\r
-                                       break;\r
-                               default:\r
-                                       strcpy(enumcsdescr, "Unknown");\r
-                                       break;\r
-                               };\r
-                       };\r
-\r
-                       // add info\r
-                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Specification method: %d ("), METH) +\r
-                               wxString::FromAscii(methdescr) +\r
-                               wxT(")"),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Precedence: %d"), PREC),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Colourspace approximation: %d"), APPROX),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-\r
-                       if (METH != 2)\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Enumerated colourspace: %d ("), EnumCS) +\r
-                                       wxString::FromAscii(enumcsdescr) +\r
-                                       wxT(")"),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-                       if (METH != 1)\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("ICC profile: there is one")),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-\r
-\r
-               };\r
-               break;\r
-\r
-\r
-\r
-\r
-               \r
-\r
-       /* Movie Header Box */\r
-       case (MVHD_BOX): {\r
-\r
-                       unsigned long int version, rate, matrix[9], next_track_ID;\r
-                       unsigned short int volume;\r
-                       fileid->Read(&version, sizeof(unsigned long int));\r
-                       version = BYTE_SWAP4(version);\r
-                       if (version == 0) {\r
-                               unsigned long int creation_time, modification_time, timescale, duration;\r
-                               fileid->Read(&creation_time, sizeof(unsigned long int));\r
-                               creation_time = BYTE_SWAP4(creation_time);\r
-                               fileid->Read(&modification_time, sizeof(unsigned long int));\r
-                               modification_time = BYTE_SWAP4(modification_time);\r
-                               fileid->Read(&timescale, sizeof(unsigned long int));\r
-                               timescale = BYTE_SWAP4(timescale);\r
-                               fileid->Read(&duration, sizeof(unsigned long int));\r
-                               duration = BYTE_SWAP4(duration);\r
-                               const long unix_time = creation_time - 2082844800L;\r
-                               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Creation time: %u (%.24s)"), creation_time, ctime(&unix_time)),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                               const long unix_time1 = modification_time - 2082844800L;\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Modification time: %u (%.24s)"), modification_time, ctime(&unix_time1)),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Timescale: %u (%.6fs)"), timescale, 1.0 / (float) timescale),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Duration: %u (%.3fs)"), duration, (float) duration / (float) timescale),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                       } else {\r
-                               int8byte creation_time, modification_time, duration;\r
-                               unsigned long int timescale;\r
-                               fileid->Read(&creation_time, sizeof(int8byte));\r
-                               creation_time = BYTE_SWAP8(creation_time);\r
-                               fileid->Read(&modification_time, sizeof(int8byte));\r
-                               modification_time = BYTE_SWAP8(modification_time);\r
-                               fileid->Read(&timescale, sizeof(unsigned long int));\r
-                               timescale = BYTE_SWAP4(timescale);\r
-                               fileid->Read(&duration, sizeof(int8byte));\r
-                               duration = BYTE_SWAP8(duration);\r
-                               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Creation time: %u"), creation_time),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Modification time: %u"), modification_time),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Timescale: %u"), timescale),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Duration: %u"), duration),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                       };\r
-                       fileid->Read(&rate, sizeof(unsigned long int));\r
-                       rate = BYTE_SWAP4(rate);\r
-                       fileid->Read(&volume, sizeof(unsigned short int));\r
-                       volume = BYTE_SWAP2(volume);\r
-                       fileid->Seek(6, wxFromCurrent);\r
-                       fileid->Read(&matrix, sizeof(unsigned char) * 9);\r
-                       fileid->Seek(4, wxFromCurrent);\r
-                       fileid->Read(&next_track_ID, sizeof(unsigned long int));\r
-                       next_track_ID = BYTE_SWAP4(next_track_ID);\r
-                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Rate: %d (%d.%d)"), rate, rate >> 16, rate & 0x0000FFFF),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-                       currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Volume: %d (%d.%d)"), volume, volume >> 8, volume & 0x00FF),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-                       currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Next track ID: %d"), next_track_ID),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-               };\r
-               break;\r
-\r
-\r
-                       /* Sample Description box */\r
-       case (STSD_BOX): {\r
-\r
-                       unsigned long int version, entry_count;\r
-                       fileid->Read(&version, sizeof(unsigned long int));\r
-                       version = BYTE_SWAP4(version);\r
-                       fileid->Read(&entry_count, sizeof(unsigned long int));\r
-                       entry_count = BYTE_SWAP4(entry_count);\r
-                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Entry count: %d"), entry_count),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
-                               );\r
-                       jpeg2000parse(fileid, filepoint + 8, filelimit, parentid, level + 1, scansign, scanpoint);\r
-               };\r
-               break;\r
-\r
-\r
-                       /* Sample Size box */\r
-       case (STSZ_BOX): {\r
-\r
-                       unsigned long int version, sample_size, sample_count, entry_size;\r
-                       \r
-                       fileid->Read(&version, sizeof(unsigned long int));\r
-                       version = BYTE_SWAP4(version);\r
-                       \r
-                       fileid->Read(&sample_size, sizeof(unsigned long int));\r
-                       sample_size = BYTE_SWAP4(sample_size);\r
-\r
-                       if (sample_size == 0) {\r
-                               fileid->Read(&sample_count, sizeof(unsigned long int));\r
-                               sample_count = BYTE_SWAP4(sample_count);\r
-\r
-                               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Sample count: %d"), sample_count),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
-                                       );\r
-\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxT("Entries size (bytes)"),\r
-                                       m_tree->TreeCtrlIcon_Folder, m_tree->TreeCtrlIcon_Folder + 1,\r
-                                       new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
-                                       );\r
-\r
-                               wxString text;\r
-                               for (unsigned int s = 0; s < sample_count; s++) {\r
-                                       fileid->Read(&entry_size, sizeof(unsigned long int));\r
-                                       entry_size = BYTE_SWAP4(entry_size);\r
-                                       \r
-                                       text << wxString::Format(wxT("%d, "), entry_size);\r
-\r
-                                       if (((s % 10) == (ITEM_PER_ROW - 1)) || (s == (sample_count - 1))) {\r
-                                               m_tree->AppendItem(currid,\r
-                                                       text,\r
-                                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                                       new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
-                                                       );\r
-                                               text = wxT("");\r
-                                       }\r
-\r
-                               }\r
-                               \r
-                       }\r
-\r
-               };\r
-               break;\r
-\r
-\r
-                       /* Video Media Header box */\r
-       case (VMHD_BOX): {\r
-\r
-                       unsigned long int version;\r
-                       unsigned short int graphicsmode, opcolor[3];\r
-                       char graphicsdescr[100];\r
-\r
-                       fileid->Read(&version, sizeof(unsigned long int));\r
-                       version = BYTE_SWAP4(version);\r
-\r
-                       fileid->Read(&graphicsmode, sizeof(unsigned short int));\r
-                       graphicsmode = BYTE_SWAP2(graphicsmode);\r
-                       switch (graphicsmode) {\r
-                       case (0x00):\r
-                                       strcpy(graphicsdescr, "copy");\r
-                                       break;\r
-                       case (0x24):\r
-                                       strcpy(graphicsdescr, "transparent");\r
-                                       break;\r
-                       case (0x0100):\r
-                                       strcpy(graphicsdescr, "alpha");\r
-                                       break;\r
-                       case (0x0101):\r
-                                       strcpy(graphicsdescr, "whitealpha");\r
-                                       break;\r
-                       case (0x0102):\r
-                                       strcpy(graphicsdescr, "blackalpha");\r
-                                       break;\r
-                       default:\r
-                                       strcpy(graphicsdescr, "unknown");\r
-                                       break;\r
-                       };\r
-\r
-                       fileid->Read(opcolor, 3 * sizeof(unsigned short int));\r
-                       opcolor[0] = BYTE_SWAP2(opcolor[0]);\r
-                       opcolor[1] = BYTE_SWAP2(opcolor[1]);\r
-                       opcolor[2] = BYTE_SWAP2(opcolor[2]);\r
-\r
-                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Composition mode: %d (")) + \r
-                               wxString::FromAscii(graphicsdescr) +\r
-                               wxT(")"),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
-                               );\r
-\r
-                       currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("OP color: %d %d %d"), opcolor[0], opcolor[1], opcolor[2]),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
-                               );\r
-               };\r
-               break;\r
-\r
-\r
-\r
-                       /* MJP2 Sample Description box */\r
-       case (MJP2_BOX): {\r
-\r
-                       unsigned short int height, width, depth;\r
-                       unsigned long int horizresolution, vertresolution;\r
-                       char compressor_name[32];\r
-                       fileid->Seek(24, wxFromCurrent);\r
-                       fileid->Read(&width, sizeof(unsigned short int));\r
-                       width = BYTE_SWAP2(width);\r
-                       fileid->Read(&height, sizeof(unsigned short int));\r
-                       height = BYTE_SWAP2(height);\r
-                       fileid->Read(&horizresolution, sizeof(unsigned long int));\r
-                       horizresolution = BYTE_SWAP4(horizresolution);\r
-                       fileid->Read(&vertresolution, sizeof(unsigned long int));\r
-                       vertresolution = BYTE_SWAP4(vertresolution);\r
-                       fileid->Seek(6, wxFromCurrent);\r
-                       fileid->Read(compressor_name, sizeof(char) * 32);\r
-                       fileid->Read(&depth, sizeof(unsigned short int));\r
-                       depth = BYTE_SWAP2(depth);\r
-                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Dimensions: %d x %d @ %d bpp"), width, height, depth),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
-                               );\r
-                       currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Resolution: %d.%d x %d.%d"), horizresolution >> 16, horizresolution & 0x0000FFFF,\r
-                               vertresolution >> 16, vertresolution & 0x0000FFFF),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-                       currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Compressor: %.32s"), compressor_name),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-                       jpeg2000parse(fileid, filepoint + 78, filelimit, parentid, level + 1, scansign, scanpoint);\r
-\r
-               };\r
-               break;\r
-\r
-               /* Media Header box */\r
-       case (MDHD_BOX): {\r
-                       unsigned long int version;\r
-                       unsigned short int language;\r
-                       fileid->Read(&version, sizeof(unsigned long int));\r
-                       version = BYTE_SWAP4(version);\r
-                       if (version == 0) {\r
-                               unsigned long int creation_time, modification_time, timescale, duration;\r
-                               fileid->Read(&creation_time, sizeof(unsigned long int));\r
-                               creation_time = BYTE_SWAP4(creation_time);\r
-                               fileid->Read(&modification_time, sizeof(unsigned long int));\r
-                               modification_time = BYTE_SWAP4(modification_time);\r
-                               fileid->Read(&timescale, sizeof(unsigned long int));\r
-                               timescale = BYTE_SWAP4(timescale);\r
-                               fileid->Read(&duration, sizeof(unsigned long int));\r
-                               duration = BYTE_SWAP4(duration);\r
-                               const long unix_time = creation_time - 2082844800L;\r
-                               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Creation time: %u (%.24s)"), creation_time, ctime(&unix_time)),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                               const long unix_time1 = modification_time - 2082844800L;\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Modification time: %u (%.24s)"), modification_time, ctime(&unix_time1)),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Timescale: %u (%.6fs)"), timescale, 1.0 / (float) timescale),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Duration: %u (%.3fs)"), duration, (float) duration / (float) timescale),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                       } else {\r
-                               int8byte creation_time, modification_time, duration;\r
-                               unsigned long int timescale;\r
-                               fileid->Read(&creation_time, sizeof(int8byte));\r
-                               creation_time = BYTE_SWAP8(creation_time);\r
-                               fileid->Read(&modification_time, sizeof(int8byte));\r
-                               modification_time = BYTE_SWAP8(modification_time);\r
-                               fileid->Read(&timescale, sizeof(unsigned long int));\r
-                               timescale = BYTE_SWAP4(timescale);\r
-                               fileid->Read(&duration, sizeof(int8byte));\r
-                               duration = BYTE_SWAP8(duration);\r
-                               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Creation time: %u"), creation_time),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Modification time: %u"), modification_time),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Timescale: %u"), timescale),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                               currid = m_tree->AppendItem(parentid,\r
-                                       wxString::Format(wxT("Duration: %u"), duration),\r
-                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                                       new OPJMarkerData(wxT("INFO"))\r
-                                       );\r
-                       }\r
-                       fileid->Read(&language, sizeof(unsigned short int));\r
-\r
-                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Language: %d (%c%c%c)"), language & 0xEFFF,\r
-                               0x60 + (char) ((language >> 10) & 0x001F), 0x60 + (char) ((language >> 5) & 0x001F), 0x60 + (char) ((language >> 0) & 0x001F)),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-               };\r
-               break;\r
-               \r
-               /* Media Handler box */\r
-       case (HDLR_BOX): {\r
-                       unsigned long int version, predefined, temp[3];\r
-                       char handler[4], name[256];\r
-                       int namelen = wxMin(256, (filelimit - filepoint - 24));\r
-                       fileid->Read(&version, sizeof(unsigned long int));\r
-                       version = BYTE_SWAP4(version);\r
-                       fileid->Read(&predefined, sizeof(unsigned long int));\r
-                       fileid->Read(handler, 4 * sizeof(char));\r
-                       fileid->Read(&temp, 3 * sizeof(unsigned long int));\r
-                       fileid->Read(name, namelen * sizeof(char));\r
-\r
-                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Handler: %.4s"), handler),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-                                        \r
-                       currid = m_tree->AppendItem(parentid,\r
-                               wxString::Format(wxT("Name: %.255s"), name),\r
-                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
-                               new OPJMarkerData(wxT("INFO"))\r
-                               );\r
-                                                                        \r
-               }\r
-               break;\r
-\r
-       /* not yet implemented */\r
-       default:\r
-               break;\r
-\r
-       };\r
-\r
-       return (0);\r
-}\r
-\r
-\r
-void OPJParseThread::ParseJP2File(wxFile *fileid, wxFileOffset filepoint, wxFileOffset filelimit, wxTreeItemId parentid)\r
-{\r
-       unsigned long int scanpoint;\r
-\r
-       jpeg2000parse(fileid, filepoint, filelimit, parentid, 0, NULL, &scanpoint);\r
-}\r
-\r
-/* the parsing function itself */\r
-/*\r
-  fileid    = fid of the file to scan (you should open it by yourself)\r
-  filepoint = first byte where to start to scan from (usually 0)\r
-  filelimit = first byte where to stop to scan from (usually the file size)\r
-  level     = set this to 0\r
-  scansign  = signature to scan for (NULL avoids search, returns "    " if successful)\r
-  scanpoint = point where the scan signature lies\r
-*/\r
-int OPJParseThread::jpeg2000parse(wxFile *fileid, wxFileOffset filepoint, wxFileOffset filelimit,\r
-                                                                 wxTreeItemId parentid, int level, char *scansign, unsigned long int *scanpoint)\r
-{\r
-       unsigned long int       LBox = 0x00000000;\r
-       //int                     LBox_read;\r
-       char                    TBox[5] = "\0\0\0\0";\r
-       //int                     TBox_read;\r
-       int8byte                                XLBox = 0x0000000000000000;\r
-       //int                     XLBox_read;\r
-       unsigned long int       box_length = 0;\r
-       int                     last_box = 0, box_num = 0;\r
-       int                     box_type = ANY_BOX;\r
-       unsigned char           /*onebyte[1], twobytes[2],*/ fourbytes[4];\r
-\r
-       /* cycle all over the file */\r
-       box_num = 0;\r
-       last_box = 0;\r
-       while (!last_box) {\r
-\r
-               /* do not exceed file limit */\r
-               if (filepoint >= filelimit)\r
-                       return (0);\r
-\r
-               /* seek on file */\r
-               if (fileid->Seek(filepoint, wxFromStart) == wxInvalidOffset)\r
-                       return (-1);\r
-\r
-               /* read the mandatory LBox, 4 bytes */\r
-               if (fileid->Read(fourbytes, 4) < 4) {\r
-                       WriteText(wxT("Problem reading LBox from the file (file ended?)"));\r
-                       return -1;\r
-               };\r
-               LBox = STREAM_TO_UINT32(fourbytes, 0);\r
-\r
-               /* read the mandatory TBox, 4 bytes */\r
-               if (fileid->Read(TBox, 4) < 4) {\r
-                       WriteText(wxT("Problem reading TBox from the file (file ended?)"));\r
-                       return -1;\r
-               };\r
-\r
-               /* look if scansign is got */\r
-               if ((scansign != NULL) && (memcmp(TBox, scansign, 4) == 0)) {\r
-                       memcpy(scansign, "    ", 4);\r
-                       *scanpoint = filepoint;\r
-\r
-                       /* hack/exploit */\r
-                       // stop as soon as you find the codebox\r
-                       return (0);\r
-\r
-               };\r
-\r
-               /* determine the box type */\r
-               for (box_type = JP_BOX; box_type < UNK_BOX; box_type++)\r
-                       if (memcmp(TBox, j22box[box_type].value, 4) == 0)\r
-                               break;  \r
-\r
-               /* read the optional XLBox, 8 bytes */\r
-               if (LBox == 1) {\r
-\r
-                       if (fileid->Read(&XLBox, 8) < 8) {\r
-                               WriteText(wxT("Problem reading XLBox from the file (file ended?)"));\r
-                               return -1;\r
-                       };\r
-                       box_length = (unsigned long int) BYTE_SWAP8(XLBox);\r
-\r
-               } else if (LBox == 0x00000000) {\r
-\r
-                       /* last box in file */\r
-                       last_box = 1; \r
-                       box_length = filelimit - filepoint;\r
-\r
-               } else\r
-\r
-                       box_length = LBox;\r
-\r
-               /* show box info */\r
-\r
-               // append the marker\r
-               int image, imageSel;\r
-               image = m_tree->TreeCtrlIcon_Folder;\r
-               imageSel = image + 1;\r
-               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
-                       wxString::Format(wxT("%03d: "), box_num) +\r
-                       wxString::FromAscii(TBox) +\r
-                       wxString::Format(wxT(" (0x%04X)"),\r
-                               ((unsigned long int) TBox[3]) + ((unsigned long int) TBox[2] << 8) +\r
-                               ((unsigned long int) TBox[1] << 16) + ((unsigned long int) TBox[0] << 24)\r
-                       ),\r
-                       image, imageSel,\r
-                       new OPJMarkerData(wxT("BOX"), m_tree->m_fname.GetFullPath(), filepoint, filepoint + box_length)\r
-                       );\r
-\r
-               // append some info\r
-               image = m_tree->TreeCtrlIcon_File;\r
-               imageSel = image + 1;\r
-\r
-               // box name\r
-               wxTreeItemId subcurrid1 = m_tree->AppendItem(currid,\r
-                       wxT("*** ") + wxString::FromAscii(j22box[box_type].name) + wxT(" ***"),\r
-                       image, imageSel,\r
-                       new OPJMarkerData(wxT("INFO"))\r
-                       );\r
-               m_tree->SetItemFont(subcurrid1, *wxITALIC_FONT);\r
-\r
-               // position and length\r
-               wxTreeItemId subcurrid2 = m_tree->AppendItem(currid,\r
-                       wxLongLong(filepoint).ToString() + wxT(" > ") + wxLongLong(filepoint + box_length - 1).ToString() + \r
-                       wxT(", ") + wxString::Format(wxT("%d + 8 (%d)"), box_length, box_length + 8),\r
-                       image, imageSel,\r
-                       new OPJMarkerData(wxT("INFO"))\r
-                       );\r
-\r
-               /* go deep in the box */\r
-               box_handler_function((int) box_type, fileid, (LBox == 1) ? (filepoint + 16) : (filepoint + 8), filepoint + box_length,\r
-                       currid, level, scansign, scanpoint);\r
-\r
-               /* if it's a superbox go inside it */\r
-               if (j22box[box_type].sbox)\r
-                       jpeg2000parse(fileid, (LBox == 1) ? (filepoint + 16) : (filepoint + 8), filepoint + box_length,\r
-                               currid, level + 1, scansign, scanpoint);\r
-\r
-               /* increment box number and filepoint*/\r
-               box_num++;\r
-               filepoint += box_length;\r
-\r
-       };\r
-\r
-       /* all good */\r
-       return (0);\r
-}\r
-\r
diff --git a/OPJ_Validate/Makefile b/OPJ_Validate/Makefile
deleted file mode 100644 (file)
index c5434f0..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-OPJ_Validate_Makee: OPJ_Validate.c md5.c 
-       gcc -o OPJ_Validate OPJ_Validate.c md5.c  -I.
diff --git a/OPJ_Validate/OPJ_Param_File_v0_1.txt b/OPJ_Validate/OPJ_Param_File_v0_1.txt
deleted file mode 100644 (file)
index 881c92d..0000000
+++ /dev/null
@@ -1,100 +0,0 @@
-#Version 0.1 - February 9th 2007\r
-#Usage: OPJ_Validate OpenJPEG_command_line\r
-#Example: OPJ_Validate image_to_j2k.exe -i original/Bretagne1.ppm -o original/Bretagne1.j2k -r 200, 50, 10\r
-#Attention: don't forget the *.exe extension for the executable file, and check the paths\r
-\r
-image_to_j2k.exe -i original/Bretagne1.ppm -o temp/Bretagne1_0.j2k -r 200,50,10\r
-j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1.ppm\r
-image_to_j2k.exe -i original/Bretagne2.ppm -o temp/Bretagne2_0.j2k -c [128,128],[128,128],[128,128] -r 100,20,2 -t 640,480 -b 32,32\r
-j2k_to_image.exe -i original/Bretagne2.j2k -o temp/Bretagne2.ppm -r 2\r
-image_to_j2k.exe -i original/Cevennes1.bmp -o temp/Cevennes1.j2k -r 10\r
-j2k_to_image.exe -i original/Cevennes1.j2k -o temp/Cevennes1.bmp -l 2\r
-image_to_j2k.exe -i original/Cevennes2.ppm -o temp/Cevennes2.jp2 -r 50\r
-j2k_to_image.exe -i original/Cevennes2.jp2 -o temp/Cevennes2.ppm\r
-image_to_j2k.exe -i original/Rome.bmp -o temp/Rome.jp2 -q 30,35,50 -p LRCP -n 3\r
-j2k_to_image.exe -i original/Rome.jp2 -o temp/Rome.ppm\r
-image_to_j2k.exe -i original/Bretagne1.ppm -o temp/Bretagne1_1.j2k -q 30,35,40 -n 2\r
-image_to_j2k.exe -i original/Bretagne1.ppm -o temp/Bretagne1_2.j2k -q 30,35,40 -b 16,16 -c [101,101]\r
-image_to_j2k.exe -i original/Bretagne2.ppm -o temp/Bretagne2_1.j2k -t 127,127 -p PCRL\r
-image_to_j2k.exe -i original/X_4_2K_24_185_CBR_WB_000.tif -o temp/X_4_2K_24_185_CBR_WB_000.j2k -cinema2K 24\r
-image_to_j2k.exe -i original/X_5_2K_24_235_CBR_STEM24_000.tif -o temp/X_5_2K_24_235_CBR_STEM24_000.j2k -cinema2K 48\r
-image_to_j2k.exe -i original/X_6_2K_24_FULL_CBR_CIRCLE_000.tif -o temp/X_6_2K_24_FULL_CBR_CIRCLE_000.j2k -cinema2K 24\r
-#� remettre\r
-#image_to_j2k.exe -i original/X_16_4K_24_185_CBR_WB_000.tif -o temp/X_16_4K_24_185_CBR_WB_000.j2k -cinema4K\r
-j2k_to_image.exe -i original/A_4_2K_24_185_CBR_WB_000.j2k -o temp/A_4_2K_24_185_CBR_WB_000.tif\r
-j2k_to_image.exe -i original/B_5_2K_24_235_CBR_STEM24_000.j2k -o temp/B_5_2K_24_235_CBR_STEM24_000.tif\r
-j2k_to_image.exe -i original/C_6_2K_24_FULL_CBR_CIRCLE_000.j2k -o temp/C_6_2K_24_FULL_CBR_CIRCLE_000.tif\r
-#� remettre\r
-#j2k_to_image.exe -i original/C_18_4K_24_FULL_CBR_CIRCLE_000.j2k -o temp/C_18_4K_24_FULL_CBR_CIRCLE_000.tif\r
-j2k_to_image.exe -i original/p0_01.j2k -o temp/p0_01.tif\r
-j2k_to_image.exe -i original/p0_02.j2k -o temp/p0_02.tif\r
-j2k_to_image.exe -i original/p0_03.j2k -o temp/p0_03.tif\r
-j2k_to_image.exe -i original/p0_04.j2k -o temp/p0_04.tif\r
-#� remettre\r
-#j2k_to_image.exe -i original/p0_07.j2k -o temp/p0_07.tif\r
-j2k_to_image.exe -i original/p0_08.j2k -o temp/p0_08.tif\r
-j2k_to_image.exe -i original/p0_09.j2k -o temp/p0_09.tif\r
-j2k_to_image.exe -i original/p0_10.j2k -o temp/p0_10.tif\r
-j2k_to_image.exe -i original/p0_11.j2k -o temp/p0_11.tif\r
-j2k_to_image.exe -i original/p0_12.j2k -o temp/p0_12.tif\r
-j2k_to_image.exe -i original/p0_14.j2k -o temp/p0_14.tif\r
-j2k_to_image.exe -i original/p0_15.j2k -o temp/p0_15.tif\r
-j2k_to_image.exe -i original/p0_16.j2k -o temp/p0_16.tif\r
-j2k_to_image.exe -i original/p1_01.j2k -o temp/p1_01.tif\r
-j2k_to_image.exe -i original/p1_02.j2k -o temp/p1_02.tif\r
-j2k_to_image.exe -i original/p1_04.j2k -o temp/p1_04.tif\r
-j2k_to_image.exe -i original/p1_05.j2k -o temp/p1_05.tif\r
-j2k_to_image.exe -i original/p1_06.j2k -o temp/p1_06.tif\r
-image_to_j2k.exe -i original/c0p0_01.pgx -o temp/c0p0_01.j2k\r
-image_to_j2k.exe -i original/c0p0_02.pgx -o temp/c0p0_02.j2k\r
-image_to_j2k.exe -i original/c0p0_03r0.pgx -o temp/c0p0_03r0.j2k\r
-image_to_j2k.exe -i original/c0p0_03r1.pgx -o temp/c0p0_03r1.j2k\r
-image_to_j2k.exe -i original/c0p0_04.pgx -o temp/c00_p04.j2k\r
-image_to_j2k.exe -i original/c0p0_05.pgx -o temp/c0p0_05.j2k\r
-image_to_j2k.exe -i original/c0p0_06.pgx -o temp/c0p0_06.j2k\r
-image_to_j2k.exe -i original/c0p0_07.pgx -o temp/c0p0_07.j2k\r
-image_to_j2k.exe -i original/c0p0_08.pgx -o temp/c0p0_08.j2k\r
-image_to_j2k.exe -i original/c0p0_09.pgx -o temp/c0p0_09.j2k\r
-image_to_j2k.exe -i original/c0p0_10.pgx -o temp/c0p0_10.j2k\r
-image_to_j2k.exe -i original/c0p0_11.pgx -o temp/c0p0_11.j2k\r
-image_to_j2k.exe -i original/c0p0_12.pgx -o temp/c0p0_12.j2k\r
-image_to_j2k.exe -i original/c0p0_13.pgx -o temp/c0p0_13.j2k\r
-image_to_j2k.exe -i original/c0p0_14.pgx -o temp/c0p0_14.j2k\r
-image_to_j2k.exe -i original/c0p0_15r0.pgx -o temp/c0p0_15r0.j2k\r
-image_to_j2k.exe -i original/c0p0_15r1.pgx -o temp/c0p0_15r1.j2k\r
-image_to_j2k.exe -i original/c0p0_16.pgx -o temp/c0p0_16.j2k\r
-image_to_j2k.exe -i original/c0p1_04r0.pgx -o temp/c0p1_04r0.j2k\r
-image_to_j2k.exe -i original/c0p1_05.pgx -o temp/c0p1_05.j2k\r
-image_to_j2k.exe -i original/c1p0_01_0.pgx -o temp/c1p0_01_0.j2k\r
-image_to_j2k.exe -i original/c1p0_02_0.pgx -o temp/c1p0_02_0.j2k\r
-image_to_j2k.exe -i original/c1p0_03_0.pgx -o temp/c1p0_03_0.j2k\r
-image_to_j2k.exe -i original/c1p0_04_0.pgx -o temp/c1p0_04_0.j2k\r
-image_to_j2k.exe -i original/c1p0_05_0.pgx -o temp/c1p0_05_0.j2k\r
-image_to_j2k.exe -i original/c1p0_06_0.pgx -o temp/c1p0_06_0.j2k\r
-image_to_j2k.exe -i original/c1p0_07_0.pgx -o temp/c1p0_07_0.j2k\r
-image_to_j2k.exe -i original/c1p0_08_0.pgx -o temp/c1p0_08_0.j2k\r
-image_to_j2k.exe -i original/c1p0_09_0.pgx -o temp/c1p0_09_0.j2k\r
-image_to_j2k.exe -i original/c1p0_10_0.pgx -o temp/c1p0_10_0.j2k\r
-image_to_j2k.exe -i original/c1p0_11_0.pgx -o temp/c1p0_11_0.j2k\r
-image_to_j2k.exe -i original/c1p0_12_0.pgx -o temp/c1p0_12_0.j2k\r
-image_to_j2k.exe -i original/c1p0_13_0.pgx -o temp/c1p0_13_0.j2k\r
-image_to_j2k.exe -i original/c1p0_14_0.pgx -o temp/c1p0_14_0.j2k\r
-image_to_j2k.exe -i original/c1p0_15_0.pgx -o temp/c1p0_15_0.j2k\r
-image_to_j2k.exe -i original/c1p0_16_0.pgx -o temp/c1p0_16_0.j2k\r
-image_to_j2k.exe -i original/c1p1_02_0.pgx -o temp/c1p1_02_0.j2k\r
-image_to_j2k.exe -i original/c1p1_05_0.pgx -o temp/c1p1_05_0.j2k\r
-image_to_j2k.exe -i original/Bretagne2.ppm -o temp/Bretagne2_2.j2k -s 2,2 -SOP\r
-image_to_j2k.exe -i original/Bretagne2.ppm -o temp/Bretagne2_3.j2k -EPH -M 38\r
-image_to_j2k.exe -i original/Bretagne2.ppm -o temp/Bretagne2_4.j2k -d 150,300 -r 800\r
-j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1.bmp\r
-j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1r2.bmp -r 2\r
-j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1.tga\r
-j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1r2.tga -r 2\r
-j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1.pnm\r
-j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1r2.pnm -r 2\r
-j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1r2.ppm -r 2\r
-j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1.raw\r
-j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1r2.raw -r 2\r
-j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1.tif\r
-j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1r2.tif -r 2\r
-j2k_to_image.exe -i original/p0_03.j2k -o p0_03.pgx\r
diff --git a/OPJ_Validate/OPJ_Validate.c b/OPJ_Validate/OPJ_Validate.c
deleted file mode 100644 (file)
index 9bd1da5..0000000
+++ /dev/null
@@ -1,244 +0,0 @@
-/*\r
-* Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
-* Copyright (c) 2002-2007, Professor Benoit Macq\r
-* Copyright (c) 2003-2007, Francois-Olivier Devaux \r
-* All rights reserved.\r
-*\r
-* Redistribution and use in source and binary forms, with or without\r
-* modification, are permitted provided that the following conditions\r
-* are met:\r
-* 1. Redistributions of source code must retain the above copyright\r
-*    notice, this list of conditions and the following disclaimer.\r
-* 2. Redistributions in binary form must reproduce the above copyright\r
-*    notice, this list of conditions and the following disclaimer in the\r
-*    documentation and/or other materials provided with the distribution.\r
-*\r
-* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
-* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
-* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
-* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
-* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
-* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
-* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
-* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
-* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
-* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
-* POSSIBILITY OF SUCH DAMAGE.\r
-*/\r
-\r
-#ifdef _WIN32\r
-#include <windows.h>\r
-#endif /* _WIN32 */\r
-#include <stdio.h>\r
-#include <string.h>\r
-#include "md5.h"\r
-\r
-#define OPJ_Bin_Dir "OPJ_Binaries"\r
-\r
-int doprocess(char programme[4096],char command_line[4096]) {\r
-\r
-#ifdef _WIN32\r
-       \r
-       int exit=STILL_ACTIVE;\r
-       STARTUPINFO siStartupInfo;\r
-       PROCESS_INFORMATION piProcessInfo;\r
-       \r
-       memset(&siStartupInfo, 0, sizeof(siStartupInfo));\r
-       memset(&piProcessInfo, 0, sizeof(piProcessInfo));\r
-       siStartupInfo.cb = sizeof(siStartupInfo);\r
-       \r
-       if(CreateProcess(programme, // Application name\r
-               command_line, // Application arguments\r
-               0,\r
-               0,\r
-               FALSE,\r
-               CREATE_DEFAULT_ERROR_MODE,\r
-               0,\r
-               0, // Working directory\r
-               &siStartupInfo,\r
-               &piProcessInfo) == FALSE)       \r
-               return 1;\r
-       \r
-       exit=STILL_ACTIVE;\r
-       while(exit==STILL_ACTIVE) {\r
-               Sleep(1000);\r
-               GetExitCodeProcess(piProcessInfo.hProcess,&exit);\r
-       }\r
-       \r
-       return 0;\r
-\r
-#else /* !_WIN32 */\r
-       printf("\n%s\n", command_line);\r
-       system(command_line);\r
-       return 0;\r
-\r
-#endif /* _WIN32 */\r
-       \r
-}\r
-\r
-char MD5_process(char *input_filename, char *md5_filename) {\r
-       MD5_CTX mdContext;\r
-       int bytes;\r
-  unsigned char data[1024];\r
-       FILE *input_file, *md5_file;\r
-       \r
-       input_file = fopen(input_filename, "rb");\r
-       if (!input_file) {\r
-               printf("Error opening file %s\n", input_filename);\r
-               return 1;\r
-       }\r
-       \r
-       md5_file = fopen(md5_filename, "wb");\r
-       if (!md5_file) {\r
-               printf("Error opening file %s\n", md5_filename);\r
-               return 1;\r
-       }\r
-       \r
-       MD5Init (&mdContext);\r
-  while ((bytes = fread (data, 1, 1024, input_file)) != 0)\r
-    MD5Update (&mdContext, data, bytes);\r
-  MD5Final (&mdContext);\r
-       \r
-       fwrite(mdContext.digest,16,1,md5_file);\r
-       \r
-       fclose(input_file);\r
-       fclose(md5_file);\r
-       \r
-       return 0;\r
-}\r
-\r
-char fcompare(char *input_filename, char *output_filename) {\r
-       FILE *input_file, *output_file;\r
-       unsigned char input_buffer[17], output_buffer[17];\r
-       char comparison;\r
-       \r
-       input_file = fopen(input_filename, "rb");\r
-       if (!input_file) {\r
-               printf("Error opening file %s\n", input_filename);\r
-               return -1;\r
-       }\r
-       \r
-       output_file = fopen(output_filename, "rb");\r
-       if (!output_file) {\r
-               printf("Error opening file %s\n", output_filename);\r
-               return -1;\r
-       }\r
-       \r
-       fread(input_buffer,16,1,input_file);\r
-       fread(output_buffer,16,1,output_file);\r
-       fclose(input_file);\r
-       fclose(output_file);\r
-       input_buffer[16] = 0;\r
-       output_buffer[16] = 0;\r
-       \r
-       comparison = strcmp(input_buffer, output_buffer);\r
-       \r
-       if (comparison)\r
-               return 1;\r
-       return 0;\r
-}\r
-\r
-int main(int argc, char* argv[]) {\r
-       FILE *param_file, *md5_file;\r
-       FILE *report_file;\r
-       char line[4096];\r
-       char md5_filename[4096], tempmd5_filename[4096], temp[4096], report_filename[4096];\r
-       char output_filename[4096];\r
-       char input_cmdline[4096];\r
-       char command_line[4096], exefile[4096];\r
-       int task_counter = 0, word_counter;\r
-       char bin_dir[4096];\r
-       unsigned int word_pointer;\r
-       char ch[4096];                          \r
-       char comparison;\r
-       int num_failed = 0;\r
-       int num_inexistant = 0;\r
-       int num_passed = 0;\r
-               \r
-       if (argc != 3) {\r
-               printf("Error with command line. \nExpected: OPJ_Validate parameter_filename bin_directory\n Example: OPJ_Validate parameters_01.txt version1.1.a\n\n");\r
-               return 1;\r
-       }\r
-       \r
-       param_file = fopen(argv[1],"rb");\r
-       if (!param_file) {\r
-               printf("Error opening parameter file %s\n",argv[1]);\r
-               return 1;\r
-       }       \r
-       \r
-       sprintf(bin_dir,"%s/%s",OPJ_Bin_Dir,argv[2]);\r
-       sprintf(tempmd5_filename,"temp/tempmd5.txt");\r
-       sprintf(report_filename,"%s/report.txt",bin_dir);\r
-       report_file = fopen(report_filename, "wb");\r
-       if (!report_file) {\r
-               printf("Unable to open report file %s", report_filename);\r
-               return 1;\r
-       }\r
-       \r
-       while (fgets(line, 4096, param_file) != NULL) {\r
-               \r
-               if (line[0] != '#' && line[0] != 0x0d) {        // If not a comment line\r
-                       sscanf(line, "%s", temp);\r
-                       word_pointer = 0;\r
-                       sprintf(input_cmdline,"");      \r
-                       sscanf(line+word_pointer,"%s",ch);\r
-                       sprintf(exefile,"%s/%s",bin_dir,ch);                            \r
-                       word_counter = 0;\r
-                       while (sscanf(line+word_pointer,"%s",ch) > 0) {\r
-                               if (word_counter == 4) \r
-                                       strcpy(output_filename, ch);\r
-                               word_pointer += strlen(ch)+1;\r
-                               sprintf(input_cmdline,"%s%s ",input_cmdline, ch);                               \r
-                               word_counter++;\r
-                       }                       \r
-                       sprintf(md5_filename,"%s.md5",output_filename);\r
-                       task_counter++;\r
-                       sprintf(command_line,"%s/%s",bin_dir,input_cmdline);\r
-                       printf("Task %d\nMD5 file: %s\nCommand line: \"%s\"\n",task_counter, md5_filename,command_line);\r
-                       fprintf(report_file,"Task %d\n   MD5 file: %s\n   Command line: \"%s\"\n",task_counter, md5_filename,command_line);\r
-                       \r
-                       if (doprocess(exefile,command_line)) {\r
-                               printf("Error executing: \"%s\" \n", command_line);\r
-                               fprintf(report_file,"Task %d failed because command line is not valid.\n\n", task_counter);\r
-                       }\r
-                       else {\r
-                               \r
-                               // Check if MD5 reference exists\r
-                               md5_file = fopen(md5_filename,"rb");\r
-                               if (md5_file) {\r
-                                       fclose(md5_file);\r
-                                       if (MD5_process(output_filename, tempmd5_filename)) \r
-                                               return 1;\r
-                                       \r
-                                       comparison = fcompare(tempmd5_filename, md5_filename);\r
-                                       if (comparison == -1)\r
-                                               return 1;\r
-                                       else if (comparison) {\r
-                                               printf("ERROR: %s and %s are different.\nThe codec seems to behave differently.\n\n", tempmd5_filename, md5_filename);\r
-                                               fprintf(report_file,"ERROR: %s and %s are different.\nThe codec seems to behave differently.\n\n", tempmd5_filename, md5_filename);\r
-                                               num_failed++;\r
-                                       }\r
-                                       else {\r
-                                               printf("%s and %s are the same.\nTask %d OK\n\n",tempmd5_filename, md5_filename, task_counter);\r
-                                               fprintf(report_file,"   %s and %s are the same.\nTask %d OK\n\n",tempmd5_filename, md5_filename, task_counter);\r
-                                               num_passed++;\r
-                                       }\r
-                                       remove(tempmd5_filename);\r
-                               }       \r
-                               else {\r
-                                       if (MD5_process(output_filename, md5_filename))\r
-                                               return 1;\r
-                                       printf("...  MD5 of %s was inexistant. It has been created\n\n", output_filename);\r
-                                       fprintf(report_file,"MD5 of %s was inexistant. It has been created\n\n", output_filename);\r
-                                       num_inexistant++;\r
-                               }\r
-                       }\r
-               }\r
-       }               \r
-\r
-       printf("\nREPORT;\n%d tests num_passed\n%d tests num_failed\n%d MD5 were num_inexistant\n", num_passed, num_failed, num_inexistant);\r
-       fprintf(report_file,"\nREPORT;\n%d tests num_passed\n%d tests num_failed\n%d MD5 were num_inexistant\n", num_passed, num_failed, num_inexistant);\r
-       fclose(param_file);\r
-       fclose(report_file);\r
-               \r
-}\r
diff --git a/OPJ_Validate/OPJ_Validate.dsp b/OPJ_Validate/OPJ_Validate.dsp
deleted file mode 100644 (file)
index 7463089..0000000
+++ /dev/null
@@ -1,108 +0,0 @@
-# Microsoft Developer Studio Project File - Name="OPJ_Validate" - Package Owner=<4>\r
-# Microsoft Developer Studio Generated Build File, Format Version 6.00\r
-# ** DO NOT EDIT **\r
-\r
-# TARGTYPE "Win32 (x86) Console Application" 0x0103\r
-\r
-CFG=OPJ_Validate - Win32 Debug\r
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r
-!MESSAGE use the Export Makefile command and run\r
-!MESSAGE \r
-!MESSAGE NMAKE /f "OPJ_Validate.mak".\r
-!MESSAGE \r
-!MESSAGE You can specify a configuration when running NMAKE\r
-!MESSAGE by defining the macro CFG on the command line. For example:\r
-!MESSAGE \r
-!MESSAGE NMAKE /f "OPJ_Validate.mak" CFG="OPJ_Validate - Win32 Debug"\r
-!MESSAGE \r
-!MESSAGE Possible choices for configuration are:\r
-!MESSAGE \r
-!MESSAGE "OPJ_Validate - Win32 Release" (based on "Win32 (x86) Console Application")\r
-!MESSAGE "OPJ_Validate - Win32 Debug" (based on "Win32 (x86) Console Application")\r
-!MESSAGE \r
-\r
-# Begin Project\r
-# PROP AllowPerConfigDependencies 0\r
-# PROP Scc_ProjName ""\r
-# PROP Scc_LocalPath ""\r
-CPP=cl.exe\r
-RSC=rc.exe\r
-\r
-!IF  "$(CFG)" == "OPJ_Validate - Win32 Release"\r
-\r
-# PROP BASE Use_MFC 0\r
-# PROP BASE Use_Debug_Libraries 0\r
-# PROP BASE Output_Dir "Release"\r
-# PROP BASE Intermediate_Dir "Release"\r
-# PROP BASE Target_Dir ""\r
-# PROP Use_MFC 0\r
-# PROP Use_Debug_Libraries 0\r
-# PROP Output_Dir "Release"\r
-# PROP Intermediate_Dir "Release"\r
-# PROP Target_Dir ""\r
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
-# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
-# ADD BASE RSC /l 0x80c /d "NDEBUG"\r
-# ADD RSC /l 0x80c /d "NDEBUG"\r
-BSC32=bscmake.exe\r
-# ADD BASE BSC32 /nologo\r
-# ADD BSC32 /nologo\r
-LINK32=link.exe\r
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
-\r
-!ELSEIF  "$(CFG)" == "OPJ_Validate - Win32 Debug"\r
-\r
-# PROP BASE Use_MFC 0\r
-# PROP BASE Use_Debug_Libraries 1\r
-# PROP BASE Output_Dir "Debug"\r
-# PROP BASE Intermediate_Dir "Debug"\r
-# PROP BASE Target_Dir ""\r
-# PROP Use_MFC 0\r
-# PROP Use_Debug_Libraries 1\r
-# PROP Output_Dir "Debug"\r
-# PROP Intermediate_Dir "Debug"\r
-# PROP Target_Dir ""\r
-# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c\r
-# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /FR /YX /FD /GZ /c\r
-# ADD BASE RSC /l 0x80c /d "_DEBUG"\r
-# ADD RSC /l 0x80c /d "_DEBUG"\r
-BSC32=bscmake.exe\r
-# ADD BASE BSC32 /nologo\r
-# ADD BSC32 /nologo\r
-LINK32=link.exe\r
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
-\r
-!ENDIF \r
-\r
-# Begin Target\r
-\r
-# Name "OPJ_Validate - Win32 Release"\r
-# Name "OPJ_Validate - Win32 Debug"\r
-# Begin Group "Source Files"\r
-\r
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"\r
-# Begin Source File\r
-\r
-SOURCE=.\md5.c\r
-# End Source File\r
-# Begin Source File\r
-\r
-SOURCE=.\OPJ_Validate.c\r
-# End Source File\r
-# End Group\r
-# Begin Group "Header Files"\r
-\r
-# PROP Default_Filter "h;hpp;hxx;hm;inl"\r
-# Begin Source File\r
-\r
-SOURCE=.\md5.h\r
-# End Source File\r
-# End Group\r
-# Begin Group "Resource Files"\r
-\r
-# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
-# End Group\r
-# End Target\r
-# End Project\r
diff --git a/OPJ_Validate/OPJ_Validate.dsw b/OPJ_Validate/OPJ_Validate.dsw
deleted file mode 100644 (file)
index 05a3403..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-Microsoft Developer Studio Workspace File, Format Version 6.00\r
-# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!\r
-\r
-###############################################################################\r
-\r
-Project: "OPJ_Validate"=".\OPJ_Validate.dsp" - Package Owner=<4>\r
-\r
-Package=<5>\r
-{{{\r
-}}}\r
-\r
-Package=<4>\r
-{{{\r
-}}}\r
-\r
-###############################################################################\r
-\r
-Global:\r
-\r
-Package=<5>\r
-{{{\r
-}}}\r
-\r
-Package=<3>\r
-{{{\r
-}}}\r
-\r
-###############################################################################\r
-\r
diff --git a/OPJ_Validate/OPJ_Validate_Candidate_vs_Ref.bat b/OPJ_Validate/OPJ_Validate_Candidate_vs_Ref.bat
deleted file mode 100644 (file)
index 0fd61ad..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-cd temp\r
-erase *.ppm\r
-erase *.j2k\r
-erase *.bmp\r
-erase *.tif\r
-erase *.jp2\r
-cd ..\r
-OPJ_Validate.exe OPJ_Param_File_v0_1.txt testv2\r
diff --git a/OPJ_Validate/OPJ_Validate_Candidate_vs_Ref.sh b/OPJ_Validate/OPJ_Validate_Candidate_vs_Ref.sh
deleted file mode 100644 (file)
index edd3eaa..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-#!/bin/bash
-cd temp
-erase *.ppm
-erase *.j2k
-erase *.bmp
-erase *.tif
-erase *.jp2
-cd ..
-
-echo
-echo "Type the name of the directory (inside OPJ_Binaries) "
-echo "containing your executables to compared with reference, followed by [ENTER] (example: rev101):"
-read compdir
-
-./OPJ_Validate linux_OPJ_Param_File_v0_1.txt $compdir
-echo
diff --git a/OPJ_Validate/OPJ_Validate_Create_Ref.bat b/OPJ_Validate/OPJ_Validate_Create_Ref.bat
deleted file mode 100644 (file)
index 83332fc..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-cd temp\r
-erase *.md5\r
-cd ..\r
-OPJ_Validate.exe OPJ_Param_File_v0_1.txt rev490\r
diff --git a/OPJ_Validate/OPJ_Validate_Create_Ref.sh b/OPJ_Validate/OPJ_Validate_Create_Ref.sh
deleted file mode 100644 (file)
index e44e053..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/bin/bash
-#Create Reference images and hash
-
-echo
-echo "Type the name of the directory (inside OPJ_Binaries) "
-echo "containing your reference executables, followed by [ENTER] (example: rev100):"
-read refdir
-cd temp
-rm *.md5
-cd ..
-./OPJ_Validate linux_OPJ_Param_File_v0_1.txt $refdir
-echo
-
diff --git a/OPJ_Validate/README.txt b/OPJ_Validate/README.txt
deleted file mode 100644 (file)
index 364ef8e..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-Initialization\r
---------------\r
-Download the source images into the /original directory from http://www.openjpeg.org/OPJ_Validate_OriginalImages.7z\r
-\r
-Usage\r
------\r
-Usage: OPJ_Validate batch_text_file bin_directory\r
-Example: OPJ_Validate OPJ_Param_File_v0_1.txt v1.1.a\r
-where OPJ_Param_File_v0_1.txt is a file containing a list of compression and decompression parameters\r
-and v1.1.a is a directory inside the directory OPJ_Binaries containing the openjpeg executables (j2k_to_image.exe and image_to_j2k.exe)\r
-\r
-Example with batch file: You consider revision 490 (/rev490) as stable, and would like to compare it a new version, revision 493 (rev493).\r
-\r
-Batch mode\r
-----------\r
-1) Calculate the reference by running the "OPJ_Validate_Create_Ref rev490" file (.sh or .bat depending on your os)\r
-2) Compare the candidate revision with ther reference by running the "OPJ_Validate_Candidate_vs_Ref rev493" file\r
-3) The results of the comparison are given at the end of the processing. They are also available in the bin directory OPJ_Binaries/rev493/report.txt\r
-\r
-Manual mode\r
------------\r
-1) Put the j2k_to_image.exe and image_to_j2k.exe binaries of both revisions in the OPJ_Binaries directory (OPJ_Binaries/rev490 and OPJ_Binaries/rev493)  \r
-2) Start by initializing the validation with revision 490. \r
-       a) Modify OPJ_Validate_init.bat and set the last line to "OPJ_Validate.exe OPJ_Param_File_v0_1.txt rev490"\r
-       b) Execute OPJ_Validate_init.bat\r
-3) Compare the reference files generated in the previous step with files generated with revision 493\r
-       a) Modify OPJ_Validate_run.bat and set the last line to "OPJ_Validate.exe OPJ_Param_File_v0_1.txt rev493"\r
-       b) Execute OPJ_Validate_run.bat\r
-4) Read the results in the binaries directory of revision 493 (OPJ_Binaries/rev493/report.txt)\r
-       Search for the word "ERROR:" in that file. \r
-       If this word is not present in the report, this means that both codecs of rev490 and rev493 gave the same results.\r
-       Otherwise, it means that for certain encoding/decoding parameters, the codecs behave differently.\r
-\r
-       Example of error\r
-               Task 17\r
-                  MD5 file: temp/A_4_2K_24_185_CBR_WB_000.tif.md5\r
-                  Command line: "OPJ_Binaries/rev473/j2k_to_image.exe -i original/A_4_2K_24_185_CBR_WB_000.j2k -o temp/A_4_2K_24_185_CBR_WB_000.tif "\r
-               ERROR: temp/tempmd5.txt and temp/A_4_2K_24_185_CBR_WB_000.tif.md5 are different.\r
-               The codec seems to behave differently.\r
-\r
-       This means that the rev490 and rev493 created two different versions of file A_4_2K_24_185_CBR_WB_000.tif with the command line given above.\r
-       An error might have been caused by switching to this new revision.\r
-\r
-       Warning: Do not take the last line of the report.txt file into account ( Cool. All files passed the tests !) as it is a bug. Search for the word "ERROR:" to detect potential errors.\r
-5) If no error is detected, you can commit the changes to the OpenJPEG repository\r
-\r
diff --git a/OPJ_Validate/linux_OPJ_Param_File_v0_1.txt b/OPJ_Validate/linux_OPJ_Param_File_v0_1.txt
deleted file mode 100644 (file)
index 0dafe2c..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-#OPJ Parameter file\r
-#Version 0.1 - February 9th 2007\r
-#Usage: OPJ_Validate OpenJPEG_command_line\r
-#Example: OPJ_Validate image_to_j2k.exe -i original/Bretagne1.ppm -o original/Bretagne1.j2k -r 200, 50, 10\r
-#Attention: don't forget the *.exe extension for the executable file, and check the paths\r
-#\r
-image_to_j2k -i original/Bretagne1.ppm -o temp/Bretagne1_0.j2k -r 200,50,10\r
-j2k_to_image -i original/Bretagne1.j2k -o temp/Bretagne1.ppm\r
-image_to_j2k -i original/Bretagne2.ppm -o temp/Bretagne2_0.j2k -c [128,128],[128,128],[128,128] -r 100,20,2 -t 640,480 -b 32,32\r
-j2k_to_image -i original/Bretagne2.j2k -o temp/Bretagne2.ppm -r 2\r
-image_to_j2k -i original/Cevennes1.bmp -o temp/Cevennes1.j2k -r 10\r
-j2k_to_image -i original/Cevennes1.j2k -o temp/Cevennes1.bmp -l 2\r
-image_to_j2k -i original/Cevennes2.ppm -o temp/Cevennes2.jp2 -r 50\r
-j2k_to_image -i original/Cevennes2.jp2 -o temp/Cevennes2.ppm\r
-image_to_j2k -i original/Rome.bmp -o temp/Rome.jp2 -q 30,35,50 -p LRCP -n 3\r
-j2k_to_image -i original/Rome.jp2 -o temp/Rome.ppm\r
-image_to_j2k -i original/Bretagne1.ppm -o temp/Bretagne1_1.j2k -q 30,35,40 -n 2\r
-image_to_j2k -i original/Bretagne1.ppm -o temp/Bretagne1_2.j2k -q 30,35,40 -b 16,16 -c [101,101]\r
-image_to_j2k -i original/Bretagne2.ppm -o temp/Bretagne2_1.j2k -t 127,127 -p PCRL\r
-image_to_j2k -i original/X_4_2K_24_185_CBR_WB_000.tif -o temp/X_4_2K_24_185_CBR_WB_000.j2k -cinema2K 24\r
-image_to_j2k -i original/X_5_2K_24_235_CBR_STEM24_000.tif -o temp/X_5_2K_24_235_CBR_STEM24_000.j2k -cinema2K 48\r
-image_to_j2k -i original/X_6_2K_24_FULL_CBR_CIRCLE_000.tif -o temp/X_6_2K_24_FULL_CBR_CIRCLE_000.j2k -cinema2K 24\r
-#� remettre\r
-#image_to_j2k -i original/X_16_4K_24_185_CBR_WB_000.tif -o temp/X_16_4K_24_185_CBR_WB_000.j2k -cinema4K \r
-j2k_to_image -i original/A_4_2K_24_185_CBR_WB_000.j2k -o temp/A_4_2K_24_185_CBR_WB_000.tif\r
-j2k_to_image -i original/B_5_2K_24_235_CBR_STEM24_000.j2k -o temp/B_5_2K_24_235_CBR_STEM24_000.tif\r
-j2k_to_image -i original/C_6_2K_24_FULL_CBR_CIRCLE_000.j2k -o temp/C_6_2K_24_FULL_CBR_CIRCLE_000.tif\r
-#� remettre\r
-#j2k_to_image -i original/C_18_4K_24_FULL_CBR_CIRCLE_000.j2k -o temp/C_18_4K_24_FULL_CBR_CIRCLE_000.tif\r
-j2k_to_image -i original/p0_01.j2k -o temp/p0_01.tif\r
-j2k_to_image -i original/p0_02.j2k -o temp/p0_02.tif\r
-j2k_to_image -i original/p0_03.j2k -o temp/p0_03.tif\r
-j2k_to_image -i original/p0_04.j2k -o temp/p0_04.tif\r
-#a remettre\r
-#j2k_to_image -i original/p0_07.j2k -o temp/p0_07.tif\r
-j2k_to_image -i original/p0_08.j2k -o temp/p0_08.tif\r
-j2k_to_image -i original/p0_09.j2k -o temp/p0_09.tif\r
-j2k_to_image -i original/p0_10.j2k -o temp/p0_10.tif\r
-j2k_to_image -i original/p0_11.j2k -o temp/p0_11.tif\r
-j2k_to_image -i original/p0_12.j2k -o temp/p0_12.tif\r
-j2k_to_image -i original/p0_14.j2k -o temp/p0_14.tif\r
-j2k_to_image -i original/p0_15.j2k -o temp/p0_15.tif\r
-j2k_to_image -i original/p0_16.j2k -o temp/p0_16.tif\r
-j2k_to_image -i original/p1_01.j2k -o temp/p1_01.tif\r
-j2k_to_image -i original/p1_02.j2k -o temp/p1_02.tif\r
-j2k_to_image -i original/p1_04.j2k -o temp/p1_04.tif\r
-j2k_to_image -i original/p1_05.j2k -o temp/p1_05.tif\r
-j2k_to_image -i original/p1_06.j2k -o temp/p1_06.tif\r
-image_to_j2k -i original/c0p0_01.pgx -o temp/c0p0_01.j2k\r
-image_to_j2k -i original/c0p0_02.pgx -o temp/c0p0_02.j2k\r
-image_to_j2k -i original/c0p0_03r0.pgx -o temp/c0p0_03r0.j2k\r
-image_to_j2k -i original/c0p0_03r1.pgx -o temp/c0p0_03r1.j2k\r
-image_to_j2k -i original/c0p0_04.pgx -o temp/c00_p04.j2k\r
-image_to_j2k -i original/c0p0_05.pgx -o temp/c0p0_05.j2k\r
-image_to_j2k -i original/c0p0_06.pgx -o temp/c0p0_06.j2k\r
-image_to_j2k -i original/c0p0_07.pgx -o temp/c0p0_07.j2k\r
-image_to_j2k -i original/c0p0_08.pgx -o temp/c0p0_08.j2k\r
-image_to_j2k -i original/c0p0_09.pgx -o temp/c0p0_09.j2k\r
-image_to_j2k -i original/c0p0_10.pgx -o temp/c0p0_10.j2k\r
-image_to_j2k -i original/c0p0_11.pgx -o temp/c0p0_11.j2k\r
-image_to_j2k -i original/c0p0_12.pgx -o temp/c0p0_12.j2k\r
-image_to_j2k -i original/c0p0_13.pgx -o temp/c0p0_13.j2k\r
-image_to_j2k -i original/c0p0_14.pgx -o temp/c0p0_14.j2k\r
-image_to_j2k -i original/c0p0_15r0.pgx -o temp/c0p0_15r0.j2k\r
-image_to_j2k -i original/c0p0_15r1.pgx -o temp/c0p0_15r1.j2k\r
-image_to_j2k -i original/c0p0_16.pgx -o temp/c0p0_16.j2k\r
-image_to_j2k -i original/c0p1_04r0.pgx -o temp/c0p1_04r0.j2k\r
-image_to_j2k -i original/c0p1_05.pgx -o temp/c0p1_05.j2k\r
-image_to_j2k -i original/c1p0_01_0.pgx -o temp/c1p0_01_0.j2k\r
-image_to_j2k -i original/c1p0_02_0.pgx -o temp/c1p0_02_0.j2k\r
-image_to_j2k -i original/c1p0_03_0.pgx -o temp/c1p0_03_0.j2k\r
-image_to_j2k -i original/c1p0_04_0.pgx -o temp/c1p0_04_0.j2k\r
-image_to_j2k -i original/c1p0_05_0.pgx -o temp/c1p0_05_0.j2k\r
-image_to_j2k -i original/c1p0_06_0.pgx -o temp/c1p0_06_0.j2k\r
-image_to_j2k -i original/c1p0_07_0.pgx -o temp/c1p0_07_0.j2k\r
-image_to_j2k -i original/c1p0_08_0.pgx -o temp/c1p0_08_0.j2k\r
-image_to_j2k -i original/c1p0_09_0.pgx -o temp/c1p0_09_0.j2k\r
-image_to_j2k -i original/c1p0_10_0.pgx -o temp/c1p0_10_0.j2k\r
-image_to_j2k -i original/c1p0_11_0.pgx -o temp/c1p0_11_0.j2k\r
-image_to_j2k -i original/c1p0_12_0.pgx -o temp/c1p0_12_0.j2k\r
-image_to_j2k -i original/c1p0_13_0.pgx -o temp/c1p0_13_0.j2k\r
-image_to_j2k -i original/c1p0_14_0.pgx -o temp/c1p0_14_0.j2k\r
-image_to_j2k -i original/c1p0_15_0.pgx -o temp/c1p0_15_0.j2k\r
-image_to_j2k -i original/c1p0_16_0.pgx -o temp/c1p0_16_0.j2k\r
-image_to_j2k -i original/c1p1_02_0.pgx -o temp/c1p1_02_0.j2k\r
-image_to_j2k -i original/c1p1_05_0.pgx -o temp/c1p1_05_0.j2k\r
-image_to_j2k -i original/Bretagne2.ppm -o temp/Bretagne2_2.j2k -s 2,2 -SOP\r
-image_to_j2k -i original/Bretagne2.ppm -o temp/Bretagne2_3.j2k -EPH -M 38\r
-image_to_j2k -i original/Bretagne2.ppm -o temp/Bretagne2_4.j2k -d 150,300 -r 800\r
diff --git a/OPJ_Validate/md5.c b/OPJ_Validate/md5.c
deleted file mode 100644 (file)
index 735a27c..0000000
+++ /dev/null
@@ -1,276 +0,0 @@
-/*\r
- **********************************************************************\r
- ** md5.c                                                            **\r
- ** RSA Data Security, Inc. MD5 Message Digest Algorithm             **\r
- ** Created: 2/17/90 RLR                                             **\r
- ** Revised: 1/91 SRD,AJ,BSK,JT Reference C Version                  **\r
- **********************************************************************\r
- */\r
-\r
-/*\r
- **********************************************************************\r
- ** Copyright (C) 1990, RSA Data Security, Inc. All rights reserved. **\r
- **                                                                  **\r
- ** License to copy and use this software is granted provided that   **\r
- ** it is identified as the "RSA Data Security, Inc. MD5 Message     **\r
- ** Digest Algorithm" in all material mentioning or referencing this **\r
- ** software or this function.                                       **\r
- **                                                                  **\r
- ** License is also granted to make and use derivative works         **\r
- ** provided that such works are identified as "derived from the RSA **\r
- ** Data Security, Inc. MD5 Message Digest Algorithm" in all         **\r
- ** material mentioning or referencing the derived work.             **\r
- **                                                                  **\r
- ** RSA Data Security, Inc. makes no representations concerning      **\r
- ** either the merchantability of this software or the suitability   **\r
- ** of this software for any particular purpose.  It is provided "as **\r
- ** is" without express or implied warranty of any kind.             **\r
- **                                                                  **\r
- ** These notices must be retained in any copies of any part of this **\r
- ** documentation and/or software.                                   **\r
- **********************************************************************\r
- */\r
-\r
-/* -- include the following line if the md5.h header file is separate -- */\r
-#include "md5.h" \r
-\r
-/* forward declaration */\r
-static void Transform ();\r
-\r
-static unsigned char PADDING[64] = {\r
-  0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\r
-};\r
-\r
-/* F, G and H are basic MD5 functions: selection, majority, parity */\r
-#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))\r
-#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))\r
-#define H(x, y, z) ((x) ^ (y) ^ (z))\r
-#define I(x, y, z) ((y) ^ ((x) | (~z))) \r
-\r
-/* ROTATE_LEFT rotates x left n bits */\r
-#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))\r
-\r
-/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4 */\r
-/* Rotation is separate from addition to prevent recomputation */\r
-#define FF(a, b, c, d, x, s, ac) \\r
-  {(a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \\r
-   (a) = ROTATE_LEFT ((a), (s)); \\r
-   (a) += (b); \\r
-  }\r
-#define GG(a, b, c, d, x, s, ac) \\r
-  {(a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \\r
-   (a) = ROTATE_LEFT ((a), (s)); \\r
-   (a) += (b); \\r
-  }\r
-#define HH(a, b, c, d, x, s, ac) \\r
-  {(a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \\r
-   (a) = ROTATE_LEFT ((a), (s)); \\r
-   (a) += (b); \\r
-  }\r
-#define II(a, b, c, d, x, s, ac) \\r
-  {(a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \\r
-   (a) = ROTATE_LEFT ((a), (s)); \\r
-   (a) += (b); \\r
-  }\r
-\r
-void MD5Init (mdContext)\r
-MD5_CTX *mdContext;\r
-{\r
-  mdContext->i[0] = mdContext->i[1] = (UINT4)0;\r
-\r
-  /* Load magic initialization constants.\r
-   */\r
-  mdContext->buf[0] = (UINT4)0x67452301;\r
-  mdContext->buf[1] = (UINT4)0xefcdab89;\r
-  mdContext->buf[2] = (UINT4)0x98badcfe;\r
-  mdContext->buf[3] = (UINT4)0x10325476;\r
-}\r
-\r
-void MD5Update (mdContext, inBuf, inLen)\r
-MD5_CTX *mdContext;\r
-unsigned char *inBuf;\r
-unsigned int inLen;\r
-{\r
-  UINT4 in[16];\r
-  int mdi;\r
-  unsigned int i, ii;\r
-\r
-  /* compute number of bytes mod 64 */\r
-  mdi = (int)((mdContext->i[0] >> 3) & 0x3F);\r
-\r
-  /* update number of bits */\r
-  if ((mdContext->i[0] + ((UINT4)inLen << 3)) < mdContext->i[0])\r
-    mdContext->i[1]++;\r
-  mdContext->i[0] += ((UINT4)inLen << 3);\r
-  mdContext->i[1] += ((UINT4)inLen >> 29);\r
-\r
-  while (inLen--) {\r
-    /* add new character to buffer, increment mdi */\r
-    mdContext->in[mdi++] = *inBuf++;\r
-\r
-    /* transform if necessary */\r
-    if (mdi == 0x40) {\r
-      for (i = 0, ii = 0; i < 16; i++, ii += 4)\r
-        in[i] = (((UINT4)mdContext->in[ii+3]) << 24) |\r
-                (((UINT4)mdContext->in[ii+2]) << 16) |\r
-                (((UINT4)mdContext->in[ii+1]) << 8) |\r
-                ((UINT4)mdContext->in[ii]);\r
-      Transform (mdContext->buf, in);\r
-      mdi = 0;\r
-    }\r
-  }\r
-}\r
-\r
-void MD5Final (mdContext)\r
-MD5_CTX *mdContext;\r
-{\r
-  UINT4 in[16];\r
-  int mdi;\r
-  unsigned int i, ii;\r
-  unsigned int padLen;\r
-\r
-  /* save number of bits */\r
-  in[14] = mdContext->i[0];\r
-  in[15] = mdContext->i[1];\r
-\r
-  /* compute number of bytes mod 64 */\r
-  mdi = (int)((mdContext->i[0] >> 3) & 0x3F);\r
-\r
-  /* pad out to 56 mod 64 */\r
-  padLen = (mdi < 56) ? (56 - mdi) : (120 - mdi);\r
-  MD5Update (mdContext, PADDING, padLen);\r
-\r
-  /* append length in bits and transform */\r
-  for (i = 0, ii = 0; i < 14; i++, ii += 4)\r
-    in[i] = (((UINT4)mdContext->in[ii+3]) << 24) |\r
-            (((UINT4)mdContext->in[ii+2]) << 16) |\r
-            (((UINT4)mdContext->in[ii+1]) << 8) |\r
-            ((UINT4)mdContext->in[ii]);\r
-  Transform (mdContext->buf, in);\r
-\r
-  /* store buffer in digest */\r
-  for (i = 0, ii = 0; i < 4; i++, ii += 4) {\r
-    mdContext->digest[ii] = (unsigned char)(mdContext->buf[i] & 0xFF);\r
-    mdContext->digest[ii+1] =\r
-      (unsigned char)((mdContext->buf[i] >> 8) & 0xFF);\r
-    mdContext->digest[ii+2] =\r
-      (unsigned char)((mdContext->buf[i] >> 16) & 0xFF);\r
-    mdContext->digest[ii+3] =\r
-      (unsigned char)((mdContext->buf[i] >> 24) & 0xFF);\r
-  }\r
-}\r
-\r
-/* Basic MD5 step. Transform buf based on in.\r
- */\r
-static void Transform (buf, in)\r
-UINT4 *buf;\r
-UINT4 *in;\r
-{\r
-  UINT4 a = buf[0], b = buf[1], c = buf[2], d = buf[3];\r
-\r
-  /* Round 1 */\r
-#define S11 7\r
-#define S12 12\r
-#define S13 17\r
-#define S14 22\r
-  FF ( a, b, c, d, in[ 0], S11, 3614090360); /* 1 */\r
-  FF ( d, a, b, c, in[ 1], S12, 3905402710); /* 2 */\r
-  FF ( c, d, a, b, in[ 2], S13,  606105819); /* 3 */\r
-  FF ( b, c, d, a, in[ 3], S14, 3250441966); /* 4 */\r
-  FF ( a, b, c, d, in[ 4], S11, 4118548399); /* 5 */\r
-  FF ( d, a, b, c, in[ 5], S12, 1200080426); /* 6 */\r
-  FF ( c, d, a, b, in[ 6], S13, 2821735955); /* 7 */\r
-  FF ( b, c, d, a, in[ 7], S14, 4249261313); /* 8 */\r
-  FF ( a, b, c, d, in[ 8], S11, 1770035416); /* 9 */\r
-  FF ( d, a, b, c, in[ 9], S12, 2336552879); /* 10 */\r
-  FF ( c, d, a, b, in[10], S13, 4294925233); /* 11 */\r
-  FF ( b, c, d, a, in[11], S14, 2304563134); /* 12 */\r
-  FF ( a, b, c, d, in[12], S11, 1804603682); /* 13 */\r
-  FF ( d, a, b, c, in[13], S12, 4254626195); /* 14 */\r
-  FF ( c, d, a, b, in[14], S13, 2792965006); /* 15 */\r
-  FF ( b, c, d, a, in[15], S14, 1236535329); /* 16 */\r
-\r
-  /* Round 2 */\r
-#define S21 5\r
-#define S22 9\r
-#define S23 14\r
-#define S24 20\r
-  GG ( a, b, c, d, in[ 1], S21, 4129170786); /* 17 */\r
-  GG ( d, a, b, c, in[ 6], S22, 3225465664); /* 18 */\r
-  GG ( c, d, a, b, in[11], S23,  643717713); /* 19 */\r
-  GG ( b, c, d, a, in[ 0], S24, 3921069994); /* 20 */\r
-  GG ( a, b, c, d, in[ 5], S21, 3593408605); /* 21 */\r
-  GG ( d, a, b, c, in[10], S22,   38016083); /* 22 */\r
-  GG ( c, d, a, b, in[15], S23, 3634488961); /* 23 */\r
-  GG ( b, c, d, a, in[ 4], S24, 3889429448); /* 24 */\r
-  GG ( a, b, c, d, in[ 9], S21,  568446438); /* 25 */\r
-  GG ( d, a, b, c, in[14], S22, 3275163606); /* 26 */\r
-  GG ( c, d, a, b, in[ 3], S23, 4107603335); /* 27 */\r
-  GG ( b, c, d, a, in[ 8], S24, 1163531501); /* 28 */\r
-  GG ( a, b, c, d, in[13], S21, 2850285829); /* 29 */\r
-  GG ( d, a, b, c, in[ 2], S22, 4243563512); /* 30 */\r
-  GG ( c, d, a, b, in[ 7], S23, 1735328473); /* 31 */\r
-  GG ( b, c, d, a, in[12], S24, 2368359562); /* 32 */\r
-\r
-  /* Round 3 */\r
-#define S31 4\r
-#define S32 11\r
-#define S33 16\r
-#define S34 23\r
-  HH ( a, b, c, d, in[ 5], S31, 4294588738); /* 33 */\r
-  HH ( d, a, b, c, in[ 8], S32, 2272392833); /* 34 */\r
-  HH ( c, d, a, b, in[11], S33, 1839030562); /* 35 */\r
-  HH ( b, c, d, a, in[14], S34, 4259657740); /* 36 */\r
-  HH ( a, b, c, d, in[ 1], S31, 2763975236); /* 37 */\r
-  HH ( d, a, b, c, in[ 4], S32, 1272893353); /* 38 */\r
-  HH ( c, d, a, b, in[ 7], S33, 4139469664); /* 39 */\r
-  HH ( b, c, d, a, in[10], S34, 3200236656); /* 40 */\r
-  HH ( a, b, c, d, in[13], S31,  681279174); /* 41 */\r
-  HH ( d, a, b, c, in[ 0], S32, 3936430074); /* 42 */\r
-  HH ( c, d, a, b, in[ 3], S33, 3572445317); /* 43 */\r
-  HH ( b, c, d, a, in[ 6], S34,   76029189); /* 44 */\r
-  HH ( a, b, c, d, in[ 9], S31, 3654602809); /* 45 */\r
-  HH ( d, a, b, c, in[12], S32, 3873151461); /* 46 */\r
-  HH ( c, d, a, b, in[15], S33,  530742520); /* 47 */\r
-  HH ( b, c, d, a, in[ 2], S34, 3299628645); /* 48 */\r
-\r
-  /* Round 4 */\r
-#define S41 6\r
-#define S42 10\r
-#define S43 15\r
-#define S44 21\r
-  II ( a, b, c, d, in[ 0], S41, 4096336452); /* 49 */\r
-  II ( d, a, b, c, in[ 7], S42, 1126891415); /* 50 */\r
-  II ( c, d, a, b, in[14], S43, 2878612391); /* 51 */\r
-  II ( b, c, d, a, in[ 5], S44, 4237533241); /* 52 */\r
-  II ( a, b, c, d, in[12], S41, 1700485571); /* 53 */\r
-  II ( d, a, b, c, in[ 3], S42, 2399980690); /* 54 */\r
-  II ( c, d, a, b, in[10], S43, 4293915773); /* 55 */\r
-  II ( b, c, d, a, in[ 1], S44, 2240044497); /* 56 */\r
-  II ( a, b, c, d, in[ 8], S41, 1873313359); /* 57 */\r
-  II ( d, a, b, c, in[15], S42, 4264355552); /* 58 */\r
-  II ( c, d, a, b, in[ 6], S43, 2734768916); /* 59 */\r
-  II ( b, c, d, a, in[13], S44, 1309151649); /* 60 */\r
-  II ( a, b, c, d, in[ 4], S41, 4149444226); /* 61 */\r
-  II ( d, a, b, c, in[11], S42, 3174756917); /* 62 */\r
-  II ( c, d, a, b, in[ 2], S43,  718787259); /* 63 */\r
-  II ( b, c, d, a, in[ 9], S44, 3951481745); /* 64 */\r
-\r
-  buf[0] += a;\r
-  buf[1] += b;\r
-  buf[2] += c;\r
-  buf[3] += d;\r
-}\r
-\r
-/*\r
- **********************************************************************\r
- ** End of md5.c                                                     **\r
- ******************************* (cut) ********************************\r
- */\r
diff --git a/OPJ_Validate/md5.h b/OPJ_Validate/md5.h
deleted file mode 100644 (file)
index 6fb35cf..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-/*\r
- **********************************************************************\r
- ** md5.h -- Header file for implementation of MD5                   **\r
- ** RSA Data Security, Inc. MD5 Message Digest Algorithm             **\r
- ** Created: 2/17/90 RLR                                             **\r
- ** Revised: 12/27/90 SRD,AJ,BSK,JT Reference C version              **\r
- ** Revised (for MD5): RLR 4/27/91                                   **\r
- **   -- G modified to have y&~z instead of y&z                      **\r
- **   -- FF, GG, HH modified to add in last register done            **\r
- **   -- Access pattern: round 2 works mod 5, round 3 works mod 3    **\r
- **   -- distinct additive constant for each step                    **\r
- **   -- round 4 added, working mod 7                                **\r
- **********************************************************************\r
- */\r
-\r
-/*\r
- **********************************************************************\r
- ** Copyright (C) 1990, RSA Data Security, Inc. All rights reserved. **\r
- **                                                                  **\r
- ** License to copy and use this software is granted provided that   **\r
- ** it is identified as the "RSA Data Security, Inc. MD5 Message     **\r
- ** Digest Algorithm" in all material mentioning or referencing this **\r
- ** software or this function.                                       **\r
- **                                                                  **\r
- ** License is also granted to make and use derivative works         **\r
- ** provided that such works are identified as "derived from the RSA **\r
- ** Data Security, Inc. MD5 Message Digest Algorithm" in all         **\r
- ** material mentioning or referencing the derived work.             **\r
- **                                                                  **\r
- ** RSA Data Security, Inc. makes no representations concerning      **\r
- ** either the merchantability of this software or the suitability   **\r
- ** of this software for any particular purpose.  It is provided "as **\r
- ** is" without express or implied warranty of any kind.             **\r
- **                                                                  **\r
- ** These notices must be retained in any copies of any part of this **\r
- ** documentation and/or software.                                   **\r
- **********************************************************************\r
- */\r
-\r
-/* typedef a 32 bit type */\r
-typedef unsigned long int UINT4;\r
-\r
-/* Data structure for MD5 (Message Digest) computation */\r
-typedef struct {\r
-  UINT4 i[2];                   /* number of _bits_ handled mod 2^64 */\r
-  UINT4 buf[4];                                    /* scratch buffer */\r
-  unsigned char in[64];                              /* input buffer */\r
-  unsigned char digest[16];     /* actual digest after MD5Final call */\r
-} MD5_CTX;\r
-\r
-void MD5Init ();\r
-void MD5Update ();\r
-void MD5Final ();\r
-\r
-/*\r
- **********************************************************************\r
- ** End of md5.h                                                     **\r
- ******************************* (cut) ********************************\r
- */\r
diff --git a/OPJ_Validate/original/README.txt b/OPJ_Validate/original/README.txt
deleted file mode 100644 (file)
index d78d1bd..0000000
+++ /dev/null
@@ -1 +0,0 @@
-Download the source images into this directory from http://www.openjpeg.org/OPJ_Validate_OriginalImages.7z
diff --git a/applications/JavaOpenJPEG/CMakeLists.txt b/applications/JavaOpenJPEG/CMakeLists.txt
new file mode 100644 (file)
index 0000000..6b1720b
--- /dev/null
@@ -0,0 +1,40 @@
+#JavaOpenJPEG/CMakeLists.txt
+
+# First thing define the common source:
+SET(common_SRCS
+  ../codec/convert.c
+  ../codec/index.c
+  )
+
+# If not getopt was found then add it to the lib:
+IF(DONT_HAVE_GETOPT)
+  SET(common_SRCS
+    ${common_SRCS}
+    ../common/getopt.c
+  )
+ENDIF(DONT_HAVE_GETOPT)
+
+
+# Headers file are located here:
+INCLUDE_DIRECTORIES(
+  ${OPENJPEG_SOURCE_DIR}/libopenjpeg
+  ${LCMS_INCLUDE_DIR}
+  ${PNG_INCLUDE_DIR}
+  ${ZLIB_INCLUDE_DIR}
+  ${TIFF_INCLUDE_DIR}
+  )
+
+# Loop over all executables:
+FOREACH(exe j2k_to_image image_to_j2k)
+  ADD_EXECUTABLE(${exe} ${exe}.c ${common_SRCS})
+  TARGET_LINK_LIBRARIES(${exe} ${OPJ_PREFIX}openjpeg ${TIFF_LIBRARIES}
+       ${PNG_LIBRARIES} ${ZLIB_LIBRARY} ${LCMS_LIB})
+  # On unix you need to link to the math library:
+  IF(UNIX)
+    TARGET_LINK_LIBRARIES(${exe} -lm)
+  ENDIF(UNIX)
+  # Install exe
+  INSTALL_TARGETS(/bin/ ${exe})
+ENDFOREACH(exe)
+
+
diff --git a/applications/JavaOpenJPEG/JavaOpenJPEG.c b/applications/JavaOpenJPEG/JavaOpenJPEG.c
new file mode 100644 (file)
index 0000000..b1f0302
--- /dev/null
@@ -0,0 +1,1976 @@
+/*\r
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
+ * Copyright (c) 2002-2007, Professor Benoit Macq\r
+ * Copyright (c) 2001-2003, David Janssens\r
+ * Copyright (c) 2002-2003, Yannick Verschueren\r
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe\r
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team \r
+ * Copyright (c) 2006-2007, Parvatha Elangovan\r
+ * Copyright (c) 2007, Patrick Piscaglia (Telemis)\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <stdlib.h>\r
+#include <jni.h>\r
+#include <math.h>\r
+\r
+#include "openjpeg.h"\r
+#include "getopt.h"\r
+#include "convert.h"\r
+#include "index.h"\r
+#include "dirent.h"\r
+#include "org_openJpeg_OpenJPEGJavaEncoder.h"\r
+\r
+#ifndef _WIN32\r
+#define stricmp strcasecmp\r
+#define strnicmp strncasecmp\r
+#endif\r
+\r
+#include "format_defs.h"\r
+\r
+#define CINEMA_24_CS 1302083   /*Codestream length for 24fps*/\r
+#define CINEMA_48_CS 651041            /*Codestream length for 48fps*/\r
+#define COMP_24_CS 1041666             /*Maximum size per color component for 2K & 4K @ 24fps*/\r
+#define COMP_48_CS 520833              /*Maximum size per color component for 2K @ 48fps*/\r
+\r
+extern int get_file_format(char *filename);\r
+extern void error_callback(const char *msg, void *client_data);\r
+extern warning_callback(const char *msg, void *client_data);\r
+extern void info_callback(const char *msg, void *client_data);\r
+\r
+typedef struct callback_variables {\r
+       JNIEnv *env;\r
+       /** 'jclass' object used to call a Java method from the C */\r
+       jobject *jobj;\r
+       /** 'jclass' object used to call a Java method from the C */\r
+       jmethodID message_mid;\r
+       jmethodID error_mid;\r
+} callback_variables_t;\r
+\r
+typedef struct dircnt{\r
+       /** Buffer for holding images read from Directory*/\r
+       char *filename_buf;\r
+       /** Pointer to the buffer*/\r
+       char **filename;\r
+}dircnt_t;\r
+\r
+typedef struct img_folder{\r
+       /** The directory path of the folder containing input images*/\r
+       char *imgdirpath;\r
+       /** Output format*/\r
+       char *out_format;\r
+       /** Enable option*/\r
+       char set_imgdir;\r
+       /** Enable Cod Format for output*/\r
+       char set_out_format;\r
+       /** User specified rate stored in case of cinema option*/\r
+       float *rates;\r
+}img_fol_t;\r
+\r
+void encode_help_display() {\r
+       fprintf(stdout,"HELP\n----\n\n");\r
+       fprintf(stdout,"- the -h option displays this help information on screen\n\n");\r
+\r
+/* UniPG>> */\r
+       fprintf(stdout,"List of parameters for the JPEG 2000 "\r
+#ifdef USE_JPWL\r
+               "+ JPWL "\r
+#endif /* USE_JPWL */\r
+               "encoder:\n");\r
+/* <<UniPG */\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"REMARKS:\n");\r
+       fprintf(stdout,"---------\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"The markers written to the main_header are : SOC SIZ COD QCD COM.\n");\r
+       fprintf(stdout,"COD and QCD never appear in the tile_header.\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"- This coder can encode a mega image, a test was made on a 24000x24000 pixels \n");\r
+       fprintf(stdout,"color image.  You need enough disk space memory (twice the original) to encode \n");\r
+       fprintf(stdout,"the image,i.e. for a 1.5 GB image you need a minimum of 3GB of disk memory)\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"By default:\n");\r
+       fprintf(stdout,"------------\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout," * Lossless\n");\r
+       fprintf(stdout," * 1 tile\n");\r
+       fprintf(stdout," * Size of precinct : 2^15 x 2^15 (means 1 precinct)\n");\r
+       fprintf(stdout," * Size of code-block : 64 x 64\n");\r
+       fprintf(stdout," * Number of resolutions: 6\n");\r
+       fprintf(stdout," * No SOP marker in the codestream\n");\r
+       fprintf(stdout," * No EPH marker in the codestream\n");\r
+       fprintf(stdout," * No sub-sampling in x or y direction\n");\r
+       fprintf(stdout," * No mode switch activated\n");\r
+       fprintf(stdout," * Progression order: LRCP\n");\r
+       fprintf(stdout," * No index file\n");\r
+       fprintf(stdout," * No ROI upshifted\n");\r
+       fprintf(stdout," * No offset of the origin of the image\n");\r
+       fprintf(stdout," * No offset of the origin of the tiles\n");\r
+       fprintf(stdout," * Reversible DWT 5-3\n");\r
+/* UniPG>> */\r
+#ifdef USE_JPWL\r
+       fprintf(stdout," * No JPWL protection\n");\r
+#endif /* USE_JPWL */\r
+/* <<UniPG */\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"Parameters:\n");\r
+       fprintf(stdout,"------------\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"Required Parameters (except with -h):\n");\r
+       fprintf(stdout,"One of the two options -ImgDir or -i must be used\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-ImgDir      : Image file Directory path (example ../Images) \n");\r
+       fprintf(stdout,"    When using this option -OutFor must be used\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-OutFor \n");\r
+       fprintf(stdout,"    REQUIRED only if -ImgDir is used\n");\r
+       fprintf(stdout,"          Need to specify only format without filename <BMP>  \n");\r
+       fprintf(stdout,"    Currently accepts PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA formats\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-i           : source file  (-i source.pnm also *.pgm, *.ppm, *.bmp, *.tif, *.raw, *.tga) \n");\r
+       fprintf(stdout,"    When using this option -o must be used\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-o           : destination file (-o dest.j2k or .jp2) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"Optional Parameters:\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-h           : display the help information \n ");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-cinema2K    : Digital Cinema 2K profile compliant codestream for 2K resolution.(-cinema2k 24 or 48) \n");\r
+       fprintf(stdout,"          Need to specify the frames per second for a 2K resolution. Only 24 or 48 fps is allowed\n"); \r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-cinema4K    : Digital Cinema 4K profile compliant codestream for 4K resolution \n");\r
+       fprintf(stdout,"          Frames per second not required. Default value is 24fps\n"); \r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-r           : different compression ratios for successive layers (-r 20,10,5)\n ");\r
+       fprintf(stdout,"                 - The rate specified for each quality level is the desired \n");\r
+       fprintf(stdout,"                   compression factor.\n");\r
+       fprintf(stdout,"                   Example: -r 20,10,1 means quality 1: compress 20x, \n");\r
+       fprintf(stdout,"                     quality 2: compress 10x and quality 3: compress lossless\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"               (options -r and -q cannot be used together)\n ");\r
+       fprintf(stdout,"\n");\r
+\r
+       fprintf(stdout,"-q           : different psnr for successive layers (-q 30,40,50) \n ");\r
+\r
+       fprintf(stdout,"               (options -r and -q cannot be used together)\n ");\r
+\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-n           : number of resolutions (-n 3) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-b           : size of code block (-b 32,32) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-c           : size of precinct (-c 128,128) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-t           : size of tile (-t 512,512) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-p           : progression order (-p LRCP) [LRCP, RLCP, RPCL, PCRL, CPRL] \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-s           : subsampling factor (-s 2,2) [-s X,Y] \n");\r
+       fprintf(stdout,"             Remark: subsampling bigger than 2 can produce error\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-POC         : Progression order change (-POC T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL) \n");\r
+       fprintf(stdout,"      Example: T1=0,0,1,5,3,CPRL \n");\r
+       fprintf(stdout,"                         : Ttilenumber=Resolution num start,Component num start,Layer num end,Resolution num end,Component num end,Progression order\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-SOP         : write SOP marker before each packet \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-EPH         : write EPH marker after each header packet \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-M           : mode switch (-M 3) [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");\r
+       fprintf(stdout,"                 8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)] \n");\r
+       fprintf(stdout,"                 Indicate multiple modes by adding their values. \n");\r
+       fprintf(stdout,"                 ex: RESTART(4) + RESET(2) + SEGMARK(32) = -M 38\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-x           : create an index file *.Idx (-x index_name.Idx) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-ROI         : c=%%d,U=%%d : quantization indices upshifted \n");\r
+       fprintf(stdout,"               for component c=%%d [%%d = 0,1,2]\n");\r
+       fprintf(stdout,"               with a value of U=%%d [0 <= %%d <= 37] (i.e. -ROI c=0,U=25) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-d           : offset of the origin of the image (-d 150,300) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-T           : offset of the origin of the tiles (-T 100,75) \n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"-I           : use the irreversible DWT 9-7 (-I) \n");\r
+       fprintf(stdout,"\n");\r
+/* UniPG>> */\r
+#ifdef USE_JPWL\r
+       fprintf(stdout,"-W           : adoption of JPWL (Part 11) capabilities (-W params)\n");\r
+       fprintf(stdout,"               The parameters can be written and repeated in any order:\n");\r
+       fprintf(stdout,"               [h<tilepart><=type>,s<tilepart><=method>,a=<addr>,...\n");\r
+       fprintf(stdout,"                ...,z=<size>,g=<range>,p<tilepart:pack><=type>]\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"                 h selects the header error protection (EPB): 'type' can be\n");\r
+       fprintf(stdout,"                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");\r
+       fprintf(stdout,"                   if 'tilepart' is absent, it is for main and tile headers\n");\r
+       fprintf(stdout,"                   if 'tilepart' is present, it applies from that tile\n");\r
+       fprintf(stdout,"                     onwards, up to the next h<> spec, or to the last tilepart\n");\r
+       fprintf(stdout,"                     in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"                 p selects the packet error protection (EEP/UEP with EPBs)\n");\r
+       fprintf(stdout,"                  to be applied to raw data: 'type' can be\n");\r
+       fprintf(stdout,"                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");\r
+       fprintf(stdout,"                   if 'tilepart:pack' is absent, it is from tile 0, packet 0\n");\r
+       fprintf(stdout,"                   if 'tilepart:pack' is present, it applies from that tile\n");\r
+       fprintf(stdout,"                     and that packet onwards, up to the next packet spec\n");\r
+       fprintf(stdout,"                     or to the last packet in the last tilepart in the stream\n");\r
+       fprintf(stdout,"                     (max. %d specs)\n", JPWL_MAX_NO_PACKSPECS);\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"                 s enables sensitivity data insertion (ESD): 'method' can be\n");\r
+       fprintf(stdout,"                   [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR\n");\r
+       fprintf(stdout,"                    4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED]\n");\r
+       fprintf(stdout,"                   if 'tilepart' is absent, it is for main header only\n");\r
+       fprintf(stdout,"                   if 'tilepart' is present, it applies from that tile\n");\r
+       fprintf(stdout,"                     onwards, up to the next s<> spec, or to the last tilepart\n");\r
+       fprintf(stdout,"                     in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"                 g determines the addressing mode: <range> can be\n");\r
+       fprintf(stdout,"                   [0=PACKET 1=BYTE RANGE 2=PACKET RANGE]\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"                 a determines the size of data addressing: <addr> can be\n");\r
+       fprintf(stdout,"                   2/4 bytes (small/large codestreams). If not set, auto-mode\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"                 z determines the size of sensitivity values: <size> can be\n");\r
+       fprintf(stdout,"                   1/2 bytes, for the transformed pseudo-floating point value\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"                 ex.:\n");\r
+       fprintf(stdout,"                   h,h0=64,h3=16,h5=32,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,\n");\r
+       fprintf(stdout,"                     s0=6,s3=-1,a=0,g=1,z=1\n");\r
+       fprintf(stdout,"                 means\n");\r
+       fprintf(stdout,"                   predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2,\n");\r
+       fprintf(stdout,"                   CRC-16 in TPH 3 and TPH 4, CRC-32 in remaining TPHs,\n");\r
+       fprintf(stdout,"                   UEP rs(78,32) for packets 0 to 23 of tile 0,\n");\r
+       fprintf(stdout,"                   UEP rs(56,32) for packs. 24 to the last of tilepart 0,\n");\r
+       fprintf(stdout,"                   UEP rs default for packets of tilepart 1,\n");\r
+       fprintf(stdout,"                   no UEP for packets 0 to 19 of tilepart 3,\n");\r
+       fprintf(stdout,"                   UEP CRC-32 for packs. 20 of tilepart 3 to last tilepart,\n");\r
+       fprintf(stdout,"                   relative sensitivity ESD for MH,\n");\r
+       fprintf(stdout,"                   TSE ESD from TPH 0 to TPH 2, byte range with automatic\n");\r
+       fprintf(stdout,"                   size of addresses and 1 byte for each sensitivity value\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"                 ex.:\n");\r
+       fprintf(stdout,"                       h,s,p\n");\r
+       fprintf(stdout,"                 means\n");\r
+       fprintf(stdout,"                   default protection to headers (MH and TPHs) as well as\n");\r
+       fprintf(stdout,"                   data packets, one ESD in MH\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"                 N.B.: use the following recommendations when specifying\n");\r
+       fprintf(stdout,"                       the JPWL parameters list\n");\r
+       fprintf(stdout,"                   - when you use UEP, always pair the 'p' option with 'h'\n");\r
+       fprintf(stdout,"                 \n");\r
+#endif /* USE_JPWL */\r
+/* <<UniPG */\r
+       fprintf(stdout,"IMPORTANT:\n");\r
+       fprintf(stdout,"-----------\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"The index file has the structure below:\n");\r
+       fprintf(stdout,"---------------------------------------\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"Image_height Image_width\n");\r
+       fprintf(stdout,"progression order\n");\r
+       fprintf(stdout,"Tiles_size_X Tiles_size_Y\n");\r
+       fprintf(stdout,"Tiles_nb_X Tiles_nb_Y\n");\r
+       fprintf(stdout,"Components_nb\n");\r
+       fprintf(stdout,"Layers_nb\n");\r
+       fprintf(stdout,"decomposition_levels\n");\r
+       fprintf(stdout,"[Precincts_size_X_res_Nr Precincts_size_Y_res_Nr]...\n");\r
+       fprintf(stdout,"   [Precincts_size_X_res_0 Precincts_size_Y_res_0]\n");\r
+       fprintf(stdout,"Main_header_start_position\n");\r
+       fprintf(stdout,"Main_header_end_position\n");\r
+       fprintf(stdout,"Codestream_size\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"INFO ON TILES\n");\r
+       fprintf(stdout,"tileno start_pos end_hd end_tile nbparts disto nbpix disto/nbpix\n");\r
+       fprintf(stdout,"Tile_0 start_pos end_Theader end_pos NumParts TotalDisto NumPix MaxMSE\n");\r
+       fprintf(stdout,"Tile_1   ''           ''        ''        ''       ''    ''      ''\n");\r
+       fprintf(stdout,"...\n");\r
+       fprintf(stdout,"Tile_Nt   ''           ''        ''        ''       ''    ''     ''\n");\r
+       fprintf(stdout,"...\n");\r
+       fprintf(stdout,"TILE 0 DETAILS\n");\r
+       fprintf(stdout,"part_nb tileno num_packs start_pos end_tph_pos end_pos\n");\r
+       fprintf(stdout,"...\n");\r
+       fprintf(stdout,"Progression_string\n");\r
+       fprintf(stdout,"pack_nb tileno layno resno compno precno start_pos end_ph_pos end_pos disto\n");\r
+       fprintf(stdout,"Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");\r
+       fprintf(stdout,"...\n");\r
+       fprintf(stdout,"Tpacket_Np ''   ''    ''   ''    ''       ''       ''     ''\n");\r
+\r
+       fprintf(stdout,"MaxDisto\n");\r
+\r
+       fprintf(stdout,"TotalDisto\n\n");\r
+}\r
+\r
+\r
+OPJ_PROG_ORDER give_progression(char progression[4]) {\r
+       if(strncmp(progression, "LRCP", 4) == 0) {\r
+               return LRCP;\r
+       }\r
+       if(strncmp(progression, "RLCP", 4) == 0) {\r
+               return RLCP;\r
+       }\r
+       if(strncmp(progression, "RPCL", 4) == 0) {\r
+               return RPCL;\r
+       }\r
+       if(strncmp(progression, "PCRL", 4) == 0) {\r
+               return PCRL;\r
+       }\r
+       if(strncmp(progression, "CPRL", 4) == 0) {\r
+               return CPRL;\r
+       }\r
+\r
+       return PROG_UNKNOWN;\r
+}\r
+\r
+\r
+/// <summary>\r
+/// Get logarithm of an integer and round downwards.\r
+/// </summary>\r
+int int_floorlog2(int a) {\r
+    int l;\r
+    for (l=0; a>1; l++) {\r
+        a>>=1;\r
+    }\r
+    return l;\r
+}\r
+\r
+static int initialise_4K_poc(opj_poc_t *POC, int numres){\r
+       POC[0].tile  = 1; \r
+       POC[0].resno0  = 0; \r
+       POC[0].compno0 = 0;\r
+       POC[0].layno1  = 1;\r
+       POC[0].resno1  = numres-1;\r
+       POC[0].compno1 = 3;\r
+       POC[0].prg1 = CPRL;\r
+       POC[1].tile  = 1;\r
+       POC[1].resno0  = numres-1; \r
+       POC[1].compno0 = 0;\r
+       POC[1].layno1  = 1;\r
+       POC[1].resno1  = numres;\r
+       POC[1].compno1 = 3;\r
+       POC[1].prg1 = CPRL;\r
+       return 2;\r
+}\r
+\r
+void cinema_parameters(opj_cparameters_t *parameters){\r
+       parameters->tile_size_on = false;\r
+       parameters->cp_tdx=1;\r
+       parameters->cp_tdy=1;\r
+       \r
+       /*Tile part*/\r
+       parameters->tp_flag = 'C';\r
+       parameters->tp_on = 1;\r
+\r
+       /*Tile and Image shall be at (0,0)*/\r
+       parameters->cp_tx0 = 0;\r
+       parameters->cp_ty0 = 0;\r
+       parameters->image_offset_x0 = 0;\r
+       parameters->image_offset_y0 = 0;\r
+\r
+       /*Codeblock size= 32*32*/\r
+       parameters->cblockw_init = 32;  \r
+       parameters->cblockh_init = 32;\r
+       parameters->csty |= 0x01;\r
+\r
+       /*The progression order shall be CPRL*/\r
+       parameters->prog_order = CPRL;\r
+\r
+       /* No ROI */\r
+       parameters->roi_compno = -1;\r
+\r
+       parameters->subsampling_dx = 1;         parameters->subsampling_dy = 1;\r
+\r
+       /* 9-7 transform */\r
+       parameters->irreversible = 1;\r
+\r
+}\r
+\r
+void cinema_setup_encoder(opj_cparameters_t *parameters,opj_image_t *image, img_fol_t *img_fol){\r
+       int i;\r
+       float temp_rate;\r
+       opj_poc_t *POC = NULL;\r
+\r
+       switch (parameters->cp_cinema){\r
+       case CINEMA2K_24:\r
+       case CINEMA2K_48:\r
+               if(parameters->numresolution > 6){\r
+                       parameters->numresolution = 6;\r
+               }\r
+               if (!((image->comps[0].w == 2048) | (image->comps[0].h == 1080))){\r
+                       fprintf(stdout,"Image coordinates %d x %d is not 2K compliant.\nJPEG Digital Cinema Profile-3"\r
+                               "(2K profile) compliance requires that at least one of coordinates match 2048 x 1080\n",\r
+                               image->comps[0].w,image->comps[0].h);\r
+                       parameters->cp_rsiz = STD_RSIZ;\r
+               }\r
+       break;\r
+       \r
+       case CINEMA4K_24:\r
+               if(parameters->numresolution < 1){\r
+                               parameters->numresolution = 1;\r
+                       }else if(parameters->numresolution > 7){\r
+                               parameters->numresolution = 7;\r
+                       }\r
+               if (!((image->comps[0].w == 4096) | (image->comps[0].h == 2160))){\r
+                       fprintf(stdout,"Image coordinates %d x %d is not 4K compliant.\nJPEG Digital Cinema Profile-4" \r
+                               "(4K profile) compliance requires that at least one of coordinates match 4096 x 2160\n",\r
+                               image->comps[0].w,image->comps[0].h);\r
+                       parameters->cp_rsiz = STD_RSIZ;\r
+               }\r
+               parameters->numpocs = initialise_4K_poc(parameters->POC,parameters->numresolution);\r
+               break;\r
+       }\r
+\r
+       switch (parameters->cp_cinema){\r
+               case CINEMA2K_24:\r
+               case CINEMA4K_24:\r
+                       for(i=0 ; i<parameters->tcp_numlayers ; i++){\r
+                               temp_rate = 0 ;\r
+                               if (img_fol->rates[i]== 0){\r
+                                       parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ \r
+                                       (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);\r
+                               }else{\r
+                                       temp_rate =((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ \r
+                                               (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy);\r
+                                       if (temp_rate > CINEMA_24_CS ){\r
+                                               parameters->tcp_rates[i]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ \r
+                                               (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);\r
+                                       }else{\r
+                                               parameters->tcp_rates[i]= img_fol->rates[i];\r
+                                       }\r
+                               }\r
+                       }\r
+                       parameters->max_comp_size = COMP_24_CS;\r
+                       break;\r
+               \r
+               case CINEMA2K_48:\r
+                       for(i=0 ; i<parameters->tcp_numlayers ; i++){\r
+                               temp_rate = 0 ;\r
+                               if (img_fol->rates[i]== 0){\r
+                                       parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ \r
+                                       (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);\r
+                               }else{\r
+                                       temp_rate =((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ \r
+                                               (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy);\r
+                                       if (temp_rate > CINEMA_48_CS ){\r
+                                               parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ \r
+                                               (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);\r
+                                       }else{\r
+                                               parameters->tcp_rates[i]= img_fol->rates[i];\r
+                                       }\r
+                               }\r
+                       }\r
+                       parameters->max_comp_size = COMP_48_CS;\r
+                       break;\r
+       }\r
+       parameters->cp_disto_alloc = 1;\r
+}\r
+\r
+\r
+/* ------------------------------------------------------------------------------------ */\r
+int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *parameters,\r
+                                                                                                       img_fol_t *img_fol, char *indexfilename) {\r
+       int i, j,totlen;\r
+       option_t long_option[]={\r
+               {"cinema2K",REQ_ARG, NULL ,'w'},\r
+               {"cinema4K",NO_ARG, NULL ,'y'},\r
+               {"ImgDir",REQ_ARG, NULL ,'z'},\r
+               {"TP",REQ_ARG, NULL ,'v'},\r
+               {"SOP",NO_ARG, NULL ,'S'},\r
+               {"EPH",NO_ARG, NULL ,'E'},\r
+               {"OutFor",REQ_ARG, NULL ,'O'},\r
+               {"POC",REQ_ARG, NULL ,'P'},\r
+               {"ROI",REQ_ARG, NULL ,'R'},\r
+       };\r
+\r
+       /* parse the command line */\r
+/* UniPG>> */\r
+       const char optlist[] = "i:o:hr:q:n:b:c:t:p:s:SEM:x:R:d:T:If:P:C:F:"\r
+#ifdef USE_JPWL\r
+               "W:"\r
+#endif /* USE_JPWL */\r
+               ;\r
+\r
+       /*printf("C: parse_cmdline_encoder:");\r
+       for (i=0; i<argc; i++) {\r
+               printf("[%s]",argv[i]);\r
+       }\r
+       printf("\n");*/\r
+\r
+       totlen=sizeof(long_option);\r
+       img_fol->set_out_format=0;\r
+       reset_options_reading();\r
+\r
+       while (1) {\r
+    int c = getopt_long(argc, argv, optlist,long_option,totlen);\r
+               if (c == -1)\r
+                       break;\r
+               switch (c) {\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'o':                       /* output file */\r
+                       {\r
+                               char *outfile = optarg;\r
+                               parameters->cod_format = get_file_format(outfile);\r
+                               switch(parameters->cod_format) {\r
+                                       case J2K_CFMT:\r
+                                       case JP2_CFMT:\r
+                                               break;\r
+                                       default:\r
+                                               fprintf(stderr, "Unknown output format image %s [only *.j2k, *.j2c or *.jp2]!! \n", outfile);\r
+                                               return 1;\r
+                               }\r
+                               strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+                       case 'O':                       /* output format */\r
+                               {\r
+                                       char outformat[50];\r
+                                       char *of = optarg;\r
+                                       sprintf(outformat,".%s",of);\r
+                                       img_fol->set_out_format = 1;\r
+                                       parameters->cod_format = get_file_format(outformat);\r
+                                       switch(parameters->cod_format) {\r
+                                               case J2K_CFMT:\r
+                                               case JP2_CFMT:\r
+                                                       img_fol->out_format = optarg;\r
+                                                       break;\r
+                                               default:\r
+                                                       fprintf(stderr, "Unknown output format image [only j2k, j2c, jp2]!! \n");\r
+                                                       return 1;\r
+                                       }\r
+                               }\r
+                               break;\r
+\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+\r
+                       case 'r':                       /* rates rates/distorsion */\r
+                       {\r
+                               char *s = optarg;\r
+                               while (sscanf(s, "%f", &parameters->tcp_rates[parameters->tcp_numlayers]) == 1) {\r
+                                       parameters->tcp_numlayers++;\r
+                                       while (*s && *s != ',') {\r
+                                               s++;\r
+                                       }\r
+                                       if (!*s)\r
+                                               break;\r
+                                       s++;\r
+                               }\r
+                               parameters->cp_disto_alloc = 1;\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'q':                       /* add fixed_quality */\r
+                       {\r
+                               char *s = optarg;\r
+                               while (sscanf(s, "%f", &parameters->tcp_distoratio[parameters->tcp_numlayers]) == 1) {\r
+                                       parameters->tcp_numlayers++;\r
+                                       while (*s && *s != ',') {\r
+                                               s++;\r
+                                       }\r
+                                       if (!*s)\r
+                                               break;\r
+                                       s++;\r
+                               }\r
+                               parameters->cp_fixed_quality = 1;\r
+                       }\r
+                       break;\r
+\r
+                               /* dda */\r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'f':                       /* mod fixed_quality (before : -q) */\r
+                       {\r
+                               int *row = NULL, *col = NULL;\r
+                               int numlayers = 0, numresolution = 0, matrix_width = 0;\r
+\r
+                               char *s = optarg;\r
+                               sscanf(s, "%d", &numlayers);\r
+                               s++;\r
+                               if (numlayers > 9)\r
+                                       s++;\r
+\r
+                               parameters->tcp_numlayers = numlayers;\r
+                               numresolution = parameters->numresolution;\r
+                               matrix_width = numresolution * 3;\r
+                               parameters->cp_matrice = (int *) malloc(numlayers * matrix_width * sizeof(int));\r
+                               s = s + 2;\r
+\r
+                               for (i = 0; i < numlayers; i++) {\r
+                                       row = &parameters->cp_matrice[i * matrix_width];\r
+                                       col = row;\r
+                                       parameters->tcp_rates[i] = 1;\r
+                                       sscanf(s, "%d,", &col[0]);\r
+                                       s += 2;\r
+                                       if (col[0] > 9)\r
+                                               s++;\r
+                                       col[1] = 0;\r
+                                       col[2] = 0;\r
+                                       for (j = 1; j < numresolution; j++) {\r
+                                               col += 3;\r
+                                               sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);\r
+                                               s += 6;\r
+                                               if (col[0] > 9)\r
+                                                       s++;\r
+                                               if (col[1] > 9)\r
+                                                       s++;\r
+                                               if (col[2] > 9)\r
+                                                       s++;\r
+                                       }\r
+                                       if (i < numlayers - 1)\r
+                                               s++;\r
+                               }\r
+                               parameters->cp_fixed_alloc = 1;\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 't':                       /* tiles */\r
+                       {\r
+                               sscanf(optarg, "%d,%d", &parameters->cp_tdx, &parameters->cp_tdy);\r
+                               parameters->tile_size_on = true;\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'n':                       /* resolution */\r
+                       {\r
+                               sscanf(optarg, "%d", &parameters->numresolution);\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+                       case 'c':                       /* precinct dimension */\r
+                       {\r
+                               char sep;\r
+                               int res_spec = 0;\r
+\r
+                               char *s = optarg;\r
+                               do {\r
+                                       sep = 0;\r
+                                       sscanf(s, "[%d,%d]%c", &parameters->prcw_init[res_spec],\r
+                                 &parameters->prch_init[res_spec], &sep);\r
+                                       parameters->csty |= 0x01;\r
+                                       res_spec++;\r
+                                       s = strpbrk(s, "]") + 2;\r
+                               }\r
+                               while (sep == ',');\r
+                               parameters->res_spec = res_spec;\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'b':                       /* code-block dimension */\r
+                       {\r
+                               int cblockw_init = 0, cblockh_init = 0;\r
+                               sscanf(optarg, "%d,%d", &cblockw_init, &cblockh_init);\r
+                               if (cblockw_init * cblockh_init > 4096 || cblockw_init > 1024\r
+                                       || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {\r
+                                       fprintf(stderr,\r
+                                               "!! Size of code_block error (option -b) !!\n\nRestriction :\n"\r
+            "    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");\r
+                                       return 1;\r
+                               }\r
+                               parameters->cblockw_init = cblockw_init;\r
+                               parameters->cblockh_init = cblockh_init;\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'x':                       /* creation of index file */\r
+                       {\r
+                               char *index = optarg;\r
+                               strncpy(indexfilename, index, OPJ_PATH_LEN);\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'p':                       /* progression order */\r
+                       {\r
+                               char progression[4];\r
+\r
+                               strncpy(progression, optarg, 4);\r
+                               parameters->prog_order = give_progression(progression);\r
+                               if (parameters->prog_order == -1) {\r
+                                       fprintf(stderr, "Unrecognized progression order "\r
+            "[LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");\r
+                                       return 1;\r
+                               }\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 's':                       /* subsampling factor */\r
+                       {\r
+                               if (sscanf(optarg, "%d,%d", &parameters->subsampling_dx,\r
+                                    &parameters->subsampling_dy) != 2) {\r
+                                       fprintf(stderr, "'-s' sub-sampling argument error !  [-s dx,dy]\n");\r
+                                       return 1;\r
+                               }\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'd':                       /* coordonnate of the reference grid */\r
+                       {\r
+                               if (sscanf(optarg, "%d,%d", &parameters->image_offset_x0,\r
+                                    &parameters->image_offset_y0) != 2) {\r
+                                       fprintf(stderr, "-d 'coordonnate of the reference grid' argument "\r
+            "error !! [-d x0,y0]\n");\r
+                                       return 1;\r
+                               }\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'h':                       /* display an help description */\r
+                               encode_help_display();\r
+                               return 1;\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'P':                       /* POC */\r
+                       {\r
+                               int numpocs = 0;                /* number of progression order change (POC) default 0 */\r
+                               opj_poc_t *POC = NULL;  /* POC : used in case of Progression order change */\r
+\r
+                               char *s = optarg;\r
+                               POC = parameters->POC;\r
+\r
+                               while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%4s", &POC[numpocs].tile,\r
+                                       &POC[numpocs].resno0, &POC[numpocs].compno0,\r
+                                       &POC[numpocs].layno1, &POC[numpocs].resno1,\r
+                                       &POC[numpocs].compno1, &POC[numpocs].progorder) == 7) {\r
+                                       POC[numpocs].prg1 = give_progression(POC[numpocs].progorder);\r
+                                       numpocs++;\r
+                                       while (*s && *s != '/') {\r
+                                               s++;\r
+                                       }\r
+                                       if (!*s) {\r
+                                               break;\r
+                                       }\r
+                                       s++;\r
+                               }\r
+                               parameters->numpocs = numpocs;\r
+                       }\r
+                       break;\r
+\r
+                               /* ------------------------------------------------------ */\r
+\r
+                       case 'S':                       /* SOP marker */\r
+                       {\r
+                               parameters->csty |= 0x02;\r
+                       }\r
+                       break;\r
+\r
+                               /* ------------------------------------------------------ */\r
+\r
+                       case 'E':                       /* EPH marker */\r
+                       {\r
+                               parameters->csty |= 0x04;\r
+                       }\r
+                       break;\r
+\r
+                               /* ------------------------------------------------------ */\r
+\r
+                       case 'M':                       /* Mode switch pas tous au point !! */\r
+                       {\r
+                               int value = 0;\r
+                               if (sscanf(optarg, "%d", &value) == 1) {\r
+                                       for (i = 0; i <= 5; i++) {\r
+                                               int cache = value & (1 << i);\r
+                                               if (cache)\r
+                                                       parameters->mode |= (1 << i);\r
+                                       }\r
+                               }\r
+                       }\r
+                       break;\r
+\r
+                               /* ------------------------------------------------------ */\r
+\r
+                       case 'R':                       /* ROI */\r
+                       {\r
+                               if (sscanf(optarg, "c=%d,U=%d", &parameters->roi_compno,\r
+                                           &parameters->roi_shift) != 2) {\r
+                                       fprintf(stderr, "ROI error !! [-ROI c='compno',U='shift']\n");\r
+                                       return 1;\r
+                               }\r
+                       }\r
+                       break;\r
+\r
+                               /* ------------------------------------------------------ */\r
+\r
+                       case 'T':                       /* Tile offset */\r
+                       {\r
+                               if (sscanf(optarg, "%d,%d", &parameters->cp_tx0, &parameters->cp_ty0) != 2) {\r
+                                       fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");\r
+                                       return 1;\r
+                               }\r
+                       }\r
+                       break;\r
+\r
+                               /* ------------------------------------------------------ */\r
+\r
+                       case 'C':                       /* add a comment */\r
+                       {\r
+                               parameters->cp_comment = (char*)malloc(strlen(optarg) + 1);\r
+                               if(parameters->cp_comment) {\r
+                                       strcpy(parameters->cp_comment, optarg);\r
+                               }\r
+                       }\r
+                       break;\r
+\r
+\r
+                               /* ------------------------------------------------------ */\r
+\r
+                       case 'I':                       /* reversible or not */\r
+                       {\r
+                               parameters->irreversible = 1;\r
+                       }\r
+                       break;\r
+\r
+                       /* ------------------------------------------------------ */\r
+                       \r
+                       case 'v':                       /* Tile part generation*/\r
+                       {\r
+                               parameters->tp_flag = optarg[0];\r
+                               parameters->tp_on = 1;\r
+                       }\r
+                       break;  \r
+\r
+                               /* ------------------------------------------------------ */\r
+                       \r
+                       case 'z':                       /* Image Directory path */\r
+                       {\r
+                               img_fol->imgdirpath = (char*)malloc(strlen(optarg) + 1);\r
+                               strcpy(img_fol->imgdirpath,optarg);\r
+                               img_fol->set_imgdir=1;\r
+                       }\r
+                       break;\r
+\r
+                               /* ------------------------------------------------------ */\r
+                       \r
+                       case 'w':                       /* Digital Cinema 2K profile compliance*/\r
+                       {\r
+                               int fps=0;\r
+                               sscanf(optarg,"%d",&fps);\r
+                               if(fps == 24){\r
+                                       parameters->cp_cinema = CINEMA2K_24;\r
+                               }else if(fps == 48 ){\r
+                                       parameters->cp_cinema = CINEMA2K_48;\r
+                               }else {\r
+                                       fprintf(stderr,"Incorrect value!! must be 24 or 48\n");\r
+                                       return 1;\r
+                               }\r
+                               fprintf(stdout,"CINEMA 2K compliant codestream\n");\r
+                               parameters->cp_rsiz = CINEMA2K;\r
+                               \r
+                       }\r
+                       break;\r
+                               \r
+                               /* ------------------------------------------------------ */\r
+                       \r
+                       case 'y':                       /* Digital Cinema 4K profile compliance*/\r
+                       {\r
+                               parameters->cp_cinema = CINEMA4K_24;\r
+                               fprintf(stdout,"CINEMA 4K compliant codestream\n");\r
+                               parameters->cp_rsiz = CINEMA4K;\r
+                       }\r
+                       break;\r
+                               \r
+                               /* ------------------------------------------------------ */\r
+\r
+/* UniPG>> */\r
+#ifdef USE_JPWL\r
+                               /* ------------------------------------------------------ */\r
+                       \r
+                       case 'W':                       /* JPWL capabilities switched on */\r
+                       {\r
+                               char *token = NULL;\r
+                               int hprot, pprot, sens, addr, size, range;\r
+\r
+                               /* we need to enable indexing */\r
+                               if (!indexfilename) {\r
+                                       strncpy(indexfilename, JPWL_PRIVATEINDEX_NAME, OPJ_PATH_LEN);\r
+                               }\r
+\r
+                               /* search for different protection methods */\r
+\r
+                               /* break the option in comma points and parse the result */\r
+                               token = strtok(optarg, ",");\r
+                               while(token != NULL) {\r
+\r
+                                       /* search header error protection method */\r
+                                       if (*token == 'h') {\r
+\r
+                                               static int tile = 0, tilespec = 0, lasttileno = 0;\r
+\r
+                                               hprot = 1; /* predefined method */\r
+\r
+                                               if(sscanf(token, "h=%d", &hprot) == 1) {\r
+                                                       /* Main header, specified */\r
+                                                       if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||\r
+                                                               ((hprot >= 37) && (hprot <= 128)))) {\r
+                                                               fprintf(stderr, "ERROR -> invalid main header protection method h = %d\n", hprot);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       parameters->jpwl_hprot_MH = hprot;\r
+\r
+                                               } else if(sscanf(token, "h%d=%d", &tile, &hprot) == 2) {\r
+                                                       /* Tile part header, specified */\r
+                                                       if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||\r
+                                                               ((hprot >= 37) && (hprot <= 128)))) {\r
+                                                               fprintf(stderr, "ERROR -> invalid tile part header protection method h = %d\n", hprot);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (tile < 0) {\r
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method t = %d\n", tile);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {\r
+                                                               parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;\r
+                                                               parameters->jpwl_hprot_TPH[tilespec++] = hprot;\r
+                                                       }\r
+\r
+                                               } else if(sscanf(token, "h%d", &tile) == 1) {\r
+                                                       /* Tile part header, unspecified */\r
+                                                       if (tile < 0) {\r
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method t = %d\n", tile);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {\r
+                                                               parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;\r
+                                                               parameters->jpwl_hprot_TPH[tilespec++] = hprot;\r
+                                                       }\r
+\r
+\r
+                                               } else if (!strcmp(token, "h")) {\r
+                                                       /* Main header, unspecified */\r
+                                                       parameters->jpwl_hprot_MH = hprot;\r
+\r
+                                               } else {\r
+                                                       fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);\r
+                                                       return 1;\r
+                                               };\r
+\r
+                                       }\r
+\r
+                                       /* search packet error protection method */\r
+                                       if (*token == 'p') {\r
+\r
+                                               static int pack = 0, tile = 0, packspec = 0, lastpackno = 0;\r
+\r
+                                               pprot = 1; /* predefined method */\r
+\r
+                                               if (sscanf(token, "p=%d", &pprot) == 1) {\r
+                                                       /* Method for all tiles and all packets */\r
+                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||\r
+                                                               ((pprot >= 37) && (pprot <= 128)))) {\r
+                                                               fprintf(stderr, "ERROR -> invalid default packet protection method p = %d\n", pprot);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       parameters->jpwl_pprot_tileno[0] = 0;\r
+                                                       parameters->jpwl_pprot_packno[0] = 0;\r
+                                                       parameters->jpwl_pprot[0] = pprot;\r
+\r
+                                               } else if (sscanf(token, "p%d=%d", &tile, &pprot) == 2) {\r
+                                                       /* method specified from that tile on */\r
+                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||\r
+                                                               ((pprot >= 37) && (pprot <= 128)))) {\r
+                                                               fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (tile < 0) {\r
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {\r
+                                                               parameters->jpwl_pprot_tileno[packspec] = tile;\r
+                                                               parameters->jpwl_pprot_packno[packspec] = 0;\r
+                                                               parameters->jpwl_pprot[packspec++] = pprot;\r
+                                                       }\r
+\r
+                                               } else if (sscanf(token, "p%d:%d=%d", &tile, &pack, &pprot) == 3) {\r
+                                                       /* method fully specified from that tile and that packet on */\r
+                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||\r
+                                                               ((pprot >= 37) && (pprot <= 128)))) {\r
+                                                               fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (tile < 0) {\r
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (pack < 0) {\r
+                                                               fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n", pack);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {\r
+                                                               parameters->jpwl_pprot_tileno[packspec] = tile;\r
+                                                               parameters->jpwl_pprot_packno[packspec] = pack;\r
+                                                               parameters->jpwl_pprot[packspec++] = pprot;\r
+                                                       }\r
+\r
+                                               } else if (sscanf(token, "p%d:%d", &tile, &pack) == 2) {\r
+                                                       /* default method from that tile and that packet on */\r
+                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||\r
+                                                               ((pprot >= 37) && (pprot <= 128)))) {\r
+                                                               fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (tile < 0) {\r
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (pack < 0) {\r
+                                                               fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n", pack);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {\r
+                                                               parameters->jpwl_pprot_tileno[packspec] = tile;\r
+                                                               parameters->jpwl_pprot_packno[packspec] = pack;\r
+                                                               parameters->jpwl_pprot[packspec++] = pprot;\r
+                                                       }\r
+\r
+                                               } else if (sscanf(token, "p%d", &tile) == 1) {\r
+                                                       /* default from a tile on */\r
+                                                       if (tile < 0) {\r
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {\r
+                                                               parameters->jpwl_pprot_tileno[packspec] = tile;\r
+                                                               parameters->jpwl_pprot_packno[packspec] = 0;\r
+                                                               parameters->jpwl_pprot[packspec++] = pprot;\r
+                                                       }\r
+\r
+\r
+                                               } else if (!strcmp(token, "p")) {\r
+                                                       /* all default */\r
+                                                       parameters->jpwl_pprot_tileno[0] = 0;\r
+                                                       parameters->jpwl_pprot_packno[0] = 0;\r
+                                                       parameters->jpwl_pprot[0] = pprot;\r
+\r
+                                               } else {\r
+                                                       fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);\r
+                                                       return 1;\r
+                                               };\r
+\r
+                                       }\r
+\r
+                                       /* search sensitivity method */\r
+                                       if (*token == 's') {\r
+\r
+                                               static int tile = 0, tilespec = 0, lasttileno = 0;\r
+\r
+                                               sens = 0; /* predefined: relative error */\r
+\r
+                                               if(sscanf(token, "s=%d", &sens) == 1) {\r
+                                                       /* Main header, specified */\r
+                                                       if ((sens < -1) || (sens > 7)) {\r
+                                                               fprintf(stderr, "ERROR -> invalid main header sensitivity method s = %d\n", sens);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       parameters->jpwl_sens_MH = sens;\r
+\r
+                                               } else if(sscanf(token, "s%d=%d", &tile, &sens) == 2) {\r
+                                                       /* Tile part header, specified */\r
+                                                       if ((sens < -1) || (sens > 7)) {\r
+                                                               fprintf(stderr, "ERROR -> invalid tile part header sensitivity method s = %d\n", sens);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (tile < 0) {\r
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {\r
+                                                               parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;\r
+                                                               parameters->jpwl_sens_TPH[tilespec++] = sens;\r
+                                                       }\r
+\r
+                                               } else if(sscanf(token, "s%d", &tile) == 1) {\r
+                                                       /* Tile part header, unspecified */\r
+                                                       if (tile < 0) {\r
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {\r
+                                                               parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;\r
+                                                               parameters->jpwl_sens_TPH[tilespec++] = hprot;\r
+                                                       }\r
+\r
+                                               } else if (!strcmp(token, "s")) {\r
+                                                       /* Main header, unspecified */\r
+                                                       parameters->jpwl_sens_MH = sens;\r
+\r
+                                               } else {\r
+                                                       fprintf(stderr, "ERROR -> invalid sensitivity method selection = %s\n", token);\r
+                                                       return 1;\r
+                                               };\r
+                                               \r
+                                               parameters->jpwl_sens_size = 2; /* 2 bytes for default size */\r
+                                       }\r
+\r
+                                       /* search addressing size */\r
+                                       if (*token == 'a') {\r
+\r
+                                               static int tile = 0, tilespec = 0, lasttileno = 0;\r
+\r
+                                               addr = 0; /* predefined: auto */\r
+\r
+                                               if(sscanf(token, "a=%d", &addr) == 1) {\r
+                                                       /* Specified */\r
+                                                       if ((addr != 0) && (addr != 2) && (addr != 4)) {\r
+                                                               fprintf(stderr, "ERROR -> invalid addressing size a = %d\n", addr);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       parameters->jpwl_sens_addr = addr;\r
+\r
+                                               } else if (!strcmp(token, "a")) {\r
+                                                       /* default */\r
+                                                       parameters->jpwl_sens_addr = addr; /* auto for default size */\r
+\r
+                                               } else {\r
+                                                       fprintf(stderr, "ERROR -> invalid addressing selection = %s\n", token);\r
+                                                       return 1;\r
+                                               };\r
+                                               \r
+                                       }\r
+\r
+                                       /* search sensitivity size */\r
+                                       if (*token == 'z') {\r
+\r
+                                               static int tile = 0, tilespec = 0, lasttileno = 0;\r
+\r
+                                               size = 1; /* predefined: 1 byte */\r
+\r
+                                               if(sscanf(token, "z=%d", &size) == 1) {\r
+                                                       /* Specified */\r
+                                                       if ((size != 0) && (size != 1) && (size != 2)) {\r
+                                                               fprintf(stderr, "ERROR -> invalid sensitivity size z = %d\n", size);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       parameters->jpwl_sens_size = size;\r
+\r
+                                               } else if (!strcmp(token, "a")) {\r
+                                                       /* default */\r
+                                                       parameters->jpwl_sens_size = size; /* 1 for default size */\r
+\r
+                                               } else {\r
+                                                       fprintf(stderr, "ERROR -> invalid size selection = %s\n", token);\r
+                                                       return 1;\r
+                                               };\r
+                                               \r
+                                       }\r
+\r
+                                       /* search range method */\r
+                                       if (*token == 'g') {\r
+\r
+                                               static int tile = 0, tilespec = 0, lasttileno = 0;\r
+\r
+                                               range = 0; /* predefined: 0 (packet) */\r
+\r
+                                               if(sscanf(token, "g=%d", &range) == 1) {\r
+                                                       /* Specified */\r
+                                                       if ((range < 0) || (range > 3)) {\r
+                                                               fprintf(stderr, "ERROR -> invalid sensitivity range method g = %d\n", range);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       parameters->jpwl_sens_range = range;\r
+\r
+                                               } else if (!strcmp(token, "g")) {\r
+                                                       /* default */\r
+                                                       parameters->jpwl_sens_range = range;\r
+\r
+                                               } else {\r
+                                                       fprintf(stderr, "ERROR -> invalid range selection = %s\n", token);\r
+                                                       return 1;\r
+                                               };\r
+                                               \r
+                                       }\r
+\r
+                                       /* next token or bust */\r
+                                       token = strtok(NULL, ",");\r
+                               };\r
+\r
+\r
+                               /* some info */\r
+                               fprintf(stdout, "Info: JPWL capabilities enabled\n");\r
+                               parameters->jpwl_epc_on = true;\r
+\r
+                       }\r
+                       break;\r
+#endif /* USE_JPWL */\r
+/* <<UniPG */\r
+\r
+                               /* ------------------------------------------------------ */\r
+\r
+                       default:\r
+                               fprintf(stderr, "ERROR -> Command line not valid\n");\r
+                               return 1;\r
+               }\r
+       }\r
+\r
+       /* check for possible errors */\r
+       if (parameters->cp_cinema){\r
+               if(parameters->tcp_numlayers > 1){\r
+                       parameters->cp_rsiz = STD_RSIZ;\r
+       fprintf(stdout,"Warning: DC profiles do not allow more than one quality layer. The codestream created will not be compliant with the DC profile\n");\r
+               }\r
+       }\r
+\r
+       if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc || parameters->cp_fixed_quality)\r
+               && (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_alloc ^ parameters->cp_fixed_quality))) {\r
+               fprintf(stderr, "Error: options -r -q and -f cannot be used together !!\n");\r
+               return 1;\r
+       }                               /* mod fixed_quality */\r
+\r
+       /* if no rate entered, lossless by default */\r
+       if (parameters->tcp_numlayers == 0) {\r
+               parameters->tcp_rates[0] = 0;   /* MOD antonin : losslessbug */\r
+               parameters->tcp_numlayers++;\r
+               parameters->cp_disto_alloc = 1;\r
+       }\r
+\r
+       if((parameters->cp_tx0 > parameters->image_offset_x0) || (parameters->cp_ty0 > parameters->image_offset_y0)) {\r
+               fprintf(stderr,\r
+                       "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",\r
+                       parameters->cp_tx0, parameters->image_offset_x0, parameters->cp_ty0, parameters->image_offset_y0);\r
+               return 1;\r
+       }\r
+\r
+       for (i = 0; i < parameters->numpocs; i++) {\r
+               if (parameters->POC[i].prg == -1) {\r
+                       fprintf(stderr,\r
+                               "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",\r
+                               i + 1);\r
+               }\r
+       }\r
+\r
+       return 0;\r
+}\r
+\r
+\r
+/** Create the same index as j2k_create_index does, but in an int[] instead of in a file ==> easy to pass it back to Java, to transfer it etc.\r
+  @param buffer_size, increased by the length of the compressed index, in number of bytes\r
+  @return a pointer to a char[]\r
+  Syntax of the index:\r
+       one char for the version number (1): one byte because no problem with little endian, big endian etc.\r
+       one int for each of the following informations:\r
+                       Image Width     \r
+                       Image Height    \r
+                       progression order       \r
+                       Tile width      \r
+                       Tile height     \r
+                       Nb tiles in X   \r
+                       Nb tiles in Y   \r
+                       Nb of components        \r
+                       Nb of layers    \r
+                       Nb of resolutions       \r
+\r
+                       for each resolution:    \r
+                               Precinct width\r
+                               Precinct height\r
+\r
+                       End main header position        \r
+                       codestream size \r
+\r
+                       For each tile:  \r
+                               tile number\r
+                               tile start pos in codestream\r
+                               tile header end position\r
+                               tile end position in codestream\r
+\r
+                       For each LRCP, RLCP etc.:       \r
+                               packet number\r
+                               tile number\r
+                               layer number\r
+                               resolution number\r
+                               component number\r
+                               precinct number\r
+                               start position in the codestream\r
+                               end position of this packet\r
+  */\r
+char* create_index_into_byte_array(opj_codestream_info_t *cstr_info, int* buffer_size) {\r
+       int tileno, compno, layno, resno, precno, pack_nb, x, y;\r
+       char* buffer = NULL;\r
+       int buffer_pos = 0;\r
+       int prec_max = 0;\r
+       \r
+       prec_max = 0;\r
+       for (tileno = 0; tileno < cstr_info->tw * cstr_info->th; tileno++) {\r
+               for (resno = 0; resno < cstr_info->numdecompos[0] + 1; resno++) {\r
+                       prec_max = max(prec_max,cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno]);\r
+               }\r
+       }\r
+\r
+       // Compute the size of the index buffer, in number of bytes*/\r
+       *buffer_size = \r
+                 1 /* version */\r
+               + (10 /* image_w until decomposition */\r
+               + (cstr_info->numdecompos[0]+1) * 2 /* pdx size for each tile */\r
+               + 2 /* main_head_end + codestream_size */\r
+               + cstr_info->tw * cstr_info->th * 4 /* tile info, without distorsion info */\r
+               + cstr_info->tw*cstr_info->th * cstr_info->numlayers * (cstr_info->numdecompos[0] + 1) * cstr_info->numcomps * prec_max *8\r
+                 ) * sizeof(int);\r
+       //printf("C: index buffer size = %d bytes\n", *buffer_size);\r
+       buffer = (char*) malloc(*buffer_size);\r
+\r
+       if (!buffer) {\r
+               //opj_event_msg(j2k->cinfo, EVT_ERROR, "failed to allocate index buffer for writing %d int\n", *buffer_size);\r
+               fprintf(stderr, "failed to allocate index buffer for writing %d int\n", *buffer_size);\r
+               return 0;\r
+       }\r
+       \r
+       buffer[0] = 1;  // Version stored on a byte\r
+       buffer++;\r
+       // Remaining informations are stored on a int.\r
+       ((int*)buffer)[buffer_pos++] = cstr_info->image_w;\r
+       ((int*)buffer)[buffer_pos++] = cstr_info->image_h;\r
+       ((int*)buffer)[buffer_pos++] = cstr_info->prog;\r
+       ((int*)buffer)[buffer_pos++] = cstr_info->tile_x;\r
+       ((int*)buffer)[buffer_pos++] = cstr_info->tile_y;\r
+       ((int*)buffer)[buffer_pos++] = cstr_info->tw;\r
+       ((int*)buffer)[buffer_pos++] = cstr_info->th;\r
+       ((int*)buffer)[buffer_pos++] = cstr_info->numcomps;\r
+       ((int*)buffer)[buffer_pos++] = cstr_info->numlayers;\r
+       ((int*)buffer)[buffer_pos++] = cstr_info->numdecompos[0];\r
+       \r
+       for (resno = cstr_info->numdecompos[0]; resno >= 0; resno--) {\r
+                       /* based on tile 0 */\r
+               ((int*)buffer)[buffer_pos++] = (1 << cstr_info->tile[0].pdx[resno]);\r
+               ((int*)buffer)[buffer_pos++] = (1 << cstr_info->tile[0].pdx[resno]);\r
+       }\r
+       ((int*)buffer)[buffer_pos++] = cstr_info->main_head_end;\r
+       ((int*)buffer)[buffer_pos++] = cstr_info->codestream_size;\r
+       \r
+       for (tileno = 0; tileno < cstr_info->tw * cstr_info->th; tileno++) {\r
+               ((int*)buffer)[buffer_pos++] = cstr_info->tile[tileno].tileno;\r
+               ((int*)buffer)[buffer_pos++] = cstr_info->tile[tileno].start_pos;\r
+               ((int*)buffer)[buffer_pos++] = cstr_info->tile[tileno].end_header;\r
+               ((int*)buffer)[buffer_pos++] = cstr_info->tile[tileno].end_pos;\r
+       }\r
+       \r
+       for (tileno = 0; tileno < cstr_info->tw * cstr_info->th; tileno++) {\r
+               int start_pos, end_pos;\r
+               int max_numdecompos = 0;\r
+               pack_nb = 0;\r
+               \r
+               for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
+                       if (max_numdecompos < cstr_info->numdecompos[compno])\r
+                               max_numdecompos = cstr_info->numdecompos[compno];\r
+               }       \r
+\r
+               if (cstr_info->prog == LRCP) {  /* LRCP */\r
+\r
+                       for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
+                               for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
+                                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
+                                               int prec_max;\r
+                                               if (resno > cstr_info->numdecompos[compno])\r
+                                                       break;\r
+                                               prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
+                                               for (precno = 0; precno < prec_max; precno++) {\r
+                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                       ((int*)buffer)[buffer_pos++] = pack_nb;\r
+                                                       ((int*)buffer)[buffer_pos++] = tileno;\r
+                                                       ((int*)buffer)[buffer_pos++] = layno;\r
+                                                       ((int*)buffer)[buffer_pos++] = resno;\r
+                                                       ((int*)buffer)[buffer_pos++] = compno;\r
+                                                       ((int*)buffer)[buffer_pos++] = precno;\r
+                                                       ((int*)buffer)[buffer_pos++] = start_pos;\r
+                                                       ((int*)buffer)[buffer_pos++] = end_pos;\r
+                                                       pack_nb++;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               } /* LRCP */\r
+               else if (cstr_info->prog == RLCP) {     /* RLCP */\r
+\r
+                       for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
+                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
+                                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
+                                               int prec_max; \r
+                                               if (resno > cstr_info->numdecompos[compno])\r
+                                                       break;\r
+                                               prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
+                                               for (precno = 0; precno < prec_max; precno++) {\r
+                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                       ((int*)buffer)[buffer_pos++] = pack_nb;\r
+                                                       ((int*)buffer)[buffer_pos++] = tileno;\r
+                                                       ((int*)buffer)[buffer_pos++] = resno;\r
+                                                       ((int*)buffer)[buffer_pos++] = layno;\r
+                                                       ((int*)buffer)[buffer_pos++] = compno;\r
+                                                       ((int*)buffer)[buffer_pos++] = precno;\r
+                                                       ((int*)buffer)[buffer_pos++] = start_pos;\r
+                                                       ((int*)buffer)[buffer_pos++] = end_pos;\r
+                                                       pack_nb++;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               } /* RLCP */\r
+               else if (cstr_info->prog == RPCL) {     /* RPCL */\r
+\r
+                       for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
+                               /* I suppose components have same XRsiz, YRsiz */\r
+                               int x0 = cstr_info->tile_Ox + tileno - (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tw * cstr_info->tile_x;\r
+                               int y0 = cstr_info->tile_Ox + (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tile_y;\r
+                               int x1 = x0 + cstr_info->tile_x;\r
+                               int y1 = y0 + cstr_info->tile_y;\r
+                               for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
+                                       int prec_max; \r
+                                       if (resno > cstr_info->numdecompos[compno])\r
+                                               break;\r
+                                       prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
+                                       for (precno = 0; precno < prec_max; precno++) {\r
+                                               int pcnx = cstr_info->tile[tileno].pw[resno];\r
+                                               int pcx = (int) pow( 2, cstr_info->tile[tileno].pdx[resno] + cstr_info->numdecompos[compno] - resno );\r
+                                               int pcy = (int) pow( 2, cstr_info->tile[tileno].pdy[resno] + cstr_info->numdecompos[compno] - resno );\r
+                                               int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
+                                               int precno_y = (int) floor( (float)precno/(float)pcnx );\r
+                                               for(y = y0; y < y1; y++) {                                                      \r
+                                                       if (precno_y*pcy == y ) {\r
+                                                               for (x = x0; x < x1; x++) {                                                                     \r
+                                                                       if (precno_x*pcx == x ) {\r
+                                                                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
+                                                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = pack_nb;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = tileno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = resno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = precno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = compno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = layno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = start_pos;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = end_pos;\r
+                                                                                       pack_nb++; \r
+                                                                               }\r
+                                                                       }\r
+                                                               }/* x = x0..x1 */\r
+                                                       } \r
+                                               }  /* y = y0..y1 */\r
+                                       } /* precno */\r
+                               } /* compno */\r
+                       } /* resno */\r
+               } /* RPCL */\r
+               else if (cstr_info->prog == PCRL) {     /* PCRL */\r
+                       /* I suppose components have same XRsiz, YRsiz */\r
+                       int x0 = cstr_info->tile_Ox + tileno - (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tw * cstr_info->tile_x;\r
+                       int y0 = cstr_info->tile_Ox + (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tile_y;\r
+                       int x1 = x0 + cstr_info->tile_x;\r
+                       int y1 = y0 + cstr_info->tile_y;\r
+\r
+                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
+                               for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
+                                       int prec_max; \r
+                                       if (resno > cstr_info->numdecompos[compno])\r
+                                               break;\r
+                                       prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
+                                       for (precno = 0; precno < prec_max; precno++) {\r
+                                               int pcnx = cstr_info->tile[tileno].pw[resno];\r
+                                               int pcx = (int) pow( 2, cstr_info->tile[tileno].pdx[resno] + cstr_info->numdecompos[compno] - resno );\r
+                                               int pcy = (int) pow( 2, cstr_info->tile[tileno].pdy[resno] + cstr_info->numdecompos[compno] - resno );\r
+                                               int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
+                                               int precno_y = (int) floor( (float)precno/(float)pcnx );\r
+                                               for(y = y0; y < y1; y++) {                                                      \r
+                                                       if (precno_y*pcy == y ) {\r
+                                                               for (x = x0; x < x1; x++) {                                                                     \r
+                                                                       if (precno_x*pcx == x ) {\r
+                                                                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
+                                                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = pack_nb;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = tileno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = precno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = compno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = resno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = layno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = start_pos;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = end_pos;\r
+                                                                                       pack_nb++; \r
+                                                                               }\r
+                                                                       }\r
+                                                               }/* x = x0..x1 */\r
+                                                       } \r
+                                               }  /* y = y0..y1 */\r
+                                       } /* precno */\r
+                               } /* resno */\r
+                       } /* compno */\r
+               } /* PCRL */\r
+               else {  /* CPRL */\r
+\r
+                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
+                               /* I suppose components have same XRsiz, YRsiz */\r
+                               int x0 = cstr_info->tile_Ox + tileno - (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tw * cstr_info->tile_x;\r
+                               int y0 = cstr_info->tile_Ox + (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tile_y;\r
+                               int x1 = x0 + cstr_info->tile_x;\r
+                               int y1 = y0 + cstr_info->tile_y;\r
+                               \r
+                               for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
+                                       int prec_max; \r
+                                       if (resno > cstr_info->numdecompos[compno])\r
+                                               break;\r
+                                       prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
+                                       for (precno = 0; precno < prec_max; precno++) {\r
+                                               int pcnx = cstr_info->tile[tileno].pw[resno];\r
+                                               int pcx = (int) pow( 2, cstr_info->tile[tileno].pdx[resno] + cstr_info->numdecompos[compno] - resno );\r
+                                               int pcy = (int) pow( 2, cstr_info->tile[tileno].pdy[resno] + cstr_info->numdecompos[compno] - resno );\r
+                                               int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
+                                               int precno_y = (int) floor( (float)precno/(float)pcnx );\r
+                                               for(y = y0; y < y1; y++) {\r
+                                                       if (precno_y*pcy == y ) {\r
+                                                               for (x = x0; x < x1; x++) {\r
+                                                                       if (precno_x*pcx == x ) {\r
+                                                                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
+                                                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = pack_nb;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = tileno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = compno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = precno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = resno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = layno;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = start_pos;\r
+                                                                                       ((int*)buffer)[buffer_pos++] = end_pos;\r
+                                                                                       pack_nb++; \r
+                                                                               }\r
+                                                                       }\r
+                                                               }/* x = x0..x1 */\r
+                                                       }\r
+                                               } /* y = y0..y1 */\r
+                                       } /* precno */\r
+                               } /* resno */\r
+                       } /* compno */\r
+               } /* CPRL */   \r
+       } /* tileno */\r
+\r
+       if (buffer_pos > *buffer_size) {\r
+               //opj_event_msg(j2k->cinfo, EVT_ERROR, "index creation: buffer_pos (%d) > buffer_size (%d)!\n", buffer_pos, *buffer_size);\r
+               fprintf(stderr, "index creation: buffer_pos (%d) > buffer_size (%d)!\n", buffer_pos, *buffer_size);\r
+               return 0;\r
+       }\r
+\r
+       return --buffer;\r
+}\r
+\r
+\r
+\r
+\r
+/* -------------------------------------------------------------------------- \r
+   ------------ Get the image byte[] from the Java object -------------------*/\r
+\r
+opj_image_t* loadImage(opj_cparameters_t *parameters, JNIEnv *env, jobject obj, jclass cls) {\r
+       int i,max,shift,w,h,depth;\r
+       opj_image_t * img = NULL;\r
+       int compno, numcomps;\r
+       opj_image_t * image = NULL;\r
+       opj_image_comp_t *comp;\r
+       opj_image_cmptparm_t cmptparm[3];       /* maximum of 3 components */\r
+       OPJ_COLOR_SPACE color_space;\r
+       jfieldID        fid;\r
+       jint            ji;\r
+       jbyteArray      jba;\r
+       jshortArray jsa;\r
+       jintArray       jia;\r
+       int                     len;\r
+       jbyte           *jbBody;\r
+       jshort          *jsBody;\r
+       jint            *jiBody;\r
+       boolean         isCopy;\r
+\r
+       // Image width, height and depth\r
+       fid = (*env)->GetFieldID(env, cls,"width", "I");\r
+       ji = (*env)->GetIntField(env, obj, fid);\r
+       w = ji;\r
+\r
+       fid = (*env)->GetFieldID(env, cls,"height", "I");\r
+       ji = (*env)->GetIntField(env, obj, fid);\r
+       h = ji;\r
+       \r
+       fid = (*env)->GetFieldID(env, cls,"depth", "I");\r
+       ji = (*env)->GetIntField(env, obj, fid);\r
+       depth = ji;\r
+\r
+       // Read the image\r
+       if (depth <=16) {\r
+               numcomps = 1;\r
+               color_space = CLRSPC_GRAY;\r
+       } else {\r
+               numcomps = 3;\r
+               color_space = CLRSPC_SRGB;\r
+       }\r
+       memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));\r
+\r
+       if (numcomps == 1) {\r
+               cmptparm[0].x0 = parameters->image_offset_x0;\r
+               cmptparm[0].y0 = parameters->image_offset_y0;\r
+               cmptparm[0].w = !cmptparm[0].x0 ? (w - 1) * parameters->subsampling_dx + 1 : cmptparm[0].x0 + (w - 1) * parameters->subsampling_dx + 1;\r
+               cmptparm[0].h = !cmptparm[0].y0 ? (h - 1) * parameters->subsampling_dy + 1 : cmptparm[0].y0 + (h - 1) * parameters->subsampling_dy + 1;\r
+               // Java types are always signed but we use them as unsigned types (shift of the negative part of \r
+               // the pixels of the images in Telemis before entering the encoder).\r
+               cmptparm[0].sgnd = 0;\r
+               if (depth<=16) \r
+                       cmptparm[0].prec=depth;\r
+               else \r
+                       cmptparm[0].prec = 8;\r
+               cmptparm[0].bpp = cmptparm[0].prec;\r
+               cmptparm[0].dx = parameters->subsampling_dx;\r
+               cmptparm[0].dy = parameters->subsampling_dy;\r
+               /*printf("C: component 0 initialised: x0=%d, y0=%d, w=%d, h=%d, sgnd=%d, bpp=%d, dx=%d, dy=%d, color_space=%d\n", cmptparm[0].x0, cmptparm[0].y0, cmptparm[0].w,\r
+                                       cmptparm[0].h, cmptparm[0].sgnd, cmptparm[0].bpp, cmptparm[0].dx, cmptparm[0].dy, color_space);*/\r
+       } else {\r
+               for(i = 0; i < numcomps; i++) {\r
+                       cmptparm[i].prec = 8;\r
+                       cmptparm[i].bpp = 8;\r
+                       cmptparm[i].sgnd = 0;\r
+                       cmptparm[i].dx = parameters->subsampling_dx;\r
+                       cmptparm[i].dy = parameters->subsampling_dy;\r
+                       cmptparm[i].w = w;\r
+                       cmptparm[i].h = h;\r
+               }\r
+       }\r
+       \r
+       /* create the image */\r
+       image = opj_image_create(numcomps, &cmptparm[0], color_space);\r
+\r
+       if (!image)\r
+               return NULL;\r
+\r
+       if (depth <=16) {\r
+               image->numcomps=1;\r
+       } else {\r
+               image->numcomps = 3;\r
+       }\r
+\r
+       /* set image offset and reference grid */\r
+       image->x0 = cmptparm[0].x0;\r
+       image->y0 = cmptparm[0].x0;\r
+       image->x1 = cmptparm[0].w;\r
+       image->y1 = cmptparm[0].h;\r
+\r
+       /* set image data */\r
+       for (compno=0; compno<numcomps; compno++) {\r
+               comp = &image->comps[compno];\r
+               max = -100000;\r
+               if (depth == 8) {\r
+                       fid = (*env)->GetFieldID(env, cls,"image8", "[B");      // byteArray []\r
+                       jba = (*env)->GetObjectField(env, obj, fid);\r
+                       len = (*env)->GetArrayLength(env, jba);\r
+                       \r
+                       jbBody = (*env)->GetPrimitiveArrayCritical(env, jba, &isCopy);\r
+                       //printf("C: before transfering 8 bpp image\n");\r
+                       if (comp->sgnd) {\r
+                               for(i=0; i< len;i++) {\r
+                                       comp->data[i] = (char) jbBody[i];\r
+                                       if (comp->data[i] > max) max = comp->data[i];\r
+                               }\r
+                       } else {\r
+                               for(i=0; i< len;i++) {\r
+                                       comp->data[i] = (unsigned char) jbBody[i];\r
+                                       if (comp->data[i] > max) max = comp->data[i];\r
+                               }\r
+                       }\r
+                       (*env)->ReleasePrimitiveArrayCritical(env, jba, jbBody, 0);\r
+               } else if(depth == 16) {\r
+                       fid = (*env)->GetFieldID(env, cls,"image16", "[S");     // shortArray []\r
+                       jsa = (*env)->GetObjectField(env, obj, fid);\r
+                       len = (*env)->GetArrayLength(env, jsa);\r
+                       \r
+                       jsBody = (*env)->GetPrimitiveArrayCritical(env, jsa, &isCopy);\r
+                       //printf("C: before transfering 16 bpp image\n");\r
+                       if (comp->sgnd) {       // Special behaviour to deal with signed elements ??\r
+                               comp->data[i] = (short) jsBody[i];\r
+                               for(i=0; i< len;i++) {\r
+                                       if (comp->data[i] > max) max = comp->data[i];\r
+                               }\r
+                       } else {\r
+                               for(i=0; i< len;i++) {\r
+                                       comp->data[i] = (unsigned short) jsBody[i];\r
+                                       if (comp->data[i] > max) max = comp->data[i];\r
+                               }\r
+                       }\r
+                       (*env)->ReleasePrimitiveArrayCritical(env, jsa, jsBody, 0);\r
+               } else if (depth == 24) {\r
+                       fid = (*env)->GetFieldID(env, cls,"image24", "[I");     // intArray []\r
+                       jia = (*env)->GetObjectField(env, obj, fid);\r
+                       len = (*env)->GetArrayLength(env, jia);\r
+                       shift = compno*8;\r
+\r
+                       jiBody = (*env)->GetPrimitiveArrayCritical(env, jia, &isCopy);\r
+                       //printf("C: before transfering 24 bpp image (component %d, signed = %d)\n", compno, comp->sgnd);\r
+                       if (comp->sgnd) {       // Special behaviour to deal with signed elements ?? XXXXX\r
+                               for(i=0; i< len;i++) {\r
+                                       comp->data[i] = ( ((int) jiBody[i]) & (0xFF << shift) ) >> shift;\r
+                                       if (comp->data[i] > max) max = comp->data[i];\r
+                               }\r
+                       } else {\r
+                               for(i=0; i< len;i++) {\r
+                                       comp->data[i] = ( ((unsigned int) jiBody[i]) & (0xFF << shift) ) >> shift;\r
+                                       if (comp->data[i] > max) max = comp->data[i];\r
+                               }\r
+                       }\r
+                       (*env)->ReleasePrimitiveArrayCritical(env, jia, jiBody, 0);\r
+               }\r
+               comp->bpp = int_floorlog2(max)+1;\r
+               comp->prec = comp->bpp;\r
+               //printf("C: component %d: max  %d, real bpp = %d\n", compno, max, comp->bpp);\r
+       }\r
+       return image;\r
+}\r
+\r
+\r
+/* --------------------------------------------------------------------------\r
+   --------------------   MAIN METHOD, CALLED BY JAVA -----------------------*/\r
+JNIEXPORT jlong JNICALL Java_org_openJpeg_OpenJPEGJavaEncoder_internalEncodeImageToJ2K(JNIEnv *env, jobject obj, jobjectArray javaParameters) {\r
+       int argc;               /* To simulate the command line parameters (taken from the javaParameters variable) and be able to re-use the */\r
+       char **argv;    /*  'parse_cmdline_decoder' method taken from the j2k_to_image project */\r
+       bool bSuccess;\r
+       opj_cparameters_t parameters;   /* compression parameters */\r
+       img_fol_t img_fol;\r
+       opj_event_mgr_t event_mgr;              /* event manager */\r
+       opj_image_t *image = NULL;\r
+       int i,j,num_images;\r
+       int imageno;\r
+       opj_codestream_info_t cstr_info;                /* Codestream information structure */\r
+       char indexfilename[OPJ_PATH_LEN];       /* index file name */\r
+\r
+       int* compressed_index = NULL;\r
+       int compressed_index_size=-1;\r
+       // ==> Access variables to the Java member variables\r
+       jsize           arraySize;\r
+       jclass          cls;\r
+       jobject         object;\r
+       jboolean        isCopy;\r
+       jfieldID        fid;\r
+       jbyteArray      jba;\r
+       jbyte           *jbBody;\r
+       callback_variables_t msgErrorCallback_vars;\r
+       // <== access variable to the Java member variables.\r
+\r
+       // For the encoding and storage into the file\r
+       opj_cinfo_t* cinfo;\r
+       int codestream_length;\r
+       opj_cio_t *cio = NULL;\r
+       FILE *f = NULL;\r
+\r
+       // JNI reference to the calling class\r
+       cls = (*env)->GetObjectClass(env, obj);\r
+       \r
+       // Pointers to be able to call a Java method for all the info and error messages\r
+       msgErrorCallback_vars.env = env;\r
+       msgErrorCallback_vars.jobj = &obj;\r
+       msgErrorCallback_vars.message_mid = (*env)->GetMethodID(env, cls, "logMessage", "(Ljava/lang/String;)V");\r
+       msgErrorCallback_vars.error_mid = (*env)->GetMethodID(env, cls, "logError", "(Ljava/lang/String;)V");\r
+\r
+       arraySize = (*env)->GetArrayLength(env, javaParameters);\r
+       argc = (int) arraySize +1;\r
+       argv = malloc(argc*sizeof(char*));\r
+       argv[0] = "ProgramName.exe";    // The program name: useless\r
+       j=0;\r
+       for (i=1; i<argc; i++) {\r
+               object = (*env)->GetObjectArrayElement(env, javaParameters, i-1);\r
+               argv[i] = (*env)->GetStringUTFChars(env, object, &isCopy);\r
+       }\r
+\r
+       /*printf("C: ");\r
+       for (i=0; i<argc; i++) {\r
+               printf("[%s]",argv[i]);\r
+       }\r
+       printf("\n");*/\r
+\r
+       /*\r
+       configure the event callbacks\r
+       */\r
+       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));\r
+       event_mgr.error_handler = error_callback;\r
+       event_mgr.warning_handler = warning_callback;\r
+       event_mgr.info_handler = info_callback;\r
+\r
+       /* set encoding parameters to default values */\r
+       opj_set_default_encoder_parameters(&parameters);\r
+       parameters.cod_format = J2K_CFMT;\r
+       //parameters.index_on = 1;\r
+\r
+       /* Initialize indexfilename and img_fol */\r
+       *indexfilename = 0;\r
+       memset(&img_fol,0,sizeof(img_fol_t));\r
+\r
+       /* parse input and get user encoding parameters */\r
+       if (parse_cmdline_encoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {\r
+               // Release the Java arguments array\r
+               for (i=1; i<argc; i++)\r
+                       (*env)->ReleaseStringUTFChars(env, (*env)->GetObjectArrayElement(env, javaParameters, i-1), argv[i]);\r
+               return -1;\r
+       }\r
+\r
+       // Release the Java arguments array\r
+       for (i=1; i<argc; i++)\r
+               (*env)->ReleaseStringUTFChars(env, (*env)->GetObjectArrayElement(env, javaParameters, i-1), argv[i]);\r
+\r
+       if (parameters.cp_cinema){\r
+               cinema_parameters(&parameters);\r
+       }\r
+                               \r
+\r
+       /* Create comment for codestream */\r
+       if(parameters.cp_comment == NULL) {\r
+               const char comment[] = "Created by JavaOpenJPEG version ";\r
+               const size_t clen = strlen(comment);\r
+               const char *version = opj_version();\r
+/* UniPG>> */\r
+#ifdef USE_JPWL\r
+               parameters.cp_comment = (char*)malloc(clen+strlen(version)+11);\r
+               sprintf(parameters.cp_comment,"%s%s with JPWL", comment, version);\r
+#else\r
+               parameters.cp_comment = (char*)malloc(clen+strlen(version)+1);\r
+               sprintf(parameters.cp_comment,"%s%s", comment, version);\r
+#endif\r
+/* <<UniPG */\r
+\r
+       }\r
+\r
+       /* Read directory if necessary */\r
+       num_images=1;\r
+\r
+       /*Encoding image one by one*/\r
+       for(imageno=0;imageno<num_images;imageno++)\r
+       {\r
+               image = NULL;\r
+               fprintf(stderr,"\n");\r
+\r
+               image = loadImage(&parameters, env, obj, cls);\r
+               //printf("C: after load image: image = %d\n", image);\r
+               if (!image) {\r
+                       fprintf(stderr, "Unable to load image\n");\r
+                       return -1; \r
+               }\r
+\r
+               /* Decide if MCT should be used */\r
+               parameters.tcp_mct = image->numcomps == 3 ? 1 : 0;\r
+\r
+               if(parameters.cp_cinema){\r
+                       cinema_setup_encoder(&parameters,image,&img_fol);\r
+               }\r
+\r
+               /* encode the destination image */\r
+               /* ---------------------------- */\r
+               /* get a J2K compressor handle */\r
+               if (parameters.cod_format == J2K_CFMT) {        /* J2K format output */\r
+                       cinfo = opj_create_compress(CODEC_J2K);\r
+               } else {                                                                        /* JP2 format output */\r
+                       cinfo = opj_create_compress(CODEC_JP2);\r
+               }\r
+               /* catch events using our callbacks and give a local context */\r
+               opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, &msgErrorCallback_vars);\r
+\r
+               /* setup the encoder parameters using the current image and user parameters */\r
+               opj_setup_encoder(cinfo, &parameters, image);\r
+\r
+               /* open a byte stream for writing */\r
+               /* allocate memory for all tiles */\r
+               cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);\r
+\r
+               /* encode the image */\r
+               bSuccess = opj_encode_with_info(cinfo, cio, image, &cstr_info);\r
+               printf("C: after opj_encode_with_info\n");\r
+               if (!bSuccess) {\r
+                       opj_cio_close(cio);\r
+                       fprintf(stderr, "failed to encode image\n");\r
+                       return -1;\r
+               }\r
+               codestream_length = cio_tell(cio);\r
+\r
+               /* write the index on disk, if needed (-x 'filename') */\r
+               if (*indexfilename) {\r
+                       bSuccess = write_index_file(&cstr_info, indexfilename);\r
+                       if (bSuccess) {\r
+                               fprintf(stderr, "Failed to output index file into [%s]\n", indexfilename);\r
+                       }\r
+               }\r
+\r
+               compressed_index = create_index_into_byte_array(&cstr_info, &compressed_index_size);\r
+               /* Allocates the Java compressedIndex byte[] and sends this index into the Java object */\r
+               fid = (*env)->GetFieldID(env, cls,"compressedIndex", "[B");\r
+               jba = (*env)->NewByteArray(env, compressed_index_size+1);\r
+               jbBody = (*env)->GetPrimitiveArrayCritical(env, jba, 0);\r
+               memcpy(jbBody, compressed_index, compressed_index_size);\r
+               (*env)->ReleasePrimitiveArrayCritical(env, jba, jbBody, 0);\r
+               (*env)->SetObjectField(env, obj, fid, jba); \r
+               free(compressed_index);\r
+\r
+               /* write the generated codestream to disk ? */\r
+               if (parameters.outfile[0]!='\0') {\r
+                       f = fopen(parameters.outfile, "wb");\r
+                       if (!f) {\r
+                               fprintf(stderr, "failed to open [%s] for writing\n", parameters.outfile);\r
+                               return -1;\r
+                       }\r
+                       fwrite(cio->buffer, 1, codestream_length, f);\r
+                       fclose(f);\r
+                       fprintf(stdout,"Generated outfile [%s]\n",parameters.outfile);\r
+               }\r
+\r
+               /* Write the generated codestream to the Java pre-allocated compressedStream byte[] */\r
+               fid = (*env)->GetFieldID(env, cls,"compressedStream", "[B");\r
+               jba = (*env)->GetObjectField(env, obj, fid);\r
+               jbBody = (*env)->GetPrimitiveArrayCritical(env, jba, 0);\r
+               memcpy(jbBody, cio->buffer, codestream_length);\r
+               (*env)->ReleasePrimitiveArrayCritical(env, jba, jbBody, 0);\r
+\r
+               /* close and free the byte stream */\r
+               opj_cio_close(cio);\r
+\r
+               /* free remaining compression structures */\r
+               opj_destroy_compress(cinfo);\r
+               opj_destroy_cstr_info(&cstr_info);\r
+\r
+               /* free image data */\r
+               opj_image_destroy(image);\r
+       }\r
+\r
+       /* free user parameters structure */\r
+  if(parameters.cp_comment) free(parameters.cp_comment);\r
+       if(parameters.cp_matrice) free(parameters.cp_matrice);\r
+\r
+       return codestream_length;\r
+}\r
diff --git a/applications/JavaOpenJPEG/JavaOpenJPEGDecoder.c b/applications/JavaOpenJPEG/JavaOpenJPEGDecoder.c
new file mode 100644 (file)
index 0000000..decc137
--- /dev/null
@@ -0,0 +1,883 @@
+/*\r
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
+ * Copyright (c) 2002-2007, Professor Benoit Macq\r
+ * Copyright (c) 2001-2003, David Janssens\r
+ * Copyright (c) 2002-2003, Yannick Verschueren\r
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe\r
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team\r
+ * Copyright (c) 2006-2007, Parvatha Elangovan\r
+ * Copyright (c) 2007, Patrick Piscaglia (Telemis)\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <stdlib.h>\r
+#include <jni.h>\r
+#include <math.h>\r
+\r
+#include "openjpeg.h"\r
+#include "getopt.h"\r
+#include "convert.h"\r
+#include "dirent.h"\r
+#include "org_openJpeg_OpenJPEGJavaDecoder.h"\r
+\r
+#ifndef _WIN32\r
+#define stricmp strcasecmp\r
+#define strnicmp strncasecmp\r
+#endif\r
+\r
+#include "format_defs.h"\r
+\r
+typedef struct callback_variables {\r
+       JNIEnv *env;\r
+       /** 'jclass' object used to call a Java method from the C */\r
+       jobject *jobj;\r
+       /** 'jclass' object used to call a Java method from the C */\r
+       jmethodID message_mid;\r
+       jmethodID error_mid;\r
+} callback_variables_t;\r
+\r
+typedef struct dircnt{\r
+       /** Buffer for holding images read from Directory*/\r
+       char *filename_buf;\r
+       /** Pointer to the buffer*/\r
+       char **filename;\r
+}dircnt_t;\r
+\r
+\r
+typedef struct img_folder{\r
+       /** The directory path of the folder containing input images*/\r
+       char *imgdirpath;\r
+       /** Output format*/\r
+       char *out_format;\r
+       /** Enable option*/\r
+       char set_imgdir;\r
+       /** Enable Cod Format for output*/\r
+       char set_out_format;\r
+\r
+}img_fol_t;\r
+\r
+\r
+void decode_help_display() {\r
+       fprintf(stdout,"HELP\n----\n\n");\r
+       fprintf(stdout,"- the -h option displays this help information on screen\n\n");\r
+\r
+/* UniPG>> */\r
+       fprintf(stdout,"List of parameters for the JPEG 2000 "\r
+#ifdef USE_JPWL\r
+               "+ JPWL "\r
+#endif /* USE_JPWL */\r
+               "decoder:\n");\r
+/* <<UniPG */\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"\n");\r
+       fprintf(stdout,"  -ImgDir \n");\r
+       fprintf(stdout,"        Image file Directory path \n");\r
+       fprintf(stdout,"  -OutFor \n");\r
+       fprintf(stdout,"    REQUIRED only if -ImgDir is used\n");\r
+       fprintf(stdout,"          Need to specify only format without filename <BMP>  \n");\r
+       fprintf(stdout,"    Currently accepts PGM, PPM, PNM, PGX, BMP format\n");\r
+       fprintf(stdout,"  -i <compressed file>\n");\r
+       fprintf(stdout,"    REQUIRED only if an Input image directory not specified\n");\r
+       fprintf(stdout,"    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n");\r
+       fprintf(stdout,"    is identified based on its suffix.\n");\r
+       fprintf(stdout,"  -o <decompressed file>\n");\r
+       fprintf(stdout,"    REQUIRED\n");\r
+       fprintf(stdout,"    Currently accepts PGM-files, PPM-files, PNM-files, PGX-files and\n");\r
+       fprintf(stdout,"    BMP-files. Binary data is written to the file (not ascii). If a PGX\n");\r
+       fprintf(stdout,"    filename is given, there will be as many output files as there are\n");\r
+       fprintf(stdout,"    components: an indice starting from 0 will then be appended to the\n");\r
+       fprintf(stdout,"    output filename, just before the \"pgx\" extension. If a PGM filename\n");\r
+       fprintf(stdout,"    is given and there are more than one component, only the first component\n");\r
+       fprintf(stdout,"    will be written to the file.\n");\r
+       fprintf(stdout,"  -r <reduce factor>\n");\r
+       fprintf(stdout,"    Set the number of highest resolution levels to be discarded. The\n");\r
+       fprintf(stdout,"    image resolution is effectively divided by 2 to the power of the\n");\r
+       fprintf(stdout,"    number of discarded levels. The reduce factor is limited by the\n");\r
+       fprintf(stdout,"    smallest total number of decomposition levels among tiles.\n");\r
+       fprintf(stdout,"  -l <number of quality layers to decode>\n");\r
+       fprintf(stdout,"    Set the maximum number of quality layers to decode. If there are\n");\r
+       fprintf(stdout,"    less quality layers than the specified number, all the quality layers\n");\r
+       fprintf(stdout,"    are decoded.\n");\r
+/* UniPG>> */\r
+#ifdef USE_JPWL\r
+       fprintf(stdout,"  -W <options>\n");\r
+       fprintf(stdout,"    Activates the JPWL correction capability, if the codestream complies.\n");\r
+       fprintf(stdout,"    Options can be a comma separated list of <param=val> tokens:\n");\r
+       fprintf(stdout,"    c, c=numcomps\n");\r
+       fprintf(stdout,"       numcomps is the number of expected components in the codestream\n");\r
+       fprintf(stdout,"       (search of first EPB rely upon this, default is %d)\n", JPWL_EXPECTED_COMPONENTS);\r
+#endif /* USE_JPWL */\r
+/* <<UniPG */\r
+       fprintf(stdout,"\n");\r
+}\r
+\r
+/* -------------------------------------------------------------------------- */\r
+\r
+int get_num_images(char *imgdirpath){\r
+       DIR *dir;\r
+       struct dirent* content; \r
+       int num_images = 0;\r
+\r
+       /*Reading the input images from given input directory*/\r
+\r
+       dir= opendir(imgdirpath);\r
+       if(!dir){\r
+               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);\r
+               return 0;\r
+       }\r
+       \r
+       while((content=readdir(dir))!=NULL){\r
+               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )\r
+                       continue;\r
+               num_images++;\r
+       }\r
+       return num_images;\r
+}\r
+\r
+int load_images(dircnt_t *dirptr, char *imgdirpath){\r
+       DIR *dir;\r
+       struct dirent* content; \r
+       int i = 0;\r
+\r
+       /*Reading the input images from given input directory*/\r
+\r
+       dir= opendir(imgdirpath);\r
+       if(!dir){\r
+               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);\r
+               return 1;\r
+       }else   {\r
+               fprintf(stderr,"Folder opened successfully\n");\r
+       }\r
+       \r
+       while((content=readdir(dir))!=NULL){\r
+               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )\r
+                       continue;\r
+\r
+               strcpy(dirptr->filename[i],content->d_name);\r
+               i++;\r
+       }\r
+       return 0;       \r
+}\r
+\r
+int get_file_format(char *filename) {\r
+       unsigned int i;\r
+       static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "tga", "j2k", "jp2", "jpt", "j2c" };\r
+       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
+       char * ext = strrchr(filename, '.');\r
+       if (ext == NULL)\r
+               return -1;\r
+       ext++;\r
+       if(ext) {\r
+               for(i = 0; i < sizeof(format)/sizeof(*format); i++) {\r
+                       if(strnicmp(ext, extension[i], 3) == 0) {\r
+                               return format[i];\r
+                       }\r
+               }\r
+       }\r
+\r
+       return -1;\r
+}\r
+\r
+\r
+/* -------------------------------------------------------------------------- */\r
+\r
+int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol) {\r
+       /* parse the command line */\r
+       int totlen;\r
+       option_t long_option[]={\r
+               {"ImgDir",REQ_ARG, NULL ,'y'},\r
+               {"OutFor",REQ_ARG, NULL ,'O'},\r
+       };\r
+\r
+/* UniPG>> */\r
+       const char optlist[] = "i:o:r:l:hx:"\r
+\r
+#ifdef USE_JPWL\r
+                                       "W:"\r
+#endif /* USE_JPWL */\r
+                                       ;\r
+       /*for (i=0; i<argc; i++) {\r
+               printf("[%s]",argv[i]);\r
+       }\r
+       printf("\n");*/\r
+\r
+/* <<UniPG */\r
+       totlen=sizeof(long_option);\r
+       img_fol->set_out_format = 0;\r
+       reset_options_reading();\r
+\r
+       while (1) {\r
+               int c = getopt_long(argc, argv,optlist,long_option,totlen);\r
+               if (c == -1)\r
+                       break;\r
+               switch (c) {\r
+                       case 'i':                       /* input file */\r
+                       {\r
+                               char *infile = optarg;\r
+                               parameters->decod_format = get_file_format(infile);\r
+                               switch(parameters->decod_format) {\r
+                                       case J2K_CFMT:\r
+                                       case JP2_CFMT:\r
+                                       case JPT_CFMT:\r
+                                               break;\r
+                                       default:\r
+                                               fprintf(stderr, \r
+                                                       "!! Unrecognized format for infile : %s [accept only *.j2k, *.jp2, *.jpc or *.jpt] !!\n\n", \r
+                                                       infile);\r
+                                               return 1;\r
+                               }\r
+                               strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);\r
+                       }\r
+                       break;\r
+                               \r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'o':                       /* output file */\r
+                       {\r
+                               char *outfile = optarg;\r
+                               parameters->cod_format = get_file_format(outfile);\r
+                               switch(parameters->cod_format) {\r
+                                       case PGX_DFMT:\r
+                                       case PXM_DFMT:\r
+                                       case BMP_DFMT:\r
+                                       case TIF_DFMT:\r
+                                       case RAW_DFMT:\r
+                                       case TGA_DFMT:\r
+                                               break;\r
+                                       default:\r
+                                               fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outfile);\r
+                                               return 1;\r
+                               }\r
+                               strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);\r
+                       }\r
+                       break;\r
+                       \r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'O':                       /* output format */\r
+                       {\r
+                               char outformat[50];\r
+                               char *of = optarg;\r
+                               sprintf(outformat,".%s",of);\r
+                               img_fol->set_out_format = 1;\r
+                               parameters->cod_format = get_file_format(outformat);\r
+                               switch(parameters->cod_format) {\r
+                                       case PGX_DFMT:\r
+                                               img_fol->out_format = "pgx";\r
+                                               break;\r
+                                       case PXM_DFMT:\r
+                                               img_fol->out_format = "ppm";\r
+                                               break;\r
+                                       case BMP_DFMT:\r
+                                               img_fol->out_format = "bmp";\r
+                                               break;\r
+                                       case TIF_DFMT:\r
+                                               img_fol->out_format = "tif";\r
+                                               break;\r
+                                       case RAW_DFMT:\r
+                                               img_fol->out_format = "raw";\r
+                                               break;\r
+                                       case TGA_DFMT:\r
+                                               img_fol->out_format = "raw";\r
+                                               break;\r
+                                       default:\r
+                                               fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outformat);\r
+                                               return 1;\r
+                                               break;\r
+                               }\r
+                       }\r
+                       break;\r
+\r
+                               /* ----------------------------------------------------- */\r
+\r
+\r
+                       case 'r':               /* reduce option */\r
+                       {\r
+                               sscanf(optarg, "%d", &parameters->cp_reduce);\r
+                       }\r
+                       break;\r
+                       \r
+                               /* ----------------------------------------------------- */\r
+      \r
+\r
+                       case 'l':               /* layering option */\r
+                       {\r
+                               sscanf(optarg, "%d", &parameters->cp_layer);\r
+                       }\r
+                       break;\r
+                       \r
+                               /* ----------------------------------------------------- */\r
+\r
+                       case 'h':                       /* display an help description */\r
+                               decode_help_display();\r
+                               return 1;                               \r
+\r
+                               /* ------------------------------------------------------ */\r
+\r
+                       case 'y':                       /* Image Directory path */\r
+                               {\r
+                                       img_fol->imgdirpath = (char*)malloc(strlen(optarg) + 1);\r
+                                       strcpy(img_fol->imgdirpath,optarg);\r
+                                       img_fol->set_imgdir=1;\r
+                               }\r
+                               break;\r
+                               /* ----------------------------------------------------- */\r
+/* UniPG>> */\r
+#ifdef USE_JPWL\r
+                       \r
+                       case 'W':                       /* activate JPWL correction */\r
+                       {\r
+                               char *token = NULL;\r
+\r
+                               token = strtok(optarg, ",");\r
+                               while(token != NULL) {\r
+\r
+                                       /* search expected number of components */\r
+                                       if (*token == 'c') {\r
+\r
+                                               static int compno;\r
+\r
+                                               compno = JPWL_EXPECTED_COMPONENTS; /* predefined no. of components */\r
+\r
+                                               if(sscanf(token, "c=%d", &compno) == 1) {\r
+                                                       /* Specified */\r
+                                                       if ((compno < 1) || (compno > 256)) {\r
+                                                               fprintf(stderr, "ERROR -> invalid number of components c = %d\n", compno);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       parameters->jpwl_exp_comps = compno;\r
+\r
+                                               } else if (!strcmp(token, "c")) {\r
+                                                       /* default */\r
+                                                       parameters->jpwl_exp_comps = compno; /* auto for default size */\r
+\r
+                                               } else {\r
+                                                       fprintf(stderr, "ERROR -> invalid components specified = %s\n", token);\r
+                                                       return 1;\r
+                                               };\r
+                                       }\r
+\r
+                                       /* search maximum number of tiles */\r
+                                       if (*token == 't') {\r
+\r
+                                               static int tileno;\r
+\r
+                                               tileno = JPWL_MAXIMUM_TILES; /* maximum no. of tiles */\r
+\r
+                                               if(sscanf(token, "t=%d", &tileno) == 1) {\r
+                                                       /* Specified */\r
+                                                       if ((tileno < 1) || (tileno > JPWL_MAXIMUM_TILES)) {\r
+                                                               fprintf(stderr, "ERROR -> invalid number of tiles t = %d\n", tileno);\r
+                                                               return 1;\r
+                                                       }\r
+                                                       parameters->jpwl_max_tiles = tileno;\r
+\r
+                                               } else if (!strcmp(token, "t")) {\r
+                                                       /* default */\r
+                                                       parameters->jpwl_max_tiles = tileno; /* auto for default size */\r
+\r
+                                               } else {\r
+                                                       fprintf(stderr, "ERROR -> invalid tiles specified = %s\n", token);\r
+                                                       return 1;\r
+                                               };\r
+                                       }\r
+\r
+                                       /* next token or bust */\r
+                                       token = strtok(NULL, ",");\r
+                               };\r
+                               parameters->jpwl_correct = true;\r
+                               fprintf(stdout, "JPWL correction capability activated\n");\r
+                               fprintf(stdout, "- expecting %d components\n", parameters->jpwl_exp_comps);\r
+                       }\r
+                       break;  \r
+#endif /* USE_JPWL */\r
+/* <<UniPG */            \r
+\r
+                               /* ----------------------------------------------------- */\r
+                       \r
+                       default:\r
+                               fprintf(stderr,"WARNING -> this option is not valid \"-%c %s\"\n",c, optarg);\r
+                               break;\r
+               }\r
+       }\r
+\r
+       /* No check for possible errors before the -i and -o options are of course not mandatory*/\r
+\r
+       return 0;\r
+}\r
+\r
+/* -------------------------------------------------------------------------- */\r
+\r
+/**\r
+error callback returning the message to Java andexpecting a callback_variables_t client object\r
+*/\r
+void error_callback(const char *msg, void *client_data) {\r
+       callback_variables_t* vars = (callback_variables_t*) client_data;\r
+       JNIEnv *env = vars->env;\r
+       jstring jbuffer;\r
+\r
+       jbuffer = (*env)->NewStringUTF(env, msg);\r
+       (*env)->ExceptionClear(env);\r
+       (*env)->CallVoidMethod(env, *(vars->jobj), vars->error_mid, jbuffer);\r
+\r
+       if ((*env)->ExceptionOccurred(env)) {\r
+               fprintf(stderr,"C: Exception during call back method\n");\r
+               (*env)->ExceptionDescribe(env);\r
+               (*env)->ExceptionClear(env);\r
+       }\r
+       (*env)->DeleteLocalRef(env, jbuffer);\r
+}\r
+/**\r
+warning callback returning the message to Java andexpecting a callback_variables_t client object\r
+*/\r
+void warning_callback(const char *msg, void *client_data) {\r
+       callback_variables_t* vars = (callback_variables_t*) client_data;\r
+       JNIEnv *env = vars->env;\r
+       jstring jbuffer;\r
+\r
+       jbuffer = (*env)->NewStringUTF(env, msg);\r
+       (*env)->ExceptionClear(env);\r
+       (*env)->CallVoidMethod(env, *(vars->jobj), vars->message_mid, jbuffer);\r
+       \r
+       if ((*env)->ExceptionOccurred(env)) {\r
+               fprintf(stderr,"C: Exception during call back method\n");\r
+               (*env)->ExceptionDescribe(env);\r
+               (*env)->ExceptionClear(env);\r
+       }\r
+       (*env)->DeleteLocalRef(env, jbuffer);\r
+}\r
+/**\r
+information callback returning the message to Java andexpecting a callback_variables_t client object\r
+*/\r
+void info_callback(const char *msg, void *client_data) {\r
+       callback_variables_t* vars = (callback_variables_t*) client_data;\r
+       JNIEnv *env = vars->env;\r
+       jstring jbuffer;\r
+\r
+       jbuffer = (*env)->NewStringUTF(env, msg);\r
+       (*env)->ExceptionClear(env);\r
+       (*env)->CallVoidMethod(env, *(vars->jobj), vars->message_mid, jbuffer);\r
+\r
+       if ((*env)->ExceptionOccurred(env)) {\r
+               fprintf(stderr,"C: Exception during call back method\n");\r
+               (*env)->ExceptionDescribe(env);\r
+               (*env)->ExceptionClear(env);\r
+       }\r
+       (*env)->DeleteLocalRef(env, jbuffer);\r
+}\r
+\r
+\r
+/* --------------------------------------------------------------------------\r
+   --------------------   MAIN METHOD, CALLED BY JAVA -----------------------*/\r
+JNIEXPORT jint JNICALL Java_org_openJpeg_OpenJPEGJavaDecoder_internalDecodeJ2KtoImage(JNIEnv *env, jobject obj, jobjectArray javaParameters) {\r
+       int argc;               /* To simulate the command line parameters (taken from the javaParameters variable) and be able to re-use the */\r
+       char **argv;    /*  'parse_cmdline_decoder' method taken from the j2k_to_image project */\r
+       opj_dparameters_t parameters;   /* decompression parameters */\r
+       img_fol_t img_fol;\r
+       opj_event_mgr_t event_mgr;              /* event manager */\r
+       opj_image_t *image = NULL;\r
+       FILE *fsrc = NULL;\r
+       unsigned char *src = NULL;\r
+       int file_length;\r
+       int num_images;\r
+       int i,j,imageno;\r
+       opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */\r
+       opj_cio_t *cio = NULL;\r
+       int w,h;\r
+       long min_value, max_value;\r
+       short tempS; unsigned char tempUC, tempUC1, tempUC2;\r
+       // ==> Access variables to the Java member variables\r
+       jsize           arraySize;\r
+       jclass          cls;\r
+       jobject         object;\r
+       jboolean        isCopy;\r
+       jfieldID        fid;\r
+       jbyteArray      jba;\r
+       jshortArray jsa;\r
+       jintArray       jia;\r
+       jbyte           *jbBody, *ptrBBody;\r
+       jshort          *jsBody, *ptrSBody;\r
+       jint            *jiBody, *ptrIBody;\r
+       callback_variables_t msgErrorCallback_vars;\r
+       // <=== access variable to Java member variables */\r
+       int *ptr, *ptr1, *ptr2;                         // <== To transfer the decoded image to Java\r
+\r
+       /* configure the event callbacks */\r
+       memset(&event_mgr, 0, sizeof(opj_event_mgr_t)); \r
+       event_mgr.error_handler = error_callback;\r
+       event_mgr.warning_handler = warning_callback;\r
+       event_mgr.info_handler = info_callback;\r
+\r
+       // JNI reference to the calling class\r
+       cls = (*env)->GetObjectClass(env, obj);\r
+\r
+       // Pointers to be able to call a Java method for all the info and error messages\r
+       msgErrorCallback_vars.env = env;\r
+       msgErrorCallback_vars.jobj = &obj;\r
+       msgErrorCallback_vars.message_mid = (*env)->GetMethodID(env, cls, "logMessage", "(Ljava/lang/String;)V");\r
+       msgErrorCallback_vars.error_mid = (*env)->GetMethodID(env, cls, "logError", "(Ljava/lang/String;)V");\r
+\r
+       // Get the String[] containing the parameters, and converts it into a char** to simulate command line arguments.\r
+       arraySize = (*env)->GetArrayLength(env, javaParameters);\r
+       argc = (int) arraySize +1;\r
+       argv = malloc(argc*sizeof(char*));\r
+       argv[0] = "ProgramName.exe";    // The program name: useless\r
+       j=0;\r
+       for (i=1; i<argc; i++) {\r
+               object = (*env)->GetObjectArrayElement(env, javaParameters, i-1);\r
+               argv[i] = (*env)->GetStringUTFChars(env, object, &isCopy);\r
+       }\r
+\r
+       /*printf("C: decoder params = ");\r
+       for (i=0; i<argc; i++) {\r
+               printf("[%s]",argv[i]);\r
+       }\r
+       printf("\n");*/\r
+\r
+       /* set decoding parameters to default values */\r
+       opj_set_default_decoder_parameters(&parameters);\r
+       parameters.decod_format = J2K_CFMT;\r
+\r
+       /* parse input and get user encoding parameters */\r
+       if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol) == 1) {\r
+               // Release the Java arguments array\r
+               for (i=1; i<argc; i++)\r
+                       (*env)->ReleaseStringUTFChars(env, (*env)->GetObjectArrayElement(env, javaParameters, i-1), argv[i]);\r
+               return -1;\r
+       }\r
+       // Release the Java arguments array\r
+       for (i=1; i<argc; i++)\r
+               (*env)->ReleaseStringUTFChars(env, (*env)->GetObjectArrayElement(env, javaParameters, i-1), argv[i]);\r
+\r
+       num_images=1;\r
+\r
+       // Get additional information from the Java object variables\r
+       fid = (*env)->GetFieldID(env, cls,"skippedResolutions", "I");\r
+       parameters.cp_reduce = (short) (*env)->GetIntField(env, obj, fid);\r
+\r
+       /*Decoding image one by one*/\r
+       for(imageno = 0; imageno < num_images ; imageno++)\r
+       {\r
+               image = NULL;\r
+               fprintf(stderr,"\n");\r
+\r
+               /* read the input file and put it in memory into the 'src' object, if the -i option is given in JavaParameters.\r
+                  Implemented for debug purpose. */\r
+               /* -------------------------------------------------------------- */\r
+               if (parameters.infile && parameters.infile[0]!='\0') {\r
+                       //printf("C: opening [%s]\n", parameters.infile);\r
+                       fsrc = fopen(parameters.infile, "rb");\r
+                       if (!fsrc) {\r
+                               fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);\r
+                               return 1;\r
+                       }\r
+                       fseek(fsrc, 0, SEEK_END);\r
+                       file_length = ftell(fsrc);\r
+                       fseek(fsrc, 0, SEEK_SET);\r
+                       src = (unsigned char *) malloc(file_length);\r
+                       fread(src, 1, file_length, fsrc);\r
+                       fclose(fsrc);\r
+                       //printf("C: %d bytes read from file\n",file_length);\r
+               } else {\r
+                       // Preparing the transfer of the codestream from Java to C\r
+                       //printf("C: before transfering codestream\n");\r
+                       fid = (*env)->GetFieldID(env, cls,"compressedStream", "[B");\r
+                       jba = (*env)->GetObjectField(env, obj, fid);\r
+                       file_length = (*env)->GetArrayLength(env, jba);\r
+                       jbBody = (*env)->GetByteArrayElements(env, jba, &isCopy);\r
+                       src = (unsigned char*)jbBody;\r
+               }\r
+\r
+               /* decode the code-stream */\r
+               /* ---------------------- */\r
+\r
+               switch(parameters.decod_format) {\r
+               case J2K_CFMT:\r
+               {\r
+                       /* JPEG-2000 codestream */\r
+\r
+                       /* get a decoder handle */\r
+                       dinfo = opj_create_decompress(CODEC_J2K);\r
+\r
+                       /* catch events using our callbacks and give a local context */\r
+                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, &msgErrorCallback_vars);\r
+\r
+                       /* setup the decoder decoding parameters using user parameters */\r
+                       opj_setup_decoder(dinfo, &parameters);\r
+\r
+                       /* open a byte stream */\r
+                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);\r
+\r
+                       /* decode the stream and fill the image structure */\r
+                       image = opj_decode(dinfo, cio);\r
+                       if(!image) {\r
+                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");\r
+                               opj_destroy_decompress(dinfo);\r
+                               opj_cio_close(cio);\r
+                               return 1;\r
+                       }\r
+\r
+                       /* close the byte stream */\r
+                       opj_cio_close(cio);\r
+               }\r
+               break;\r
+\r
+               case JP2_CFMT:\r
+               {\r
+                       /* JPEG 2000 compressed image data */\r
+\r
+                       /* get a decoder handle */\r
+                       dinfo = opj_create_decompress(CODEC_JP2);\r
+\r
+                       /* catch events using our callbacks and give a local context */\r
+                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, &msgErrorCallback_vars);\r
+\r
+                       /* setup the decoder decoding parameters using the current image and user parameters */\r
+                       opj_setup_decoder(dinfo, &parameters);\r
+\r
+                       /* open a byte stream */\r
+                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);\r
+\r
+                       /* decode the stream and fill the image structure */\r
+                       image = opj_decode(dinfo, cio);\r
+                       if(!image) {\r
+                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");\r
+                               opj_destroy_decompress(dinfo);\r
+                               opj_cio_close(cio);\r
+                               return 1;\r
+                       }\r
+\r
+                       /* close the byte stream */\r
+                       opj_cio_close(cio);\r
+\r
+               }\r
+               break;\r
+\r
+               case JPT_CFMT:\r
+               {\r
+                       /* JPEG 2000, JPIP */\r
+\r
+                       /* get a decoder handle */\r
+                       dinfo = opj_create_decompress(CODEC_JPT);\r
+\r
+                       /* catch events using our callbacks and give a local context */\r
+                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, &msgErrorCallback_vars);\r
+\r
+                       /* setup the decoder decoding parameters using user parameters */\r
+                       opj_setup_decoder(dinfo, &parameters);\r
+\r
+                       /* open a byte stream */\r
+                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);\r
+\r
+                       /* decode the stream and fill the image structure */\r
+                       image = opj_decode(dinfo, cio);\r
+                       if(!image) {\r
+                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");\r
+                               opj_destroy_decompress(dinfo);\r
+                               opj_cio_close(cio);\r
+                               return 1;\r
+                       }\r
+\r
+                       /* close the byte stream */\r
+                       opj_cio_close(cio);\r
+               }\r
+               break;\r
+\r
+               default:\r
+                       fprintf(stderr, "skipping file..\n");\r
+                       continue;\r
+       }\r
+\r
+               /* free the memory containing the code-stream */\r
+               if (parameters.infile && parameters.infile[0]!='\0') {\r
+                       free(src);\r
+               } else {\r
+                       (*env)->ReleaseByteArrayElements(env, jba, jbBody, 0);\r
+               }\r
+               src = NULL;\r
+\r
+               /* create output image.\r
+                       If the -o parameter is given in the JavaParameters, write the decoded version into a file.\r
+                       Implemented for debug purpose. */\r
+               /* ---------------------------------- */\r
+               switch (parameters.cod_format) {\r
+               case PXM_DFMT:                  /* PNM PGM PPM */\r
+                       if (imagetopnm(image, parameters.outfile)) {\r
+                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);\r
+                       }\r
+                       else {\r
+                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);\r
+                       }\r
+                       break;\r
+\r
+               case PGX_DFMT:                  /* PGX */\r
+                       if(imagetopgx(image, parameters.outfile)){\r
+                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);\r
+                       }\r
+                       else {\r
+                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);\r
+                       }\r
+                       break;\r
+\r
+               case BMP_DFMT:                  /* BMP */\r
+                       if(imagetobmp(image, parameters.outfile)){\r
+                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);\r
+                       }\r
+                       else {\r
+                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);\r
+                       }\r
+                       break;\r
+\r
+               }\r
+\r
+               // ========= Return the image to the Java structure ===============\r
+#ifdef CHECK_THRESHOLDS\r
+               printf("C: checking thresholds\n");\r
+#endif\r
+               // First compute the real with and height, in function of the resolutions decoded.\r
+               //wr = (image->comps[0].w + (1 << image->comps[0].factor) -1) >> image->comps[0].factor;\r
+               //hr = (image->comps[0].h + (1 << image->comps[0].factor) -1) >> image->comps[0].factor;\r
+               w = image->comps[0].w;\r
+               h = image->comps[0].h;\r
+\r
+               if (image->numcomps==3) {       // 3 components color image\r
+                       ptr = image->comps[0].data;\r
+                       ptr1 = image->comps[1].data;\r
+                       ptr2 = image->comps[2].data;\r
+#ifdef CHECK_THRESHOLDS \r
+                       if (image->comps[0].sgnd) {\r
+                               min_value = -128;\r
+                               max_value = 127;\r
+                       } else {\r
+                               min_value = 0;\r
+                               max_value = 255;\r
+                       }\r
+#endif                 \r
+                       // Get the pointer to the Java structure where the data must be copied\r
+                       fid = (*env)->GetFieldID(env, cls,"image24", "[I");\r
+                       jia = (*env)->GetObjectField(env, obj, fid);\r
+                       jiBody = (*env)->GetIntArrayElements(env, jia, 0);\r
+                       ptrIBody = jiBody;\r
+                       printf("C: transfering image24: %d int to Java pointer=%d\n",image->numcomps*w*h, ptrIBody);\r
+\r
+                       for (i=0; i<w*h; i++) {\r
+                               tempUC = (unsigned char)(ptr[i]);\r
+                               tempUC1 = (unsigned char)(ptr1[i]);\r
+                               tempUC2 = (unsigned char)(ptr2[i]);\r
+#ifdef CHECK_THRESHOLDS\r
+                               if (tempUC < min_value)\r
+                                       tempUC=min_value;\r
+                               else if (tempUC > max_value)\r
+                                       tempUC=max_value;\r
+                               if (tempUC1 < min_value)\r
+                                       tempUC1=min_value;\r
+                               else if (tempUC1 > max_value)\r
+                                       tempUC1=max_value;\r
+                               if (tempUC2 < min_value)\r
+                                       tempUC2=min_value;\r
+                               else if (tempUC2 > max_value)\r
+                                       tempUC2=max_value;\r
+#endif\r
+                               *(ptrIBody++)  = (int) ( (tempUC2<<16) + (tempUC1<<8) + tempUC );\r
+                       }\r
+                       (*env)->ReleaseIntArrayElements(env, jia, jiBody, 0);\r
+\r
+               } else {        // 1 component 8 or 16 bpp image\r
+                       ptr = image->comps[0].data;\r
+                       printf("C: before transfering a %d bpp image to java (length = %d)\n",image->comps[0].prec ,w*h);\r
+                       if (image->comps[0].prec<=8) {\r
+                               fid = (*env)->GetFieldID(env, cls,"image8", "[B");\r
+                               jba = (*env)->GetObjectField(env, obj, fid);\r
+                               jbBody = (*env)->GetByteArrayElements(env, jba, 0);\r
+                               ptrBBody = jbBody;\r
+#ifdef CHECK_THRESHOLDS \r
+                               if (image->comps[0].sgnd) {\r
+                                       min_value = -128;\r
+                                       max_value = 127;\r
+                               } else {\r
+                                       min_value = 0;\r
+                                       max_value = 255;\r
+                               }\r
+#endif                                                         \r
+                               //printf("C: transfering %d shorts to Java image8 pointer = %d\n", wr*hr,ptrSBody);\r
+                               for (i=0; i<w*h; i++) {\r
+                                       tempUC = (unsigned char) (ptr[i]);\r
+#ifdef CHECK_THRESHOLDS\r
+                                       if (tempUC<min_value)\r
+                                               tempUC = min_value;\r
+                                       else if (tempUC > max_value)\r
+                                               tempUC = max_value;\r
+#endif\r
+                                       *(ptrBBody++) = tempUC;\r
+                               }\r
+                               (*env)->ReleaseByteArrayElements(env, jba, jbBody, 0);\r
+                               printf("C: image8 transfered to Java\n");\r
+                       } else {\r
+                               fid = (*env)->GetFieldID(env, cls,"image16", "[S");\r
+                               jsa = (*env)->GetObjectField(env, obj, fid);\r
+                               jsBody = (*env)->GetShortArrayElements(env, jsa, 0);\r
+                               ptrSBody = jsBody;\r
+#ifdef CHECK_THRESHOLDS \r
+                               if (image->comps[0].sgnd) {\r
+                                       min_value = -32768;\r
+                                       max_value = 32767;\r
+                               } else {\r
+                                       min_value = 0;\r
+                                       max_value = 65535;\r
+                               }\r
+                               printf("C: minValue = %d, maxValue = %d\n", min_value, max_value);\r
+#endif                         \r
+                               printf("C: transfering %d shorts to Java image16 pointer = %d\n", w*h,ptrSBody);\r
+                               for (i=0; i<w*h; i++) {\r
+                                       tempS = (short) (ptr[i]);\r
+#ifdef CHECK_THRESHOLDS\r
+                                       if (tempS<min_value) {\r
+                                               printf("C: value %d truncated to %d\n", tempS, min_value);\r
+                                               tempS = min_value;\r
+                                       } else if (tempS > max_value) {\r
+                                               printf("C: value %d truncated to %d\n", tempS, max_value);\r
+                                               tempS = max_value;\r
+                                       }\r
+#endif\r
+                                       *(ptrSBody++) = tempS;\r
+                               }\r
+                               (*env)->ReleaseShortArrayElements(env, jsa, jsBody, 0);\r
+                               printf("C: image16 completely filled\n");\r
+                       }\r
+               }       \r
+\r
+\r
+               /* free remaining structures */\r
+               if(dinfo) {\r
+                       opj_destroy_decompress(dinfo);\r
+               }\r
+               /* free image data structure */\r
+               opj_image_destroy(image);\r
+\r
+       }\r
+       return 1; /* OK */\r
+}\r
+//end main\r
+\r
diff --git a/applications/JavaOpenJPEG/Makefile b/applications/JavaOpenJPEG/Makefile
new file mode 100644 (file)
index 0000000..9ac3e40
--- /dev/null
@@ -0,0 +1,14 @@
+# Makefile for the main OpenJPEG codecs: j2k_to_image and image_to_j2k
+
+CFLAGS = -O3 -lstdc++ # -g -p -pg
+
+all: j2k_to_image image_to_j2k
+
+j2k_to_image: j2k_to_image.c ../libopenjpeg.a
+       gcc $(CFLAGS) ../common/getopt.c convert.c j2k_to_image.c -o j2k_to_image -L.. -lopenjpeg -I ../libopenjpeg/ -lm -ltiff
+
+image_to_j2k: image_to_j2k.c ../libopenjpeg.a
+       gcc $(CFLAGS) ../common/getopt.c convert.c image_to_j2k.c -o image_to_j2k -L.. -lopenjpeg -I ../libopenjpeg/ -lm -ltiff
+
+clean:
+       rm -f j2k_to_image image_to_j2k
diff --git a/applications/JavaOpenJPEG/java-jni/include/jawt.h b/applications/JavaOpenJPEG/java-jni/include/jawt.h
new file mode 100644 (file)
index 0000000..30a49ad
--- /dev/null
@@ -0,0 +1,278 @@
+/*\r
+ * @(#)jawt.h  1.10 03/12/19\r
+ *\r
+ * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
+ * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
+ */\r
+\r
+#ifndef _JAVASOFT_JAWT_H_\r
+#define _JAVASOFT_JAWT_H_\r
+\r
+#include "jni.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+/*\r
+ * AWT native interface (new in JDK 1.3)\r
+ *\r
+ * The AWT native interface allows a native C or C++ application a means\r
+ * by which to access native structures in AWT.  This is to facilitate moving\r
+ * legacy C and C++ applications to Java and to target the needs of the\r
+ * community who, at present, wish to do their own native rendering to canvases\r
+ * for performance reasons.  Standard extensions such as Java3D also require a\r
+ * means to access the underlying native data structures of AWT.\r
+ *\r
+ * There may be future extensions to this API depending on demand.\r
+ *\r
+ * A VM does not have to implement this API in order to pass the JCK.\r
+ * It is recommended, however, that this API is implemented on VMs that support\r
+ * standard extensions, such as Java3D.\r
+ *\r
+ * Since this is a native API, any program which uses it cannot be considered\r
+ * 100% pure java.\r
+ */\r
+\r
+/*\r
+ * AWT Native Drawing Surface (JAWT_DrawingSurface).\r
+ *\r
+ * For each platform, there is a native drawing surface structure.  This\r
+ * platform-specific structure can be found in jawt_md.h.  It is recommended\r
+ * that additional platforms follow the same model.  It is also recommended\r
+ * that VMs on Win32 and Solaris support the existing structures in jawt_md.h.\r
+ *\r
+ *******************\r
+ * EXAMPLE OF USAGE:\r
+ *******************\r
+ *\r
+ * In Win32, a programmer wishes to access the HWND of a canvas to perform\r
+ * native rendering into it.  The programmer has declared the paint() method\r
+ * for their canvas subclass to be native:\r
+ *\r
+ *\r
+ * MyCanvas.java:\r
+ *\r
+ * import java.awt.*;\r
+ *\r
+ * public class MyCanvas extends Canvas {\r
+ *\r
+ *     static {\r
+ *         System.loadLibrary("mylib");\r
+ *     }\r
+ *\r
+ *     public native void paint(Graphics g);\r
+ * }\r
+ *\r
+ *\r
+ * myfile.c:\r
+ *\r
+ * #include "jawt_md.h"\r
+ * #include <assert.h>\r
+ *\r
+ * JNIEXPORT void JNICALL\r
+ * Java_MyCanvas_paint(JNIEnv* env, jobject canvas, jobject graphics)\r
+ * {\r
+ *     JAWT awt;\r
+ *     JAWT_DrawingSurface* ds;\r
+ *     JAWT_DrawingSurfaceInfo* dsi;\r
+ *     JAWT_Win32DrawingSurfaceInfo* dsi_win;\r
+ *     jboolean result;\r
+ *     jint lock;\r
+ *\r
+ *     // Get the AWT\r
+ *     awt.version = JAWT_VERSION_1_3;\r
+ *     result = JAWT_GetAWT(env, &awt);\r
+ *     assert(result != JNI_FALSE);\r
+ *\r
+ *     // Get the drawing surface\r
+ *     ds = awt.GetDrawingSurface(env, canvas);\r
+ *     assert(ds != NULL);\r
+ *\r
+ *     // Lock the drawing surface\r
+ *     lock = ds->Lock(ds);\r
+ *     assert((lock & JAWT_LOCK_ERROR) == 0);\r
+ *\r
+ *     // Get the drawing surface info\r
+ *     dsi = ds->GetDrawingSurfaceInfo(ds);\r
+ *\r
+ *     // Get the platform-specific drawing info\r
+ *     dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo;\r
+ *\r
+ *     //////////////////////////////\r
+ *     // !!! DO PAINTING HERE !!! //\r
+ *     //////////////////////////////\r
+ *\r
+ *     // Free the drawing surface info\r
+ *     ds->FreeDrawingSurfaceInfo(dsi);\r
+ *\r
+ *     // Unlock the drawing surface\r
+ *     ds->Unlock(ds);\r
+ *\r
+ *     // Free the drawing surface\r
+ *     awt.FreeDrawingSurface(ds);\r
+ * }\r
+ *\r
+ */\r
+\r
+/*\r
+ * JAWT_Rectangle\r
+ * Structure for a native rectangle.\r
+ */\r
+typedef struct jawt_Rectangle {\r
+    jint x;\r
+    jint y;\r
+    jint width;\r
+    jint height;\r
+} JAWT_Rectangle;\r
+\r
+struct jawt_DrawingSurface;\r
+\r
+/*\r
+ * JAWT_DrawingSurfaceInfo\r
+ * Structure for containing the underlying drawing information of a component.\r
+ */\r
+typedef struct jawt_DrawingSurfaceInfo {\r
+    /*\r
+     * Pointer to the platform-specific information.  This can be safely\r
+     * cast to a JAWT_Win32DrawingSurfaceInfo on Windows or a\r
+     * JAWT_X11DrawingSurfaceInfo on Solaris.  See jawt_md.h for details.\r
+     */\r
+    void* platformInfo;\r
+    /* Cached pointer to the underlying drawing surface */\r
+    struct jawt_DrawingSurface* ds;\r
+    /* Bounding rectangle of the drawing surface */\r
+    JAWT_Rectangle bounds;\r
+    /* Number of rectangles in the clip */\r
+    jint clipSize;\r
+    /* Clip rectangle array */\r
+    JAWT_Rectangle* clip;\r
+} JAWT_DrawingSurfaceInfo;\r
+\r
+#define JAWT_LOCK_ERROR                 0x00000001\r
+#define JAWT_LOCK_CLIP_CHANGED          0x00000002\r
+#define JAWT_LOCK_BOUNDS_CHANGED        0x00000004\r
+#define JAWT_LOCK_SURFACE_CHANGED       0x00000008\r
+\r
+/*\r
+ * JAWT_DrawingSurface\r
+ * Structure for containing the underlying drawing information of a component.\r
+ * All operations on a JAWT_DrawingSurface MUST be performed from the same\r
+ * thread as the call to GetDrawingSurface.\r
+ */\r
+typedef struct jawt_DrawingSurface {\r
+    /*\r
+     * Cached reference to the Java environment of the calling thread.\r
+     * If Lock(), Unlock(), GetDrawingSurfaceInfo() or\r
+     * FreeDrawingSurfaceInfo() are called from a different thread,\r
+     * this data member should be set before calling those functions.\r
+     */\r
+    JNIEnv* env;\r
+    /* Cached reference to the target object */\r
+    jobject target;\r
+    /*\r
+     * Lock the surface of the target component for native rendering.\r
+     * When finished drawing, the surface must be unlocked with\r
+     * Unlock().  This function returns a bitmask with one or more of the\r
+     * following values:\r
+     *\r
+     * JAWT_LOCK_ERROR - When an error has occurred and the surface could not\r
+     * be locked.\r
+     *\r
+     * JAWT_LOCK_CLIP_CHANGED - When the clip region has changed.\r
+     *\r
+     * JAWT_LOCK_BOUNDS_CHANGED - When the bounds of the surface have changed.\r
+     *\r
+     * JAWT_LOCK_SURFACE_CHANGED - When the surface itself has changed\r
+     */\r
+    jint (JNICALL *Lock)\r
+        (struct jawt_DrawingSurface* ds);\r
+    /*\r
+     * Get the drawing surface info.\r
+     * The value returned may be cached, but the values may change if\r
+     * additional calls to Lock() or Unlock() are made.\r
+     * Lock() must be called before this can return a valid value.\r
+     * Returns NULL if an error has occurred.\r
+     * When finished with the returned value, FreeDrawingSurfaceInfo must be\r
+     * called.\r
+     */\r
+    JAWT_DrawingSurfaceInfo* (JNICALL *GetDrawingSurfaceInfo)\r
+        (struct jawt_DrawingSurface* ds);\r
+    /*\r
+     * Free the drawing surface info.\r
+     */\r
+    void (JNICALL *FreeDrawingSurfaceInfo)\r
+        (JAWT_DrawingSurfaceInfo* dsi);\r
+    /* \r
+     * Unlock the drawing surface of the target component for native rendering.\r
+     */\r
+    void (JNICALL *Unlock)\r
+        (struct jawt_DrawingSurface* ds);\r
+} JAWT_DrawingSurface;\r
+\r
+/*\r
+ * JAWT\r
+ * Structure for containing native AWT functions.\r
+ */\r
+typedef struct jawt {\r
+    /*\r
+     * Version of this structure.  This must always be set before\r
+     * calling JAWT_GetAWT()\r
+     */\r
+    jint version;\r
+    /*\r
+     * Return a drawing surface from a target jobject.  This value\r
+     * may be cached.\r
+     * Returns NULL if an error has occurred.\r
+     * Target must be a java.awt.Component (should be a Canvas\r
+     * or Window for native rendering).\r
+     * FreeDrawingSurface() must be called when finished with the\r
+     * returned JAWT_DrawingSurface.\r
+     */\r
+    JAWT_DrawingSurface* (JNICALL *GetDrawingSurface)\r
+        (JNIEnv* env, jobject target);\r
+    /*\r
+     * Free the drawing surface allocated in GetDrawingSurface.\r
+     */\r
+    void (JNICALL *FreeDrawingSurface)\r
+        (JAWT_DrawingSurface* ds);\r
+    /*\r
+     * Since 1.4\r
+     * Locks the entire AWT for synchronization purposes\r
+     */\r
+    void (JNICALL *Lock)(JNIEnv* env);\r
+    /*\r
+     * Since 1.4\r
+     * Unlocks the entire AWT for synchronization purposes\r
+     */\r
+    void (JNICALL *Unlock)(JNIEnv* env);\r
+    /*\r
+     * Since 1.4\r
+     * Returns a reference to a java.awt.Component from a native\r
+     * platform handle.  On Windows, this corresponds to an HWND;\r
+     * on Solaris and Linux, this is a Drawable.  For other platforms,\r
+     * see the appropriate machine-dependent header file for a description.\r
+     * The reference returned by this function is a local\r
+     * reference that is only valid in this environment.\r
+     * This function returns a NULL reference if no component could be\r
+     * found with matching platform information.\r
+     */\r
+    jobject (JNICALL *GetComponent)(JNIEnv* env, void* platformInfo);\r
+\r
+} JAWT;\r
+\r
+/*\r
+ * Get the AWT native structure.  This function returns JNI_FALSE if\r
+ * an error occurs.\r
+ */\r
+_JNI_IMPORT_OR_EXPORT_\r
+jboolean JNICALL JAWT_GetAWT(JNIEnv* env, JAWT* awt);\r
+\r
+#define JAWT_VERSION_1_3 0x00010003\r
+#define JAWT_VERSION_1_4 0x00010004\r
+\r
+#ifdef __cplusplus\r
+} /* extern "C" */\r
+#endif\r
+\r
+#endif /* !_JAVASOFT_JAWT_H_ */\r
diff --git a/applications/JavaOpenJPEG/java-jni/include/jdwpTransport.h b/applications/JavaOpenJPEG/java-jni/include/jdwpTransport.h
new file mode 100644 (file)
index 0000000..1d78009
--- /dev/null
@@ -0,0 +1,237 @@
+/*\r
+ * @(#)jdwpTransport.h 1.7 03/12/19\r
+ *\r
+ * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
+ * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
+ */\r
+\r
+/*\r
+ * Java Debug Wire Protocol Transport Service Provider Interface.\r
+ */\r
+\r
+#ifndef JDWPTRANSPORT_H\r
+#define JDWPTRANSPORT_H\r
+\r
+#include "jni.h"\r
+\r
+enum {\r
+    JDWPTRANSPORT_VERSION_1_0 = 0x00010000\r
+};\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+struct jdwpTransportNativeInterface_;\r
+\r
+struct _jdwpTransportEnv;\r
+\r
+#ifdef __cplusplus\r
+typedef _jdwpTransportEnv jdwpTransportEnv;\r
+#else\r
+typedef const struct jdwpTransportNativeInterface_ *jdwpTransportEnv;\r
+#endif /* __cplusplus */\r
+\r
+/*\r
+ * Errors. Universal errors with JVMTI/JVMDI equivalents keep the\r
+ * values the same.\r
+ */\r
+typedef enum {\r
+    JDWPTRANSPORT_ERROR_NONE = 0,\r
+    JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT = 103,\r
+    JDWPTRANSPORT_ERROR_OUT_OF_MEMORY = 110,\r
+    JDWPTRANSPORT_ERROR_INTERNAL = 113,\r
+    JDWPTRANSPORT_ERROR_ILLEGAL_STATE = 201,\r
+    JDWPTRANSPORT_ERROR_IO_ERROR = 202,\r
+    JDWPTRANSPORT_ERROR_TIMEOUT = 203,\r
+    JDWPTRANSPORT_ERROR_MSG_NOT_AVAILABLE = 204\r
+} jdwpTransportError;\r
+    \r
+\r
+/*\r
+ * Structure to define capabilities\r
+ */\r
+typedef struct {\r
+    unsigned int can_timeout_attach     :1;\r
+    unsigned int can_timeout_accept     :1;\r
+    unsigned int can_timeout_handshake  :1;\r
+    unsigned int reserved3              :1;\r
+    unsigned int reserved4              :1;\r
+    unsigned int reserved5              :1;\r
+    unsigned int reserved6              :1;\r
+    unsigned int reserved7              :1;\r
+    unsigned int reserved8              :1;\r
+    unsigned int reserved9              :1;\r
+    unsigned int reserved10             :1;\r
+    unsigned int reserved11             :1;\r
+    unsigned int reserved12             :1;\r
+    unsigned int reserved13             :1;\r
+    unsigned int reserved14            :1;\r
+    unsigned int reserved15            :1;\r
+} JDWPTransportCapabilities;\r
+\r
+\r
+/*\r
+ * Structures to define packet layout.\r
+ * \r
+ * See: http://java.sun.com/j2se/1.5/docs/guide/jpda/jdwp-spec.html\r
+ */\r
+\r
+enum {\r
+    JDWPTRANSPORT_FLAGS_NONE    = 0x0,\r
+    JDWPTRANSPORT_FLAGS_REPLY   = 0x80\r
+};\r
+\r
+typedef struct {\r
+    jint len; \r
+    jint id;\r
+    jbyte flags;\r
+    jbyte cmdSet;\r
+    jbyte cmd;\r
+    jbyte *data;\r
+} jdwpCmdPacket;\r
+\r
+typedef struct {\r
+    jint len;\r
+    jint id;\r
+    jbyte flags;\r
+    jshort errorCode;\r
+    jbyte *data;\r
+} jdwpReplyPacket;\r
+\r
+typedef struct {\r
+    union {\r
+        jdwpCmdPacket cmd;\r
+        jdwpReplyPacket reply;\r
+    } type;\r
+} jdwpPacket;\r
+\r
+/*\r
+ * JDWP functions called by the transport.\r
+ */\r
+typedef struct jdwpTransportCallback {\r
+    void *(*alloc)(jint numBytes);   /* Call this for all allocations */\r
+    void (*free)(void *buffer);      /* Call this for all deallocations */\r
+} jdwpTransportCallback;\r
+\r
+typedef jint (JNICALL *jdwpTransport_OnLoad_t)(JavaVM *jvm,\r
+                                              jdwpTransportCallback *callback,\r
+                                              jint version,\r
+                                              jdwpTransportEnv** env);\r
+\r
+\r
+\r
+/* Function Interface */\r
+\r
+struct jdwpTransportNativeInterface_ {\r
+    /*  1 :  RESERVED */\r
+    void *reserved1;\r
+\r
+    /* 2 : Get Capabilities */\r
+    jdwpTransportError (JNICALL *GetCapabilities)(jdwpTransportEnv* env,\r
+        JDWPTransportCapabilities *capabilities_ptr);\r
+\r
+    /*  3 : Attach */\r
+    jdwpTransportError (JNICALL *Attach)(jdwpTransportEnv* env,\r
+       const char* address,\r
+       jlong attach_timeout,\r
+       jlong handshake_timeout);\r
+\r
+    /*  4: StartListening */\r
+    jdwpTransportError (JNICALL *StartListening)(jdwpTransportEnv* env,\r
+       const char* address, \r
+       char** actual_address);\r
+\r
+    /*  5: StopListening */\r
+    jdwpTransportError (JNICALL *StopListening)(jdwpTransportEnv* env);\r
+\r
+    /*  6: Accept */\r
+    jdwpTransportError (JNICALL *Accept)(jdwpTransportEnv* env,\r
+       jlong accept_timeout, \r
+       jlong handshake_timeout);\r
+\r
+    /*  7: IsOpen */\r
+    jboolean (JNICALL *IsOpen)(jdwpTransportEnv* env);\r
+\r
+    /*  8: Close */\r
+    jdwpTransportError (JNICALL *Close)(jdwpTransportEnv* env);\r
+\r
+    /*  9: ReadPacket */\r
+    jdwpTransportError (JNICALL *ReadPacket)(jdwpTransportEnv* env,\r
+       jdwpPacket *pkt);\r
+\r
+    /*  10: Write Packet */\r
+    jdwpTransportError (JNICALL *WritePacket)(jdwpTransportEnv* env,\r
+       const jdwpPacket* pkt);\r
+\r
+    /*  11:  GetLastError */\r
+    jdwpTransportError (JNICALL *GetLastError)(jdwpTransportEnv* env,\r
+       char** error);\r
+\r
+};\r
+\r
+\r
+/*\r
+ * Use inlined functions so that C++ code can use syntax such as\r
+ *     env->Attach("mymachine:5000", 10*1000, 0);\r
+ *\r
+ * rather than using C's :-\r
+ *\r
+ *     (*env)->Attach(env, "mymachine:5000", 10*1000, 0);\r
+ */\r
+struct _jdwpTransportEnv {\r
+    const struct jdwpTransportNativeInterface_ *functions;\r
+#ifdef __cplusplus\r
+\r
+    jdwpTransportError GetCapabilities(JDWPTransportCapabilities *capabilities_ptr) {\r
+       return functions->GetCapabilities(this, capabilities_ptr);\r
+    }\r
+\r
+    jdwpTransportError Attach(const char* address, jlong attach_timeout,\r
+               jlong handshake_timeout) {\r
+       return functions->Attach(this, address, attach_timeout, handshake_timeout);\r
+    }\r
+\r
+    jdwpTransportError StartListening(const char* address,\r
+               char** actual_address) {\r
+       return functions->StartListening(this, address, actual_address);\r
+    }\r
+\r
+    jdwpTransportError StopListening(void) {\r
+       return functions->StopListening(this);\r
+    }\r
+\r
+    jdwpTransportError Accept(jlong accept_timeout, jlong handshake_timeout) {\r
+       return functions->Accept(this, accept_timeout, handshake_timeout);\r
+    }\r
+\r
+    jboolean IsOpen(void) {\r
+        return functions->IsOpen(this);\r
+    }\r
+\r
+    jdwpTransportError Close(void) {\r
+        return functions->Close(this);\r
+    }\r
+\r
+    jdwpTransportError ReadPacket(jdwpPacket *pkt) {\r
+       return functions->ReadPacket(this, pkt);\r
+    }\r
+\r
+    jdwpTransportError WritePacket(const jdwpPacket* pkt) {\r
+       return functions->WritePacket(this, pkt);\r
+    }\r
+\r
+    jdwpTransportError GetLastError(char** error) {\r
+       return functions->GetLastError(this, error);\r
+    }\r
+\r
+\r
+#endif /* __cplusplus */\r
+};\r
+\r
+#ifdef __cplusplus\r
+} /* extern "C" */\r
+#endif /* __cplusplus */\r
+\r
+#endif /* JDWPTRANSPORT_H */\r
+\r
diff --git a/applications/JavaOpenJPEG/java-jni/include/jni.h b/applications/JavaOpenJPEG/java-jni/include/jni.h
new file mode 100644 (file)
index 0000000..cb3baef
--- /dev/null
@@ -0,0 +1,1951 @@
+/*\r
+ * @(#)jni.h   1.56 03/12/19\r
+ *\r
+ * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
+ * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
+ */\r
+\r
+/*\r
+ * We used part of Netscape's Java Runtime Interface (JRI) as the starting\r
+ * point of our design and implementation.\r
+ */\r
+\r
+/******************************************************************************\r
+ * Java Runtime Interface\r
+ * Copyright (c) 1996 Netscape Communications Corporation. All rights reserved.\r
+ *****************************************************************************/\r
+\r
+#ifndef _JAVASOFT_JNI_H_\r
+#define _JAVASOFT_JNI_H_\r
+\r
+#include <stdio.h>\r
+#include <stdarg.h>\r
+\r
+/* jni_md.h contains the machine-dependent typedefs for jbyte, jint\r
+   and jlong */\r
+\r
+#include "jni_md.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+/*\r
+ * JNI Types\r
+ */\r
+\r
+#ifndef JNI_TYPES_ALREADY_DEFINED_IN_JNI_MD_H\r
+\r
+typedef unsigned char  jboolean;\r
+typedef unsigned short jchar;\r
+typedef short          jshort;\r
+typedef float          jfloat;\r
+typedef double         jdouble;\r
+\r
+typedef jint            jsize;\r
+\r
+#ifdef __cplusplus\r
+\r
+class _jobject {};\r
+class _jclass : public _jobject {};\r
+class _jthrowable : public _jobject {};\r
+class _jstring : public _jobject {};\r
+class _jarray : public _jobject {};\r
+class _jbooleanArray : public _jarray {};\r
+class _jbyteArray : public _jarray {};\r
+class _jcharArray : public _jarray {};\r
+class _jshortArray : public _jarray {};\r
+class _jintArray : public _jarray {};\r
+class _jlongArray : public _jarray {};\r
+class _jfloatArray : public _jarray {};\r
+class _jdoubleArray : public _jarray {};\r
+class _jobjectArray : public _jarray {};\r
+\r
+typedef _jobject *jobject;\r
+typedef _jclass *jclass;\r
+typedef _jthrowable *jthrowable;\r
+typedef _jstring *jstring;\r
+typedef _jarray *jarray;\r
+typedef _jbooleanArray *jbooleanArray;\r
+typedef _jbyteArray *jbyteArray;\r
+typedef _jcharArray *jcharArray;\r
+typedef _jshortArray *jshortArray;\r
+typedef _jintArray *jintArray;\r
+typedef _jlongArray *jlongArray;\r
+typedef _jfloatArray *jfloatArray;\r
+typedef _jdoubleArray *jdoubleArray;\r
+typedef _jobjectArray *jobjectArray;\r
+\r
+#else\r
+\r
+struct _jobject;\r
+\r
+typedef struct _jobject *jobject;\r
+typedef jobject jclass;\r
+typedef jobject jthrowable;\r
+typedef jobject jstring;\r
+typedef jobject jarray;\r
+typedef jarray jbooleanArray;\r
+typedef jarray jbyteArray;\r
+typedef jarray jcharArray;\r
+typedef jarray jshortArray;\r
+typedef jarray jintArray;\r
+typedef jarray jlongArray;\r
+typedef jarray jfloatArray;\r
+typedef jarray jdoubleArray;\r
+typedef jarray jobjectArray;\r
+\r
+#endif\r
+\r
+typedef jobject jweak;\r
+\r
+typedef union jvalue {\r
+    jboolean z;\r
+    jbyte    b;\r
+    jchar    c;\r
+    jshort   s;\r
+    jint     i;\r
+    jlong    j;\r
+    jfloat   f;\r
+    jdouble  d;\r
+    jobject  l;\r
+} jvalue;\r
+\r
+struct _jfieldID;\r
+typedef struct _jfieldID *jfieldID;\r
+\r
+struct _jmethodID;\r
+typedef struct _jmethodID *jmethodID;\r
+\r
+#endif /* JNI_TYPES_ALREADY_DEFINED_IN_JNI_MD_H */\r
+\r
+/*\r
+ * jboolean constants\r
+ */\r
+\r
+#define JNI_FALSE 0\r
+#define JNI_TRUE 1\r
+\r
+/*\r
+ * possible return values for JNI functions.\r
+ */\r
+\r
+#define JNI_OK           0                 /* success */\r
+#define JNI_ERR          (-1)              /* unknown error */\r
+#define JNI_EDETACHED    (-2)              /* thread detached from the VM */\r
+#define JNI_EVERSION     (-3)              /* JNI version error */\r
+#define JNI_ENOMEM       (-4)              /* not enough memory */\r
+#define JNI_EEXIST       (-5)              /* VM already created */\r
+#define JNI_EINVAL       (-6)              /* invalid arguments */\r
+\r
+/*\r
+ * used in ReleaseScalarArrayElements\r
+ */\r
+\r
+#define JNI_COMMIT 1\r
+#define JNI_ABORT 2\r
+\r
+/*\r
+ * used in RegisterNatives to describe native method name, signature,\r
+ * and function pointer.\r
+ */\r
+\r
+typedef struct {\r
+    char *name;\r
+    char *signature;\r
+    void *fnPtr;\r
+} JNINativeMethod;\r
+\r
+/*\r
+ * JNI Native Method Interface.\r
+ */\r
+\r
+struct JNINativeInterface_;\r
+\r
+struct JNIEnv_;\r
+\r
+#ifdef __cplusplus\r
+typedef JNIEnv_ JNIEnv;\r
+#else\r
+typedef const struct JNINativeInterface_ *JNIEnv;\r
+#endif\r
+\r
+/*\r
+ * JNI Invocation Interface.\r
+ */\r
+\r
+struct JNIInvokeInterface_;\r
+\r
+struct JavaVM_;\r
+\r
+#ifdef __cplusplus\r
+typedef JavaVM_ JavaVM;\r
+#else\r
+typedef const struct JNIInvokeInterface_ *JavaVM;\r
+#endif\r
+\r
+struct JNINativeInterface_ {\r
+    void *reserved0;\r
+    void *reserved1;\r
+    void *reserved2;\r
+\r
+    void *reserved3;\r
+    jint (JNICALL *GetVersion)(JNIEnv *env);\r
+\r
+    jclass (JNICALL *DefineClass)\r
+      (JNIEnv *env, const char *name, jobject loader, const jbyte *buf,\r
+       jsize len);\r
+    jclass (JNICALL *FindClass)\r
+      (JNIEnv *env, const char *name);\r
+\r
+    jmethodID (JNICALL *FromReflectedMethod)\r
+      (JNIEnv *env, jobject method);\r
+    jfieldID (JNICALL *FromReflectedField)\r
+      (JNIEnv *env, jobject field);\r
+\r
+    jobject (JNICALL *ToReflectedMethod)\r
+      (JNIEnv *env, jclass cls, jmethodID methodID, jboolean isStatic);\r
+\r
+    jclass (JNICALL *GetSuperclass)\r
+      (JNIEnv *env, jclass sub);\r
+    jboolean (JNICALL *IsAssignableFrom)\r
+      (JNIEnv *env, jclass sub, jclass sup);\r
+\r
+    jobject (JNICALL *ToReflectedField)\r
+      (JNIEnv *env, jclass cls, jfieldID fieldID, jboolean isStatic);\r
+\r
+    jint (JNICALL *Throw)\r
+      (JNIEnv *env, jthrowable obj);\r
+    jint (JNICALL *ThrowNew)\r
+      (JNIEnv *env, jclass clazz, const char *msg);\r
+    jthrowable (JNICALL *ExceptionOccurred)\r
+      (JNIEnv *env);\r
+    void (JNICALL *ExceptionDescribe)\r
+      (JNIEnv *env);\r
+    void (JNICALL *ExceptionClear)\r
+      (JNIEnv *env);\r
+    void (JNICALL *FatalError)\r
+      (JNIEnv *env, const char *msg);\r
+\r
+    jint (JNICALL *PushLocalFrame)\r
+      (JNIEnv *env, jint capacity);\r
+    jobject (JNICALL *PopLocalFrame)\r
+      (JNIEnv *env, jobject result);\r
+\r
+    jobject (JNICALL *NewGlobalRef)\r
+      (JNIEnv *env, jobject lobj);\r
+    void (JNICALL *DeleteGlobalRef)\r
+      (JNIEnv *env, jobject gref);\r
+    void (JNICALL *DeleteLocalRef)\r
+      (JNIEnv *env, jobject obj);\r
+    jboolean (JNICALL *IsSameObject)\r
+      (JNIEnv *env, jobject obj1, jobject obj2);\r
+    jobject (JNICALL *NewLocalRef)\r
+      (JNIEnv *env, jobject ref);\r
+    jint (JNICALL *EnsureLocalCapacity)\r
+      (JNIEnv *env, jint capacity);\r
+\r
+    jobject (JNICALL *AllocObject)\r
+      (JNIEnv *env, jclass clazz);\r
+    jobject (JNICALL *NewObject)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
+    jobject (JNICALL *NewObjectV)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
+    jobject (JNICALL *NewObjectA)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
+\r
+    jclass (JNICALL *GetObjectClass)\r
+      (JNIEnv *env, jobject obj);\r
+    jboolean (JNICALL *IsInstanceOf)\r
+      (JNIEnv *env, jobject obj, jclass clazz);\r
+\r
+    jmethodID (JNICALL *GetMethodID)\r
+      (JNIEnv *env, jclass clazz, const char *name, const char *sig);\r
+\r
+    jobject (JNICALL *CallObjectMethod)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
+    jobject (JNICALL *CallObjectMethodV)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
+    jobject (JNICALL *CallObjectMethodA)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);\r
+\r
+    jboolean (JNICALL *CallBooleanMethod)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
+    jboolean (JNICALL *CallBooleanMethodV)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
+    jboolean (JNICALL *CallBooleanMethodA)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);\r
+\r
+    jbyte (JNICALL *CallByteMethod)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
+    jbyte (JNICALL *CallByteMethodV)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
+    jbyte (JNICALL *CallByteMethodA)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
+\r
+    jchar (JNICALL *CallCharMethod)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
+    jchar (JNICALL *CallCharMethodV)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
+    jchar (JNICALL *CallCharMethodA)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
+\r
+    jshort (JNICALL *CallShortMethod)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
+    jshort (JNICALL *CallShortMethodV)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
+    jshort (JNICALL *CallShortMethodA)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
+\r
+    jint (JNICALL *CallIntMethod)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
+    jint (JNICALL *CallIntMethodV)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
+    jint (JNICALL *CallIntMethodA)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
+\r
+    jlong (JNICALL *CallLongMethod)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
+    jlong (JNICALL *CallLongMethodV)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
+    jlong (JNICALL *CallLongMethodA)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
+\r
+    jfloat (JNICALL *CallFloatMethod)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
+    jfloat (JNICALL *CallFloatMethodV)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
+    jfloat (JNICALL *CallFloatMethodA)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
+\r
+    jdouble (JNICALL *CallDoubleMethod)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
+    jdouble (JNICALL *CallDoubleMethodV)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
+    jdouble (JNICALL *CallDoubleMethodA)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);\r
+\r
+    void (JNICALL *CallVoidMethod)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, ...);\r
+    void (JNICALL *CallVoidMethodV)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);\r
+    void (JNICALL *CallVoidMethodA)\r
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);\r
+\r
+    jobject (JNICALL *CallNonvirtualObjectMethod)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
+    jobject (JNICALL *CallNonvirtualObjectMethodV)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       va_list args);\r
+    jobject (JNICALL *CallNonvirtualObjectMethodA)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       const jvalue * args);\r
+\r
+    jboolean (JNICALL *CallNonvirtualBooleanMethod)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
+    jboolean (JNICALL *CallNonvirtualBooleanMethodV)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       va_list args);\r
+    jboolean (JNICALL *CallNonvirtualBooleanMethodA)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       const jvalue * args);\r
+\r
+    jbyte (JNICALL *CallNonvirtualByteMethod)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
+    jbyte (JNICALL *CallNonvirtualByteMethodV)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       va_list args);\r
+    jbyte (JNICALL *CallNonvirtualByteMethodA)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       const jvalue *args);\r
+\r
+    jchar (JNICALL *CallNonvirtualCharMethod)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
+    jchar (JNICALL *CallNonvirtualCharMethodV)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       va_list args);\r
+    jchar (JNICALL *CallNonvirtualCharMethodA)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       const jvalue *args);\r
+\r
+    jshort (JNICALL *CallNonvirtualShortMethod)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
+    jshort (JNICALL *CallNonvirtualShortMethodV)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       va_list args);\r
+    jshort (JNICALL *CallNonvirtualShortMethodA)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       const jvalue *args);\r
+\r
+    jint (JNICALL *CallNonvirtualIntMethod)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
+    jint (JNICALL *CallNonvirtualIntMethodV)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       va_list args);\r
+    jint (JNICALL *CallNonvirtualIntMethodA)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       const jvalue *args);\r
+\r
+    jlong (JNICALL *CallNonvirtualLongMethod)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
+    jlong (JNICALL *CallNonvirtualLongMethodV)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       va_list args);\r
+    jlong (JNICALL *CallNonvirtualLongMethodA)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       const jvalue *args);\r
+\r
+    jfloat (JNICALL *CallNonvirtualFloatMethod)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
+    jfloat (JNICALL *CallNonvirtualFloatMethodV)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       va_list args);\r
+    jfloat (JNICALL *CallNonvirtualFloatMethodA)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       const jvalue *args);\r
+\r
+    jdouble (JNICALL *CallNonvirtualDoubleMethod)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
+    jdouble (JNICALL *CallNonvirtualDoubleMethodV)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       va_list args);\r
+    jdouble (JNICALL *CallNonvirtualDoubleMethodA)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       const jvalue *args);\r
+\r
+    void (JNICALL *CallNonvirtualVoidMethod)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);\r
+    void (JNICALL *CallNonvirtualVoidMethodV)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       va_list args);\r
+    void (JNICALL *CallNonvirtualVoidMethodA)\r
+      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,\r
+       const jvalue * args);\r
+\r
+    jfieldID (JNICALL *GetFieldID)\r
+      (JNIEnv *env, jclass clazz, const char *name, const char *sig);\r
+\r
+    jobject (JNICALL *GetObjectField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
+    jboolean (JNICALL *GetBooleanField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
+    jbyte (JNICALL *GetByteField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
+    jchar (JNICALL *GetCharField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
+    jshort (JNICALL *GetShortField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
+    jint (JNICALL *GetIntField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
+    jlong (JNICALL *GetLongField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
+    jfloat (JNICALL *GetFloatField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
+    jdouble (JNICALL *GetDoubleField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID);\r
+\r
+    void (JNICALL *SetObjectField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jobject val);\r
+    void (JNICALL *SetBooleanField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jboolean val);\r
+    void (JNICALL *SetByteField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jbyte val);\r
+    void (JNICALL *SetCharField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jchar val);\r
+    void (JNICALL *SetShortField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jshort val);\r
+    void (JNICALL *SetIntField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jint val);\r
+    void (JNICALL *SetLongField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jlong val);\r
+    void (JNICALL *SetFloatField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jfloat val);\r
+    void (JNICALL *SetDoubleField)\r
+      (JNIEnv *env, jobject obj, jfieldID fieldID, jdouble val);\r
+\r
+    jmethodID (JNICALL *GetStaticMethodID)\r
+      (JNIEnv *env, jclass clazz, const char *name, const char *sig);\r
+\r
+    jobject (JNICALL *CallStaticObjectMethod)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
+    jobject (JNICALL *CallStaticObjectMethodV)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
+    jobject (JNICALL *CallStaticObjectMethodA)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
+\r
+    jboolean (JNICALL *CallStaticBooleanMethod)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
+    jboolean (JNICALL *CallStaticBooleanMethodV)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
+    jboolean (JNICALL *CallStaticBooleanMethodA)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
+\r
+    jbyte (JNICALL *CallStaticByteMethod)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
+    jbyte (JNICALL *CallStaticByteMethodV)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
+    jbyte (JNICALL *CallStaticByteMethodA)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
+\r
+    jchar (JNICALL *CallStaticCharMethod)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
+    jchar (JNICALL *CallStaticCharMethodV)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
+    jchar (JNICALL *CallStaticCharMethodA)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
+\r
+    jshort (JNICALL *CallStaticShortMethod)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
+    jshort (JNICALL *CallStaticShortMethodV)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
+    jshort (JNICALL *CallStaticShortMethodA)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
+\r
+    jint (JNICALL *CallStaticIntMethod)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
+    jint (JNICALL *CallStaticIntMethodV)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
+    jint (JNICALL *CallStaticIntMethodA)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
+\r
+    jlong (JNICALL *CallStaticLongMethod)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
+    jlong (JNICALL *CallStaticLongMethodV)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
+    jlong (JNICALL *CallStaticLongMethodA)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
+\r
+    jfloat (JNICALL *CallStaticFloatMethod)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
+    jfloat (JNICALL *CallStaticFloatMethodV)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
+    jfloat (JNICALL *CallStaticFloatMethodA)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
+\r
+    jdouble (JNICALL *CallStaticDoubleMethod)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);\r
+    jdouble (JNICALL *CallStaticDoubleMethodV)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);\r
+    jdouble (JNICALL *CallStaticDoubleMethodA)\r
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);\r
+\r
+    void (JNICALL *CallStaticVoidMethod)\r
+      (JNIEnv *env, jclass cls, jmethodID methodID, ...);\r
+    void (JNICALL *CallStaticVoidMethodV)\r
+      (JNIEnv *env, jclass cls, jmethodID methodID, va_list args);\r
+    void (JNICALL *CallStaticVoidMethodA)\r
+      (JNIEnv *env, jclass cls, jmethodID methodID, const jvalue * args);\r
+\r
+    jfieldID (JNICALL *GetStaticFieldID)\r
+      (JNIEnv *env, jclass clazz, const char *name, const char *sig);\r
+    jobject (JNICALL *GetStaticObjectField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
+    jboolean (JNICALL *GetStaticBooleanField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
+    jbyte (JNICALL *GetStaticByteField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
+    jchar (JNICALL *GetStaticCharField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
+    jshort (JNICALL *GetStaticShortField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
+    jint (JNICALL *GetStaticIntField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
+    jlong (JNICALL *GetStaticLongField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
+    jfloat (JNICALL *GetStaticFloatField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
+    jdouble (JNICALL *GetStaticDoubleField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID);\r
+\r
+    void (JNICALL *SetStaticObjectField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jobject value);\r
+    void (JNICALL *SetStaticBooleanField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jboolean value);\r
+    void (JNICALL *SetStaticByteField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jbyte value);\r
+    void (JNICALL *SetStaticCharField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jchar value);\r
+    void (JNICALL *SetStaticShortField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jshort value);\r
+    void (JNICALL *SetStaticIntField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jint value);\r
+    void (JNICALL *SetStaticLongField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jlong value);\r
+    void (JNICALL *SetStaticFloatField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jfloat value);\r
+    void (JNICALL *SetStaticDoubleField)\r
+      (JNIEnv *env, jclass clazz, jfieldID fieldID, jdouble value);\r
+\r
+    jstring (JNICALL *NewString)\r
+      (JNIEnv *env, const jchar *unicode, jsize len);\r
+    jsize (JNICALL *GetStringLength)\r
+      (JNIEnv *env, jstring str);\r
+    const jchar *(JNICALL *GetStringChars)\r
+      (JNIEnv *env, jstring str, jboolean *isCopy);\r
+    void (JNICALL *ReleaseStringChars)\r
+      (JNIEnv *env, jstring str, const jchar *chars);\r
+\r
+    jstring (JNICALL *NewStringUTF)\r
+      (JNIEnv *env, const char *utf);\r
+    jsize (JNICALL *GetStringUTFLength)\r
+      (JNIEnv *env, jstring str);\r
+    const char* (JNICALL *GetStringUTFChars)\r
+      (JNIEnv *env, jstring str, jboolean *isCopy);\r
+    void (JNICALL *ReleaseStringUTFChars)\r
+      (JNIEnv *env, jstring str, const char* chars);\r
+\r
+\r
+    jsize (JNICALL *GetArrayLength)\r
+      (JNIEnv *env, jarray array);\r
+\r
+    jobjectArray (JNICALL *NewObjectArray)\r
+      (JNIEnv *env, jsize len, jclass clazz, jobject init);\r
+    jobject (JNICALL *GetObjectArrayElement)\r
+      (JNIEnv *env, jobjectArray array, jsize index);\r
+    void (JNICALL *SetObjectArrayElement)\r
+      (JNIEnv *env, jobjectArray array, jsize index, jobject val);\r
+\r
+    jbooleanArray (JNICALL *NewBooleanArray)\r
+      (JNIEnv *env, jsize len);\r
+    jbyteArray (JNICALL *NewByteArray)\r
+      (JNIEnv *env, jsize len);\r
+    jcharArray (JNICALL *NewCharArray)\r
+      (JNIEnv *env, jsize len);\r
+    jshortArray (JNICALL *NewShortArray)\r
+      (JNIEnv *env, jsize len);\r
+    jintArray (JNICALL *NewIntArray)\r
+      (JNIEnv *env, jsize len);\r
+    jlongArray (JNICALL *NewLongArray)\r
+      (JNIEnv *env, jsize len);\r
+    jfloatArray (JNICALL *NewFloatArray)\r
+      (JNIEnv *env, jsize len);\r
+    jdoubleArray (JNICALL *NewDoubleArray)\r
+      (JNIEnv *env, jsize len);\r
+\r
+    jboolean * (JNICALL *GetBooleanArrayElements)\r
+      (JNIEnv *env, jbooleanArray array, jboolean *isCopy);\r
+    jbyte * (JNICALL *GetByteArrayElements)\r
+      (JNIEnv *env, jbyteArray array, jboolean *isCopy);\r
+    jchar * (JNICALL *GetCharArrayElements)\r
+      (JNIEnv *env, jcharArray array, jboolean *isCopy);\r
+    jshort * (JNICALL *GetShortArrayElements)\r
+      (JNIEnv *env, jshortArray array, jboolean *isCopy);\r
+    jint * (JNICALL *GetIntArrayElements)\r
+      (JNIEnv *env, jintArray array, jboolean *isCopy);\r
+    jlong * (JNICALL *GetLongArrayElements)\r
+      (JNIEnv *env, jlongArray array, jboolean *isCopy);\r
+    jfloat * (JNICALL *GetFloatArrayElements)\r
+      (JNIEnv *env, jfloatArray array, jboolean *isCopy);\r
+    jdouble * (JNICALL *GetDoubleArrayElements)\r
+      (JNIEnv *env, jdoubleArray array, jboolean *isCopy);\r
+\r
+    void (JNICALL *ReleaseBooleanArrayElements)\r
+      (JNIEnv *env, jbooleanArray array, jboolean *elems, jint mode);\r
+    void (JNICALL *ReleaseByteArrayElements)\r
+      (JNIEnv *env, jbyteArray array, jbyte *elems, jint mode);\r
+    void (JNICALL *ReleaseCharArrayElements)\r
+      (JNIEnv *env, jcharArray array, jchar *elems, jint mode);\r
+    void (JNICALL *ReleaseShortArrayElements)\r
+      (JNIEnv *env, jshortArray array, jshort *elems, jint mode);\r
+    void (JNICALL *ReleaseIntArrayElements)\r
+      (JNIEnv *env, jintArray array, jint *elems, jint mode);\r
+    void (JNICALL *ReleaseLongArrayElements)\r
+      (JNIEnv *env, jlongArray array, jlong *elems, jint mode);\r
+    void (JNICALL *ReleaseFloatArrayElements)\r
+      (JNIEnv *env, jfloatArray array, jfloat *elems, jint mode);\r
+    void (JNICALL *ReleaseDoubleArrayElements)\r
+      (JNIEnv *env, jdoubleArray array, jdouble *elems, jint mode);\r
+\r
+    void (JNICALL *GetBooleanArrayRegion)\r
+      (JNIEnv *env, jbooleanArray array, jsize start, jsize l, jboolean *buf);\r
+    void (JNICALL *GetByteArrayRegion)\r
+      (JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);\r
+    void (JNICALL *GetCharArrayRegion)\r
+      (JNIEnv *env, jcharArray array, jsize start, jsize len, jchar *buf);\r
+    void (JNICALL *GetShortArrayRegion)\r
+      (JNIEnv *env, jshortArray array, jsize start, jsize len, jshort *buf);\r
+    void (JNICALL *GetIntArrayRegion)\r
+      (JNIEnv *env, jintArray array, jsize start, jsize len, jint *buf);\r
+    void (JNICALL *GetLongArrayRegion)\r
+      (JNIEnv *env, jlongArray array, jsize start, jsize len, jlong *buf);\r
+    void (JNICALL *GetFloatArrayRegion)\r
+      (JNIEnv *env, jfloatArray array, jsize start, jsize len, jfloat *buf);\r
+    void (JNICALL *GetDoubleArrayRegion)\r
+      (JNIEnv *env, jdoubleArray array, jsize start, jsize len, jdouble *buf);\r
+\r
+    void (JNICALL *SetBooleanArrayRegion)\r
+      (JNIEnv *env, jbooleanArray array, jsize start, jsize l, const jboolean *buf);\r
+    void (JNICALL *SetByteArrayRegion)\r
+      (JNIEnv *env, jbyteArray array, jsize start, jsize len, const jbyte *buf);\r
+    void (JNICALL *SetCharArrayRegion)\r
+      (JNIEnv *env, jcharArray array, jsize start, jsize len, const jchar *buf);\r
+    void (JNICALL *SetShortArrayRegion)\r
+      (JNIEnv *env, jshortArray array, jsize start, jsize len, const jshort *buf);\r
+    void (JNICALL *SetIntArrayRegion)\r
+      (JNIEnv *env, jintArray array, jsize start, jsize len, const jint *buf);\r
+    void (JNICALL *SetLongArrayRegion)\r
+      (JNIEnv *env, jlongArray array, jsize start, jsize len, const jlong *buf);\r
+    void (JNICALL *SetFloatArrayRegion)\r
+      (JNIEnv *env, jfloatArray array, jsize start, jsize len, const jfloat *buf);\r
+    void (JNICALL *SetDoubleArrayRegion)\r
+      (JNIEnv *env, jdoubleArray array, jsize start, jsize len, const jdouble *buf);\r
+\r
+    jint (JNICALL *RegisterNatives)\r
+      (JNIEnv *env, jclass clazz, const JNINativeMethod *methods,\r
+       jint nMethods);\r
+    jint (JNICALL *UnregisterNatives)\r
+      (JNIEnv *env, jclass clazz);\r
+\r
+    jint (JNICALL *MonitorEnter)\r
+      (JNIEnv *env, jobject obj);\r
+    jint (JNICALL *MonitorExit)\r
+      (JNIEnv *env, jobject obj);\r
+\r
+    jint (JNICALL *GetJavaVM)\r
+      (JNIEnv *env, JavaVM **vm);\r
+\r
+    void (JNICALL *GetStringRegion)\r
+      (JNIEnv *env, jstring str, jsize start, jsize len, jchar *buf);\r
+    void (JNICALL *GetStringUTFRegion)\r
+      (JNIEnv *env, jstring str, jsize start, jsize len, char *buf);\r
+\r
+    void * (JNICALL *GetPrimitiveArrayCritical)\r
+      (JNIEnv *env, jarray array, jboolean *isCopy);\r
+    void (JNICALL *ReleasePrimitiveArrayCritical)\r
+      (JNIEnv *env, jarray array, void *carray, jint mode);\r
+\r
+    const jchar * (JNICALL *GetStringCritical)\r
+      (JNIEnv *env, jstring string, jboolean *isCopy);\r
+    void (JNICALL *ReleaseStringCritical)\r
+      (JNIEnv *env, jstring string, const jchar *cstring);\r
+\r
+    jweak (JNICALL *NewWeakGlobalRef)\r
+       (JNIEnv *env, jobject obj);\r
+    void (JNICALL *DeleteWeakGlobalRef)\r
+       (JNIEnv *env, jweak ref);\r
+\r
+    jboolean (JNICALL *ExceptionCheck)\r
+       (JNIEnv *env);\r
+\r
+    jobject (JNICALL *NewDirectByteBuffer)\r
+       (JNIEnv* env, void* address, jlong capacity);\r
+    void* (JNICALL *GetDirectBufferAddress)\r
+       (JNIEnv* env, jobject buf);\r
+    jlong (JNICALL *GetDirectBufferCapacity)\r
+       (JNIEnv* env, jobject buf);\r
+};\r
+\r
+/*\r
+ * We use inlined functions for C++ so that programmers can write:\r
+ *\r
+ *    env->FindClass("java/lang/String")\r
+ *\r
+ * in C++ rather than:\r
+ *\r
+ *    (*env)->FindClass(env, "java/lang/String")\r
+ *\r
+ * in C.\r
+ */\r
+\r
+struct JNIEnv_ {\r
+    const struct JNINativeInterface_ *functions;\r
+#ifdef __cplusplus\r
+\r
+    jint GetVersion() {\r
+        return functions->GetVersion(this);\r
+    }\r
+    jclass DefineClass(const char *name, jobject loader, const jbyte *buf,\r
+                      jsize len) {\r
+        return functions->DefineClass(this, name, loader, buf, len);\r
+    }\r
+    jclass FindClass(const char *name) {\r
+        return functions->FindClass(this, name);\r
+    }\r
+    jmethodID FromReflectedMethod(jobject method) {\r
+        return functions->FromReflectedMethod(this,method);\r
+    }\r
+    jfieldID FromReflectedField(jobject field) {\r
+        return functions->FromReflectedField(this,field);\r
+    }\r
+\r
+    jobject ToReflectedMethod(jclass cls, jmethodID methodID, jboolean isStatic) {\r
+        return functions->ToReflectedMethod(this, cls, methodID, isStatic);\r
+    }\r
+\r
+    jclass GetSuperclass(jclass sub) {\r
+        return functions->GetSuperclass(this, sub);\r
+    }\r
+    jboolean IsAssignableFrom(jclass sub, jclass sup) {\r
+        return functions->IsAssignableFrom(this, sub, sup);\r
+    }\r
+\r
+    jobject ToReflectedField(jclass cls, jfieldID fieldID, jboolean isStatic) {\r
+        return functions->ToReflectedField(this,cls,fieldID,isStatic);\r
+    }\r
+\r
+    jint Throw(jthrowable obj) {\r
+        return functions->Throw(this, obj);\r
+    }\r
+    jint ThrowNew(jclass clazz, const char *msg) {\r
+        return functions->ThrowNew(this, clazz, msg);\r
+    }\r
+    jthrowable ExceptionOccurred() {\r
+        return functions->ExceptionOccurred(this);\r
+    }\r
+    void ExceptionDescribe() {\r
+        functions->ExceptionDescribe(this);\r
+    }\r
+    void ExceptionClear() {\r
+        functions->ExceptionClear(this);\r
+    }\r
+    void FatalError(const char *msg) {\r
+        functions->FatalError(this, msg);\r
+    }\r
+\r
+    jint PushLocalFrame(jint capacity) {\r
+        return functions->PushLocalFrame(this,capacity);\r
+    }\r
+    jobject PopLocalFrame(jobject result) {\r
+        return functions->PopLocalFrame(this,result);\r
+    }\r
+\r
+    jobject NewGlobalRef(jobject lobj) {\r
+        return functions->NewGlobalRef(this,lobj);\r
+    }\r
+    void DeleteGlobalRef(jobject gref) {\r
+        functions->DeleteGlobalRef(this,gref);\r
+    }\r
+    void DeleteLocalRef(jobject obj) {\r
+        functions->DeleteLocalRef(this, obj);\r
+    }\r
+\r
+    jboolean IsSameObject(jobject obj1, jobject obj2) {\r
+        return functions->IsSameObject(this,obj1,obj2);\r
+    }\r
+\r
+    jobject NewLocalRef(jobject ref) {\r
+        return functions->NewLocalRef(this,ref);\r
+    }\r
+    jint EnsureLocalCapacity(jint capacity) {\r
+        return functions->EnsureLocalCapacity(this,capacity);\r
+    }\r
+\r
+    jobject AllocObject(jclass clazz) {\r
+        return functions->AllocObject(this,clazz);\r
+    }\r
+    jobject NewObject(jclass clazz, jmethodID methodID, ...) {\r
+        va_list args;\r
+       jobject result;\r
+       va_start(args, methodID);\r
+        result = functions->NewObjectV(this,clazz,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jobject NewObjectV(jclass clazz, jmethodID methodID,\r
+                      va_list args) {\r
+        return functions->NewObjectV(this,clazz,methodID,args);\r
+    }\r
+    jobject NewObjectA(jclass clazz, jmethodID methodID,\r
+                      const jvalue *args) {\r
+        return functions->NewObjectA(this,clazz,methodID,args);\r
+    }\r
+\r
+    jclass GetObjectClass(jobject obj) {\r
+        return functions->GetObjectClass(this,obj);\r
+    }\r
+    jboolean IsInstanceOf(jobject obj, jclass clazz) {\r
+        return functions->IsInstanceOf(this,obj,clazz);\r
+    }\r
+\r
+    jmethodID GetMethodID(jclass clazz, const char *name,\r
+                         const char *sig) {\r
+        return functions->GetMethodID(this,clazz,name,sig);\r
+    }\r
+\r
+    jobject CallObjectMethod(jobject obj, jmethodID methodID, ...) {\r
+        va_list args;\r
+       jobject result;\r
+       va_start(args,methodID);\r
+       result = functions->CallObjectMethodV(this,obj,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jobject CallObjectMethodV(jobject obj, jmethodID methodID,\r
+                       va_list args) {\r
+        return functions->CallObjectMethodV(this,obj,methodID,args);\r
+    }\r
+    jobject CallObjectMethodA(jobject obj, jmethodID methodID,\r
+                       const jvalue * args) {\r
+        return functions->CallObjectMethodA(this,obj,methodID,args);\r
+    }\r
+\r
+    jboolean CallBooleanMethod(jobject obj,\r
+                              jmethodID methodID, ...) {\r
+        va_list args;\r
+       jboolean result;\r
+       va_start(args,methodID);\r
+       result = functions->CallBooleanMethodV(this,obj,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jboolean CallBooleanMethodV(jobject obj, jmethodID methodID,\r
+                               va_list args) {\r
+        return functions->CallBooleanMethodV(this,obj,methodID,args);\r
+    }\r
+    jboolean CallBooleanMethodA(jobject obj, jmethodID methodID,\r
+                               const jvalue * args) {\r
+        return functions->CallBooleanMethodA(this,obj,methodID, args);\r
+    }\r
+\r
+    jbyte CallByteMethod(jobject obj, jmethodID methodID, ...) {\r
+        va_list args;\r
+       jbyte result;\r
+       va_start(args,methodID);\r
+       result = functions->CallByteMethodV(this,obj,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jbyte CallByteMethodV(jobject obj, jmethodID methodID,\r
+                         va_list args) {\r
+        return functions->CallByteMethodV(this,obj,methodID,args);\r
+    }\r
+    jbyte CallByteMethodA(jobject obj, jmethodID methodID,\r
+                         const jvalue * args) {\r
+        return functions->CallByteMethodA(this,obj,methodID,args);\r
+    }\r
+\r
+    jchar CallCharMethod(jobject obj, jmethodID methodID, ...) {\r
+        va_list args;\r
+       jchar result;\r
+       va_start(args,methodID);\r
+       result = functions->CallCharMethodV(this,obj,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jchar CallCharMethodV(jobject obj, jmethodID methodID,\r
+                         va_list args) {\r
+        return functions->CallCharMethodV(this,obj,methodID,args);\r
+    }\r
+    jchar CallCharMethodA(jobject obj, jmethodID methodID,\r
+                         const jvalue * args) {\r
+        return functions->CallCharMethodA(this,obj,methodID,args);\r
+    }\r
+\r
+    jshort CallShortMethod(jobject obj, jmethodID methodID, ...) {\r
+        va_list args;\r
+       jshort result;\r
+       va_start(args,methodID);\r
+       result = functions->CallShortMethodV(this,obj,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jshort CallShortMethodV(jobject obj, jmethodID methodID,\r
+                           va_list args) {\r
+        return functions->CallShortMethodV(this,obj,methodID,args);\r
+    }\r
+    jshort CallShortMethodA(jobject obj, jmethodID methodID,\r
+                           const jvalue * args) {\r
+        return functions->CallShortMethodA(this,obj,methodID,args);\r
+    }\r
+\r
+    jint CallIntMethod(jobject obj, jmethodID methodID, ...) {\r
+        va_list args;\r
+       jint result;\r
+       va_start(args,methodID);\r
+       result = functions->CallIntMethodV(this,obj,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jint CallIntMethodV(jobject obj, jmethodID methodID,\r
+                       va_list args) {\r
+        return functions->CallIntMethodV(this,obj,methodID,args);\r
+    }\r
+    jint CallIntMethodA(jobject obj, jmethodID methodID,\r
+                       const jvalue * args) {\r
+        return functions->CallIntMethodA(this,obj,methodID,args);\r
+    }\r
+\r
+    jlong CallLongMethod(jobject obj, jmethodID methodID, ...) {\r
+        va_list args;\r
+       jlong result;\r
+       va_start(args,methodID);\r
+       result = functions->CallLongMethodV(this,obj,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jlong CallLongMethodV(jobject obj, jmethodID methodID,\r
+                         va_list args) {\r
+        return functions->CallLongMethodV(this,obj,methodID,args);\r
+    }\r
+    jlong CallLongMethodA(jobject obj, jmethodID methodID,\r
+                         const jvalue * args) {\r
+        return functions->CallLongMethodA(this,obj,methodID,args);\r
+    }\r
+\r
+    jfloat CallFloatMethod(jobject obj, jmethodID methodID, ...) {\r
+        va_list args;\r
+       jfloat result;\r
+       va_start(args,methodID);\r
+       result = functions->CallFloatMethodV(this,obj,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jfloat CallFloatMethodV(jobject obj, jmethodID methodID,\r
+                           va_list args) {\r
+        return functions->CallFloatMethodV(this,obj,methodID,args);\r
+    }\r
+    jfloat CallFloatMethodA(jobject obj, jmethodID methodID,\r
+                           const jvalue * args) {\r
+        return functions->CallFloatMethodA(this,obj,methodID,args);\r
+    }\r
+\r
+    jdouble CallDoubleMethod(jobject obj, jmethodID methodID, ...) {\r
+        va_list args;\r
+       jdouble result;\r
+       va_start(args,methodID);\r
+       result = functions->CallDoubleMethodV(this,obj,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jdouble CallDoubleMethodV(jobject obj, jmethodID methodID,\r
+                       va_list args) {\r
+        return functions->CallDoubleMethodV(this,obj,methodID,args);\r
+    }\r
+    jdouble CallDoubleMethodA(jobject obj, jmethodID methodID,\r
+                       const jvalue * args) {\r
+        return functions->CallDoubleMethodA(this,obj,methodID,args);\r
+    }\r
+\r
+    void CallVoidMethod(jobject obj, jmethodID methodID, ...) {\r
+        va_list args;\r
+       va_start(args,methodID);\r
+       functions->CallVoidMethodV(this,obj,methodID,args);\r
+       va_end(args);\r
+    }\r
+    void CallVoidMethodV(jobject obj, jmethodID methodID,\r
+                        va_list args) {\r
+        functions->CallVoidMethodV(this,obj,methodID,args);\r
+    }\r
+    void CallVoidMethodA(jobject obj, jmethodID methodID,\r
+                        const jvalue * args) {\r
+        functions->CallVoidMethodA(this,obj,methodID,args);\r
+    }\r
+\r
+    jobject CallNonvirtualObjectMethod(jobject obj, jclass clazz,\r
+                                      jmethodID methodID, ...) {\r
+        va_list args;\r
+       jobject result;\r
+       va_start(args,methodID);\r
+       result = functions->CallNonvirtualObjectMethodV(this,obj,clazz,\r
+                                                       methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jobject CallNonvirtualObjectMethodV(jobject obj, jclass clazz,\r
+                                       jmethodID methodID, va_list args) {\r
+        return functions->CallNonvirtualObjectMethodV(this,obj,clazz,\r
+                                                     methodID,args);\r
+    }\r
+    jobject CallNonvirtualObjectMethodA(jobject obj, jclass clazz,\r
+                                       jmethodID methodID, const jvalue * args) {\r
+        return functions->CallNonvirtualObjectMethodA(this,obj,clazz,\r
+                                                     methodID,args);\r
+    }\r
+\r
+    jboolean CallNonvirtualBooleanMethod(jobject obj, jclass clazz,\r
+                                        jmethodID methodID, ...) {\r
+        va_list args;\r
+       jboolean result;\r
+       va_start(args,methodID);\r
+       result = functions->CallNonvirtualBooleanMethodV(this,obj,clazz,\r
+                                                        methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jboolean CallNonvirtualBooleanMethodV(jobject obj, jclass clazz,\r
+                                         jmethodID methodID, va_list args) {\r
+        return functions->CallNonvirtualBooleanMethodV(this,obj,clazz,\r
+                                                      methodID,args);\r
+    }\r
+    jboolean CallNonvirtualBooleanMethodA(jobject obj, jclass clazz,\r
+                                         jmethodID methodID, const jvalue * args) {\r
+        return functions->CallNonvirtualBooleanMethodA(this,obj,clazz,\r
+                                                      methodID, args);\r
+    }\r
+\r
+    jbyte CallNonvirtualByteMethod(jobject obj, jclass clazz,\r
+                                  jmethodID methodID, ...) {\r
+        va_list args;\r
+       jbyte result;\r
+       va_start(args,methodID);\r
+       result = functions->CallNonvirtualByteMethodV(this,obj,clazz,\r
+                                                     methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jbyte CallNonvirtualByteMethodV(jobject obj, jclass clazz,\r
+                                   jmethodID methodID, va_list args) {\r
+        return functions->CallNonvirtualByteMethodV(this,obj,clazz,\r
+                                                   methodID,args);\r
+    }\r
+    jbyte CallNonvirtualByteMethodA(jobject obj, jclass clazz,\r
+                                   jmethodID methodID, const jvalue * args) {\r
+        return functions->CallNonvirtualByteMethodA(this,obj,clazz,\r
+                                                   methodID,args);\r
+    }\r
+\r
+    jchar CallNonvirtualCharMethod(jobject obj, jclass clazz,\r
+                                  jmethodID methodID, ...) {\r
+        va_list args;\r
+       jchar result;\r
+       va_start(args,methodID);\r
+       result = functions->CallNonvirtualCharMethodV(this,obj,clazz,\r
+                                                     methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jchar CallNonvirtualCharMethodV(jobject obj, jclass clazz,\r
+                                   jmethodID methodID, va_list args) {\r
+        return functions->CallNonvirtualCharMethodV(this,obj,clazz,\r
+                                                   methodID,args);\r
+    }\r
+    jchar CallNonvirtualCharMethodA(jobject obj, jclass clazz,\r
+                                   jmethodID methodID, const jvalue * args) {\r
+        return functions->CallNonvirtualCharMethodA(this,obj,clazz,\r
+                                                   methodID,args);\r
+    }\r
+\r
+    jshort CallNonvirtualShortMethod(jobject obj, jclass clazz,\r
+                                    jmethodID methodID, ...) {\r
+        va_list args;\r
+       jshort result;\r
+       va_start(args,methodID);\r
+       result = functions->CallNonvirtualShortMethodV(this,obj,clazz,\r
+                                                      methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jshort CallNonvirtualShortMethodV(jobject obj, jclass clazz,\r
+                                     jmethodID methodID, va_list args) {\r
+        return functions->CallNonvirtualShortMethodV(this,obj,clazz,\r
+                                                    methodID,args);\r
+    }\r
+    jshort CallNonvirtualShortMethodA(jobject obj, jclass clazz,\r
+                                     jmethodID methodID, const jvalue * args) {\r
+        return functions->CallNonvirtualShortMethodA(this,obj,clazz,\r
+                                                    methodID,args);\r
+    }\r
+\r
+    jint CallNonvirtualIntMethod(jobject obj, jclass clazz,\r
+                                jmethodID methodID, ...) {\r
+        va_list args;\r
+       jint result;\r
+       va_start(args,methodID);\r
+       result = functions->CallNonvirtualIntMethodV(this,obj,clazz,\r
+                                                    methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jint CallNonvirtualIntMethodV(jobject obj, jclass clazz,\r
+                                 jmethodID methodID, va_list args) {\r
+        return functions->CallNonvirtualIntMethodV(this,obj,clazz,\r
+                                                  methodID,args);\r
+    }\r
+    jint CallNonvirtualIntMethodA(jobject obj, jclass clazz,\r
+                                 jmethodID methodID, const jvalue * args) {\r
+        return functions->CallNonvirtualIntMethodA(this,obj,clazz,\r
+                                                  methodID,args);\r
+    }\r
+\r
+    jlong CallNonvirtualLongMethod(jobject obj, jclass clazz,\r
+                                  jmethodID methodID, ...) {\r
+        va_list args;\r
+       jlong result;\r
+       va_start(args,methodID);\r
+       result = functions->CallNonvirtualLongMethodV(this,obj,clazz,\r
+                                                     methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jlong CallNonvirtualLongMethodV(jobject obj, jclass clazz,\r
+                                   jmethodID methodID, va_list args) {\r
+        return functions->CallNonvirtualLongMethodV(this,obj,clazz,\r
+                                                   methodID,args);\r
+    }\r
+    jlong CallNonvirtualLongMethodA(jobject obj, jclass clazz,\r
+                                   jmethodID methodID, const jvalue * args) {\r
+        return functions->CallNonvirtualLongMethodA(this,obj,clazz,\r
+                                                   methodID,args);\r
+    }\r
+\r
+    jfloat CallNonvirtualFloatMethod(jobject obj, jclass clazz,\r
+                                    jmethodID methodID, ...) {\r
+        va_list args;\r
+       jfloat result;\r
+       va_start(args,methodID);\r
+       result = functions->CallNonvirtualFloatMethodV(this,obj,clazz,\r
+                                                      methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jfloat CallNonvirtualFloatMethodV(jobject obj, jclass clazz,\r
+                                     jmethodID methodID,\r
+                                     va_list args) {\r
+        return functions->CallNonvirtualFloatMethodV(this,obj,clazz,\r
+                                                    methodID,args);\r
+    }\r
+    jfloat CallNonvirtualFloatMethodA(jobject obj, jclass clazz,\r
+                                     jmethodID methodID,\r
+                                     const jvalue * args) {\r
+        return functions->CallNonvirtualFloatMethodA(this,obj,clazz,\r
+                                                    methodID,args);\r
+    }\r
+\r
+    jdouble CallNonvirtualDoubleMethod(jobject obj, jclass clazz,\r
+                                      jmethodID methodID, ...) {\r
+        va_list args;\r
+       jdouble result;\r
+       va_start(args,methodID);\r
+       result = functions->CallNonvirtualDoubleMethodV(this,obj,clazz,\r
+                                                       methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jdouble CallNonvirtualDoubleMethodV(jobject obj, jclass clazz,\r
+                                       jmethodID methodID,\r
+                                       va_list args) {\r
+        return functions->CallNonvirtualDoubleMethodV(this,obj,clazz,\r
+                                                     methodID,args);\r
+    }\r
+    jdouble CallNonvirtualDoubleMethodA(jobject obj, jclass clazz,\r
+                                       jmethodID methodID,\r
+                                       const jvalue * args) {\r
+        return functions->CallNonvirtualDoubleMethodA(this,obj,clazz,\r
+                                                     methodID,args);\r
+    }\r
+\r
+    void CallNonvirtualVoidMethod(jobject obj, jclass clazz,\r
+                                 jmethodID methodID, ...) {\r
+        va_list args;\r
+       va_start(args,methodID);\r
+       functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);\r
+       va_end(args);\r
+    }\r
+    void CallNonvirtualVoidMethodV(jobject obj, jclass clazz,\r
+                                  jmethodID methodID,\r
+                                  va_list args) {\r
+        functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);\r
+    }\r
+    void CallNonvirtualVoidMethodA(jobject obj, jclass clazz,\r
+                                  jmethodID methodID,\r
+                                  const jvalue * args) {\r
+        functions->CallNonvirtualVoidMethodA(this,obj,clazz,methodID,args);\r
+    }\r
+\r
+    jfieldID GetFieldID(jclass clazz, const char *name,\r
+                       const char *sig) {\r
+        return functions->GetFieldID(this,clazz,name,sig);\r
+    }\r
+\r
+    jobject GetObjectField(jobject obj, jfieldID fieldID) {\r
+        return functions->GetObjectField(this,obj,fieldID);\r
+    }\r
+    jboolean GetBooleanField(jobject obj, jfieldID fieldID) {\r
+        return functions->GetBooleanField(this,obj,fieldID);\r
+    }\r
+    jbyte GetByteField(jobject obj, jfieldID fieldID) {\r
+        return functions->GetByteField(this,obj,fieldID);\r
+    }\r
+    jchar GetCharField(jobject obj, jfieldID fieldID) {\r
+        return functions->GetCharField(this,obj,fieldID);\r
+    }\r
+    jshort GetShortField(jobject obj, jfieldID fieldID) {\r
+        return functions->GetShortField(this,obj,fieldID);\r
+    }\r
+    jint GetIntField(jobject obj, jfieldID fieldID) {\r
+        return functions->GetIntField(this,obj,fieldID);\r
+    }\r
+    jlong GetLongField(jobject obj, jfieldID fieldID) {\r
+        return functions->GetLongField(this,obj,fieldID);\r
+    }\r
+    jfloat GetFloatField(jobject obj, jfieldID fieldID) {\r
+        return functions->GetFloatField(this,obj,fieldID);\r
+    }\r
+    jdouble GetDoubleField(jobject obj, jfieldID fieldID) {\r
+        return functions->GetDoubleField(this,obj,fieldID);\r
+    }\r
+\r
+    void SetObjectField(jobject obj, jfieldID fieldID, jobject val) {\r
+        functions->SetObjectField(this,obj,fieldID,val);\r
+    }\r
+    void SetBooleanField(jobject obj, jfieldID fieldID,\r
+                        jboolean val) {\r
+        functions->SetBooleanField(this,obj,fieldID,val);\r
+    }\r
+    void SetByteField(jobject obj, jfieldID fieldID,\r
+                     jbyte val) {\r
+        functions->SetByteField(this,obj,fieldID,val);\r
+    }\r
+    void SetCharField(jobject obj, jfieldID fieldID,\r
+                     jchar val) {\r
+        functions->SetCharField(this,obj,fieldID,val);\r
+    }\r
+    void SetShortField(jobject obj, jfieldID fieldID,\r
+                      jshort val) {\r
+        functions->SetShortField(this,obj,fieldID,val);\r
+    }\r
+    void SetIntField(jobject obj, jfieldID fieldID,\r
+                    jint val) {\r
+        functions->SetIntField(this,obj,fieldID,val);\r
+    }\r
+    void SetLongField(jobject obj, jfieldID fieldID,\r
+                     jlong val) {\r
+        functions->SetLongField(this,obj,fieldID,val);\r
+    }\r
+    void SetFloatField(jobject obj, jfieldID fieldID,\r
+                      jfloat val) {\r
+        functions->SetFloatField(this,obj,fieldID,val);\r
+    }\r
+    void SetDoubleField(jobject obj, jfieldID fieldID,\r
+                       jdouble val) {\r
+        functions->SetDoubleField(this,obj,fieldID,val);\r
+    }\r
+\r
+    jmethodID GetStaticMethodID(jclass clazz, const char *name,\r
+                               const char *sig) {\r
+        return functions->GetStaticMethodID(this,clazz,name,sig);\r
+    }\r
+\r
+    jobject CallStaticObjectMethod(jclass clazz, jmethodID methodID,\r
+                            ...) {\r
+        va_list args;\r
+       jobject result;\r
+       va_start(args,methodID);\r
+       result = functions->CallStaticObjectMethodV(this,clazz,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jobject CallStaticObjectMethodV(jclass clazz, jmethodID methodID,\r
+                             va_list args) {\r
+        return functions->CallStaticObjectMethodV(this,clazz,methodID,args);\r
+    }\r
+    jobject CallStaticObjectMethodA(jclass clazz, jmethodID methodID,\r
+                             const jvalue *args) {\r
+        return functions->CallStaticObjectMethodA(this,clazz,methodID,args);\r
+    }\r
+\r
+    jboolean CallStaticBooleanMethod(jclass clazz,\r
+                                    jmethodID methodID, ...) {\r
+        va_list args;\r
+       jboolean result;\r
+       va_start(args,methodID);\r
+       result = functions->CallStaticBooleanMethodV(this,clazz,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jboolean CallStaticBooleanMethodV(jclass clazz,\r
+                                     jmethodID methodID, va_list args) {\r
+        return functions->CallStaticBooleanMethodV(this,clazz,methodID,args);\r
+    }\r
+    jboolean CallStaticBooleanMethodA(jclass clazz,\r
+                                     jmethodID methodID, const jvalue *args) {\r
+        return functions->CallStaticBooleanMethodA(this,clazz,methodID,args);\r
+    }\r
+\r
+    jbyte CallStaticByteMethod(jclass clazz,\r
+                              jmethodID methodID, ...) {\r
+        va_list args;\r
+       jbyte result;\r
+       va_start(args,methodID);\r
+       result = functions->CallStaticByteMethodV(this,clazz,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jbyte CallStaticByteMethodV(jclass clazz,\r
+                               jmethodID methodID, va_list args) {\r
+        return functions->CallStaticByteMethodV(this,clazz,methodID,args);\r
+    }\r
+    jbyte CallStaticByteMethodA(jclass clazz,\r
+                               jmethodID methodID, const jvalue *args) {\r
+        return functions->CallStaticByteMethodA(this,clazz,methodID,args);\r
+    }\r
+\r
+    jchar CallStaticCharMethod(jclass clazz,\r
+                              jmethodID methodID, ...) {\r
+        va_list args;\r
+       jchar result;\r
+       va_start(args,methodID);\r
+       result = functions->CallStaticCharMethodV(this,clazz,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jchar CallStaticCharMethodV(jclass clazz,\r
+                               jmethodID methodID, va_list args) {\r
+        return functions->CallStaticCharMethodV(this,clazz,methodID,args);\r
+    }\r
+    jchar CallStaticCharMethodA(jclass clazz,\r
+                               jmethodID methodID, const jvalue *args) {\r
+        return functions->CallStaticCharMethodA(this,clazz,methodID,args);\r
+    }\r
+\r
+    jshort CallStaticShortMethod(jclass clazz,\r
+                                jmethodID methodID, ...) {\r
+        va_list args;\r
+       jshort result;\r
+       va_start(args,methodID);\r
+       result = functions->CallStaticShortMethodV(this,clazz,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jshort CallStaticShortMethodV(jclass clazz,\r
+                                 jmethodID methodID, va_list args) {\r
+        return functions->CallStaticShortMethodV(this,clazz,methodID,args);\r
+    }\r
+    jshort CallStaticShortMethodA(jclass clazz,\r
+                                 jmethodID methodID, const jvalue *args) {\r
+        return functions->CallStaticShortMethodA(this,clazz,methodID,args);\r
+    }\r
+\r
+    jint CallStaticIntMethod(jclass clazz,\r
+                            jmethodID methodID, ...) {\r
+        va_list args;\r
+       jint result;\r
+       va_start(args,methodID);\r
+       result = functions->CallStaticIntMethodV(this,clazz,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jint CallStaticIntMethodV(jclass clazz,\r
+                             jmethodID methodID, va_list args) {\r
+        return functions->CallStaticIntMethodV(this,clazz,methodID,args);\r
+    }\r
+    jint CallStaticIntMethodA(jclass clazz,\r
+                             jmethodID methodID, const jvalue *args) {\r
+        return functions->CallStaticIntMethodA(this,clazz,methodID,args);\r
+    }\r
+\r
+    jlong CallStaticLongMethod(jclass clazz,\r
+                              jmethodID methodID, ...) {\r
+        va_list args;\r
+       jlong result;\r
+       va_start(args,methodID);\r
+       result = functions->CallStaticLongMethodV(this,clazz,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jlong CallStaticLongMethodV(jclass clazz,\r
+                               jmethodID methodID, va_list args) {\r
+        return functions->CallStaticLongMethodV(this,clazz,methodID,args);\r
+    }\r
+    jlong CallStaticLongMethodA(jclass clazz,\r
+                               jmethodID methodID, const jvalue *args) {\r
+        return functions->CallStaticLongMethodA(this,clazz,methodID,args);\r
+    }\r
+\r
+    jfloat CallStaticFloatMethod(jclass clazz,\r
+                                jmethodID methodID, ...) {\r
+        va_list args;\r
+       jfloat result;\r
+       va_start(args,methodID);\r
+       result = functions->CallStaticFloatMethodV(this,clazz,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jfloat CallStaticFloatMethodV(jclass clazz,\r
+                                 jmethodID methodID, va_list args) {\r
+        return functions->CallStaticFloatMethodV(this,clazz,methodID,args);\r
+    }\r
+    jfloat CallStaticFloatMethodA(jclass clazz,\r
+                                 jmethodID methodID, const jvalue *args) {\r
+        return functions->CallStaticFloatMethodA(this,clazz,methodID,args);\r
+    }\r
+\r
+    jdouble CallStaticDoubleMethod(jclass clazz,\r
+                                  jmethodID methodID, ...) {\r
+        va_list args;\r
+       jdouble result;\r
+       va_start(args,methodID);\r
+       result = functions->CallStaticDoubleMethodV(this,clazz,methodID,args);\r
+       va_end(args);\r
+       return result;\r
+    }\r
+    jdouble CallStaticDoubleMethodV(jclass clazz,\r
+                                   jmethodID methodID, va_list args) {\r
+        return functions->CallStaticDoubleMethodV(this,clazz,methodID,args);\r
+    }\r
+    jdouble CallStaticDoubleMethodA(jclass clazz,\r
+                                   jmethodID methodID, const jvalue *args) {\r
+        return functions->CallStaticDoubleMethodA(this,clazz,methodID,args);\r
+    }\r
+\r
+    void CallStaticVoidMethod(jclass cls, jmethodID methodID, ...) {\r
+        va_list args;\r
+       va_start(args,methodID);\r
+       functions->CallStaticVoidMethodV(this,cls,methodID,args);\r
+       va_end(args);\r
+    }\r
+    void CallStaticVoidMethodV(jclass cls, jmethodID methodID,\r
+                              va_list args) {\r
+        functions->CallStaticVoidMethodV(this,cls,methodID,args);\r
+    }\r
+    void CallStaticVoidMethodA(jclass cls, jmethodID methodID,\r
+                              const jvalue * args) {\r
+        functions->CallStaticVoidMethodA(this,cls,methodID,args);\r
+    }\r
+\r
+    jfieldID GetStaticFieldID(jclass clazz, const char *name,\r
+                             const char *sig) {\r
+        return functions->GetStaticFieldID(this,clazz,name,sig);\r
+    }\r
+    jobject GetStaticObjectField(jclass clazz, jfieldID fieldID) {\r
+        return functions->GetStaticObjectField(this,clazz,fieldID);\r
+    }\r
+    jboolean GetStaticBooleanField(jclass clazz, jfieldID fieldID) {\r
+        return functions->GetStaticBooleanField(this,clazz,fieldID);\r
+    }\r
+    jbyte GetStaticByteField(jclass clazz, jfieldID fieldID) {\r
+        return functions->GetStaticByteField(this,clazz,fieldID);\r
+    }\r
+    jchar GetStaticCharField(jclass clazz, jfieldID fieldID) {\r
+        return functions->GetStaticCharField(this,clazz,fieldID);\r
+    }\r
+    jshort GetStaticShortField(jclass clazz, jfieldID fieldID) {\r
+        return functions->GetStaticShortField(this,clazz,fieldID);\r
+    }\r
+    jint GetStaticIntField(jclass clazz, jfieldID fieldID) {\r
+        return functions->GetStaticIntField(this,clazz,fieldID);\r
+    }\r
+    jlong GetStaticLongField(jclass clazz, jfieldID fieldID) {\r
+        return functions->GetStaticLongField(this,clazz,fieldID);\r
+    }\r
+    jfloat GetStaticFloatField(jclass clazz, jfieldID fieldID) {\r
+        return functions->GetStaticFloatField(this,clazz,fieldID);\r
+    }\r
+    jdouble GetStaticDoubleField(jclass clazz, jfieldID fieldID) {\r
+        return functions->GetStaticDoubleField(this,clazz,fieldID);\r
+    }\r
+\r
+    void SetStaticObjectField(jclass clazz, jfieldID fieldID,\r
+                       jobject value) {\r
+      functions->SetStaticObjectField(this,clazz,fieldID,value);\r
+    }\r
+    void SetStaticBooleanField(jclass clazz, jfieldID fieldID,\r
+                       jboolean value) {\r
+      functions->SetStaticBooleanField(this,clazz,fieldID,value);\r
+    }\r
+    void SetStaticByteField(jclass clazz, jfieldID fieldID,\r
+                       jbyte value) {\r
+      functions->SetStaticByteField(this,clazz,fieldID,value);\r
+    }\r
+    void SetStaticCharField(jclass clazz, jfieldID fieldID,\r
+                       jchar value) {\r
+      functions->SetStaticCharField(this,clazz,fieldID,value);\r
+    }\r
+    void SetStaticShortField(jclass clazz, jfieldID fieldID,\r
+                       jshort value) {\r
+      functions->SetStaticShortField(this,clazz,fieldID,value);\r
+    }\r
+    void SetStaticIntField(jclass clazz, jfieldID fieldID,\r
+                       jint value) {\r
+      functions->SetStaticIntField(this,clazz,fieldID,value);\r
+    }\r
+    void SetStaticLongField(jclass clazz, jfieldID fieldID,\r
+                       jlong value) {\r
+      functions->SetStaticLongField(this,clazz,fieldID,value);\r
+    }\r
+    void SetStaticFloatField(jclass clazz, jfieldID fieldID,\r
+                       jfloat value) {\r
+      functions->SetStaticFloatField(this,clazz,fieldID,value);\r
+    }\r
+    void SetStaticDoubleField(jclass clazz, jfieldID fieldID,\r
+                       jdouble value) {\r
+      functions->SetStaticDoubleField(this,clazz,fieldID,value);\r
+    }\r
+\r
+    jstring NewString(const jchar *unicode, jsize len) {\r
+        return functions->NewString(this,unicode,len);\r
+    }\r
+    jsize GetStringLength(jstring str) {\r
+        return functions->GetStringLength(this,str);\r
+    }\r
+    const jchar *GetStringChars(jstring str, jboolean *isCopy) {\r
+        return functions->GetStringChars(this,str,isCopy);\r
+    }\r
+    void ReleaseStringChars(jstring str, const jchar *chars) {\r
+        functions->ReleaseStringChars(this,str,chars);\r
+    }\r
+\r
+    jstring NewStringUTF(const char *utf) {\r
+        return functions->NewStringUTF(this,utf);\r
+    }\r
+    jsize GetStringUTFLength(jstring str) {\r
+        return functions->GetStringUTFLength(this,str);\r
+    }\r
+    const char* GetStringUTFChars(jstring str, jboolean *isCopy) {\r
+        return functions->GetStringUTFChars(this,str,isCopy);\r
+    }\r
+    void ReleaseStringUTFChars(jstring str, const char* chars) {\r
+        functions->ReleaseStringUTFChars(this,str,chars);\r
+    }\r
+\r
+    jsize GetArrayLength(jarray array) {\r
+        return functions->GetArrayLength(this,array);\r
+    }\r
+\r
+    jobjectArray NewObjectArray(jsize len, jclass clazz,\r
+                               jobject init) {\r
+        return functions->NewObjectArray(this,len,clazz,init);\r
+    }\r
+    jobject GetObjectArrayElement(jobjectArray array, jsize index) {\r
+        return functions->GetObjectArrayElement(this,array,index);\r
+    }\r
+    void SetObjectArrayElement(jobjectArray array, jsize index,\r
+                              jobject val) {\r
+        functions->SetObjectArrayElement(this,array,index,val);\r
+    }\r
+\r
+    jbooleanArray NewBooleanArray(jsize len) {\r
+        return functions->NewBooleanArray(this,len);\r
+    }\r
+    jbyteArray NewByteArray(jsize len) {\r
+        return functions->NewByteArray(this,len);\r
+    }\r
+    jcharArray NewCharArray(jsize len) {\r
+        return functions->NewCharArray(this,len);\r
+    }\r
+    jshortArray NewShortArray(jsize len) {\r
+        return functions->NewShortArray(this,len);\r
+    }\r
+    jintArray NewIntArray(jsize len) {\r
+        return functions->NewIntArray(this,len);\r
+    }\r
+    jlongArray NewLongArray(jsize len) {\r
+        return functions->NewLongArray(this,len);\r
+    }\r
+    jfloatArray NewFloatArray(jsize len) {\r
+        return functions->NewFloatArray(this,len);\r
+    }\r
+    jdoubleArray NewDoubleArray(jsize len) {\r
+        return functions->NewDoubleArray(this,len);\r
+    }\r
+\r
+    jboolean * GetBooleanArrayElements(jbooleanArray array, jboolean *isCopy) {\r
+        return functions->GetBooleanArrayElements(this,array,isCopy);\r
+    }\r
+    jbyte * GetByteArrayElements(jbyteArray array, jboolean *isCopy) {\r
+        return functions->GetByteArrayElements(this,array,isCopy);\r
+    }\r
+    jchar * GetCharArrayElements(jcharArray array, jboolean *isCopy) {\r
+        return functions->GetCharArrayElements(this,array,isCopy);\r
+    }\r
+    jshort * GetShortArrayElements(jshortArray array, jboolean *isCopy) {\r
+        return functions->GetShortArrayElements(this,array,isCopy);\r
+    }\r
+    jint * GetIntArrayElements(jintArray array, jboolean *isCopy) {\r
+        return functions->GetIntArrayElements(this,array,isCopy);\r
+    }\r
+    jlong * GetLongArrayElements(jlongArray array, jboolean *isCopy) {\r
+        return functions->GetLongArrayElements(this,array,isCopy);\r
+    }\r
+    jfloat * GetFloatArrayElements(jfloatArray array, jboolean *isCopy) {\r
+        return functions->GetFloatArrayElements(this,array,isCopy);\r
+    }\r
+    jdouble * GetDoubleArrayElements(jdoubleArray array, jboolean *isCopy) {\r
+        return functions->GetDoubleArrayElements(this,array,isCopy);\r
+    }\r
+\r
+    void ReleaseBooleanArrayElements(jbooleanArray array,\r
+                                    jboolean *elems,\r
+                                    jint mode) {\r
+        functions->ReleaseBooleanArrayElements(this,array,elems,mode);\r
+    }\r
+    void ReleaseByteArrayElements(jbyteArray array,\r
+                                 jbyte *elems,\r
+                                 jint mode) {\r
+        functions->ReleaseByteArrayElements(this,array,elems,mode);\r
+    }\r
+    void ReleaseCharArrayElements(jcharArray array,\r
+                                 jchar *elems,\r
+                                 jint mode) {\r
+        functions->ReleaseCharArrayElements(this,array,elems,mode);\r
+    }\r
+    void ReleaseShortArrayElements(jshortArray array,\r
+                                  jshort *elems,\r
+                                  jint mode) {\r
+        functions->ReleaseShortArrayElements(this,array,elems,mode);\r
+    }\r
+    void ReleaseIntArrayElements(jintArray array,\r
+                                jint *elems,\r
+                                jint mode) {\r
+        functions->ReleaseIntArrayElements(this,array,elems,mode);\r
+    }\r
+    void ReleaseLongArrayElements(jlongArray array,\r
+                                 jlong *elems,\r
+                                 jint mode) {\r
+        functions->ReleaseLongArrayElements(this,array,elems,mode);\r
+    }\r
+    void ReleaseFloatArrayElements(jfloatArray array,\r
+                                  jfloat *elems,\r
+                                  jint mode) {\r
+        functions->ReleaseFloatArrayElements(this,array,elems,mode);\r
+    }\r
+    void ReleaseDoubleArrayElements(jdoubleArray array,\r
+                                   jdouble *elems,\r
+                                   jint mode) {\r
+        functions->ReleaseDoubleArrayElements(this,array,elems,mode);\r
+    }\r
+\r
+    void GetBooleanArrayRegion(jbooleanArray array,\r
+                              jsize start, jsize len, jboolean *buf) {\r
+        functions->GetBooleanArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void GetByteArrayRegion(jbyteArray array,\r
+                           jsize start, jsize len, jbyte *buf) {\r
+        functions->GetByteArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void GetCharArrayRegion(jcharArray array,\r
+                           jsize start, jsize len, jchar *buf) {\r
+        functions->GetCharArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void GetShortArrayRegion(jshortArray array,\r
+                            jsize start, jsize len, jshort *buf) {\r
+        functions->GetShortArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void GetIntArrayRegion(jintArray array,\r
+                          jsize start, jsize len, jint *buf) {\r
+        functions->GetIntArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void GetLongArrayRegion(jlongArray array,\r
+                           jsize start, jsize len, jlong *buf) {\r
+        functions->GetLongArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void GetFloatArrayRegion(jfloatArray array,\r
+                            jsize start, jsize len, jfloat *buf) {\r
+        functions->GetFloatArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void GetDoubleArrayRegion(jdoubleArray array,\r
+                             jsize start, jsize len, jdouble *buf) {\r
+        functions->GetDoubleArrayRegion(this,array,start,len,buf);\r
+    }\r
+\r
+    void SetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len,\r
+                              const jboolean *buf) {\r
+        functions->SetBooleanArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void SetByteArrayRegion(jbyteArray array, jsize start, jsize len,\r
+                           const jbyte *buf) {\r
+        functions->SetByteArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void SetCharArrayRegion(jcharArray array, jsize start, jsize len,\r
+                           const jchar *buf) {\r
+        functions->SetCharArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void SetShortArrayRegion(jshortArray array, jsize start, jsize len,\r
+                            const jshort *buf) {\r
+        functions->SetShortArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void SetIntArrayRegion(jintArray array, jsize start, jsize len,\r
+                          const jint *buf) {\r
+        functions->SetIntArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void SetLongArrayRegion(jlongArray array, jsize start, jsize len,\r
+                           const jlong *buf) {\r
+        functions->SetLongArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void SetFloatArrayRegion(jfloatArray array, jsize start, jsize len,\r
+                            const jfloat *buf) {\r
+        functions->SetFloatArrayRegion(this,array,start,len,buf);\r
+    }\r
+    void SetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len,\r
+                             const jdouble *buf) {\r
+        functions->SetDoubleArrayRegion(this,array,start,len,buf);\r
+    }\r
+\r
+    jint RegisterNatives(jclass clazz, const JNINativeMethod *methods,\r
+                        jint nMethods) {\r
+        return functions->RegisterNatives(this,clazz,methods,nMethods);\r
+    }\r
+    jint UnregisterNatives(jclass clazz) {\r
+        return functions->UnregisterNatives(this,clazz);\r
+    }\r
+\r
+    jint MonitorEnter(jobject obj) {\r
+        return functions->MonitorEnter(this,obj);\r
+    }\r
+    jint MonitorExit(jobject obj) {\r
+        return functions->MonitorExit(this,obj);\r
+    }\r
+\r
+    jint GetJavaVM(JavaVM **vm) {\r
+        return functions->GetJavaVM(this,vm);\r
+    }\r
+\r
+    void GetStringRegion(jstring str, jsize start, jsize len, jchar *buf) {\r
+        functions->GetStringRegion(this,str,start,len,buf);\r
+    }\r
+    void GetStringUTFRegion(jstring str, jsize start, jsize len, char *buf) {\r
+        functions->GetStringUTFRegion(this,str,start,len,buf);\r
+    }\r
+\r
+    void * GetPrimitiveArrayCritical(jarray array, jboolean *isCopy) {\r
+        return functions->GetPrimitiveArrayCritical(this,array,isCopy);\r
+    }\r
+    void ReleasePrimitiveArrayCritical(jarray array, void *carray, jint mode) {\r
+        functions->ReleasePrimitiveArrayCritical(this,array,carray,mode);\r
+    }\r
+\r
+    const jchar * GetStringCritical(jstring string, jboolean *isCopy) {\r
+        return functions->GetStringCritical(this,string,isCopy);\r
+    }\r
+    void ReleaseStringCritical(jstring string, const jchar *cstring) {\r
+        functions->ReleaseStringCritical(this,string,cstring);\r
+    }\r
+\r
+    jweak NewWeakGlobalRef(jobject obj) {\r
+        return functions->NewWeakGlobalRef(this,obj);\r
+    }\r
+    void DeleteWeakGlobalRef(jweak ref) {\r
+        functions->DeleteWeakGlobalRef(this,ref);\r
+    }\r
+\r
+    jboolean ExceptionCheck() {\r
+       return functions->ExceptionCheck(this);\r
+    }\r
+\r
+    jobject NewDirectByteBuffer(void* address, jlong capacity) {\r
+        return functions->NewDirectByteBuffer(this, address, capacity);\r
+    }\r
+    void* GetDirectBufferAddress(jobject buf) {\r
+        return functions->GetDirectBufferAddress(this, buf);\r
+    }\r
+    jlong GetDirectBufferCapacity(jobject buf) {\r
+        return functions->GetDirectBufferCapacity(this, buf);\r
+    }\r
+\r
+#endif /* __cplusplus */\r
+};\r
+\r
+typedef struct JavaVMOption {\r
+    char *optionString;\r
+    void *extraInfo;\r
+} JavaVMOption;\r
+\r
+typedef struct JavaVMInitArgs {\r
+    jint version;\r
+\r
+    jint nOptions;\r
+    JavaVMOption *options;\r
+    jboolean ignoreUnrecognized;\r
+} JavaVMInitArgs;\r
+\r
+typedef struct JavaVMAttachArgs {\r
+    jint version;\r
+\r
+    char *name;\r
+    jobject group;\r
+} JavaVMAttachArgs;\r
+\r
+/* These structures will be VM-specific. */\r
+\r
+typedef struct JDK1_1InitArgs {\r
+    jint version;\r
+\r
+    char **properties;\r
+    jint checkSource;\r
+    jint nativeStackSize;\r
+    jint javaStackSize;\r
+    jint minHeapSize;\r
+    jint maxHeapSize;\r
+    jint verifyMode;\r
+    char *classpath;\r
+\r
+    jint (JNICALL *vfprintf)(FILE *fp, const char *format, va_list args);\r
+    void (JNICALL *exit)(jint code);\r
+    void (JNICALL *abort)(void);\r
+\r
+    jint enableClassGC;\r
+    jint enableVerboseGC;\r
+    jint disableAsyncGC;\r
+    jint verbose;\r
+    jboolean debugging;\r
+    jint debugPort;\r
+} JDK1_1InitArgs;\r
+\r
+typedef struct JDK1_1AttachArgs {\r
+    void * __padding; /* C compilers don't allow empty structures. */\r
+} JDK1_1AttachArgs;\r
+\r
+#define JDK1_2\r
+#define JDK1_4\r
+\r
+/* End VM-specific. */\r
+\r
+struct JNIInvokeInterface_ {\r
+    void *reserved0;\r
+    void *reserved1;\r
+    void *reserved2;\r
+\r
+    jint (JNICALL *DestroyJavaVM)(JavaVM *vm);\r
+\r
+    jint (JNICALL *AttachCurrentThread)(JavaVM *vm, void **penv, void *args);\r
+\r
+    jint (JNICALL *DetachCurrentThread)(JavaVM *vm);\r
+\r
+    jint (JNICALL *GetEnv)(JavaVM *vm, void **penv, jint version);\r
+\r
+    jint (JNICALL *AttachCurrentThreadAsDaemon)(JavaVM *vm, void **penv, void *args);\r
+};\r
+\r
+struct JavaVM_ {\r
+    const struct JNIInvokeInterface_ *functions;\r
+#ifdef __cplusplus\r
+\r
+    jint DestroyJavaVM() {\r
+        return functions->DestroyJavaVM(this);\r
+    }\r
+    jint AttachCurrentThread(void **penv, void *args) {\r
+        return functions->AttachCurrentThread(this, penv, args);\r
+    }\r
+    jint DetachCurrentThread() {\r
+        return functions->DetachCurrentThread(this);\r
+    }\r
+\r
+    jint GetEnv(void **penv, jint version) {\r
+        return functions->GetEnv(this, penv, version);\r
+    }\r
+    jint AttachCurrentThreadAsDaemon(void **penv, void *args) {\r
+        return functions->AttachCurrentThreadAsDaemon(this, penv, args);\r
+    }\r
+#endif\r
+};\r
+\r
+#ifdef _JNI_IMPLEMENTATION_\r
+#define _JNI_IMPORT_OR_EXPORT_ JNIEXPORT\r
+#else\r
+#define _JNI_IMPORT_OR_EXPORT_ JNIIMPORT\r
+#endif\r
+_JNI_IMPORT_OR_EXPORT_ jint JNICALL\r
+JNI_GetDefaultJavaVMInitArgs(void *args);\r
+\r
+_JNI_IMPORT_OR_EXPORT_ jint JNICALL\r
+JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args);\r
+\r
+_JNI_IMPORT_OR_EXPORT_ jint JNICALL\r
+JNI_GetCreatedJavaVMs(JavaVM **, jsize, jsize *);\r
+\r
+/* Defined by native libraries. */\r
+JNIEXPORT jint JNICALL\r
+JNI_OnLoad(JavaVM *vm, void *reserved);\r
+\r
+JNIEXPORT void JNICALL\r
+JNI_OnUnload(JavaVM *vm, void *reserved);\r
+\r
+#define JNI_VERSION_1_1 0x00010001\r
+#define JNI_VERSION_1_2 0x00010002\r
+#define JNI_VERSION_1_4 0x00010004\r
+\r
+#ifdef __cplusplus\r
+} /* extern "C" */\r
+#endif /* __cplusplus */\r
+\r
+#endif /* !_JAVASOFT_JNI_H_ */\r
diff --git a/applications/JavaOpenJPEG/java-jni/include/jvmdi.h b/applications/JavaOpenJPEG/java-jni/include/jvmdi.h
new file mode 100644 (file)
index 0000000..d39c4a9
--- /dev/null
@@ -0,0 +1,1012 @@
+/*\r
+ * @(#)jvmdi.h 1.48 03/12/19\r
+ *\r
+ * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
+ * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
+ */\r
+\r
+/*\r
+ *   Java Virtual Machine Debug Interface\r
+ *\r
+ *   Defines debugging functionality that a VM should provide.  \r
+ *\r
+ *   Should not overlap functionality in jni.h\r
+ */\r
+\r
+#ifndef _JAVASOFT_JVMDI_H_\r
+#define _JAVASOFT_JVMDI_H_\r
+\r
+#include "jni.h"\r
+\r
+#define JVMDI_VERSION_1    0x20010000\r
+#define JVMDI_VERSION_1_1  0x20010001\r
+#define JVMDI_VERSION_1_2  0x20010002\r
+#define JVMDI_VERSION_1_3  0x20010003\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+typedef jobject jthread;\r
+\r
+typedef jobject jthreadGroup;\r
+\r
+struct _jframeID;\r
+typedef struct _jframeID *jframeID;\r
+\r
+  /* specifies program location "pc" - often byte code index */\r
+typedef jlong jlocation;\r
+\r
+  /* The jmethodID for methods that have been replaced */\r
+  /* via RedefineClasses - used when the implementation */\r
+  /* does not wish to retain replaced jmethodIDs */\r
+#define OBSOLETE_METHOD_ID ((jmethodID)(NULL))\r
+\r
+  /*\r
+   *  Errors\r
+   */\r
+\r
+typedef jint jvmdiError;\r
+\r
+  /* no error */\r
+#define JVMDI_ERROR_NONE                 ((jvmdiError)0)\r
+\r
+  /*\r
+   * Errors on thread operations\r
+   */\r
+\r
+  /* invalid thread */\r
+#define JVMDI_ERROR_INVALID_THREAD       ((jvmdiError)10)\r
+  /* invalid thread group */\r
+#define JVMDI_ERROR_INVALID_THREAD_GROUP ((jvmdiError)11)\r
+  /* invalid thread priority */\r
+#define JVMDI_ERROR_INVALID_PRIORITY     ((jvmdiError)12)\r
+  /* thread not suspended */\r
+#define JVMDI_ERROR_THREAD_NOT_SUSPENDED ((jvmdiError)13)\r
+  /* thread already suspended */\r
+#define JVMDI_ERROR_THREAD_SUSPENDED     ((jvmdiError)14)\r
+\r
+  /* \r
+   * Errors on object and class operations\r
+   */\r
+\r
+  /* invalid object (implementation not required to gracefully catch) */\r
+#define JVMDI_ERROR_INVALID_OBJECT       ((jvmdiError)20)\r
+  /* invalid class (implementation not required to gracefully catch) */\r
+#define JVMDI_ERROR_INVALID_CLASS        ((jvmdiError)21)\r
+  /* class not prepared */\r
+#define JVMDI_ERROR_CLASS_NOT_PREPARED   ((jvmdiError)22)\r
+  /* invalid methodID (implementation not required to gracefully catch) */\r
+#define JVMDI_ERROR_INVALID_METHODID     ((jvmdiError)23)\r
+  /* invalid location */\r
+#define JVMDI_ERROR_INVALID_LOCATION     ((jvmdiError)24)\r
+  /* invalid fieldID (implementation not required to gracefully catch) */\r
+#define JVMDI_ERROR_INVALID_FIELDID      ((jvmdiError)25)\r
+\r
+  /*\r
+   * Errors on frame operations\r
+   */\r
+\r
+  /* invalid frameID (implementation not required to gracefully catch) */\r
+#define JVMDI_ERROR_INVALID_FRAMEID      ((jvmdiError)30)\r
+  /* there are no more frames on the stack */\r
+#define JVMDI_ERROR_NO_MORE_FRAMES       ((jvmdiError)31)\r
+  /* operation cannot be performed on this frame */\r
+#define JVMDI_ERROR_OPAQUE_FRAME         ((jvmdiError)32)\r
+  /* operation can only be performed on current frame */\r
+#define JVMDI_ERROR_NOT_CURRENT_FRAME    ((jvmdiError)33)\r
+  /* type mismatch (implementation not required to gracefully catch) */\r
+#define JVMDI_ERROR_TYPE_MISMATCH        ((jvmdiError)34)\r
+  /* invalid slot */\r
+#define JVMDI_ERROR_INVALID_SLOT         ((jvmdiError)35)\r
+\r
+  /*\r
+   * Errors on set/clear/find operations\r
+   */\r
+\r
+  /* item already present */\r
+#define JVMDI_ERROR_DUPLICATE            ((jvmdiError)40)\r
+  /* item not found */\r
+#define JVMDI_ERROR_NOT_FOUND            ((jvmdiError)41)\r
+\r
+  /*\r
+   * Errors on monitor operations\r
+   */\r
+\r
+  /* invalid monitor */\r
+#define JVMDI_ERROR_INVALID_MONITOR      ((jvmdiError)50)\r
+  /* wait, notify, notify all tried without entering monitor  */\r
+#define JVMDI_ERROR_NOT_MONITOR_OWNER    ((jvmdiError)51)\r
+  /* waiting thread interrupted */\r
+#define JVMDI_ERROR_INTERRUPT            ((jvmdiError)52)\r
+  \r
+  /*\r
+   * Class redefinition / operand stack errors\r
+   */\r
+\r
+  /* The equivalent of ClassFormatError */\r
+#define JVMDI_ERROR_INVALID_CLASS_FORMAT          ((jvmdiError)60)\r
+  /* The equivalent of ClassCircularityError */\r
+#define JVMDI_ERROR_CIRCULAR_CLASS_DEFINITION     ((jvmdiError)61)\r
+  /* The class bytes fail verification */\r
+#define JVMDI_ERROR_FAILS_VERIFICATION            ((jvmdiError)62)\r
+  /* The new class version adds new methods */\r
+  /* and can_add_method is false */\r
+#define JVMDI_ERROR_ADD_METHOD_NOT_IMPLEMENTED    ((jvmdiError)63)\r
+  /* The new class version changes fields */ \r
+  /* and can_unrestrictedly_redefine_classes is false */\r
+#define JVMDI_ERROR_SCHEMA_CHANGE_NOT_IMPLEMENTED ((jvmdiError)64)\r
+  /* bci/operand stack/local var combination is not verifiably */\r
+  /* type safe */\r
+#define JVMDI_ERROR_INVALID_TYPESTATE             ((jvmdiError)65)\r
+  /* A direct superclass is different for the new class */\r
+  /* version, or the set of directly implemented */\r
+  /* interfaces is different */\r
+  /* and can_unrestrictedly_redefine_classes is false */\r
+#define JVMDI_ERROR_HIERARCHY_CHANGE_NOT_IMPLEMENTED ((jvmdiError)66)\r
+  /* The new class version does not declare a method */\r
+  /* declared in the old class version */\r
+  /* and can_unrestrictedly_redefine_classes is false */\r
+#define JVMDI_ERROR_DELETE_METHOD_NOT_IMPLEMENTED ((jvmdiError)67)\r
+  /* A class file has a version number not supported */\r
+  /* by this VM. */\r
+#define JVMDI_ERROR_UNSUPPORTED_VERSION           ((jvmdiError)68)\r
+  /* The class name defined in the new class file is */\r
+  /* different from the name in the old class object */\r
+#define JVMDI_ERROR_NAMES_DONT_MATCH              ((jvmdiError)69)\r
+  /* The new class version has different modifiers and */\r
+  /* can_unrestrictedly_redefine_classes is false */\r
+#define JVMDI_ERROR_CLASS_MODIFIERS_CHANGE_NOT_IMPLEMENTED   ((jvmdiError)70)\r
+  /* A method in the new class version has different modifiers */\r
+  /* than its counterpart in the old class version */\r
+  /* and can_unrestrictedly_redefine_classes is false */\r
+#define JVMDI_ERROR_METHOD_MODIFIERS_CHANGE_NOT_IMPLEMENTED  ((jvmdiError)71)\r
+\r
+  /*\r
+   * Miscellaneous errors\r
+   */\r
+\r
+  /* Not yet implemented */\r
+#define JVMDI_ERROR_NOT_IMPLEMENTED      ((jvmdiError)99)\r
+  /* null pointer */\r
+#define JVMDI_ERROR_NULL_POINTER         ((jvmdiError)100)\r
+  /* information is absent */\r
+#define JVMDI_ERROR_ABSENT_INFORMATION   ((jvmdiError)101)\r
+  /* invalid event type  */\r
+#define JVMDI_ERROR_INVALID_EVENT_TYPE   ((jvmdiError)102)\r
+  /* invalid argument  */\r
+#define JVMDI_ERROR_ILLEGAL_ARGUMENT     ((jvmdiError)103)\r
+\r
+  /*\r
+   * Universal errors. These errors may be returned by\r
+   * any JVMDI function, not just the ones for which they are listed\r
+   * below.\r
+   */\r
+\r
+  /* no more memory available for allocation */\r
+#define JVMDI_ERROR_OUT_OF_MEMORY        ((jvmdiError)110)\r
+  /* debugging has not been enabled in this VM */\r
+#define JVMDI_ERROR_ACCESS_DENIED        ((jvmdiError)111)\r
+  /* VM is dead (implementation not required to gracefully catch) */\r
+#define JVMDI_ERROR_VM_DEAD              ((jvmdiError)112)\r
+  /* internal error  */\r
+#define JVMDI_ERROR_INTERNAL             ((jvmdiError)113)\r
+  /* Thread calling JVMDI function not attached to VM */\r
+#define JVMDI_ERROR_UNATTACHED_THREAD    ((jvmdiError)115)\r
+\r
+\r
+  /*\r
+   *  Threads\r
+   */\r
+\r
+  /* Thread status is unknown */\r
+#define JVMDI_THREAD_STATUS_UNKNOWN      ((jint)-1)\r
+  /* Thread is waiting to die */\r
+#define JVMDI_THREAD_STATUS_ZOMBIE       ((jint)0)\r
+  /* Thread is runnable */\r
+#define JVMDI_THREAD_STATUS_RUNNING      ((jint)1)\r
+  /* Thread is sleeping - Thread.sleep() or JVM_Sleep() was called */\r
+#define JVMDI_THREAD_STATUS_SLEEPING     ((jint)2)\r
+  /* Thread is waiting on a java monitor */\r
+#define JVMDI_THREAD_STATUS_MONITOR      ((jint)3)\r
+  /* Thread is waiting - Thread.wait() or JVM_MonitorWait() was called */\r
+#define JVMDI_THREAD_STATUS_WAIT         ((jint)4)\r
+\r
+  /* Thread is suspended - Thread.suspend(), JVM_Suspend() or\r
+   * JVMDI_Suspend was called */\r
+#define JVMDI_SUSPEND_STATUS_SUSPENDED   ((jint)0x1)\r
+  /* Thread is at a breakpoint */\r
+#define JVMDI_SUSPEND_STATUS_BREAK       ((jint)0x2)\r
+\r
+\r
+  /* Thread priority constants */\r
+#define JVMDI_THREAD_MIN_PRIORITY   ((jint)1)\r
+#define JVMDI_THREAD_NORM_PRIORITY  ((jint)5)\r
+#define JVMDI_THREAD_MAX_PRIORITY   ((jint)10)\r
+\r
+typedef struct {\r
+    char *name;\r
+    jint  priority;\r
+    jboolean is_daemon;\r
+    jthreadGroup thread_group;\r
+    jobject context_class_loader;\r
+} JVMDI_thread_info;\r
+\r
+typedef struct {\r
+    jthreadGroup parent;\r
+    char *name;\r
+    jint  max_priority;\r
+    jboolean is_daemon;\r
+} JVMDI_thread_group_info;\r
+\r
+#define JVMDI_DISABLE ((jint) 0)\r
+#define JVMDI_ENABLE  ((jint) 1)\r
+\r
+/*\r
+ * Initial function for debug threads created through JVMDI\r
+ */\r
+typedef void (*JVMDI_StartFunction)(void *);\r
+\r
+/*\r
+ * Type for debug monitors created through JVMDI\r
+ */\r
+typedef void *JVMDI_RawMonitor;\r
+\r
+#define JVMDI_MONITOR_WAIT_FOREVER ((jlong)(-1))\r
+\r
+/*\r
+ * Monitor information\r
+ */\r
+typedef struct {\r
+    jthread owner;\r
+    jint entry_count;\r
+    jint waiter_count;\r
+    jthread *waiters;\r
+} JVMDI_monitor_info;\r
+\r
+typedef struct {\r
+    jint owned_monitor_count;\r
+    jobject *owned_monitors;\r
+} JVMDI_owned_monitor_info;\r
+\r
+  /*\r
+   *  Events\r
+   */\r
+\r
+    /* kind = JVMDI_EVENT_SINGLE_STEP */\r
+    typedef struct { \r
+        jthread thread;\r
+        jclass clazz;\r
+        jmethodID method;\r
+        jlocation location;\r
+    } JVMDI_single_step_event_data;\r
+                       \r
+    /* kind = JVMDI_EVENT_BREAKPOINT */\r
+    typedef struct { \r
+        jthread thread;\r
+        jclass clazz;\r
+        jmethodID method;\r
+        jlocation location;\r
+    } JVMDI_breakpoint_event_data;\r
+    \r
+    /* kind = JVMDI_EVENT_FIELD_ACCESS */\r
+    typedef struct { \r
+        jthread thread;\r
+        jclass clazz;\r
+        jmethodID method;\r
+        jlocation location;\r
+        jclass field_clazz;\r
+        jobject object;\r
+        jfieldID field;\r
+    } JVMDI_field_access_event_data;\r
+    \r
+    /* kind = JVMDI_EVENT_FIELD_MODIFICATION */\r
+    typedef struct { \r
+        jthread thread;\r
+        jclass clazz;\r
+        jmethodID method;\r
+        jlocation location;\r
+        jclass field_clazz;\r
+        jobject object;\r
+        jfieldID field;\r
+        char signature_type;\r
+        jvalue new_value;\r
+    } JVMDI_field_modification_event_data;\r
+    \r
+    /* kind = JVMDI_EVENT_FRAME_POP */\r
+    /* kind = JVMDI_EVENT_METHOD_ENTRY */\r
+    /* kind = JVMDI_EVENT_METHOD_EXIT */\r
+    typedef struct { \r
+        jthread thread;\r
+        jclass clazz;\r
+        jmethodID method;\r
+        jframeID frame;\r
+    } JVMDI_frame_event_data;\r
+    \r
+    /* kind = JVMDI_EVENT_EXCEPTION */\r
+    typedef struct { \r
+        jthread thread;\r
+        jclass clazz;\r
+        jmethodID method;\r
+        jlocation location;\r
+        jobject exception;\r
+        jclass catch_clazz;\r
+        jmethodID catch_method;\r
+        jlocation catch_location;\r
+    } JVMDI_exception_event_data;\r
+    \r
+    /* kind = JVMDI_EVENT_EXCEPTION_CATCH */\r
+    typedef struct { \r
+        jthread thread;\r
+        jclass clazz;\r
+        jmethodID method;\r
+        jlocation location;\r
+        jobject exception;\r
+    } JVMDI_exception_catch_event_data;\r
+    \r
+    /* kind = JVMDI_EVENT_USER_DEFINED */\r
+    typedef struct { \r
+        jobject object;\r
+        jint key;\r
+    } JVMDI_user_event_data;\r
+    \r
+    /* kind = JVMDI_EVENT_THREAD_END or */\r
+    /* JVMDI_EVENT_THREAD_START */\r
+    typedef struct { \r
+        jthread thread;\r
+    } JVMDI_thread_change_event_data;\r
+    \r
+    /* kind = JVMDI_EVENT_CLASS_LOAD, */\r
+    /* JVMDI_EVENT_CLASS_UNLOAD, or */\r
+    /* JVMDI_EVENT_CLASS_PREPARE */\r
+    typedef struct { \r
+        jthread thread;\r
+        jclass clazz;\r
+    } JVMDI_class_event_data;\r
+    \r
+/* This stucture passes information about the event.\r
+ * location is the index of the last instruction executed. \r
+ */\r
+typedef struct {\r
+    jint kind;         /* the discriminant */\r
+\r
+    union {\r
+       /* kind = JVMDI_EVENT_SINGLE_STEP */\r
+        JVMDI_single_step_event_data single_step;\r
+                       \r
+        /* kind = JVMDI_EVENT_BREAKPOINT */\r
+        JVMDI_breakpoint_event_data breakpoint;\r
+\r
+        /* kind = JVMDI_EVENT_FRAME_POP */\r
+        /* kind = JVMDI_EVENT_METHOD_ENTRY */\r
+        /* kind = JVMDI_EVENT_METHOD_EXIT */\r
+        JVMDI_frame_event_data frame;\r
+\r
+        /* kind = JVMDI_EVENT_FIELD_ACCESS */\r
+        JVMDI_field_access_event_data field_access;\r
+\r
+        /* kind = JVMDI_EVENT_FIELD_MODIFICATION */\r
+        JVMDI_field_modification_event_data field_modification;\r
+\r
+        /* kind = JVMDI_EVENT_EXCEPTION */\r
+        JVMDI_exception_event_data exception;\r
+\r
+        /* kind = JVMDI_EVENT_EXCEPTION_CATCH */\r
+        JVMDI_exception_catch_event_data exception_catch;\r
+\r
+        /* kind = JVMDI_EVENT_USER_DEFINED */\r
+        JVMDI_user_event_data user;\r
+                       \r
+        /* kind = JVMDI_EVENT_THREAD_END or */\r
+        /* JVMDI_EVENT_THREAD_START */\r
+        JVMDI_thread_change_event_data thread_change;\r
+                       \r
+        /* kind = JVMDI_EVENT_CLASS_LOAD, */\r
+        /* JVMDI_EVENT_CLASS_UNLOAD, or */\r
+        /* JVMDI_EVENT_CLASS_PREPARE */\r
+        JVMDI_class_event_data class_event;\r
+                       \r
+        /* kind = JVMDI_EVENT_VM_DEATH, JVMDI_EVENT_VM_INIT */\r
+        /* no additional fields */             \r
+    } u;\r
+} JVMDI_Event;\r
+\r
+       /*** event kinds ***/\r
+#define JVMDI_EVENT_SINGLE_STEP   ((jint)1)\r
+#define JVMDI_EVENT_BREAKPOINT    ((jint)2)\r
+#define JVMDI_EVENT_FRAME_POP     ((jint)3)\r
+#define JVMDI_EVENT_EXCEPTION     ((jint)4)\r
+#define JVMDI_EVENT_USER_DEFINED  ((jint)5)\r
+#define JVMDI_EVENT_THREAD_START  ((jint)6)\r
+#define JVMDI_EVENT_THREAD_END    ((jint)7)\r
+#define JVMDI_EVENT_CLASS_PREPARE ((jint)8)\r
+#define JVMDI_EVENT_CLASS_UNLOAD  ((jint)9)\r
+#define JVMDI_EVENT_CLASS_LOAD    ((jint)10)\r
+#define JVMDI_EVENT_FIELD_ACCESS       ((jint)20)\r
+#define JVMDI_EVENT_FIELD_MODIFICATION ((jint)21)\r
+#define JVMDI_EVENT_EXCEPTION_CATCH    ((jint)30)\r
+#define JVMDI_EVENT_METHOD_ENTRY       ((jint)40)\r
+#define JVMDI_EVENT_METHOD_EXIT        ((jint)41)\r
+#define JVMDI_EVENT_VM_INIT            ((jint)90)\r
+#define JVMDI_EVENT_VM_DEATH           ((jint)99)\r
+\r
+#define JVMDI_MAX_EVENT_TYPE_VAL       ((jint)99)\r
+\r
+\r
+\r
+/* event handler hook */\r
+typedef void (*JVMDI_EventHook)(JNIEnv *env, JVMDI_Event *event);\r
+\r
+typedef jvmdiError (*JVMDI_AllocHook) (jlong size, jbyte** memPtr);\r
+typedef jvmdiError (*JVMDI_DeallocHook) (jbyte* buffer);\r
+\r
+/*\r
+ * Class states used in JVMDI_GetClassStatus\r
+ */\r
+#define JVMDI_CLASS_STATUS_VERIFIED          ((jint)0x01)\r
+#define JVMDI_CLASS_STATUS_PREPARED          ((jint)0x02)\r
+#define JVMDI_CLASS_STATUS_INITIALIZED       ((jint)0x04)\r
+ /* Error prevents initialization */\r
+#define JVMDI_CLASS_STATUS_ERROR             ((jint)0x08) \r
+\r
+/* structure for returning line number information \r
+ */\r
+typedef struct {\r
+    jlocation start_location;\r
+    jint line_number;\r
+} JVMDI_line_number_entry;\r
+\r
+\r
+/* structure for returning local variable information \r
+ */\r
+typedef struct {\r
+    jlocation start_location;   /* variable valid start_location */\r
+    jint length;                /* upto start_location+length */ \r
+    char *name;                 /* name in UTF8 */\r
+    char *signature;            /* type signature in UTF8 */\r
+    jint slot;                  /* variable slot, see JVMDI_GetLocal*()  */\r
+} JVMDI_local_variable_entry;\r
+\r
+/* structure for returning exception handler information \r
+ */\r
+typedef struct {\r
+    jlocation start_location;\r
+    jlocation end_location;\r
+    jlocation handler_location;\r
+    jclass exception;           /* if null, all exceptions */\r
+} JVMDI_exception_handler_entry;\r
+\r
+#define JVMDI_OPERAND_TYPE_REFERENCE      ((jint)1)\r
+#define JVMDI_OPERAND_TYPE_INT            ((jint)2)\r
+#define JVMDI_OPERAND_TYPE_FLOAT          ((jint)3)\r
+#define JVMDI_OPERAND_TYPE_LONG0          ((jint)4) /* least sig. 32 bits */\r
+#define JVMDI_OPERAND_TYPE_LONG1          ((jint)5) /* most sig. 32 bits */\r
+#define JVMDI_OPERAND_TYPE_DOUBLE0        ((jint)6) /* least sig. 32 bits */\r
+#define JVMDI_OPERAND_TYPE_DOUBLE1        ((jint)7) /* most sig. 32 bits */\r
+#define JVMDI_OPERAND_TYPE_RETURN_ADDRESS ((jint)8)\r
+\r
+typedef struct {\r
+    jint word;                 /* 32 bit operand stack quantities */\r
+    jint type;                 /* type encoding of the operand word */\r
+                               /* one of JVMDI_OPERAND_TYPE_* */\r
+} JVMDI_operand_stack_element;\r
+\r
+typedef struct { \r
+    jint instance_field_count; /* number of instance fields referencing obj */\r
+    struct JVMDI_instance_field {\r
+        jobject instance;      /* instance referencing obj */\r
+        jfieldID field;        /* field holding reference */\r
+    } *instance_fields;        /* instanceField_count of them */\r
+     \r
+    jint static_field_count;   /* number of static fields referencing obj */\r
+    struct JVMDI_static_field {\r
+        jclass clazz;          /* class referencing obj */\r
+        jfieldID static_field; /* field holding reference */\r
+    } *static_fields;          /* static_field_count of them */\r
+    \r
+    jint array_element_count;  /* number of array elements referencing obj */\r
+    struct JVMDI_array_element {\r
+        jobjectArray array;    /* array referencing obj */\r
+        jint index;            /* index holding reference */\r
+    } *array_elements;         /* array_element_count of them */\r
+    \r
+    jint frame_slot_count;     /* number of frame slots referencing obj */\r
+    struct JVMDI_frame_slot {\r
+        jthread thread;        /* thread of the frame */\r
+        jframeID frame;        /* frame referencing obj */\r
+        jint slot;             /* slot holding reference */\r
+    } *frame_slots;            /* frame_slot_count of them */\r
+} JVMDI_object_reference_info;\r
+\r
+/* structure for defining a class\r
+*/\r
+typedef struct {\r
+    jclass clazz;              /* Class object for this class */\r
+    jint class_byte_count;     /* number of bytes defining class (below) */\r
+    jbyte *class_bytes;        /* bytes defining class (in JVM spec */\r
+                               /* Class File Format) */\r
+} JVMDI_class_definition;\r
+\r
+  /* For backwards compatibility */\r
+#define can_change_schema can_unrestrictedly_redefine_classes\r
+\r
+typedef struct {\r
+    unsigned int can_watch_field_modification      : 1;\r
+    unsigned int can_watch_field_access            : 1;\r
+    unsigned int can_get_bytecodes                 : 1;\r
+    unsigned int can_get_synthetic_attribute       : 1;\r
+    unsigned int can_get_owned_monitor_info        : 1;\r
+    unsigned int can_get_current_contended_monitor : 1;\r
+    unsigned int can_get_monitor_info              : 1;\r
+    unsigned int can_get_heap_info                 : 1;\r
+    unsigned int can_get_operand_stack             : 1;\r
+    unsigned int can_set_operand_stack             : 1;\r
+    unsigned int can_pop_frame                     : 1;\r
+    unsigned int can_get_class_definition          : 1;\r
+    unsigned int can_redefine_classes              : 1; \r
+    unsigned int can_add_method                    : 1;\r
+    unsigned int can_unrestrictedly_redefine_classes : 1;\r
+    unsigned int can_suspend_resume_thread_lists   : 1;\r
+} JVMDI_capabilities;\r
+\r
+typedef struct JVMDI_Interface_1_ {\r
+    jvmdiError (JNICALL *SetEventHook)\r
+      (JVMDI_EventHook hook);\r
+    jvmdiError (JNICALL *SetEventNotificationMode)\r
+      (jint mode, jint eventType, jthread thread, ...);\r
+\r
+    jvmdiError (JNICALL *GetThreadStatus)\r
+      (jthread thread,\r
+       jint *threadStatusPtr, jint *suspendStatusPtr);\r
+    jvmdiError (JNICALL *GetAllThreads)\r
+      (jint *threadsCountPtr, jthread **threadsPtr);\r
+    jvmdiError (JNICALL *SuspendThread)\r
+      (jthread thread); \r
+    jvmdiError (JNICALL *ResumeThread)\r
+      (jthread thread);\r
+    jvmdiError (JNICALL *StopThread)\r
+      (jthread thread, jobject exception);\r
+    jvmdiError (JNICALL *InterruptThread)\r
+      (jthread thread);\r
+    jvmdiError (JNICALL *GetThreadInfo)\r
+      (jthread thread, JVMDI_thread_info *infoPtr);\r
+    jvmdiError (JNICALL *GetOwnedMonitorInfo)\r
+      (jthread thread, JVMDI_owned_monitor_info *infoPtr);\r
+    jvmdiError (JNICALL *GetCurrentContendedMonitor)\r
+      (jthread thread, jobject *monitor);\r
+    jvmdiError (JNICALL *RunDebugThread)\r
+      (jthread thread, JVMDI_StartFunction proc, void *arg,\r
+       int priority);\r
+\r
+    jvmdiError (JNICALL *GetTopThreadGroups)\r
+      (jint *groupCountPtr, jthreadGroup **groupsPtr);\r
+    jvmdiError (JNICALL *GetThreadGroupInfo)\r
+      (jthreadGroup group, JVMDI_thread_group_info *infoPtr);\r
+    jvmdiError (JNICALL *GetThreadGroupChildren)\r
+      (jthreadGroup group, \r
+       jint *threadCountPtr, jthread **threadsPtr,\r
+       jint *groupCountPtr, jthreadGroup **groupsPtr);\r
+\r
+    jvmdiError (JNICALL *GetFrameCount)\r
+      (jthread thread, jint *countPtr);\r
+    jvmdiError (JNICALL *GetCurrentFrame)\r
+      (jthread thread, jframeID *framePtr);\r
+    jvmdiError (JNICALL *GetCallerFrame)\r
+      (jframeID called, jframeID *framePtr);\r
+    jvmdiError (JNICALL *GetFrameLocation)\r
+      (jframeID frame, jclass *classPtr, jmethodID *methodPtr,\r
+       jlocation *locationPtr);\r
+    jvmdiError (JNICALL *NotifyFramePop)\r
+      (jframeID frame); \r
+    jvmdiError (JNICALL *GetLocalObject)\r
+      (jframeID frame, jint slot, jobject *valuePtr);\r
+    jvmdiError (JNICALL *GetLocalInt)\r
+      (jframeID frame, jint slot, jint *valuePtr);\r
+    jvmdiError (JNICALL *GetLocalLong)\r
+      (jframeID frame, jint slot, jlong *valuePtr);\r
+    jvmdiError (JNICALL *GetLocalFloat)\r
+      (jframeID frame, jint slot, jfloat *valuePtr);\r
+    jvmdiError (JNICALL *GetLocalDouble)\r
+      (jframeID frame, jint slot, jdouble *valuePtr);\r
+    jvmdiError (JNICALL *SetLocalObject)\r
+      (jframeID frame, jint slot, jobject value);\r
+    jvmdiError (JNICALL *SetLocalInt)\r
+      (jframeID frame, jint slot, jint value);\r
+    jvmdiError (JNICALL *SetLocalLong)\r
+      (jframeID frame, jint slot, jlong value);\r
+    jvmdiError (JNICALL *SetLocalFloat)\r
+      (jframeID frame, jint slot, jfloat value);\r
+    jvmdiError (JNICALL *SetLocalDouble)\r
+      (jframeID frame, jint slot, jdouble value);\r
+\r
+    jvmdiError (JNICALL *CreateRawMonitor)\r
+      (char *name, JVMDI_RawMonitor *monitorPtr);\r
+    jvmdiError (JNICALL *DestroyRawMonitor)\r
+      (JVMDI_RawMonitor monitor);\r
+    jvmdiError (JNICALL *RawMonitorEnter)\r
+      (JVMDI_RawMonitor monitor);\r
+    jvmdiError (JNICALL *RawMonitorExit)\r
+      (JVMDI_RawMonitor monitor);\r
+    jvmdiError (JNICALL *RawMonitorWait)\r
+      (JVMDI_RawMonitor monitor, jlong millis);\r
+    jvmdiError (JNICALL *RawMonitorNotify)\r
+      (JVMDI_RawMonitor monitor);\r
+    jvmdiError (JNICALL *RawMonitorNotifyAll)\r
+      (JVMDI_RawMonitor monitor);\r
+\r
+    jvmdiError (JNICALL *SetBreakpoint)\r
+      (jclass clazz, jmethodID method, jlocation location);\r
+    jvmdiError (JNICALL *ClearBreakpoint)\r
+      (jclass clazz, jmethodID method, jlocation location);\r
+    jvmdiError (JNICALL *ClearAllBreakpoints)\r
+      ();\r
+\r
+    jvmdiError (JNICALL *SetFieldAccessWatch)\r
+      (jclass clazz, jfieldID field);\r
+    jvmdiError (JNICALL *ClearFieldAccessWatch)\r
+      (jclass clazz, jfieldID field);\r
+    jvmdiError (JNICALL *SetFieldModificationWatch)\r
+      (jclass clazz, jfieldID field);\r
+    jvmdiError (JNICALL *ClearFieldModificationWatch)\r
+      (jclass clazz, jfieldID field);\r
+\r
+    jvmdiError (JNICALL *SetAllocationHooks)\r
+      (JVMDI_AllocHook ahook, JVMDI_DeallocHook dhook);\r
+    jvmdiError (JNICALL *Allocate)\r
+      (jlong size, jbyte** memPtr);\r
+    jvmdiError (JNICALL *Deallocate)\r
+      (jbyte* mem);\r
+\r
+    jvmdiError (JNICALL *GetClassSignature)\r
+      (jclass clazz, char **sigPtr);\r
+    jvmdiError (JNICALL *GetClassStatus)\r
+      (jclass clazz, jint *statusPtr);\r
+    jvmdiError (JNICALL *GetSourceFileName)\r
+      (jclass clazz, char **sourceNamePtr);\r
+    jvmdiError (JNICALL *GetClassModifiers)\r
+      (jclass clazz, jint *modifiersPtr);\r
+    jvmdiError (JNICALL *GetClassMethods)\r
+      (jclass clazz, jint *methodCountPtr, jmethodID **methodsPtr);\r
+    jvmdiError (JNICALL *GetClassFields)\r
+       (jclass clazz, jint *fieldCountPtr, jfieldID **fieldsPtr);\r
+    jvmdiError (JNICALL *GetImplementedInterfaces)\r
+      (jclass clazz, jint *interfaceCountPtr, jclass **interfacesPtr);\r
+    jvmdiError (JNICALL *IsInterface)\r
+      (jclass clazz, jboolean *isInterfacePtr);\r
+    jvmdiError (JNICALL *IsArrayClass)\r
+      (jclass clazz, jboolean *isArrayClassPtr);\r
+    jvmdiError (JNICALL *GetClassLoader)\r
+      (jclass clazz, jobject *classloaderPtr);\r
+\r
+    jvmdiError (JNICALL *GetObjectHashCode)\r
+      (jobject object, jint *hashCodePtr);\r
+    jvmdiError (JNICALL *GetMonitorInfo)\r
+      (jobject object, JVMDI_monitor_info *infoPtr);\r
+\r
+    jvmdiError (JNICALL *GetFieldName)\r
+      (jclass clazz, jfieldID field, char **namePtr, char **signaturePtr);\r
+    jvmdiError (JNICALL *GetFieldDeclaringClass)\r
+      (jclass clazz, jfieldID field, jclass *declaringClassPtr);\r
+    jvmdiError (JNICALL *GetFieldModifiers)\r
+      (jclass clazz, jfieldID field, jint *modifiersPtr);\r
+    jvmdiError (JNICALL *IsFieldSynthetic)\r
+      (jclass clazz, jfieldID field, jboolean *isSyntheticPtr);\r
+\r
+    jvmdiError (JNICALL *GetMethodName)\r
+      (jclass clazz, jmethodID method, \r
+       char **namePtr, char **signaturePtr);\r
+    jvmdiError (JNICALL *GetMethodDeclaringClass)\r
+      (jclass clazz, jmethodID method, jclass *declaringClassPtr);\r
+    jvmdiError (JNICALL *GetMethodModifiers)\r
+      (jclass clazz, jmethodID method, jint *modifiersPtr);\r
+    jvmdiError (JNICALL *GetMaxStack)\r
+      (jclass clazz, jmethodID method, jint *maxPtr);\r
+    jvmdiError (JNICALL *GetMaxLocals)\r
+      (jclass clazz, jmethodID method, jint *maxPtr);\r
+    jvmdiError (JNICALL *GetArgumentsSize)\r
+      (jclass clazz, jmethodID method, jint *sizePtr);\r
+    jvmdiError (JNICALL *GetLineNumberTable)\r
+      (jclass clazz, jmethodID method,\r
+       jint *entryCountPtr, JVMDI_line_number_entry **tablePtr);\r
+    jvmdiError (JNICALL *GetMethodLocation)\r
+      (jclass clazz, jmethodID method,\r
+       jlocation *startLocationPtr, jlocation *endLocationPtr);\r
+    jvmdiError (JNICALL *GetLocalVariableTable)\r
+      (jclass clazz, jmethodID method,\r
+       jint *entryCountPtr, JVMDI_local_variable_entry **tablePtr);\r
+    jvmdiError (JNICALL *GetExceptionHandlerTable)\r
+      (jclass clazz, jmethodID method,\r
+       jint *entryCountPtr, JVMDI_exception_handler_entry **tablePtr);\r
+    jvmdiError (JNICALL *GetThrownExceptions)\r
+      (jclass clazz, jmethodID method,\r
+       jint *exceptionCountPtr, jclass **exceptionsPtr);\r
+    jvmdiError (JNICALL *GetBytecodes)\r
+      (jclass clazz, jmethodID method,\r
+       jint *bytecodeCountPtr, jbyte **bytecodesPtr);\r
+    jvmdiError (JNICALL *IsMethodNative)\r
+      (jclass clazz, jmethodID method, jboolean *isNativePtr);\r
+    jvmdiError (JNICALL *IsMethodSynthetic)\r
+      (jclass clazz, jmethodID method, jboolean *isSyntheticPtr);\r
+\r
+    jvmdiError (JNICALL *GetLoadedClasses)\r
+      (jint *classCountPtr, jclass **classesPtr);\r
+    jvmdiError (JNICALL *GetClassLoaderClasses)\r
+      (jobject initiatingLoader, jint *classesCountPtr, \r
+       jclass **classesPtr);\r
+\r
+    jvmdiError (JNICALL *PopFrame)\r
+      (jthread thread);\r
+    jvmdiError (JNICALL *SetFrameLocation)\r
+      (jframeID frame, jlocation location);\r
+    jvmdiError (JNICALL *GetOperandStack)\r
+      (jframeID frame, jint *operandStackSizePtr, \r
+       JVMDI_operand_stack_element **operandStackPtr);\r
+    jvmdiError (JNICALL *SetOperandStack)\r
+      (jframeID frame, jint operandStackSize, \r
+       JVMDI_operand_stack_element *operandStack);\r
+    jvmdiError (JNICALL *AllInstances)\r
+      (jclass clazz, jint *instanceCountPtr, jobject **instancesPtr);\r
+    jvmdiError (JNICALL *References)\r
+      (jobject obj, JVMDI_object_reference_info *refs);\r
+    jvmdiError (JNICALL *GetClassDefinition)\r
+      (jclass clazz, JVMDI_class_definition *classDefPtr);\r
+    jvmdiError (JNICALL *RedefineClasses)\r
+      (jint classCount, JVMDI_class_definition *classDefs);\r
+\r
+    jvmdiError (JNICALL *GetVersionNumber)\r
+      (jint *versionPtr);\r
+    jvmdiError (JNICALL *GetCapabilities)\r
+      (JVMDI_capabilities *capabilitiesPtr);\r
+\r
+    jvmdiError (JNICALL *GetSourceDebugExtension)\r
+      (jclass clazz, char **sourceDebugExtension);\r
+    jvmdiError (JNICALL *IsMethodObsolete)\r
+      (jclass clazz, jmethodID method, jboolean *isObsoletePtr);\r
+\r
+    jvmdiError (JNICALL *SuspendThreadList)\r
+      (jint reqCount, jthread *reqList, jvmdiError *results); \r
+    jvmdiError (JNICALL *ResumeThreadList)\r
+      (jint reqCount, jthread *reqList, jvmdiError *results); \r
+} JVMDI_Interface_1;\r
+  \r
+#ifndef NO_JVMDI_MACROS\r
+\r
+#define JVMDI_ERROR_DUPLICATE_BREAKPOINT JVMDI_ERROR_DUPLICATE\r
+#define JVMDI_ERROR_NO_SUCH_BREAKPOINT   JVMDI_ERROR_NOT_FOUND\r
+#define JVMDI_ERROR_DUPLICATE_FRAME_POP  JVMDI_ERROR_DUPLICATE\r
+\r
+\r
+static JVMDI_Interface_1 *jvmdi_interface = NULL;\r
+static JavaVM *j_vm;\r
+\r
+#ifdef __cplusplus\r
+#define SetJVMDIfromJNIEnv(a_env) ( (jvmdi_interface == NULL)?  \\r
+              ((a_env)->GetJavaVM(&j_vm),  \\r
+               (j_vm)->GetEnv((void **)&jvmdi_interface,  \\r
+                               JVMDI_VERSION_1)):0)\r
+#else\r
+#define SetJVMDIfromJNIEnv(a_env) ( (jvmdi_interface == NULL)?  \\r
+              ((*a_env)->GetJavaVM(a_env, &j_vm), \\r
+               (*j_vm)->GetEnv(j_vm, (void **)&jvmdi_interface, \\r
+                               JVMDI_VERSION_1)):0)\r
+#endif\r
+\r
+#define JVMDI_SetEventHook(a_env, a1) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->SetEventHook(a1) )\r
+#define JVMDI_GetThreadStatus(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetThreadStatus(a1, a2, a3) )\r
+#define JVMDI_GetAllThreads(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetAllThreads(a1, a2) )\r
+#define JVMDI_SuspendThread(a_env, a1) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->SuspendThread(a1) )\r
+#define JVMDI_ResumeThread(a_env, a1) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->ResumeThread(a1) )\r
+#define JVMDI_StopThread(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->StopThread(a1, a2) )\r
+#define JVMDI_InterruptThread(a_env, a1) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->InterruptThread(a1) )\r
+#define JVMDI_SetSingleStep(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->SetEventNotificationMode( \\r
+                                       (a2) ? JVMDI_ENABLE : JVMDI_DISABLE, \\r
+                                        JVMDI_EVENT_SINGLE_STEP, a1) )\r
+#define JVMDI_GetThreadInfo(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetThreadInfo(a1, a2) )\r
+#define JVMDI_RunDebugThread(a_env, a1, a2, a3, a4) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->RunDebugThread(a1, a2, a3, a4) )\r
+#define JVMDI_GetTopThreadGroups(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetTopThreadGroups(a1, a2) )\r
+#define JVMDI_GetThreadGroupInfo(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetThreadGroupInfo(a1, a2) )\r
+#define JVMDI_GetThreadGroupChildren(a_env, a1, a2, a3, a4, a5) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetThreadGroupChildren(a1, a2, a3, a4, a5) )\r
+#define JVMDI_GetCurrentFrame(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetCurrentFrame(a1, a2) )\r
+#define JVMDI_GetCallerFrame(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetCallerFrame(a1, a2) )\r
+#define JVMDI_GetFrameLocation(a_env, a1, a2, a3, a4) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetFrameLocation(a1, a2, a3, a4) )\r
+#define JVMDI_NotifyFramePop(a_env, a1) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->NotifyFramePop(a1) )\r
+#define JVMDI_GetLocalObject(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetLocalObject(a1, a2, a3) )\r
+#define JVMDI_GetLocalInt(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetLocalInt(a1, a2, a3) )\r
+#define JVMDI_GetLocalLong(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetLocalLong(a1, a2, a3) )\r
+#define JVMDI_GetLocalFloat(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetLocalFloat(a1, a2, a3) )\r
+#define JVMDI_GetLocalDouble(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetLocalDouble(a1, a2, a3) )\r
+#define JVMDI_SetLocalObject(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->SetLocalObject(a1, a2, a3) )\r
+#define JVMDI_SetLocalInt(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->SetLocalInt(a1, a2, a3) )\r
+#define JVMDI_SetLocalLong(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->SetLocalLong(a1, a2, a3) )\r
+#define JVMDI_SetLocalFloat(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->SetLocalFloat(a1, a2, a3) )\r
+#define JVMDI_SetLocalDouble(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->SetLocalDouble(a1, a2, a3) )\r
+#define JVMDI_CreateRawMonitor(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->CreateRawMonitor(a1, a2) )\r
+#define JVMDI_DestroyRawMonitor(a_env, a1) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->DestroyRawMonitor(a1) )\r
+#define JVMDI_RawMonitorEnter(a_env, a1) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->RawMonitorEnter(a1) )\r
+#define JVMDI_RawMonitorExit(a_env, a1) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->RawMonitorExit(a1) )\r
+#define JVMDI_RawMonitorWait(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->RawMonitorWait(a1, a2) )\r
+#define JVMDI_RawMonitorNotify(a_env, a1) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->RawMonitorNotify(a1) )\r
+#define JVMDI_RawMonitorNotifyAll(a_env, a1) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->RawMonitorNotifyAll(a1) )\r
+#define JVMDI_SetBreakpoint(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->SetBreakpoint(a1, a2, a3) )\r
+#define JVMDI_ClearBreakpoint(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->ClearBreakpoint(a1, a2, a3) )\r
+#define JVMDI_ClearAllBreakpoints(a_env) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->ClearAllBreakpoints() )\r
+#define JVMDI_SetAllocationHooks(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->SetAllocationHooks(a1, a2) )\r
+#define JVMDI_Allocate(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->Allocate(a1, a2) )\r
+#define JVMDI_Deallocate(a_env, a1) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->Deallocate(a1) )\r
+#define JVMDI_GetClassSignature(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetClassSignature(a1, a2) )\r
+#define JVMDI_GetClassStatus(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetClassStatus(a1, a2) )\r
+#define JVMDI_GetSourceFileName(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetSourceFileName(a1, a2) )\r
+#define JVMDI_GetClassModifiers(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetClassModifiers(a1, a2) )\r
+#define JVMDI_GetClassMethods(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetClassMethods(a1, a2, a3) )\r
+#define JVMDI_GetClassFields(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetClassFields(a1, a2, a3) )\r
+#define JVMDI_GetImplementedInterfaces(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetImplementedInterfaces(a1, a2, a3) )\r
+#define JVMDI_IsInterface(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->IsInterface(a1, a2) )\r
+#define JVMDI_IsArrayClass(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->IsArrayClass(a1, a2) )\r
+#define JVMDI_ClassLoader(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetClassLoader(a1, a2) )\r
+#define JVMDI_GetFieldName(a_env, a1, a2, a3, a4) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetFieldName(a1, a2, a3, a4) )\r
+#define JVMDI_GetFieldDeclaringClass(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetFieldDeclaringClass(a1, a2, a3) )\r
+#define JVMDI_GetFieldModifiers(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetFieldModifiers(a1, a2, a3) )\r
+#define JVMDI_GetMethodName(a_env, a1, a2, a3, a4) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetMethodName(a1, a2, a3, a4) )\r
+#define JVMDI_GetMethodDeclaringClass(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetMethodDeclaringClass(a1, a2, a3) )\r
+#define JVMDI_GetMethodModifiers(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetMethodModifiers(a1, a2, a3) )\r
+#define JVMDI_GetMaxStack(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetMaxStack(a1, a2, a3) )\r
+#define JVMDI_GetMaxLocals(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetMaxLocals(a1, a2, a3) )\r
+#define JVMDI_GetArgumentsSize(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetArgumentsSize(a1, a2, a3) )\r
+#define JVMDI_GetLineNumberTable(a_env, a1, a2, a3, a4) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetLineNumberTable(a1, a2, a3, a4) )\r
+#define JVMDI_GetMethodLocation(a_env, a1, a2, a3, a4) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetMethodLocation(a1, a2, a3, a4) )\r
+#define JVMDI_GetLocalVariableTable(a_env, a1, a2, a3, a4) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetLocalVariableTable(a1, a2, a3, a4) )\r
+#define JVMDI_GetExceptionHandlerTable(a_env, a1, a2, a3, a4) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetExceptionHandlerTable(a1, a2, a3, a4) )\r
+#define JVMDI_GetThrownExceptions(a_env, a1, a2, a3, a4) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetThrownExceptions(a1, a2, a3, a4) )\r
+#define JVMDI_GetBytecodes(a_env, a1, a2, a3, a4) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetBytecodes(a1, a2, a3, a4) )\r
+#define JVMDI_IsMethodNative(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->IsMethodNative(a1, a2, a3) )\r
+#define JVMDI_GetLoadedClasses(a_env, a1, a2) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetLoadedClasses(a1, a2) )\r
+#define JVMDI_GetClassLoaderClasses(a_env, a1, a2, a3) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetClassLoaderClasses(a1, a2, a3) )\r
+#define JVMDI_GetVersionNumber(a_env, a1) ( \\r
+              SetJVMDIfromJNIEnv(a_env), \\r
+              jvmdi_interface->GetVersionNumber(a1) )\r
+\r
+#endif /* !NO_JVMDI_MACROS */\r
+\r
+#ifdef __cplusplus\r
+} /* extern "C" */\r
+#endif /* __cplusplus */\r
+\r
+#endif /* !_JAVASOFT_JVMDI_H_ */\r
+\r
+\r
diff --git a/applications/JavaOpenJPEG/java-jni/include/jvmpi.h b/applications/JavaOpenJPEG/java-jni/include/jvmpi.h
new file mode 100644 (file)
index 0000000..557b231
--- /dev/null
@@ -0,0 +1,642 @@
+/*\r
+ * @(#)jvmpi.h 1.28 03/12/19\r
+ *\r
+ * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
+ * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
+ */\r
+\r
+#ifndef _JAVASOFT_JVMPI_H_\r
+#define _JAVASOFT_JVMPI_H_\r
+\r
+#include "jni.h"\r
+\r
+#define JVMPI_VERSION_1   ((jint)0x10000001)  /* implied 0 for minor version */\r
+#define JVMPI_VERSION_1_1 ((jint)0x10000002)\r
+#define JVMPI_VERSION_1_2 ((jint)0x10000003)\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+  typedef void (*jvmpi_void_function_of_void)(void *);\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+/****************************************************************\r
+ * Profiler interface data structures.\r
+ ****************************************************************/\r
+/* identifier types. */\r
+struct _jobjectID;\r
+typedef struct _jobjectID * jobjectID;       /* type of object ids */ \r
+\r
+/* raw monitors */\r
+struct _JVMPI_RawMonitor;\r
+typedef struct _JVMPI_RawMonitor * JVMPI_RawMonitor;\r
+\r
+/* call frame */\r
+typedef struct {\r
+    jint lineno;                      /* line number in the source file */\r
+    jmethodID method_id;              /* method executed in this frame */\r
+} JVMPI_CallFrame;\r
+\r
+/* call trace */\r
+typedef struct {\r
+    JNIEnv *env_id;                   /* Env where trace was recorded */\r
+    jint num_frames;                  /* number of frames in this trace */\r
+    JVMPI_CallFrame *frames;          /* frames */\r
+} JVMPI_CallTrace;\r
+\r
+/* method */\r
+typedef struct {\r
+    char *method_name;                /* name of method */\r
+    char *method_signature;           /* signature of method */\r
+    jint start_lineno;                /* -1 if native, abstract .. */\r
+    jint end_lineno;                  /* -1 if native, abstract .. */\r
+    jmethodID method_id;              /* id assigned to this method */\r
+} JVMPI_Method;\r
+\r
+/* Field */\r
+typedef struct {\r
+    char *field_name;                 /* name of field */\r
+    char *field_signature;            /* signature of field */\r
+} JVMPI_Field;\r
+\r
+/* line number info for a compiled method */\r
+typedef struct {\r
+    jint offset;                      /* offset from beginning of method */\r
+    jint lineno;                      /* lineno from beginning of src file */\r
+} JVMPI_Lineno;\r
+\r
+/* event */\r
+typedef struct {\r
+    jint event_type;                  /* event_type */\r
+    JNIEnv *env_id;                   /* env where this event occured */\r
+  \r
+    union {\r
+        struct {\r
+           const char *class_name;   /* class name */\r
+           char *source_name;        /* name of source file */\r
+           jint num_interfaces;      /* number of interfaces implemented */\r
+           jint num_methods;         /* number of methods in the class */\r
+           JVMPI_Method *methods;    /* methods */\r
+           jint num_static_fields;   /* number of static fields */\r
+           JVMPI_Field *statics;     /* static fields */\r
+           jint num_instance_fields; /* number of instance fields */\r
+           JVMPI_Field *instances;   /* instance fields */\r
+           jobjectID class_id;       /* id of the class object */\r
+       } class_load;\r
+\r
+        struct {\r
+           jobjectID class_id;       /* id of the class object */\r
+       } class_unload;\r
+\r
+        struct {\r
+           unsigned char *class_data;        /* content of class file */\r
+           jint class_data_len;              /* class file length */\r
+           unsigned char *new_class_data;    /* instrumented class file */\r
+           jint new_class_data_len;          /* new class file length */\r
+           void * (*malloc_f)(unsigned int); /* memory allocation function */\r
+       } class_load_hook;\r
+\r
+        struct {\r
+            jint arena_id;\r
+           jobjectID class_id;       /* id of object class */\r
+           jint is_array;            /* JVMPI_NORMAL_OBJECT, ... */\r
+           jint size;                /* size in number of bytes */\r
+           jobjectID obj_id;         /* id assigned to this object */\r
+        } obj_alloc;\r
+\r
+        struct {\r
+           jobjectID obj_id;         /* id of the object */\r
+       } obj_free;\r
+\r
+        struct {\r
+           jint arena_id;            /* cur arena id */\r
+           jobjectID obj_id;         /* cur object id */\r
+           jint new_arena_id;        /* new arena id */\r
+           jobjectID new_obj_id;     /* new object id */         \r
+       } obj_move;\r
+\r
+        struct {\r
+           jint arena_id;            /* id of arena */\r
+           const char *arena_name;   /* name of arena */\r
+       } new_arena;\r
+\r
+        struct {\r
+           jint arena_id;            /* id of arena */\r
+       } delete_arena;\r
+\r
+        struct {\r
+           char *thread_name;        /* name of thread */\r
+           char *group_name;         /* name of group */\r
+           char *parent_name;        /* name of parent */\r
+           jobjectID thread_id;      /* id of the thread object */\r
+           JNIEnv *thread_env_id;\r
+        } thread_start;\r
+\r
+        struct {\r
+           int dump_level;           /* level of the heap dump info */\r
+           char *begin;              /* where all the root records begin,\r
+                                        please see the heap dump buffer \r
+                                        format described below */\r
+           char *end;                /* where the object records end. */\r
+           jint num_traces;          /* number of thread traces, \r
+                                        0 if dump level = JVMPI_DUMP_LEVEL_0 */\r
+           JVMPI_CallTrace *traces;  /* thread traces collected during \r
+                                        heap dump */ \r
+       } heap_dump;\r
+\r
+        struct {\r
+           jobjectID obj_id;         /* object id */\r
+           jobject ref_id;           /* id assigned to the globalref */\r
+       } jni_globalref_alloc;\r
+      \r
+        struct {\r
+           jobject ref_id;           /* id of the global ref */\r
+       } jni_globalref_free;\r
+\r
+        struct {\r
+           jmethodID method_id;      /* method */\r
+       } method;\r
+\r
+        struct {\r
+           jmethodID method_id;      /* id of method */\r
+           jobjectID obj_id;         /* id of target object */\r
+       } method_entry2;\r
+\r
+        struct {\r
+           jmethodID method_id;        /* id of compiled method */\r
+           void *code_addr;            /* code start addr. in memory */\r
+           jint code_size;             /* code size */\r
+           jint lineno_table_size;     /* size of lineno table */\r
+           JVMPI_Lineno *lineno_table; /* lineno info */\r
+       } compiled_method_load;\r
+        \r
+        struct {\r
+           jmethodID method_id;        /* id of unloaded compiled method */\r
+       } compiled_method_unload;\r
+\r
+       struct {\r
+           jmethodID method_id; /* id of the method the instruction belongs to */\r
+           jint offset;         /* instruction offset in the method's bytecode */\r
+           union {\r
+               struct {\r
+                   jboolean is_true; /* whether true or false branch is taken  */\r
+               } if_info;\r
+               struct {\r
+                   jint key; /* top stack value used as an index */\r
+                   jint low; /* min value of the index           */\r
+                   jint hi;  /* max value of the index           */\r
+               } tableswitch_info;\r
+               struct {\r
+                   jint chosen_pair_index; /* actually chosen pair index (0-based)\r
+                                             * if chosen_pair_index == pairs_total then\r
+                                             * the 'default' branch is taken\r
+                                             */\r
+                   jint pairs_total;       /* total number of lookupswitch pairs */\r
+               } lookupswitch_info;\r
+           } u;\r
+       } instruction;\r
+       \r
+        struct {\r
+           char *begin;                /* beginning of dump buffer, \r
+                                          see below for format */\r
+           char *end;                  /* end of dump buffer */\r
+           jint num_traces;            /* number of traces */\r
+           JVMPI_CallTrace *traces;    /* traces of all threads */\r
+           jint *threads_status;       /* status of all threads */\r
+       } monitor_dump;\r
+\r
+        struct {\r
+           const char *name;           /* name of raw monitor */\r
+           JVMPI_RawMonitor id;        /* id */\r
+       } raw_monitor;\r
+\r
+        struct {\r
+           jobjectID object;           /* Java object */\r
+       } monitor;\r
+\r
+        struct {\r
+           jobjectID object;           /* Java object */\r
+           jlong timeout;              /* timeout period */\r
+       } monitor_wait;\r
+\r
+        struct {\r
+           jlong used_objects;\r
+           jlong used_object_space;\r
+           jlong total_object_space;\r
+       } gc_info;\r
+\r
+        struct {\r
+           jint data_len;\r
+           char *data;\r
+       } object_dump;\r
+    } u;\r
+} JVMPI_Event;\r
+\r
+/* interface functions */\r
+typedef struct {\r
+    jint version;   /* JVMPI version */\r
+    \r
+    /* ------interface implemented by the profiler------ */\r
+\r
+    /**\r
+     * Function called by the JVM to notify an event. \r
+     */\r
+    void (*NotifyEvent)(JVMPI_Event *event);\r
+  \r
+    /* ------interface implemented by the JVM------ */\r
+    \r
+    /**\r
+     * Function called by the profiler to enable/disable/send notification \r
+     * for a particular event type.  \r
+     * \r
+     * event_type - event_type\r
+     * arg - event specific arg\r
+     *\r
+     * return JVMPI_NOT_AVAILABLE, JVMPI_SUCCESS or JVMPI_FAIL\r
+     */\r
+    jint (*EnableEvent)(jint event_type, void *arg);\r
+    jint (*DisableEvent)(jint event_type, void *arg);\r
+    jint (*RequestEvent)(jint event_type, void *arg);\r
+  \r
+    /**\r
+     * Function called by the profiler to get a stack\r
+     * trace from the JVM.\r
+     *\r
+     * trace - trace data structure to be filled\r
+     * depth - maximum depth of the trace.\r
+     */\r
+    void (*GetCallTrace)(JVMPI_CallTrace *trace, jint depth);\r
+\r
+    /**\r
+     * Function called by profiler when it wants to exit/stop.\r
+     */\r
+    void (*ProfilerExit)(jint);\r
+\r
+    /**\r
+     * Utility functions provided by the JVM.\r
+     */\r
+    JVMPI_RawMonitor (*RawMonitorCreate)(char *lock_name);\r
+    void (*RawMonitorEnter)(JVMPI_RawMonitor lock_id);\r
+    void (*RawMonitorExit)(JVMPI_RawMonitor lock_id);\r
+    void (*RawMonitorWait)(JVMPI_RawMonitor lock_id, jlong ms);\r
+    void (*RawMonitorNotifyAll)(JVMPI_RawMonitor lock_id);\r
+    void (*RawMonitorDestroy)(JVMPI_RawMonitor lock_id);\r
+\r
+    /**\r
+     * Function called by the profiler to get the current thread's CPU time.\r
+     *\r
+     * return time in nanoseconds;\r
+     */\r
+    jlong (*GetCurrentThreadCpuTime)(void);\r
+\r
+    void (*SuspendThread)(JNIEnv *env);\r
+    void (*ResumeThread)(JNIEnv *env);\r
+    jint (*GetThreadStatus)(JNIEnv *env);\r
+    jboolean (*ThreadHasRun)(JNIEnv *env);\r
+\r
+    /* This function can be called safely only after JVMPI_EVENT_VM_INIT_DONE\r
+       notification by the JVM. */\r
+    jint (*CreateSystemThread)(char *name, jint priority, void (*f)(void *));\r
+\r
+    /* thread local storage access functions to avoid locking in time \r
+       critical functions */\r
+    void (*SetThreadLocalStorage)(JNIEnv *env_id, void *ptr);\r
+    void * (*GetThreadLocalStorage)(JNIEnv *env_id);\r
+\r
+    /* control GC */\r
+    void (*DisableGC)(void);\r
+    void (*EnableGC)(void);\r
+    void (*RunGC)(void);\r
+\r
+    jobjectID (*GetThreadObject)(JNIEnv *env);\r
+    jobjectID (*GetMethodClass)(jmethodID mid);\r
+\r
+    /* JNI <-> jobject conversions */\r
+    jobject   (*jobjectID2jobject)(jobjectID jid);\r
+    jobjectID (*jobject2jobjectID)(jobject jobj);\r
+\r
+    void (*SuspendThreadList)\r
+      (jint reqCount, JNIEnv **reqList, jint *results);\r
+    void (*ResumeThreadList)\r
+      (jint reqCount, JNIEnv **reqList, jint *results);\r
+} JVMPI_Interface;\r
+\r
+/* type of argument passed to RequestEvent for heap dumps */\r
+typedef struct {\r
+    jint heap_dump_level;\r
+} JVMPI_HeapDumpArg;\r
+\r
+/**********************************************************************\r
+ * Constants and formats used in JVM Profiler Interface.\r
+ **********************************************************************/\r
+/*\r
+ * Event type constants.\r
+ */\r
+#define JVMPI_EVENT_METHOD_ENTRY            ((jint)1) \r
+#define JVMPI_EVENT_METHOD_ENTRY2           ((jint)2) \r
+#define JVMPI_EVENT_METHOD_EXIT             ((jint)3) \r
+\r
+#define JVMPI_EVENT_OBJECT_ALLOC            ((jint)4) \r
+#define JVMPI_EVENT_OBJECT_FREE             ((jint)5) \r
+#define JVMPI_EVENT_OBJECT_MOVE             ((jint)6) \r
+\r
+#define JVMPI_EVENT_COMPILED_METHOD_LOAD    ((jint)7) \r
+#define JVMPI_EVENT_COMPILED_METHOD_UNLOAD  ((jint)8) \r
+\r
+#define JVMPI_EVENT_INSTRUCTION_START       ((jint)9) \r
+\r
+#define JVMPI_EVENT_THREAD_START           ((jint)33) \r
+#define JVMPI_EVENT_THREAD_END             ((jint)34) \r
+\r
+#define JVMPI_EVENT_CLASS_LOAD_HOOK        ((jint)35) \r
+\r
+#define JVMPI_EVENT_HEAP_DUMP                     ((jint)37) \r
+#define JVMPI_EVENT_JNI_GLOBALREF_ALLOC           ((jint)38) \r
+#define JVMPI_EVENT_JNI_GLOBALREF_FREE            ((jint)39) \r
+#define JVMPI_EVENT_JNI_WEAK_GLOBALREF_ALLOC      ((jint)40) \r
+#define JVMPI_EVENT_JNI_WEAK_GLOBALREF_FREE       ((jint)41) \r
+#define JVMPI_EVENT_CLASS_LOAD                    ((jint)42) \r
+#define JVMPI_EVENT_CLASS_UNLOAD                  ((jint)43) \r
+#define JVMPI_EVENT_DATA_DUMP_REQUEST             ((jint)44) \r
+#define JVMPI_EVENT_DATA_RESET_REQUEST            ((jint)45) \r
+\r
+#define JVMPI_EVENT_JVM_INIT_DONE          ((jint)46) \r
+#define JVMPI_EVENT_JVM_SHUT_DOWN          ((jint)47) \r
+\r
+#define JVMPI_EVENT_ARENA_NEW              ((jint)48)\r
+#define JVMPI_EVENT_ARENA_DELETE           ((jint)49)\r
+\r
+#define JVMPI_EVENT_OBJECT_DUMP            ((jint)50)\r
+\r
+#define JVMPI_EVENT_RAW_MONITOR_CONTENDED_ENTER   ((jint)51)\r
+#define JVMPI_EVENT_RAW_MONITOR_CONTENDED_ENTERED ((jint)52)\r
+#define JVMPI_EVENT_RAW_MONITOR_CONTENDED_EXIT    ((jint)53)\r
+#define JVMPI_EVENT_MONITOR_CONTENDED_ENTER       ((jint)54)\r
+#define JVMPI_EVENT_MONITOR_CONTENDED_ENTERED     ((jint)55)\r
+#define JVMPI_EVENT_MONITOR_CONTENDED_EXIT        ((jint)56)\r
+#define JVMPI_EVENT_MONITOR_WAIT                  ((jint)57)\r
+#define JVMPI_EVENT_MONITOR_WAITED                ((jint)58)\r
+#define JVMPI_EVENT_MONITOR_DUMP                  ((jint)59)\r
+\r
+#define JVMPI_EVENT_GC_START                      ((jint)60)\r
+#define JVMPI_EVENT_GC_FINISH                     ((jint)61)\r
+\r
+#define JVMPI_MAX_EVENT_TYPE_VAL                  ((jint)61)\r
+\r
+/* old definitions, to be removed */\r
+#define JVMPI_EVENT_LOAD_COMPILED_METHOD          ((jint)7) \r
+#define JVMPI_EVENT_UNLOAD_COMPILED_METHOD        ((jint)8) \r
+#define JVMPI_EVENT_NEW_ARENA                     ((jint)48)\r
+#define JVMPI_EVENT_DELETE_ARENA                  ((jint)49)\r
+#define JVMPI_EVENT_DUMP_DATA_REQUEST             ((jint)44) \r
+#define JVMPI_EVENT_RESET_DATA_REQUEST            ((jint)45) \r
+#define JVMPI_EVENT_OBJ_ALLOC                     ((jint)4) \r
+#define JVMPI_EVENT_OBJ_FREE                      ((jint)5) \r
+#define JVMPI_EVENT_OBJ_MOVE                      ((jint)6) \r
+\r
+#define JVMPI_REQUESTED_EVENT                     ((jint)0x10000000)\r
+\r
+\r
\r
+/* \r
+ * enabling/disabling event notification.\r
+ */\r
+/* results */\r
+#define JVMPI_SUCCESS                    ((jint)0)\r
+#define JVMPI_NOT_AVAILABLE              ((jint)1)\r
+#define JVMPI_FAIL                       ((jint)-1)\r
+\r
+/*\r
+ * Thread status\r
+ */\r
+enum {\r
+    JVMPI_THREAD_RUNNABLE = 1,\r
+    JVMPI_THREAD_MONITOR_WAIT,\r
+    JVMPI_THREAD_CONDVAR_WAIT\r
+};\r
+\r
+#define JVMPI_THREAD_SUSPENDED        0x8000\r
+#define JVMPI_THREAD_INTERRUPTED      0x4000\r
+\r
+/*\r
+ * Thread priority\r
+ */\r
+#define JVMPI_MINIMUM_PRIORITY     1\r
+#define JVMPI_MAXIMUM_PRIORITY     10\r
+#define JVMPI_NORMAL_PRIORITY      5\r
+\r
+/*\r
+ * Object type constants.\r
+ */\r
+#define JVMPI_NORMAL_OBJECT             ((jint)0)\r
+#define JVMPI_CLASS                     ((jint)2)\r
+#define JVMPI_BOOLEAN                   ((jint)4)\r
+#define JVMPI_CHAR                       ((jint)5)\r
+#define JVMPI_FLOAT                      ((jint)6)\r
+#define JVMPI_DOUBLE                     ((jint)7)\r
+#define JVMPI_BYTE                       ((jint)8)\r
+#define JVMPI_SHORT                      ((jint)9)\r
+#define JVMPI_INT                        ((jint)10)\r
+#define JVMPI_LONG                       ((jint)11)    \r
+\r
+/*\r
+ * Monitor dump constants.\r
+ */\r
+\r
+#define JVMPI_MONITOR_JAVA          0x01\r
+#define JVMPI_MONITOR_RAW           0x02\r
+\r
+/*\r
+ * Heap dump constants.\r
+ */\r
+#define JVMPI_GC_ROOT_UNKNOWN       0xff\r
+#define JVMPI_GC_ROOT_JNI_GLOBAL    0x01\r
+#define JVMPI_GC_ROOT_JNI_LOCAL     0x02\r
+#define JVMPI_GC_ROOT_JAVA_FRAME    0x03\r
+#define JVMPI_GC_ROOT_NATIVE_STACK  0x04\r
+#define JVMPI_GC_ROOT_STICKY_CLASS  0x05\r
+#define JVMPI_GC_ROOT_THREAD_BLOCK  0x06\r
+#define JVMPI_GC_ROOT_MONITOR_USED  0x07\r
+#define JVMPI_GC_ROOT_THREAD_OBJ    0x08\r
+\r
+#define JVMPI_GC_CLASS_DUMP         0x20\r
+#define JVMPI_GC_INSTANCE_DUMP      0x21 \r
+#define JVMPI_GC_OBJ_ARRAY_DUMP     0x22\r
+#define JVMPI_GC_PRIM_ARRAY_DUMP    0x23\r
+\r
+/*\r
+ * Dump levels\r
+ */\r
+#define JVMPI_DUMP_LEVEL_0    ((jint)0)\r
+#define JVMPI_DUMP_LEVEL_1    ((jint)1)\r
+#define JVMPI_DUMP_LEVEL_2    ((jint)2)\r
+\r
+/* Types used in dumps -\r
+ *\r
+ * u1: 1 byte\r
+ * u2: 2 bytes\r
+ * u4: 4 bytes\r
+ * u8: 8 bytes\r
+ *\r
+ * ty: u1 where:\r
+ *     JVMPI_CLASS:   object\r
+ *     JVMPI_BOOLEAN: boolean\r
+ *     JVMPI_CHAR:    char\r
+ *     JVMPI_FLOAT:   float\r
+ *     JVMPI_DOUBLE:  double\r
+ *     JVMPI_BYTE:    byte\r
+ *     JVMPI_SHORT:   short\r
+ *     JVMPI_INT:     int\r
+ *     JVMPI_LONG:    long\r
+ *\r
+ * vl: values, exact type depends on the type of the value:\r
+ *     JVMPI_BOOLEAN & JVMPI_BYTE:   u1\r
+ *     JVMPI_SHORT & JVMPI_CHAR:     u2\r
+ *     JVMPI_INT & JVMPI_FLOAT:      u4\r
+ *     JVMPI_LONG & JVMPI_DOUBLE:    u8\r
+ *     JVMPI_CLASS:                  jobjectID\r
+ */\r
+\r
+/* Format of the monitor dump buffer:\r
+ *\r
+ *               u1                          monitor type\r
+ *\r
+ *               JVMPI_MONITOR_JAVA          Java monitor\r
+ *\r
+ *                          jobjectID        object\r
+ *                          JNIEnv *         owner thread\r
+ *                          u4               entry count\r
+ *                          u4               # of threads waiting to enter\r
+ *                          [JNIEnv *]*      threads waiting to enter\r
+ *                          u4               # of threads waiting to be notified\r
+ *                          [JNIEnv *]*      threads waiting to be notified\r
+ *\r
+ *               JVMPI_MONITOR_RAW           raw monitor\r
+ *\r
+ *                          char *           name\r
+ *                          JVMPI_RawMonitor raw monitor\r
+ *                          JNIEnv *         owner thread\r
+ *                          u4               entry count\r
+ *                          u4               # of threads waiting to enter\r
+ *                          [JNIEnv *]*      threads waiting to enter\r
+ *                          u4               # of threads waiting to be notified\r
+ *                          [JNIEnv *]*      threads waiting to be notified\r
+ */\r
+\r
+/* Format of the heap dump buffer depends on the dump level \r
+ * specified in the JVMPI_HeapDumpArg passed to RequestEvent as arg. \r
+ * The default is JVMPI_DUMP_LEVEL_2.\r
+ *\r
+ * JVMPI_DUMP_LEVEL_0:\r
+ * \r
+ *               u1                          object type (JVMPI_CLASS ...)\r
+ *               jobjectID                   object\r
+ *\r
+ * JVMPI_DUMP_LEVEL_1 and JVMPI_DUMP_LEVEL_2 use the following format:  \r
+ * In the case of JVMPI_DUMP_LEVEL_1 the values of primitive fields in object \r
+ * instance dumps , the values of primitive statics in class dumps and the \r
+ * values of primitive arrays are excluded.  JVMPI_DUMP_LEVEL_2 includes the\r
+ * primitive values.\r
+ *\r
+ *               u1                          record type\r
+ *\r
+ *               JVMPI_GC_ROOT_UNKNOWN       unknown root\r
+ *\r
+ *                          jobjectID        object\r
+ *\r
+ *               JVMPI_GC_ROOT_JNI_GLOBAL    JNI global ref root\r
+ *\r
+ *                          jobjectID        object\r
+ *                          jobject          JNI global reference\r
+ *\r
+ *               JVMPI_GC_ROOT_JNI_LOCAL     JNI local ref\r
+ *\r
+ *                          jobjectID        object\r
+ *                          JNIEnv *         thread\r
+ *                          u4               frame # in stack trace (-1 for empty)\r
+ *\r
+ *               JVMPI_GC_ROOT_JAVA_FRAME    Java stack frame\r
+ *\r
+ *                          jobjectID        object\r
+ *                          JNIEnv *         thread\r
+ *                          u4               frame # in stack trace (-1 for empty)\r
+ *\r
+ *               JVMPI_GC_ROOT_NATIVE_STACK  Native stack\r
+ *\r
+ *                          jobjectID        object\r
+ *                          JNIEnv *         thread\r
+ *\r
+ *               JVMPI_GC_ROOT_STICKY_CLASS  System class\r
+ *\r
+ *                          jobjectID        class object\r
+ *\r
+ *               JVMPI_GC_ROOT_THREAD_BLOCK  Reference from thread block\r
+ *\r
+ *                          jobjectID        thread object\r
+ *                          JNIEnv *         thread\r
+ *\r
+ *               JVMPI_GC_ROOT_MONITOR_USED  Busy monitor\r
+ *\r
+ *                          jobjectID        object\r
+ *\r
+ *               JVMPI_GC_CLASS_DUMP         dump of a class object\r
+ *\r
+ *                          jobjectID        class\r
+ *                          jobjectID        super\r
+ *                          jobjectID        class loader\r
+ *                          jobjectID        signers\r
+ *                          jobjectID        protection domain\r
+ *                          jobjectID        class name\r
+ *                          void *           reserved\r
+ *\r
+ *                          u4               instance size (in bytes)\r
+ *\r
+ *                          [jobjectID]*     interfaces\r
+ *\r
+ *                          u2               size of constant pool\r
+ *                          [u2,             constant pool index,\r
+ *                           ty,             type, \r
+ *                           vl]*            value\r
+ *\r
+ *                          [vl]*            static field values\r
+ *\r
+ *               JVMPI_GC_INSTANCE_DUMP      dump of a normal object\r
+ *\r
+ *                          jobjectID        object\r
+ *                          jobjectID        class\r
+ *                          u4               number of bytes that follow\r
+ *                          [vl]*            instance field values (class, followed\r
+ *                                           by super, super's super ...)\r
+ *\r
+ *               JVMPI_GC_OBJ_ARRAY_DUMP     dump of an object array\r
+ *\r
+ *                          jobjectID        array object\r
+ *                          u4               number of elements\r
+ *                          jobjectID        element class\r
+ *                          [jobjectID]*     elements\r
+ *\r
+ *               JVMPI_GC_PRIM_ARRAY_DUMP    dump of a primitive array\r
+ *\r
+ *                          jobjectID        array object\r
+ *                          u4               number of elements\r
+ *                          ty               element type\r
+ *                          [vl]*            elements\r
+ *\r
+ */\r
+\r
+/* Format of the dump received in JVMPI_EVENT_OBJECT_DUMP:\r
+ * All the records have JVMPI_DUMP_LEVEL_2 information.\r
+ *\r
+ *               u1                          record type\r
+ *\r
+ *                     followed by a:\r
+ *\r
+ *                          JVMPI_GC_CLASS_DUMP,\r
+ *                          JVMPI_GC_INSTANCE_DUMP,\r
+ *                          JVMPI_GC_OBJ_ARRAY_DUMP, or\r
+ *                          JVMPI_GC_PRIM_ARRAY_DUMP record.\r
+ */\r
+\r
+#endif /* !_JAVASOFT_JVMPI_H_ */\r
diff --git a/applications/JavaOpenJPEG/java-jni/include/jvmti.h b/applications/JavaOpenJPEG/java-jni/include/jvmti.h
new file mode 100644 (file)
index 0000000..de24e3e
--- /dev/null
@@ -0,0 +1,2181 @@
+#ifdef USE_PRAGMA_IDENT_HDR\r
+#pragma ident "@(#)jvmtiLib.xsl        1.32 04/06/01 20:19:53 JVM"\r
+#endif\r
+/*\r
+ * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.\r
+ * SUN PROPRIETARY/CONFIDENTIAL.  Use is subject to license terms.\r
+ */\r
+\r
+    /* AUTOMATICALLY GENERATED FILE - DO NOT EDIT */\r
+\r
+\r
+    /* Include file for the Java(tm) Virtual Machine Tool Interface */\r
+\r
+#ifndef _JAVA_JVMTI_H_\r
+#define _JAVA_JVMTI_H_\r
+\r
+#include "jni.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+enum {\r
+    JVMTI_VERSION_1   = 0x30010000,\r
+    JVMTI_VERSION_1_0 = 0x30010000,\r
+\r
+    JVMTI_VERSION = 0x30000000 + (1 * 0x10000) + (0 * 0x100) + 33  /* version: 1.0.33 */\r
+};\r
+\r
+JNIEXPORT jint JNICALL \r
+Agent_OnLoad(JavaVM *vm, char *options, void *reserved);\r
+\r
+JNIEXPORT void JNICALL \r
+Agent_OnUnload(JavaVM *vm);\r
+\r
+    /* Forward declaration of the environment */\r
+        \r
+struct _jvmtiEnv;\r
+\r
+struct jvmtiInterface_1_;\r
+  \r
+#ifdef __cplusplus\r
+typedef _jvmtiEnv jvmtiEnv;\r
+#else\r
+typedef const struct jvmtiInterface_1_ *jvmtiEnv;\r
+#endif /* __cplusplus */\r
+\r
+/* Derived Base Types */\r
+\r
+typedef jobject jthread;\r
+typedef jobject jthreadGroup;\r
+typedef jlong jlocation;\r
+struct _jrawMonitorID;\r
+typedef struct _jrawMonitorID *jrawMonitorID;\r
+typedef struct JNINativeInterface_ jniNativeInterface;\r
+\r
+    /* Constants */\r
+\r
+\r
+    /* Thread State Flags */ \r
+\r
+enum {\r
+    JVMTI_THREAD_STATE_ALIVE = 0x0001,\r
+    JVMTI_THREAD_STATE_TERMINATED = 0x0002,\r
+    JVMTI_THREAD_STATE_RUNNABLE = 0x0004,\r
+    JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER = 0x0400,\r
+    JVMTI_THREAD_STATE_WAITING = 0x0080,\r
+    JVMTI_THREAD_STATE_WAITING_INDEFINITELY = 0x0010,\r
+    JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT = 0x0020,\r
+    JVMTI_THREAD_STATE_SLEEPING = 0x0040,\r
+    JVMTI_THREAD_STATE_IN_OBJECT_WAIT = 0x0100,\r
+    JVMTI_THREAD_STATE_PARKED = 0x0200,\r
+    JVMTI_THREAD_STATE_SUSPENDED = 0x100000,\r
+    JVMTI_THREAD_STATE_INTERRUPTED = 0x200000,\r
+    JVMTI_THREAD_STATE_IN_NATIVE = 0x400000,\r
+    JVMTI_THREAD_STATE_VENDOR_1 = 0x10000000,\r
+    JVMTI_THREAD_STATE_VENDOR_2 = 0x20000000,\r
+    JVMTI_THREAD_STATE_VENDOR_3 = 0x40000000\r
+};\r
+\r
+    /* java.lang.Thread.State Conversion Masks */ \r
+\r
+enum {\r
+    JVMTI_JAVA_LANG_THREAD_STATE_MASK = JVMTI_THREAD_STATE_TERMINATED | JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_RUNNABLE | JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER | JVMTI_THREAD_STATE_WAITING | JVMTI_THREAD_STATE_WAITING_INDEFINITELY | JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT,\r
+    JVMTI_JAVA_LANG_THREAD_STATE_NEW = 0,\r
+    JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED = JVMTI_THREAD_STATE_TERMINATED,\r
+    JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE = JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_RUNNABLE,\r
+    JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED = JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER,\r
+    JVMTI_JAVA_LANG_THREAD_STATE_WAITING = JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_WAITING | JVMTI_THREAD_STATE_WAITING_INDEFINITELY,\r
+    JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING = JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_WAITING | JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT\r
+};\r
+\r
+    /* Thread Priority Constants */ \r
+\r
+enum {\r
+    JVMTI_THREAD_MIN_PRIORITY = 1,\r
+    JVMTI_THREAD_NORM_PRIORITY = 5,\r
+    JVMTI_THREAD_MAX_PRIORITY = 10\r
+};\r
+\r
+    /* Heap Object Filter Enumeration */ \r
+\r
+typedef enum {\r
+    JVMTI_HEAP_OBJECT_TAGGED = 1,\r
+    JVMTI_HEAP_OBJECT_UNTAGGED = 2,\r
+    JVMTI_HEAP_OBJECT_EITHER = 3\r
+} jvmtiHeapObjectFilter;\r
+\r
+    /* Heap Root Kind Enumeration */ \r
+\r
+typedef enum {\r
+    JVMTI_HEAP_ROOT_JNI_GLOBAL = 1,\r
+    JVMTI_HEAP_ROOT_SYSTEM_CLASS = 2,\r
+    JVMTI_HEAP_ROOT_MONITOR = 3,\r
+    JVMTI_HEAP_ROOT_STACK_LOCAL = 4,\r
+    JVMTI_HEAP_ROOT_JNI_LOCAL = 5,\r
+    JVMTI_HEAP_ROOT_THREAD = 6,\r
+    JVMTI_HEAP_ROOT_OTHER = 7\r
+} jvmtiHeapRootKind;\r
+\r
+    /* Object Reference Enumeration */ \r
+\r
+typedef enum {\r
+    JVMTI_REFERENCE_CLASS = 1,\r
+    JVMTI_REFERENCE_FIELD = 2,\r
+    JVMTI_REFERENCE_ARRAY_ELEMENT = 3,\r
+    JVMTI_REFERENCE_CLASS_LOADER = 4,\r
+    JVMTI_REFERENCE_SIGNERS = 5,\r
+    JVMTI_REFERENCE_PROTECTION_DOMAIN = 6,\r
+    JVMTI_REFERENCE_INTERFACE = 7,\r
+    JVMTI_REFERENCE_STATIC_FIELD = 8,\r
+    JVMTI_REFERENCE_CONSTANT_POOL = 9\r
+} jvmtiObjectReferenceKind;\r
+\r
+    /* Iteration Control Enumeration */ \r
+\r
+typedef enum {\r
+    JVMTI_ITERATION_CONTINUE = 1,\r
+    JVMTI_ITERATION_IGNORE = 2,\r
+    JVMTI_ITERATION_ABORT = 0\r
+} jvmtiIterationControl;\r
+\r
+    /* Class Status Flags */ \r
+\r
+enum {\r
+    JVMTI_CLASS_STATUS_VERIFIED = 1,\r
+    JVMTI_CLASS_STATUS_PREPARED = 2,\r
+    JVMTI_CLASS_STATUS_INITIALIZED = 4,\r
+    JVMTI_CLASS_STATUS_ERROR = 8,\r
+    JVMTI_CLASS_STATUS_ARRAY = 16,\r
+    JVMTI_CLASS_STATUS_PRIMITIVE = 32\r
+};\r
+\r
+    /* Event Enable/Disable */ \r
+\r
+typedef enum {\r
+    JVMTI_ENABLE = 1,\r
+    JVMTI_DISABLE = 0\r
+} jvmtiEventMode;\r
+\r
+    /* Extension Function/Event Parameter Types */ \r
+\r
+typedef enum {\r
+    JVMTI_TYPE_JBYTE = 101,\r
+    JVMTI_TYPE_JCHAR = 102,\r
+    JVMTI_TYPE_JSHORT = 103,\r
+    JVMTI_TYPE_JINT = 104,\r
+    JVMTI_TYPE_JLONG = 105,\r
+    JVMTI_TYPE_JFLOAT = 106,\r
+    JVMTI_TYPE_JDOUBLE = 107,\r
+    JVMTI_TYPE_JBOOLEAN = 108,\r
+    JVMTI_TYPE_JOBJECT = 109,\r
+    JVMTI_TYPE_JTHREAD = 110,\r
+    JVMTI_TYPE_JCLASS = 111,\r
+    JVMTI_TYPE_JVALUE = 112,\r
+    JVMTI_TYPE_JFIELDID = 113,\r
+    JVMTI_TYPE_JMETHODID = 114,\r
+    JVMTI_TYPE_CCHAR = 115,\r
+    JVMTI_TYPE_CVOID = 116,\r
+    JVMTI_TYPE_JNIENV = 117\r
+} jvmtiParamTypes;\r
+\r
+    /* Extension Function/Event Parameter Kinds */ \r
+\r
+typedef enum {\r
+    JVMTI_KIND_IN = 91,\r
+    JVMTI_KIND_IN_PTR = 92,\r
+    JVMTI_KIND_IN_BUF = 93,\r
+    JVMTI_KIND_ALLOC_BUF = 94,\r
+    JVMTI_KIND_ALLOC_ALLOC_BUF = 95,\r
+    JVMTI_KIND_OUT = 96,\r
+    JVMTI_KIND_OUT_BUF = 97\r
+} jvmtiParamKind;\r
+\r
+    /* Timer Kinds */ \r
+\r
+typedef enum {\r
+    JVMTI_TIMER_USER_CPU = 30,\r
+    JVMTI_TIMER_TOTAL_CPU = 31,\r
+    JVMTI_TIMER_ELAPSED = 32\r
+} jvmtiTimerKind;\r
+\r
+    /* Phases of execution */ \r
+\r
+typedef enum {\r
+    JVMTI_PHASE_ONLOAD = 1,\r
+    JVMTI_PHASE_PRIMORDIAL = 2,\r
+    JVMTI_PHASE_START = 6,\r
+    JVMTI_PHASE_LIVE = 4,\r
+    JVMTI_PHASE_DEAD = 8\r
+} jvmtiPhase;\r
+\r
+    /* Version Interface Types */ \r
+\r
+enum {\r
+    JVMTI_VERSION_INTERFACE_JNI = 0x00000000,\r
+    JVMTI_VERSION_INTERFACE_JVMTI = 0x30000000\r
+};\r
+\r
+    /* Version Masks */ \r
+\r
+enum {\r
+    JVMTI_VERSION_MASK_INTERFACE_TYPE = 0x70000000,\r
+    JVMTI_VERSION_MASK_MAJOR = 0x0FFF0000,\r
+    JVMTI_VERSION_MASK_MINOR = 0x0000FF00,\r
+    JVMTI_VERSION_MASK_MICRO = 0x000000FF\r
+};\r
+\r
+    /* Version Shifts */ \r
+\r
+enum {\r
+    JVMTI_VERSION_SHIFT_MAJOR = 16,\r
+    JVMTI_VERSION_SHIFT_MINOR = 8,\r
+    JVMTI_VERSION_SHIFT_MICRO = 0\r
+};\r
+\r
+    /* Verbose Flag Enumeration */ \r
+\r
+typedef enum {\r
+    JVMTI_VERBOSE_OTHER = 0,\r
+    JVMTI_VERBOSE_GC = 1,\r
+    JVMTI_VERBOSE_CLASS = 2,\r
+    JVMTI_VERBOSE_JNI = 4\r
+} jvmtiVerboseFlag;\r
+\r
+    /* JLocation Format Enumeration */ \r
+\r
+typedef enum {\r
+    JVMTI_JLOCATION_JVMBCI = 1,\r
+    JVMTI_JLOCATION_MACHINEPC = 2,\r
+    JVMTI_JLOCATION_OTHER = 0\r
+} jvmtiJlocationFormat;\r
+\r
+    /* Errors */\r
+\r
+typedef enum {\r
+    JVMTI_ERROR_NONE = 0,\r
+    JVMTI_ERROR_INVALID_THREAD = 10,\r
+    JVMTI_ERROR_INVALID_THREAD_GROUP = 11,\r
+    JVMTI_ERROR_INVALID_PRIORITY = 12,\r
+    JVMTI_ERROR_THREAD_NOT_SUSPENDED = 13,\r
+    JVMTI_ERROR_THREAD_SUSPENDED = 14,\r
+    JVMTI_ERROR_THREAD_NOT_ALIVE = 15,\r
+    JVMTI_ERROR_INVALID_OBJECT = 20,\r
+    JVMTI_ERROR_INVALID_CLASS = 21,\r
+    JVMTI_ERROR_CLASS_NOT_PREPARED = 22,\r
+    JVMTI_ERROR_INVALID_METHODID = 23,\r
+    JVMTI_ERROR_INVALID_LOCATION = 24,\r
+    JVMTI_ERROR_INVALID_FIELDID = 25,\r
+    JVMTI_ERROR_NO_MORE_FRAMES = 31,\r
+    JVMTI_ERROR_OPAQUE_FRAME = 32,\r
+    JVMTI_ERROR_TYPE_MISMATCH = 34,\r
+    JVMTI_ERROR_INVALID_SLOT = 35,\r
+    JVMTI_ERROR_DUPLICATE = 40,\r
+    JVMTI_ERROR_NOT_FOUND = 41,\r
+    JVMTI_ERROR_INVALID_MONITOR = 50,\r
+    JVMTI_ERROR_NOT_MONITOR_OWNER = 51,\r
+    JVMTI_ERROR_INTERRUPT = 52,\r
+    JVMTI_ERROR_INVALID_CLASS_FORMAT = 60,\r
+    JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION = 61,\r
+    JVMTI_ERROR_FAILS_VERIFICATION = 62,\r
+    JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED = 63,\r
+    JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED = 64,\r
+    JVMTI_ERROR_INVALID_TYPESTATE = 65,\r
+    JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED = 66,\r
+    JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED = 67,\r
+    JVMTI_ERROR_UNSUPPORTED_VERSION = 68,\r
+    JVMTI_ERROR_NAMES_DONT_MATCH = 69,\r
+    JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED = 70,\r
+    JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED = 71,\r
+    JVMTI_ERROR_UNMODIFIABLE_CLASS = 79,\r
+    JVMTI_ERROR_NOT_AVAILABLE = 98,\r
+    JVMTI_ERROR_MUST_POSSESS_CAPABILITY = 99,\r
+    JVMTI_ERROR_NULL_POINTER = 100,\r
+    JVMTI_ERROR_ABSENT_INFORMATION = 101,\r
+    JVMTI_ERROR_INVALID_EVENT_TYPE = 102,\r
+    JVMTI_ERROR_ILLEGAL_ARGUMENT = 103,\r
+    JVMTI_ERROR_NATIVE_METHOD = 104,\r
+    JVMTI_ERROR_OUT_OF_MEMORY = 110,\r
+    JVMTI_ERROR_ACCESS_DENIED = 111,\r
+    JVMTI_ERROR_WRONG_PHASE = 112,\r
+    JVMTI_ERROR_INTERNAL = 113,\r
+    JVMTI_ERROR_UNATTACHED_THREAD = 115,\r
+    JVMTI_ERROR_INVALID_ENVIRONMENT = 116,\r
+    JVMTI_ERROR_MAX = 116\r
+} jvmtiError;\r
+\r
+    /* Event IDs */\r
+\r
+typedef enum {\r
+    JVMTI_MIN_EVENT_TYPE_VAL = 50,\r
+    JVMTI_EVENT_VM_INIT = 50,\r
+    JVMTI_EVENT_VM_DEATH = 51,\r
+    JVMTI_EVENT_THREAD_START = 52,\r
+    JVMTI_EVENT_THREAD_END = 53,\r
+    JVMTI_EVENT_CLASS_FILE_LOAD_HOOK = 54,\r
+    JVMTI_EVENT_CLASS_LOAD = 55,\r
+    JVMTI_EVENT_CLASS_PREPARE = 56,\r
+    JVMTI_EVENT_VM_START = 57,\r
+    JVMTI_EVENT_EXCEPTION = 58,\r
+    JVMTI_EVENT_EXCEPTION_CATCH = 59,\r
+    JVMTI_EVENT_SINGLE_STEP = 60,\r
+    JVMTI_EVENT_FRAME_POP = 61,\r
+    JVMTI_EVENT_BREAKPOINT = 62,\r
+    JVMTI_EVENT_FIELD_ACCESS = 63,\r
+    JVMTI_EVENT_FIELD_MODIFICATION = 64,\r
+    JVMTI_EVENT_METHOD_ENTRY = 65,\r
+    JVMTI_EVENT_METHOD_EXIT = 66,\r
+    JVMTI_EVENT_NATIVE_METHOD_BIND = 67,\r
+    JVMTI_EVENT_COMPILED_METHOD_LOAD = 68,\r
+    JVMTI_EVENT_COMPILED_METHOD_UNLOAD = 69,\r
+    JVMTI_EVENT_DYNAMIC_CODE_GENERATED = 70,\r
+    JVMTI_EVENT_DATA_DUMP_REQUEST = 71,\r
+    JVMTI_EVENT_MONITOR_WAIT = 73,\r
+    JVMTI_EVENT_MONITOR_WAITED = 74,\r
+    JVMTI_EVENT_MONITOR_CONTENDED_ENTER = 75,\r
+    JVMTI_EVENT_MONITOR_CONTENDED_ENTERED = 76,\r
+    JVMTI_EVENT_GARBAGE_COLLECTION_START = 81,\r
+    JVMTI_EVENT_GARBAGE_COLLECTION_FINISH = 82,\r
+    JVMTI_EVENT_OBJECT_FREE = 83,\r
+    JVMTI_EVENT_VM_OBJECT_ALLOC = 84,\r
+    JVMTI_MAX_EVENT_TYPE_VAL = 84\r
+} jvmtiEvent;\r
+\r
+\r
+    /* Function Types */\r
+\r
+typedef void (JNICALL *jvmtiStartFunction)\r
+    (jvmtiEnv* jvmti_env, JNIEnv* jni_env, void* arg);\r
+\r
+typedef jvmtiIterationControl (JNICALL *jvmtiHeapObjectCallback)\r
+    (jlong class_tag, jlong size, jlong* tag_ptr, void* user_data);\r
+\r
+typedef jvmtiIterationControl (JNICALL *jvmtiHeapRootCallback)\r
+    (jvmtiHeapRootKind root_kind, jlong class_tag, jlong size, jlong* tag_ptr, void* user_data);\r
+\r
+typedef jvmtiIterationControl (JNICALL *jvmtiStackReferenceCallback)\r
+    (jvmtiHeapRootKind root_kind, jlong class_tag, jlong size, jlong* tag_ptr, jlong thread_tag, jint depth, jmethodID method, jint slot, void* user_data);\r
+\r
+typedef jvmtiIterationControl (JNICALL *jvmtiObjectReferenceCallback)\r
+    (jvmtiObjectReferenceKind reference_kind, jlong class_tag, jlong size, jlong* tag_ptr, jlong referrer_tag, jint referrer_index, void* user_data);\r
+\r
+typedef jvmtiError (JNICALL *jvmtiExtensionFunction)\r
+    (jvmtiEnv* jvmti_env,  ...);\r
+\r
+typedef void (JNICALL *jvmtiExtensionEvent)\r
+    (jvmtiEnv* jvmti_env,  ...);\r
+\r
+\r
+    /* Structure Types */\r
+\r
+typedef struct {\r
+    char* name;\r
+    jint priority;\r
+    jboolean is_daemon;\r
+    jthreadGroup thread_group;\r
+    jobject context_class_loader;\r
+} jvmtiThreadInfo;\r
+\r
+typedef struct {\r
+    jthreadGroup parent;\r
+    char* name;\r
+    jint max_priority;\r
+    jboolean is_daemon;\r
+} jvmtiThreadGroupInfo;\r
+\r
+typedef struct {\r
+    jmethodID method;\r
+    jlocation location;\r
+} jvmtiFrameInfo;\r
+\r
+typedef struct {\r
+    jthread thread;\r
+    jint state;\r
+    jvmtiFrameInfo* frame_buffer;\r
+    jint frame_count;\r
+} jvmtiStackInfo;\r
+\r
+typedef struct {\r
+    jclass klass;\r
+    jint class_byte_count;\r
+    const unsigned char* class_bytes;\r
+} jvmtiClassDefinition;\r
+\r
+typedef struct {\r
+    jthread owner;\r
+    jint entry_count;\r
+    jint waiter_count;\r
+    jthread* waiters;\r
+    jint notify_waiter_count;\r
+    jthread* notify_waiters;\r
+} jvmtiMonitorUsage;\r
+\r
+typedef struct {\r
+    jlocation start_location;\r
+    jint line_number;\r
+} jvmtiLineNumberEntry;\r
+\r
+typedef struct {\r
+    jlocation start_location;\r
+    jint length;\r
+    char* name;\r
+    char* signature;\r
+    char* generic_signature;\r
+    jint slot;\r
+} jvmtiLocalVariableEntry;\r
+\r
+typedef struct {\r
+    char* name;\r
+    jvmtiParamKind kind;\r
+    jvmtiParamTypes base_type;\r
+    jboolean null_ok;\r
+} jvmtiParamInfo;\r
+\r
+typedef struct {\r
+    jvmtiExtensionFunction func;\r
+    char* id;\r
+    char* short_description;\r
+    jint param_count;\r
+    jvmtiParamInfo* params;\r
+    jint error_count;\r
+    jvmtiError* errors;\r
+} jvmtiExtensionFunctionInfo;\r
+\r
+typedef struct {\r
+    jint extension_event_index;\r
+    char* id;\r
+    char* short_description;\r
+    jint param_count;\r
+    jvmtiParamInfo* params;\r
+} jvmtiExtensionEventInfo;\r
+\r
+typedef struct {\r
+    jlong max_value;\r
+    jboolean may_skip_forward;\r
+    jboolean may_skip_backward;\r
+    jvmtiTimerKind kind;\r
+    jlong reserved1;\r
+    jlong reserved2;\r
+} jvmtiTimerInfo;\r
+\r
+typedef struct {\r
+    const void* start_address;\r
+    jlocation location;\r
+} jvmtiAddrLocationMap;\r
+\r
+typedef struct {\r
+    unsigned int can_tag_objects : 1;\r
+    unsigned int can_generate_field_modification_events : 1;\r
+    unsigned int can_generate_field_access_events : 1;\r
+    unsigned int can_get_bytecodes : 1;\r
+    unsigned int can_get_synthetic_attribute : 1;\r
+    unsigned int can_get_owned_monitor_info : 1;\r
+    unsigned int can_get_current_contended_monitor : 1;\r
+    unsigned int can_get_monitor_info : 1;\r
+    unsigned int can_pop_frame : 1;\r
+    unsigned int can_redefine_classes : 1;\r
+    unsigned int can_signal_thread : 1;\r
+    unsigned int can_get_source_file_name : 1;\r
+    unsigned int can_get_line_numbers : 1;\r
+    unsigned int can_get_source_debug_extension : 1;\r
+    unsigned int can_access_local_variables : 1;\r
+    unsigned int can_maintain_original_method_order : 1;\r
+    unsigned int can_generate_single_step_events : 1;\r
+    unsigned int can_generate_exception_events : 1;\r
+    unsigned int can_generate_frame_pop_events : 1;\r
+    unsigned int can_generate_breakpoint_events : 1;\r
+    unsigned int can_suspend : 1;\r
+    unsigned int can_redefine_any_class : 1;\r
+    unsigned int can_get_current_thread_cpu_time : 1;\r
+    unsigned int can_get_thread_cpu_time : 1;\r
+    unsigned int can_generate_method_entry_events : 1;\r
+    unsigned int can_generate_method_exit_events : 1;\r
+    unsigned int can_generate_all_class_hook_events : 1;\r
+    unsigned int can_generate_compiled_method_load_events : 1;\r
+    unsigned int can_generate_monitor_events : 1;\r
+    unsigned int can_generate_vm_object_alloc_events : 1;\r
+    unsigned int can_generate_native_method_bind_events : 1;\r
+    unsigned int can_generate_garbage_collection_events : 1;\r
+    unsigned int can_generate_object_free_events : 1;\r
+    unsigned int : 15;\r
+    unsigned int : 16;\r
+    unsigned int : 16;\r
+    unsigned int : 16;\r
+    unsigned int : 16;\r
+    unsigned int : 16;\r
+} jvmtiCapabilities;\r
+\r
+\r
+    /* Event Definitions */\r
+\r
+typedef void (JNICALL *jvmtiEventReserved)(void);\r
+\r
+\r
+typedef void (JNICALL *jvmtiEventBreakpoint)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jmethodID method, \r
+     jlocation location);\r
+\r
+typedef void (JNICALL *jvmtiEventClassFileLoadHook)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jclass class_being_redefined, \r
+     jobject loader, \r
+     const char* name, \r
+     jobject protection_domain, \r
+     jint class_data_len, \r
+     const unsigned char* class_data, \r
+     jint* new_class_data_len, \r
+     unsigned char** new_class_data);\r
+\r
+typedef void (JNICALL *jvmtiEventClassLoad)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jclass klass);\r
+\r
+typedef void (JNICALL *jvmtiEventClassPrepare)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jclass klass);\r
+\r
+typedef void (JNICALL *jvmtiEventCompiledMethodLoad)\r
+    (jvmtiEnv *jvmti_env, \r
+     jmethodID method, \r
+     jint code_size, \r
+     const void* code_addr, \r
+     jint map_length, \r
+     const jvmtiAddrLocationMap* map, \r
+     const void* compile_info);\r
+\r
+typedef void (JNICALL *jvmtiEventCompiledMethodUnload)\r
+    (jvmtiEnv *jvmti_env, \r
+     jmethodID method, \r
+     const void* code_addr);\r
+\r
+typedef void (JNICALL *jvmtiEventDataDumpRequest)\r
+    (jvmtiEnv *jvmti_env);\r
+\r
+typedef void (JNICALL *jvmtiEventDynamicCodeGenerated)\r
+    (jvmtiEnv *jvmti_env, \r
+     const char* name, \r
+     const void* address, \r
+     jint length);\r
+\r
+typedef void (JNICALL *jvmtiEventException)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jmethodID method, \r
+     jlocation location, \r
+     jobject exception, \r
+     jmethodID catch_method, \r
+     jlocation catch_location);\r
+\r
+typedef void (JNICALL *jvmtiEventExceptionCatch)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jmethodID method, \r
+     jlocation location, \r
+     jobject exception);\r
+\r
+typedef void (JNICALL *jvmtiEventFieldAccess)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jmethodID method, \r
+     jlocation location, \r
+     jclass field_klass, \r
+     jobject object, \r
+     jfieldID field);\r
+\r
+typedef void (JNICALL *jvmtiEventFieldModification)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jmethodID method, \r
+     jlocation location, \r
+     jclass field_klass, \r
+     jobject object, \r
+     jfieldID field, \r
+     char signature_type, \r
+     jvalue new_value);\r
+\r
+typedef void (JNICALL *jvmtiEventFramePop)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jmethodID method, \r
+     jboolean was_popped_by_exception);\r
+\r
+typedef void (JNICALL *jvmtiEventGarbageCollectionFinish)\r
+    (jvmtiEnv *jvmti_env);\r
+\r
+typedef void (JNICALL *jvmtiEventGarbageCollectionStart)\r
+    (jvmtiEnv *jvmti_env);\r
+\r
+typedef void (JNICALL *jvmtiEventMethodEntry)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jmethodID method);\r
+\r
+typedef void (JNICALL *jvmtiEventMethodExit)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jmethodID method, \r
+     jboolean was_popped_by_exception, \r
+     jvalue return_value);\r
+\r
+typedef void (JNICALL *jvmtiEventMonitorContendedEnter)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jobject object);\r
+\r
+typedef void (JNICALL *jvmtiEventMonitorContendedEntered)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jobject object);\r
+\r
+typedef void (JNICALL *jvmtiEventMonitorWait)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jobject object, \r
+     jlong timeout);\r
+\r
+typedef void (JNICALL *jvmtiEventMonitorWaited)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jobject object, \r
+     jboolean timed_out);\r
+\r
+typedef void (JNICALL *jvmtiEventNativeMethodBind)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jmethodID method, \r
+     void* address, \r
+     void** new_address_ptr);\r
+\r
+typedef void (JNICALL *jvmtiEventObjectFree)\r
+    (jvmtiEnv *jvmti_env, \r
+     jlong tag);\r
+\r
+typedef void (JNICALL *jvmtiEventSingleStep)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jmethodID method, \r
+     jlocation location);\r
+\r
+typedef void (JNICALL *jvmtiEventThreadEnd)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread);\r
+\r
+typedef void (JNICALL *jvmtiEventThreadStart)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread);\r
+\r
+typedef void (JNICALL *jvmtiEventVMDeath)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env);\r
+\r
+typedef void (JNICALL *jvmtiEventVMInit)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread);\r
+\r
+typedef void (JNICALL *jvmtiEventVMObjectAlloc)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env, \r
+     jthread thread, \r
+     jobject object, \r
+     jclass object_klass, \r
+     jlong size);\r
+\r
+typedef void (JNICALL *jvmtiEventVMStart)\r
+    (jvmtiEnv *jvmti_env, \r
+     JNIEnv* jni_env);\r
+\r
+    /* Event Callback Structure */\r
+\r
+typedef struct {\r
+                              /*   50 : VM Initialization Event */\r
+    jvmtiEventVMInit VMInit;\r
+                              /*   51 : VM Death Event */\r
+    jvmtiEventVMDeath VMDeath;\r
+                              /*   52 : Thread Start */\r
+    jvmtiEventThreadStart ThreadStart;\r
+                              /*   53 : Thread End */\r
+    jvmtiEventThreadEnd ThreadEnd;\r
+                              /*   54 : Class File Load Hook */\r
+    jvmtiEventClassFileLoadHook ClassFileLoadHook;\r
+                              /*   55 : Class Load */\r
+    jvmtiEventClassLoad ClassLoad;\r
+                              /*   56 : Class Prepare */\r
+    jvmtiEventClassPrepare ClassPrepare;\r
+                              /*   57 : VM Start Event */\r
+    jvmtiEventVMStart VMStart;\r
+                              /*   58 : Exception */\r
+    jvmtiEventException Exception;\r
+                              /*   59 : Exception Catch */\r
+    jvmtiEventExceptionCatch ExceptionCatch;\r
+                              /*   60 : Single Step */\r
+    jvmtiEventSingleStep SingleStep;\r
+                              /*   61 : Frame Pop */\r
+    jvmtiEventFramePop FramePop;\r
+                              /*   62 : Breakpoint */\r
+    jvmtiEventBreakpoint Breakpoint;\r
+                              /*   63 : Field Access */\r
+    jvmtiEventFieldAccess FieldAccess;\r
+                              /*   64 : Field Modification */\r
+    jvmtiEventFieldModification FieldModification;\r
+                              /*   65 : Method Entry */\r
+    jvmtiEventMethodEntry MethodEntry;\r
+                              /*   66 : Method Exit */\r
+    jvmtiEventMethodExit MethodExit;\r
+                              /*   67 : Native Method Bind */\r
+    jvmtiEventNativeMethodBind NativeMethodBind;\r
+                              /*   68 : Compiled Method Load */\r
+    jvmtiEventCompiledMethodLoad CompiledMethodLoad;\r
+                              /*   69 : Compiled Method Unload */\r
+    jvmtiEventCompiledMethodUnload CompiledMethodUnload;\r
+                              /*   70 : Dynamic Code Generated */\r
+    jvmtiEventDynamicCodeGenerated DynamicCodeGenerated;\r
+                              /*   71 : Data Dump Request */\r
+    jvmtiEventDataDumpRequest DataDumpRequest;\r
+                              /*   72 */\r
+    jvmtiEventReserved reserved72;\r
+                              /*   73 : Monitor Wait */\r
+    jvmtiEventMonitorWait MonitorWait;\r
+                              /*   74 : Monitor Waited */\r
+    jvmtiEventMonitorWaited MonitorWaited;\r
+                              /*   75 : Monitor Contended Enter */\r
+    jvmtiEventMonitorContendedEnter MonitorContendedEnter;\r
+                              /*   76 : Monitor Contended Entered */\r
+    jvmtiEventMonitorContendedEntered MonitorContendedEntered;\r
+                              /*   77 */\r
+    jvmtiEventReserved reserved77;\r
+                              /*   78 */\r
+    jvmtiEventReserved reserved78;\r
+                              /*   79 */\r
+    jvmtiEventReserved reserved79;\r
+                              /*   80 */\r
+    jvmtiEventReserved reserved80;\r
+                              /*   81 : Garbage Collection Start */\r
+    jvmtiEventGarbageCollectionStart GarbageCollectionStart;\r
+                              /*   82 : Garbage Collection Finish */\r
+    jvmtiEventGarbageCollectionFinish GarbageCollectionFinish;\r
+                              /*   83 : Object Free */\r
+    jvmtiEventObjectFree ObjectFree;\r
+                              /*   84 : VM Object Allocation */\r
+    jvmtiEventVMObjectAlloc VMObjectAlloc;\r
+} jvmtiEventCallbacks;\r
+\r
+\r
+    /* Function Interface */\r
+    \r
+typedef struct jvmtiInterface_1_ {\r
+\r
+  /*   1 :  RESERVED */\r
+  void *reserved1;\r
+\r
+  /*   2 : Set Event Notification Mode */\r
+  jvmtiError (JNICALL *SetEventNotificationMode) (jvmtiEnv* env, \r
+    jvmtiEventMode mode, \r
+    jvmtiEvent event_type, \r
+    jthread event_thread, \r
+     ...);\r
+\r
+  /*   3 :  RESERVED */\r
+  void *reserved3;\r
+\r
+  /*   4 : Get All Threads */\r
+  jvmtiError (JNICALL *GetAllThreads) (jvmtiEnv* env, \r
+    jint* threads_count_ptr, \r
+    jthread** threads_ptr);\r
+\r
+  /*   5 : Suspend Thread */\r
+  jvmtiError (JNICALL *SuspendThread) (jvmtiEnv* env, \r
+    jthread thread);\r
+\r
+  /*   6 : Resume Thread */\r
+  jvmtiError (JNICALL *ResumeThread) (jvmtiEnv* env, \r
+    jthread thread);\r
+\r
+  /*   7 : Stop Thread */\r
+  jvmtiError (JNICALL *StopThread) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jobject exception);\r
+\r
+  /*   8 : Interrupt Thread */\r
+  jvmtiError (JNICALL *InterruptThread) (jvmtiEnv* env, \r
+    jthread thread);\r
+\r
+  /*   9 : Get Thread Info */\r
+  jvmtiError (JNICALL *GetThreadInfo) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jvmtiThreadInfo* info_ptr);\r
+\r
+  /*   10 : Get Owned Monitor Info */\r
+  jvmtiError (JNICALL *GetOwnedMonitorInfo) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint* owned_monitor_count_ptr, \r
+    jobject** owned_monitors_ptr);\r
+\r
+  /*   11 : Get Current Contended Monitor */\r
+  jvmtiError (JNICALL *GetCurrentContendedMonitor) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jobject* monitor_ptr);\r
+\r
+  /*   12 : Run Agent Thread */\r
+  jvmtiError (JNICALL *RunAgentThread) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jvmtiStartFunction proc, \r
+    const void* arg, \r
+    jint priority);\r
+\r
+  /*   13 : Get Top Thread Groups */\r
+  jvmtiError (JNICALL *GetTopThreadGroups) (jvmtiEnv* env, \r
+    jint* group_count_ptr, \r
+    jthreadGroup** groups_ptr);\r
+\r
+  /*   14 : Get Thread Group Info */\r
+  jvmtiError (JNICALL *GetThreadGroupInfo) (jvmtiEnv* env, \r
+    jthreadGroup group, \r
+    jvmtiThreadGroupInfo* info_ptr);\r
+\r
+  /*   15 : Get Thread Group Children */\r
+  jvmtiError (JNICALL *GetThreadGroupChildren) (jvmtiEnv* env, \r
+    jthreadGroup group, \r
+    jint* thread_count_ptr, \r
+    jthread** threads_ptr, \r
+    jint* group_count_ptr, \r
+    jthreadGroup** groups_ptr);\r
+\r
+  /*   16 : Get Frame Count */\r
+  jvmtiError (JNICALL *GetFrameCount) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint* count_ptr);\r
+\r
+  /*   17 : Get Thread State */\r
+  jvmtiError (JNICALL *GetThreadState) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint* thread_state_ptr);\r
+\r
+  /*   18 :  RESERVED */\r
+  void *reserved18;\r
+\r
+  /*   19 : Get Frame Location */\r
+  jvmtiError (JNICALL *GetFrameLocation) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint depth, \r
+    jmethodID* method_ptr, \r
+    jlocation* location_ptr);\r
+\r
+  /*   20 : Notify Frame Pop */\r
+  jvmtiError (JNICALL *NotifyFramePop) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint depth);\r
+\r
+  /*   21 : Get Local Variable - Object */\r
+  jvmtiError (JNICALL *GetLocalObject) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint depth, \r
+    jint slot, \r
+    jobject* value_ptr);\r
+\r
+  /*   22 : Get Local Variable - Int */\r
+  jvmtiError (JNICALL *GetLocalInt) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint depth, \r
+    jint slot, \r
+    jint* value_ptr);\r
+\r
+  /*   23 : Get Local Variable - Long */\r
+  jvmtiError (JNICALL *GetLocalLong) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint depth, \r
+    jint slot, \r
+    jlong* value_ptr);\r
+\r
+  /*   24 : Get Local Variable - Float */\r
+  jvmtiError (JNICALL *GetLocalFloat) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint depth, \r
+    jint slot, \r
+    jfloat* value_ptr);\r
+\r
+  /*   25 : Get Local Variable - Double */\r
+  jvmtiError (JNICALL *GetLocalDouble) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint depth, \r
+    jint slot, \r
+    jdouble* value_ptr);\r
+\r
+  /*   26 : Set Local Variable - Object */\r
+  jvmtiError (JNICALL *SetLocalObject) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint depth, \r
+    jint slot, \r
+    jobject value);\r
+\r
+  /*   27 : Set Local Variable - Int */\r
+  jvmtiError (JNICALL *SetLocalInt) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint depth, \r
+    jint slot, \r
+    jint value);\r
+\r
+  /*   28 : Set Local Variable - Long */\r
+  jvmtiError (JNICALL *SetLocalLong) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint depth, \r
+    jint slot, \r
+    jlong value);\r
+\r
+  /*   29 : Set Local Variable - Float */\r
+  jvmtiError (JNICALL *SetLocalFloat) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint depth, \r
+    jint slot, \r
+    jfloat value);\r
+\r
+  /*   30 : Set Local Variable - Double */\r
+  jvmtiError (JNICALL *SetLocalDouble) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint depth, \r
+    jint slot, \r
+    jdouble value);\r
+\r
+  /*   31 : Create Raw Monitor */\r
+  jvmtiError (JNICALL *CreateRawMonitor) (jvmtiEnv* env, \r
+    const char* name, \r
+    jrawMonitorID* monitor_ptr);\r
+\r
+  /*   32 : Destroy Raw Monitor */\r
+  jvmtiError (JNICALL *DestroyRawMonitor) (jvmtiEnv* env, \r
+    jrawMonitorID monitor);\r
+\r
+  /*   33 : Raw Monitor Enter */\r
+  jvmtiError (JNICALL *RawMonitorEnter) (jvmtiEnv* env, \r
+    jrawMonitorID monitor);\r
+\r
+  /*   34 : Raw Monitor Exit */\r
+  jvmtiError (JNICALL *RawMonitorExit) (jvmtiEnv* env, \r
+    jrawMonitorID monitor);\r
+\r
+  /*   35 : Raw Monitor Wait */\r
+  jvmtiError (JNICALL *RawMonitorWait) (jvmtiEnv* env, \r
+    jrawMonitorID monitor, \r
+    jlong millis);\r
+\r
+  /*   36 : Raw Monitor Notify */\r
+  jvmtiError (JNICALL *RawMonitorNotify) (jvmtiEnv* env, \r
+    jrawMonitorID monitor);\r
+\r
+  /*   37 : Raw Monitor Notify All */\r
+  jvmtiError (JNICALL *RawMonitorNotifyAll) (jvmtiEnv* env, \r
+    jrawMonitorID monitor);\r
+\r
+  /*   38 : Set Breakpoint */\r
+  jvmtiError (JNICALL *SetBreakpoint) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    jlocation location);\r
+\r
+  /*   39 : Clear Breakpoint */\r
+  jvmtiError (JNICALL *ClearBreakpoint) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    jlocation location);\r
+\r
+  /*   40 :  RESERVED */\r
+  void *reserved40;\r
+\r
+  /*   41 : Set Field Access Watch */\r
+  jvmtiError (JNICALL *SetFieldAccessWatch) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jfieldID field);\r
+\r
+  /*   42 : Clear Field Access Watch */\r
+  jvmtiError (JNICALL *ClearFieldAccessWatch) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jfieldID field);\r
+\r
+  /*   43 : Set Field Modification Watch */\r
+  jvmtiError (JNICALL *SetFieldModificationWatch) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jfieldID field);\r
+\r
+  /*   44 : Clear Field Modification Watch */\r
+  jvmtiError (JNICALL *ClearFieldModificationWatch) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jfieldID field);\r
+\r
+  /*   45 :  RESERVED */\r
+  void *reserved45;\r
+\r
+  /*   46 : Allocate */\r
+  jvmtiError (JNICALL *Allocate) (jvmtiEnv* env, \r
+    jlong size, \r
+    unsigned char** mem_ptr);\r
+\r
+  /*   47 : Deallocate */\r
+  jvmtiError (JNICALL *Deallocate) (jvmtiEnv* env, \r
+    unsigned char* mem);\r
+\r
+  /*   48 : Get Class Signature */\r
+  jvmtiError (JNICALL *GetClassSignature) (jvmtiEnv* env, \r
+    jclass klass, \r
+    char** signature_ptr, \r
+    char** generic_ptr);\r
+\r
+  /*   49 : Get Class Status */\r
+  jvmtiError (JNICALL *GetClassStatus) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jint* status_ptr);\r
+\r
+  /*   50 : Get Source File Name */\r
+  jvmtiError (JNICALL *GetSourceFileName) (jvmtiEnv* env, \r
+    jclass klass, \r
+    char** source_name_ptr);\r
+\r
+  /*   51 : Get Class Modifiers */\r
+  jvmtiError (JNICALL *GetClassModifiers) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jint* modifiers_ptr);\r
+\r
+  /*   52 : Get Class Methods */\r
+  jvmtiError (JNICALL *GetClassMethods) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jint* method_count_ptr, \r
+    jmethodID** methods_ptr);\r
+\r
+  /*   53 : Get Class Fields */\r
+  jvmtiError (JNICALL *GetClassFields) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jint* field_count_ptr, \r
+    jfieldID** fields_ptr);\r
+\r
+  /*   54 : Get Implemented Interfaces */\r
+  jvmtiError (JNICALL *GetImplementedInterfaces) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jint* interface_count_ptr, \r
+    jclass** interfaces_ptr);\r
+\r
+  /*   55 : Is Interface */\r
+  jvmtiError (JNICALL *IsInterface) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jboolean* is_interface_ptr);\r
+\r
+  /*   56 : Is Array Class */\r
+  jvmtiError (JNICALL *IsArrayClass) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jboolean* is_array_class_ptr);\r
+\r
+  /*   57 : Get Class Loader */\r
+  jvmtiError (JNICALL *GetClassLoader) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jobject* classloader_ptr);\r
+\r
+  /*   58 : Get Object Hash Code */\r
+  jvmtiError (JNICALL *GetObjectHashCode) (jvmtiEnv* env, \r
+    jobject object, \r
+    jint* hash_code_ptr);\r
+\r
+  /*   59 : Get Object Monitor Usage */\r
+  jvmtiError (JNICALL *GetObjectMonitorUsage) (jvmtiEnv* env, \r
+    jobject object, \r
+    jvmtiMonitorUsage* info_ptr);\r
+\r
+  /*   60 : Get Field Name (and Signature) */\r
+  jvmtiError (JNICALL *GetFieldName) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jfieldID field, \r
+    char** name_ptr, \r
+    char** signature_ptr, \r
+    char** generic_ptr);\r
+\r
+  /*   61 : Get Field Declaring Class */\r
+  jvmtiError (JNICALL *GetFieldDeclaringClass) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jfieldID field, \r
+    jclass* declaring_class_ptr);\r
+\r
+  /*   62 : Get Field Modifiers */\r
+  jvmtiError (JNICALL *GetFieldModifiers) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jfieldID field, \r
+    jint* modifiers_ptr);\r
+\r
+  /*   63 : Is Field Synthetic */\r
+  jvmtiError (JNICALL *IsFieldSynthetic) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jfieldID field, \r
+    jboolean* is_synthetic_ptr);\r
+\r
+  /*   64 : Get Method Name (and Signature) */\r
+  jvmtiError (JNICALL *GetMethodName) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    char** name_ptr, \r
+    char** signature_ptr, \r
+    char** generic_ptr);\r
+\r
+  /*   65 : Get Method Declaring Class */\r
+  jvmtiError (JNICALL *GetMethodDeclaringClass) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    jclass* declaring_class_ptr);\r
+\r
+  /*   66 : Get Method Modifiers */\r
+  jvmtiError (JNICALL *GetMethodModifiers) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    jint* modifiers_ptr);\r
+\r
+  /*   67 :  RESERVED */\r
+  void *reserved67;\r
+\r
+  /*   68 : Get Max Locals */\r
+  jvmtiError (JNICALL *GetMaxLocals) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    jint* max_ptr);\r
+\r
+  /*   69 : Get Arguments Size */\r
+  jvmtiError (JNICALL *GetArgumentsSize) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    jint* size_ptr);\r
+\r
+  /*   70 : Get Line Number Table */\r
+  jvmtiError (JNICALL *GetLineNumberTable) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    jint* entry_count_ptr, \r
+    jvmtiLineNumberEntry** table_ptr);\r
+\r
+  /*   71 : Get Method Location */\r
+  jvmtiError (JNICALL *GetMethodLocation) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    jlocation* start_location_ptr, \r
+    jlocation* end_location_ptr);\r
+\r
+  /*   72 : Get Local Variable Table */\r
+  jvmtiError (JNICALL *GetLocalVariableTable) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    jint* entry_count_ptr, \r
+    jvmtiLocalVariableEntry** table_ptr);\r
+\r
+  /*   73 :  RESERVED */\r
+  void *reserved73;\r
+\r
+  /*   74 :  RESERVED */\r
+  void *reserved74;\r
+\r
+  /*   75 : Get Bytecodes */\r
+  jvmtiError (JNICALL *GetBytecodes) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    jint* bytecode_count_ptr, \r
+    unsigned char** bytecodes_ptr);\r
+\r
+  /*   76 : Is Method Native */\r
+  jvmtiError (JNICALL *IsMethodNative) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    jboolean* is_native_ptr);\r
+\r
+  /*   77 : Is Method Synthetic */\r
+  jvmtiError (JNICALL *IsMethodSynthetic) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    jboolean* is_synthetic_ptr);\r
+\r
+  /*   78 : Get Loaded Classes */\r
+  jvmtiError (JNICALL *GetLoadedClasses) (jvmtiEnv* env, \r
+    jint* class_count_ptr, \r
+    jclass** classes_ptr);\r
+\r
+  /*   79 : Get Classloader Classes */\r
+  jvmtiError (JNICALL *GetClassLoaderClasses) (jvmtiEnv* env, \r
+    jobject initiating_loader, \r
+    jint* class_count_ptr, \r
+    jclass** classes_ptr);\r
+\r
+  /*   80 : Pop Frame */\r
+  jvmtiError (JNICALL *PopFrame) (jvmtiEnv* env, \r
+    jthread thread);\r
+\r
+  /*   81 :  RESERVED */\r
+  void *reserved81;\r
+\r
+  /*   82 :  RESERVED */\r
+  void *reserved82;\r
+\r
+  /*   83 :  RESERVED */\r
+  void *reserved83;\r
+\r
+  /*   84 :  RESERVED */\r
+  void *reserved84;\r
+\r
+  /*   85 :  RESERVED */\r
+  void *reserved85;\r
+\r
+  /*   86 :  RESERVED */\r
+  void *reserved86;\r
+\r
+  /*   87 : Redefine Classes */\r
+  jvmtiError (JNICALL *RedefineClasses) (jvmtiEnv* env, \r
+    jint class_count, \r
+    const jvmtiClassDefinition* class_definitions);\r
+\r
+  /*   88 : Get Version Number */\r
+  jvmtiError (JNICALL *GetVersionNumber) (jvmtiEnv* env, \r
+    jint* version_ptr);\r
+\r
+  /*   89 : Get Capabilities */\r
+  jvmtiError (JNICALL *GetCapabilities) (jvmtiEnv* env, \r
+    jvmtiCapabilities* capabilities_ptr);\r
+\r
+  /*   90 : Get Source Debug Extension */\r
+  jvmtiError (JNICALL *GetSourceDebugExtension) (jvmtiEnv* env, \r
+    jclass klass, \r
+    char** source_debug_extension_ptr);\r
+\r
+  /*   91 : Is Method Obsolete */\r
+  jvmtiError (JNICALL *IsMethodObsolete) (jvmtiEnv* env, \r
+    jmethodID method, \r
+    jboolean* is_obsolete_ptr);\r
+\r
+  /*   92 : Suspend Thread List */\r
+  jvmtiError (JNICALL *SuspendThreadList) (jvmtiEnv* env, \r
+    jint request_count, \r
+    const jthread* request_list, \r
+    jvmtiError* results);\r
+\r
+  /*   93 : Resume Thread List */\r
+  jvmtiError (JNICALL *ResumeThreadList) (jvmtiEnv* env, \r
+    jint request_count, \r
+    const jthread* request_list, \r
+    jvmtiError* results);\r
+\r
+  /*   94 :  RESERVED */\r
+  void *reserved94;\r
+\r
+  /*   95 :  RESERVED */\r
+  void *reserved95;\r
+\r
+  /*   96 :  RESERVED */\r
+  void *reserved96;\r
+\r
+  /*   97 :  RESERVED */\r
+  void *reserved97;\r
+\r
+  /*   98 :  RESERVED */\r
+  void *reserved98;\r
+\r
+  /*   99 :  RESERVED */\r
+  void *reserved99;\r
+\r
+  /*   100 : Get All Stack Traces */\r
+  jvmtiError (JNICALL *GetAllStackTraces) (jvmtiEnv* env, \r
+    jint max_frame_count, \r
+    jvmtiStackInfo** stack_info_ptr, \r
+    jint* thread_count_ptr);\r
+\r
+  /*   101 : Get Thread List Stack Traces */\r
+  jvmtiError (JNICALL *GetThreadListStackTraces) (jvmtiEnv* env, \r
+    jint thread_count, \r
+    const jthread* thread_list, \r
+    jint max_frame_count, \r
+    jvmtiStackInfo** stack_info_ptr);\r
+\r
+  /*   102 : Get Thread Local Storage */\r
+  jvmtiError (JNICALL *GetThreadLocalStorage) (jvmtiEnv* env, \r
+    jthread thread, \r
+    void** data_ptr);\r
+\r
+  /*   103 : Set Thread Local Storage */\r
+  jvmtiError (JNICALL *SetThreadLocalStorage) (jvmtiEnv* env, \r
+    jthread thread, \r
+    const void* data);\r
+\r
+  /*   104 : Get Stack Trace */\r
+  jvmtiError (JNICALL *GetStackTrace) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jint start_depth, \r
+    jint max_frame_count, \r
+    jvmtiFrameInfo* frame_buffer, \r
+    jint* count_ptr);\r
+\r
+  /*   105 :  RESERVED */\r
+  void *reserved105;\r
+\r
+  /*   106 : Get Tag */\r
+  jvmtiError (JNICALL *GetTag) (jvmtiEnv* env, \r
+    jobject object, \r
+    jlong* tag_ptr);\r
+\r
+  /*   107 : Set Tag */\r
+  jvmtiError (JNICALL *SetTag) (jvmtiEnv* env, \r
+    jobject object, \r
+    jlong tag);\r
+\r
+  /*   108 : Force Garbage Collection */\r
+  jvmtiError (JNICALL *ForceGarbageCollection) (jvmtiEnv* env);\r
+\r
+  /*   109 : Iterate Over Objects Reachable From Object */\r
+  jvmtiError (JNICALL *IterateOverObjectsReachableFromObject) (jvmtiEnv* env, \r
+    jobject object, \r
+    jvmtiObjectReferenceCallback object_reference_callback, \r
+    void* user_data);\r
+\r
+  /*   110 : Iterate Over Reachable Objects */\r
+  jvmtiError (JNICALL *IterateOverReachableObjects) (jvmtiEnv* env, \r
+    jvmtiHeapRootCallback heap_root_callback, \r
+    jvmtiStackReferenceCallback stack_ref_callback, \r
+    jvmtiObjectReferenceCallback object_ref_callback, \r
+    void* user_data);\r
+\r
+  /*   111 : Iterate Over Heap */\r
+  jvmtiError (JNICALL *IterateOverHeap) (jvmtiEnv* env, \r
+    jvmtiHeapObjectFilter object_filter, \r
+    jvmtiHeapObjectCallback heap_object_callback, \r
+    void* user_data);\r
+\r
+  /*   112 : Iterate Over Instances Of Class */\r
+  jvmtiError (JNICALL *IterateOverInstancesOfClass) (jvmtiEnv* env, \r
+    jclass klass, \r
+    jvmtiHeapObjectFilter object_filter, \r
+    jvmtiHeapObjectCallback heap_object_callback, \r
+    void* user_data);\r
+\r
+  /*   113 :  RESERVED */\r
+  void *reserved113;\r
+\r
+  /*   114 : Get Objects With Tags */\r
+  jvmtiError (JNICALL *GetObjectsWithTags) (jvmtiEnv* env, \r
+    jint tag_count, \r
+    const jlong* tags, \r
+    jint* count_ptr, \r
+    jobject** object_result_ptr, \r
+    jlong** tag_result_ptr);\r
+\r
+  /*   115 :  RESERVED */\r
+  void *reserved115;\r
+\r
+  /*   116 :  RESERVED */\r
+  void *reserved116;\r
+\r
+  /*   117 :  RESERVED */\r
+  void *reserved117;\r
+\r
+  /*   118 :  RESERVED */\r
+  void *reserved118;\r
+\r
+  /*   119 :  RESERVED */\r
+  void *reserved119;\r
+\r
+  /*   120 : Set JNI Function Table */\r
+  jvmtiError (JNICALL *SetJNIFunctionTable) (jvmtiEnv* env, \r
+    const jniNativeInterface* function_table);\r
+\r
+  /*   121 : Get JNI Function Table */\r
+  jvmtiError (JNICALL *GetJNIFunctionTable) (jvmtiEnv* env, \r
+    jniNativeInterface** function_table);\r
+\r
+  /*   122 : Set Event Callbacks */\r
+  jvmtiError (JNICALL *SetEventCallbacks) (jvmtiEnv* env, \r
+    const jvmtiEventCallbacks* callbacks, \r
+    jint size_of_callbacks);\r
+\r
+  /*   123 : Generate Events */\r
+  jvmtiError (JNICALL *GenerateEvents) (jvmtiEnv* env, \r
+    jvmtiEvent event_type);\r
+\r
+  /*   124 : Get Extension Functions */\r
+  jvmtiError (JNICALL *GetExtensionFunctions) (jvmtiEnv* env, \r
+    jint* extension_count_ptr, \r
+    jvmtiExtensionFunctionInfo** extensions);\r
+\r
+  /*   125 : Get Extension Events */\r
+  jvmtiError (JNICALL *GetExtensionEvents) (jvmtiEnv* env, \r
+    jint* extension_count_ptr, \r
+    jvmtiExtensionEventInfo** extensions);\r
+\r
+  /*   126 : Set Extension Event Callback */\r
+  jvmtiError (JNICALL *SetExtensionEventCallback) (jvmtiEnv* env, \r
+    jint extension_event_index, \r
+    jvmtiExtensionEvent callback);\r
+\r
+  /*   127 : Dispose Environment */\r
+  jvmtiError (JNICALL *DisposeEnvironment) (jvmtiEnv* env);\r
+\r
+  /*   128 : Get Error Name */\r
+  jvmtiError (JNICALL *GetErrorName) (jvmtiEnv* env, \r
+    jvmtiError error, \r
+    char** name_ptr);\r
+\r
+  /*   129 : Get JLocation Format */\r
+  jvmtiError (JNICALL *GetJLocationFormat) (jvmtiEnv* env, \r
+    jvmtiJlocationFormat* format_ptr);\r
+\r
+  /*   130 : Get System Properties */\r
+  jvmtiError (JNICALL *GetSystemProperties) (jvmtiEnv* env, \r
+    jint* count_ptr, \r
+    char*** property_ptr);\r
+\r
+  /*   131 : Get System Property */\r
+  jvmtiError (JNICALL *GetSystemProperty) (jvmtiEnv* env, \r
+    const char* property, \r
+    char** value_ptr);\r
+\r
+  /*   132 : Set System Property */\r
+  jvmtiError (JNICALL *SetSystemProperty) (jvmtiEnv* env, \r
+    const char* property, \r
+    const char* value);\r
+\r
+  /*   133 : Get Phase */\r
+  jvmtiError (JNICALL *GetPhase) (jvmtiEnv* env, \r
+    jvmtiPhase* phase_ptr);\r
+\r
+  /*   134 : Get Current Thread CPU Timer Information */\r
+  jvmtiError (JNICALL *GetCurrentThreadCpuTimerInfo) (jvmtiEnv* env, \r
+    jvmtiTimerInfo* info_ptr);\r
+\r
+  /*   135 : Get Current Thread CPU Time */\r
+  jvmtiError (JNICALL *GetCurrentThreadCpuTime) (jvmtiEnv* env, \r
+    jlong* nanos_ptr);\r
+\r
+  /*   136 : Get Thread CPU Timer Information */\r
+  jvmtiError (JNICALL *GetThreadCpuTimerInfo) (jvmtiEnv* env, \r
+    jvmtiTimerInfo* info_ptr);\r
+\r
+  /*   137 : Get Thread CPU Time */\r
+  jvmtiError (JNICALL *GetThreadCpuTime) (jvmtiEnv* env, \r
+    jthread thread, \r
+    jlong* nanos_ptr);\r
+\r
+  /*   138 : Get Timer Information */\r
+  jvmtiError (JNICALL *GetTimerInfo) (jvmtiEnv* env, \r
+    jvmtiTimerInfo* info_ptr);\r
+\r
+  /*   139 : Get Time */\r
+  jvmtiError (JNICALL *GetTime) (jvmtiEnv* env, \r
+    jlong* nanos_ptr);\r
+\r
+  /*   140 : Get Potential Capabilities */\r
+  jvmtiError (JNICALL *GetPotentialCapabilities) (jvmtiEnv* env, \r
+    jvmtiCapabilities* capabilities_ptr);\r
+\r
+  /*   141 :  RESERVED */\r
+  void *reserved141;\r
+\r
+  /*   142 : Add Capabilities */\r
+  jvmtiError (JNICALL *AddCapabilities) (jvmtiEnv* env, \r
+    const jvmtiCapabilities* capabilities_ptr);\r
+\r
+  /*   143 : Relinquish Capabilities */\r
+  jvmtiError (JNICALL *RelinquishCapabilities) (jvmtiEnv* env, \r
+    const jvmtiCapabilities* capabilities_ptr);\r
+\r
+  /*   144 : Get Available Processors */\r
+  jvmtiError (JNICALL *GetAvailableProcessors) (jvmtiEnv* env, \r
+    jint* processor_count_ptr);\r
+\r
+  /*   145 :  RESERVED */\r
+  void *reserved145;\r
+\r
+  /*   146 :  RESERVED */\r
+  void *reserved146;\r
+\r
+  /*   147 : Get Environment Local Storage */\r
+  jvmtiError (JNICALL *GetEnvironmentLocalStorage) (jvmtiEnv* env, \r
+    void** data_ptr);\r
+\r
+  /*   148 : Set Environment Local Storage */\r
+  jvmtiError (JNICALL *SetEnvironmentLocalStorage) (jvmtiEnv* env, \r
+    const void* data);\r
+\r
+  /*   149 : Add To Bootstrap Class Loader Search */\r
+  jvmtiError (JNICALL *AddToBootstrapClassLoaderSearch) (jvmtiEnv* env, \r
+    const char* segment);\r
+\r
+  /*   150 : Set Verbose Flag */\r
+  jvmtiError (JNICALL *SetVerboseFlag) (jvmtiEnv* env, \r
+    jvmtiVerboseFlag flag, \r
+    jboolean value);\r
+\r
+  /*   151 :  RESERVED */\r
+  void *reserved151;\r
+\r
+  /*   152 :  RESERVED */\r
+  void *reserved152;\r
+\r
+  /*   153 :  RESERVED */\r
+  void *reserved153;\r
+\r
+  /*   154 : Get Object Size */\r
+  jvmtiError (JNICALL *GetObjectSize) (jvmtiEnv* env, \r
+    jobject object, \r
+    jlong* size_ptr);\r
+\r
+} jvmtiInterface_1;\r
+\r
+struct _jvmtiEnv {\r
+    const struct jvmtiInterface_1_ *functions;\r
+#ifdef __cplusplus\r
+\r
+\r
+  jvmtiError Allocate(jlong size,\r
+            unsigned char** mem_ptr) {\r
+    return functions->Allocate(this, size, mem_ptr);\r
+  }\r
+\r
+  jvmtiError Deallocate(unsigned char* mem) {\r
+    return functions->Deallocate(this, mem);\r
+  }\r
+\r
+  jvmtiError GetThreadState(jthread thread,\r
+            jint* thread_state_ptr) {\r
+    return functions->GetThreadState(this, thread, thread_state_ptr);\r
+  }\r
+\r
+  jvmtiError GetAllThreads(jint* threads_count_ptr,\r
+            jthread** threads_ptr) {\r
+    return functions->GetAllThreads(this, threads_count_ptr, threads_ptr);\r
+  }\r
+\r
+  jvmtiError SuspendThread(jthread thread) {\r
+    return functions->SuspendThread(this, thread);\r
+  }\r
+\r
+  jvmtiError SuspendThreadList(jint request_count,\r
+            const jthread* request_list,\r
+            jvmtiError* results) {\r
+    return functions->SuspendThreadList(this, request_count, request_list, results);\r
+  }\r
+\r
+  jvmtiError ResumeThread(jthread thread) {\r
+    return functions->ResumeThread(this, thread);\r
+  }\r
+\r
+  jvmtiError ResumeThreadList(jint request_count,\r
+            const jthread* request_list,\r
+            jvmtiError* results) {\r
+    return functions->ResumeThreadList(this, request_count, request_list, results);\r
+  }\r
+\r
+  jvmtiError StopThread(jthread thread,\r
+            jobject exception) {\r
+    return functions->StopThread(this, thread, exception);\r
+  }\r
+\r
+  jvmtiError InterruptThread(jthread thread) {\r
+    return functions->InterruptThread(this, thread);\r
+  }\r
+\r
+  jvmtiError GetThreadInfo(jthread thread,\r
+            jvmtiThreadInfo* info_ptr) {\r
+    return functions->GetThreadInfo(this, thread, info_ptr);\r
+  }\r
+\r
+  jvmtiError GetOwnedMonitorInfo(jthread thread,\r
+            jint* owned_monitor_count_ptr,\r
+            jobject** owned_monitors_ptr) {\r
+    return functions->GetOwnedMonitorInfo(this, thread, owned_monitor_count_ptr, owned_monitors_ptr);\r
+  }\r
+\r
+  jvmtiError GetCurrentContendedMonitor(jthread thread,\r
+            jobject* monitor_ptr) {\r
+    return functions->GetCurrentContendedMonitor(this, thread, monitor_ptr);\r
+  }\r
+\r
+  jvmtiError RunAgentThread(jthread thread,\r
+            jvmtiStartFunction proc,\r
+            const void* arg,\r
+            jint priority) {\r
+    return functions->RunAgentThread(this, thread, proc, arg, priority);\r
+  }\r
+\r
+  jvmtiError SetThreadLocalStorage(jthread thread,\r
+            const void* data) {\r
+    return functions->SetThreadLocalStorage(this, thread, data);\r
+  }\r
+\r
+  jvmtiError GetThreadLocalStorage(jthread thread,\r
+            void** data_ptr) {\r
+    return functions->GetThreadLocalStorage(this, thread, data_ptr);\r
+  }\r
+\r
+  jvmtiError GetTopThreadGroups(jint* group_count_ptr,\r
+            jthreadGroup** groups_ptr) {\r
+    return functions->GetTopThreadGroups(this, group_count_ptr, groups_ptr);\r
+  }\r
+\r
+  jvmtiError GetThreadGroupInfo(jthreadGroup group,\r
+            jvmtiThreadGroupInfo* info_ptr) {\r
+    return functions->GetThreadGroupInfo(this, group, info_ptr);\r
+  }\r
+\r
+  jvmtiError GetThreadGroupChildren(jthreadGroup group,\r
+            jint* thread_count_ptr,\r
+            jthread** threads_ptr,\r
+            jint* group_count_ptr,\r
+            jthreadGroup** groups_ptr) {\r
+    return functions->GetThreadGroupChildren(this, group, thread_count_ptr, threads_ptr, group_count_ptr, groups_ptr);\r
+  }\r
+\r
+  jvmtiError GetStackTrace(jthread thread,\r
+            jint start_depth,\r
+            jint max_frame_count,\r
+            jvmtiFrameInfo* frame_buffer,\r
+            jint* count_ptr) {\r
+    return functions->GetStackTrace(this, thread, start_depth, max_frame_count, frame_buffer, count_ptr);\r
+  }\r
+\r
+  jvmtiError GetAllStackTraces(jint max_frame_count,\r
+            jvmtiStackInfo** stack_info_ptr,\r
+            jint* thread_count_ptr) {\r
+    return functions->GetAllStackTraces(this, max_frame_count, stack_info_ptr, thread_count_ptr);\r
+  }\r
+\r
+  jvmtiError GetThreadListStackTraces(jint thread_count,\r
+            const jthread* thread_list,\r
+            jint max_frame_count,\r
+            jvmtiStackInfo** stack_info_ptr) {\r
+    return functions->GetThreadListStackTraces(this, thread_count, thread_list, max_frame_count, stack_info_ptr);\r
+  }\r
+\r
+  jvmtiError GetFrameCount(jthread thread,\r
+            jint* count_ptr) {\r
+    return functions->GetFrameCount(this, thread, count_ptr);\r
+  }\r
+\r
+  jvmtiError PopFrame(jthread thread) {\r
+    return functions->PopFrame(this, thread);\r
+  }\r
+\r
+  jvmtiError GetFrameLocation(jthread thread,\r
+            jint depth,\r
+            jmethodID* method_ptr,\r
+            jlocation* location_ptr) {\r
+    return functions->GetFrameLocation(this, thread, depth, method_ptr, location_ptr);\r
+  }\r
+\r
+  jvmtiError NotifyFramePop(jthread thread,\r
+            jint depth) {\r
+    return functions->NotifyFramePop(this, thread, depth);\r
+  }\r
+\r
+  jvmtiError GetTag(jobject object,\r
+            jlong* tag_ptr) {\r
+    return functions->GetTag(this, object, tag_ptr);\r
+  }\r
+\r
+  jvmtiError SetTag(jobject object,\r
+            jlong tag) {\r
+    return functions->SetTag(this, object, tag);\r
+  }\r
+\r
+  jvmtiError ForceGarbageCollection() {\r
+    return functions->ForceGarbageCollection(this);\r
+  }\r
+\r
+  jvmtiError IterateOverObjectsReachableFromObject(jobject object,\r
+            jvmtiObjectReferenceCallback object_reference_callback,\r
+            void* user_data) {\r
+    return functions->IterateOverObjectsReachableFromObject(this, object, object_reference_callback, user_data);\r
+  }\r
+\r
+  jvmtiError IterateOverReachableObjects(jvmtiHeapRootCallback heap_root_callback,\r
+            jvmtiStackReferenceCallback stack_ref_callback,\r
+            jvmtiObjectReferenceCallback object_ref_callback,\r
+            void* user_data) {\r
+    return functions->IterateOverReachableObjects(this, heap_root_callback, stack_ref_callback, object_ref_callback, user_data);\r
+  }\r
+\r
+  jvmtiError IterateOverHeap(jvmtiHeapObjectFilter object_filter,\r
+            jvmtiHeapObjectCallback heap_object_callback,\r
+            void* user_data) {\r
+    return functions->IterateOverHeap(this, object_filter, heap_object_callback, user_data);\r
+  }\r
+\r
+  jvmtiError IterateOverInstancesOfClass(jclass klass,\r
+            jvmtiHeapObjectFilter object_filter,\r
+            jvmtiHeapObjectCallback heap_object_callback,\r
+            void* user_data) {\r
+    return functions->IterateOverInstancesOfClass(this, klass, object_filter, heap_object_callback, user_data);\r
+  }\r
+\r
+  jvmtiError GetObjectsWithTags(jint tag_count,\r
+            const jlong* tags,\r
+            jint* count_ptr,\r
+            jobject** object_result_ptr,\r
+            jlong** tag_result_ptr) {\r
+    return functions->GetObjectsWithTags(this, tag_count, tags, count_ptr, object_result_ptr, tag_result_ptr);\r
+  }\r
+\r
+  jvmtiError GetLocalObject(jthread thread,\r
+            jint depth,\r
+            jint slot,\r
+            jobject* value_ptr) {\r
+    return functions->GetLocalObject(this, thread, depth, slot, value_ptr);\r
+  }\r
+\r
+  jvmtiError GetLocalInt(jthread thread,\r
+            jint depth,\r
+            jint slot,\r
+            jint* value_ptr) {\r
+    return functions->GetLocalInt(this, thread, depth, slot, value_ptr);\r
+  }\r
+\r
+  jvmtiError GetLocalLong(jthread thread,\r
+            jint depth,\r
+            jint slot,\r
+            jlong* value_ptr) {\r
+    return functions->GetLocalLong(this, thread, depth, slot, value_ptr);\r
+  }\r
+\r
+  jvmtiError GetLocalFloat(jthread thread,\r
+            jint depth,\r
+            jint slot,\r
+            jfloat* value_ptr) {\r
+    return functions->GetLocalFloat(this, thread, depth, slot, value_ptr);\r
+  }\r
+\r
+  jvmtiError GetLocalDouble(jthread thread,\r
+            jint depth,\r
+            jint slot,\r
+            jdouble* value_ptr) {\r
+    return functions->GetLocalDouble(this, thread, depth, slot, value_ptr);\r
+  }\r
+\r
+  jvmtiError SetLocalObject(jthread thread,\r
+            jint depth,\r
+            jint slot,\r
+            jobject value) {\r
+    return functions->SetLocalObject(this, thread, depth, slot, value);\r
+  }\r
+\r
+  jvmtiError SetLocalInt(jthread thread,\r
+            jint depth,\r
+            jint slot,\r
+            jint value) {\r
+    return functions->SetLocalInt(this, thread, depth, slot, value);\r
+  }\r
+\r
+  jvmtiError SetLocalLong(jthread thread,\r
+            jint depth,\r
+            jint slot,\r
+            jlong value) {\r
+    return functions->SetLocalLong(this, thread, depth, slot, value);\r
+  }\r
+\r
+  jvmtiError SetLocalFloat(jthread thread,\r
+            jint depth,\r
+            jint slot,\r
+            jfloat value) {\r
+    return functions->SetLocalFloat(this, thread, depth, slot, value);\r
+  }\r
+\r
+  jvmtiError SetLocalDouble(jthread thread,\r
+            jint depth,\r
+            jint slot,\r
+            jdouble value) {\r
+    return functions->SetLocalDouble(this, thread, depth, slot, value);\r
+  }\r
+\r
+  jvmtiError SetBreakpoint(jmethodID method,\r
+            jlocation location) {\r
+    return functions->SetBreakpoint(this, method, location);\r
+  }\r
+\r
+  jvmtiError ClearBreakpoint(jmethodID method,\r
+            jlocation location) {\r
+    return functions->ClearBreakpoint(this, method, location);\r
+  }\r
+\r
+  jvmtiError SetFieldAccessWatch(jclass klass,\r
+            jfieldID field) {\r
+    return functions->SetFieldAccessWatch(this, klass, field);\r
+  }\r
+\r
+  jvmtiError ClearFieldAccessWatch(jclass klass,\r
+            jfieldID field) {\r
+    return functions->ClearFieldAccessWatch(this, klass, field);\r
+  }\r
+\r
+  jvmtiError SetFieldModificationWatch(jclass klass,\r
+            jfieldID field) {\r
+    return functions->SetFieldModificationWatch(this, klass, field);\r
+  }\r
+\r
+  jvmtiError ClearFieldModificationWatch(jclass klass,\r
+            jfieldID field) {\r
+    return functions->ClearFieldModificationWatch(this, klass, field);\r
+  }\r
+\r
+  jvmtiError GetLoadedClasses(jint* class_count_ptr,\r
+            jclass** classes_ptr) {\r
+    return functions->GetLoadedClasses(this, class_count_ptr, classes_ptr);\r
+  }\r
+\r
+  jvmtiError GetClassLoaderClasses(jobject initiating_loader,\r
+            jint* class_count_ptr,\r
+            jclass** classes_ptr) {\r
+    return functions->GetClassLoaderClasses(this, initiating_loader, class_count_ptr, classes_ptr);\r
+  }\r
+\r
+  jvmtiError GetClassSignature(jclass klass,\r
+            char** signature_ptr,\r
+            char** generic_ptr) {\r
+    return functions->GetClassSignature(this, klass, signature_ptr, generic_ptr);\r
+  }\r
+\r
+  jvmtiError GetClassStatus(jclass klass,\r
+            jint* status_ptr) {\r
+    return functions->GetClassStatus(this, klass, status_ptr);\r
+  }\r
+\r
+  jvmtiError GetSourceFileName(jclass klass,\r
+            char** source_name_ptr) {\r
+    return functions->GetSourceFileName(this, klass, source_name_ptr);\r
+  }\r
+\r
+  jvmtiError GetClassModifiers(jclass klass,\r
+            jint* modifiers_ptr) {\r
+    return functions->GetClassModifiers(this, klass, modifiers_ptr);\r
+  }\r
+\r
+  jvmtiError GetClassMethods(jclass klass,\r
+            jint* method_count_ptr,\r
+            jmethodID** methods_ptr) {\r
+    return functions->GetClassMethods(this, klass, method_count_ptr, methods_ptr);\r
+  }\r
+\r
+  jvmtiError GetClassFields(jclass klass,\r
+            jint* field_count_ptr,\r
+            jfieldID** fields_ptr) {\r
+    return functions->GetClassFields(this, klass, field_count_ptr, fields_ptr);\r
+  }\r
+\r
+  jvmtiError GetImplementedInterfaces(jclass klass,\r
+            jint* interface_count_ptr,\r
+            jclass** interfaces_ptr) {\r
+    return functions->GetImplementedInterfaces(this, klass, interface_count_ptr, interfaces_ptr);\r
+  }\r
+\r
+  jvmtiError IsInterface(jclass klass,\r
+            jboolean* is_interface_ptr) {\r
+    return functions->IsInterface(this, klass, is_interface_ptr);\r
+  }\r
+\r
+  jvmtiError IsArrayClass(jclass klass,\r
+            jboolean* is_array_class_ptr) {\r
+    return functions->IsArrayClass(this, klass, is_array_class_ptr);\r
+  }\r
+\r
+  jvmtiError GetClassLoader(jclass klass,\r
+            jobject* classloader_ptr) {\r
+    return functions->GetClassLoader(this, klass, classloader_ptr);\r
+  }\r
+\r
+  jvmtiError GetSourceDebugExtension(jclass klass,\r
+            char** source_debug_extension_ptr) {\r
+    return functions->GetSourceDebugExtension(this, klass, source_debug_extension_ptr);\r
+  }\r
+\r
+  jvmtiError RedefineClasses(jint class_count,\r
+            const jvmtiClassDefinition* class_definitions) {\r
+    return functions->RedefineClasses(this, class_count, class_definitions);\r
+  }\r
+\r
+  jvmtiError GetObjectSize(jobject object,\r
+            jlong* size_ptr) {\r
+    return functions->GetObjectSize(this, object, size_ptr);\r
+  }\r
+\r
+  jvmtiError GetObjectHashCode(jobject object,\r
+            jint* hash_code_ptr) {\r
+    return functions->GetObjectHashCode(this, object, hash_code_ptr);\r
+  }\r
+\r
+  jvmtiError GetObjectMonitorUsage(jobject object,\r
+            jvmtiMonitorUsage* info_ptr) {\r
+    return functions->GetObjectMonitorUsage(this, object, info_ptr);\r
+  }\r
+\r
+  jvmtiError GetFieldName(jclass klass,\r
+            jfieldID field,\r
+            char** name_ptr,\r
+            char** signature_ptr,\r
+            char** generic_ptr) {\r
+    return functions->GetFieldName(this, klass, field, name_ptr, signature_ptr, generic_ptr);\r
+  }\r
+\r
+  jvmtiError GetFieldDeclaringClass(jclass klass,\r
+            jfieldID field,\r
+            jclass* declaring_class_ptr) {\r
+    return functions->GetFieldDeclaringClass(this, klass, field, declaring_class_ptr);\r
+  }\r
+\r
+  jvmtiError GetFieldModifiers(jclass klass,\r
+            jfieldID field,\r
+            jint* modifiers_ptr) {\r
+    return functions->GetFieldModifiers(this, klass, field, modifiers_ptr);\r
+  }\r
+\r
+  jvmtiError IsFieldSynthetic(jclass klass,\r
+            jfieldID field,\r
+            jboolean* is_synthetic_ptr) {\r
+    return functions->IsFieldSynthetic(this, klass, field, is_synthetic_ptr);\r
+  }\r
+\r
+  jvmtiError GetMethodName(jmethodID method,\r
+            char** name_ptr,\r
+            char** signature_ptr,\r
+            char** generic_ptr) {\r
+    return functions->GetMethodName(this, method, name_ptr, signature_ptr, generic_ptr);\r
+  }\r
+\r
+  jvmtiError GetMethodDeclaringClass(jmethodID method,\r
+            jclass* declaring_class_ptr) {\r
+    return functions->GetMethodDeclaringClass(this, method, declaring_class_ptr);\r
+  }\r
+\r
+  jvmtiError GetMethodModifiers(jmethodID method,\r
+            jint* modifiers_ptr) {\r
+    return functions->GetMethodModifiers(this, method, modifiers_ptr);\r
+  }\r
+\r
+  jvmtiError GetMaxLocals(jmethodID method,\r
+            jint* max_ptr) {\r
+    return functions->GetMaxLocals(this, method, max_ptr);\r
+  }\r
+\r
+  jvmtiError GetArgumentsSize(jmethodID method,\r
+            jint* size_ptr) {\r
+    return functions->GetArgumentsSize(this, method, size_ptr);\r
+  }\r
+\r
+  jvmtiError GetLineNumberTable(jmethodID method,\r
+            jint* entry_count_ptr,\r
+            jvmtiLineNumberEntry** table_ptr) {\r
+    return functions->GetLineNumberTable(this, method, entry_count_ptr, table_ptr);\r
+  }\r
+\r
+  jvmtiError GetMethodLocation(jmethodID method,\r
+            jlocation* start_location_ptr,\r
+            jlocation* end_location_ptr) {\r
+    return functions->GetMethodLocation(this, method, start_location_ptr, end_location_ptr);\r
+  }\r
+\r
+  jvmtiError GetLocalVariableTable(jmethodID method,\r
+            jint* entry_count_ptr,\r
+            jvmtiLocalVariableEntry** table_ptr) {\r
+    return functions->GetLocalVariableTable(this, method, entry_count_ptr, table_ptr);\r
+  }\r
+\r
+  jvmtiError GetBytecodes(jmethodID method,\r
+            jint* bytecode_count_ptr,\r
+            unsigned char** bytecodes_ptr) {\r
+    return functions->GetBytecodes(this, method, bytecode_count_ptr, bytecodes_ptr);\r
+  }\r
+\r
+  jvmtiError IsMethodNative(jmethodID method,\r
+            jboolean* is_native_ptr) {\r
+    return functions->IsMethodNative(this, method, is_native_ptr);\r
+  }\r
+\r
+  jvmtiError IsMethodSynthetic(jmethodID method,\r
+            jboolean* is_synthetic_ptr) {\r
+    return functions->IsMethodSynthetic(this, method, is_synthetic_ptr);\r
+  }\r
+\r
+  jvmtiError IsMethodObsolete(jmethodID method,\r
+            jboolean* is_obsolete_ptr) {\r
+    return functions->IsMethodObsolete(this, method, is_obsolete_ptr);\r
+  }\r
+\r
+  jvmtiError CreateRawMonitor(const char* name,\r
+            jrawMonitorID* monitor_ptr) {\r
+    return functions->CreateRawMonitor(this, name, monitor_ptr);\r
+  }\r
+\r
+  jvmtiError DestroyRawMonitor(jrawMonitorID monitor) {\r
+    return functions->DestroyRawMonitor(this, monitor);\r
+  }\r
+\r
+  jvmtiError RawMonitorEnter(jrawMonitorID monitor) {\r
+    return functions->RawMonitorEnter(this, monitor);\r
+  }\r
+\r
+  jvmtiError RawMonitorExit(jrawMonitorID monitor) {\r
+    return functions->RawMonitorExit(this, monitor);\r
+  }\r
+\r
+  jvmtiError RawMonitorWait(jrawMonitorID monitor,\r
+            jlong millis) {\r
+    return functions->RawMonitorWait(this, monitor, millis);\r
+  }\r
+\r
+  jvmtiError RawMonitorNotify(jrawMonitorID monitor) {\r
+    return functions->RawMonitorNotify(this, monitor);\r
+  }\r
+\r
+  jvmtiError RawMonitorNotifyAll(jrawMonitorID monitor) {\r
+    return functions->RawMonitorNotifyAll(this, monitor);\r
+  }\r
+\r
+  jvmtiError SetJNIFunctionTable(const jniNativeInterface* function_table) {\r
+    return functions->SetJNIFunctionTable(this, function_table);\r
+  }\r
+\r
+  jvmtiError GetJNIFunctionTable(jniNativeInterface** function_table) {\r
+    return functions->GetJNIFunctionTable(this, function_table);\r
+  }\r
+\r
+  jvmtiError SetEventCallbacks(const jvmtiEventCallbacks* callbacks,\r
+            jint size_of_callbacks) {\r
+    return functions->SetEventCallbacks(this, callbacks, size_of_callbacks);\r
+  }\r
+\r
+  jvmtiError SetEventNotificationMode(jvmtiEventMode mode,\r
+            jvmtiEvent event_type,\r
+            jthread event_thread,\r
+             ...) {\r
+    return functions->SetEventNotificationMode(this, mode, event_type, event_thread);\r
+  }\r
+\r
+  jvmtiError GenerateEvents(jvmtiEvent event_type) {\r
+    return functions->GenerateEvents(this, event_type);\r
+  }\r
+\r
+  jvmtiError GetExtensionFunctions(jint* extension_count_ptr,\r
+            jvmtiExtensionFunctionInfo** extensions) {\r
+    return functions->GetExtensionFunctions(this, extension_count_ptr, extensions);\r
+  }\r
+\r
+  jvmtiError GetExtensionEvents(jint* extension_count_ptr,\r
+            jvmtiExtensionEventInfo** extensions) {\r
+    return functions->GetExtensionEvents(this, extension_count_ptr, extensions);\r
+  }\r
+\r
+  jvmtiError SetExtensionEventCallback(jint extension_event_index,\r
+            jvmtiExtensionEvent callback) {\r
+    return functions->SetExtensionEventCallback(this, extension_event_index, callback);\r
+  }\r
+\r
+  jvmtiError GetPotentialCapabilities(jvmtiCapabilities* capabilities_ptr) {\r
+    return functions->GetPotentialCapabilities(this, capabilities_ptr);\r
+  }\r
+\r
+  jvmtiError AddCapabilities(const jvmtiCapabilities* capabilities_ptr) {\r
+    return functions->AddCapabilities(this, capabilities_ptr);\r
+  }\r
+\r
+  jvmtiError RelinquishCapabilities(const jvmtiCapabilities* capabilities_ptr) {\r
+    return functions->RelinquishCapabilities(this, capabilities_ptr);\r
+  }\r
+\r
+  jvmtiError GetCapabilities(jvmtiCapabilities* capabilities_ptr) {\r
+    return functions->GetCapabilities(this, capabilities_ptr);\r
+  }\r
+\r
+  jvmtiError GetCurrentThreadCpuTimerInfo(jvmtiTimerInfo* info_ptr) {\r
+    return functions->GetCurrentThreadCpuTimerInfo(this, info_ptr);\r
+  }\r
+\r
+  jvmtiError GetCurrentThreadCpuTime(jlong* nanos_ptr) {\r
+    return functions->GetCurrentThreadCpuTime(this, nanos_ptr);\r
+  }\r
+\r
+  jvmtiError GetThreadCpuTimerInfo(jvmtiTimerInfo* info_ptr) {\r
+    return functions->GetThreadCpuTimerInfo(this, info_ptr);\r
+  }\r
+\r
+  jvmtiError GetThreadCpuTime(jthread thread,\r
+            jlong* nanos_ptr) {\r
+    return functions->GetThreadCpuTime(this, thread, nanos_ptr);\r
+  }\r
+\r
+  jvmtiError GetTimerInfo(jvmtiTimerInfo* info_ptr) {\r
+    return functions->GetTimerInfo(this, info_ptr);\r
+  }\r
+\r
+  jvmtiError GetTime(jlong* nanos_ptr) {\r
+    return functions->GetTime(this, nanos_ptr);\r
+  }\r
+\r
+  jvmtiError GetAvailableProcessors(jint* processor_count_ptr) {\r
+    return functions->GetAvailableProcessors(this, processor_count_ptr);\r
+  }\r
+\r
+  jvmtiError AddToBootstrapClassLoaderSearch(const char* segment) {\r
+    return functions->AddToBootstrapClassLoaderSearch(this, segment);\r
+  }\r
+\r
+  jvmtiError GetSystemProperties(jint* count_ptr,\r
+            char*** property_ptr) {\r
+    return functions->GetSystemProperties(this, count_ptr, property_ptr);\r
+  }\r
+\r
+  jvmtiError GetSystemProperty(const char* property,\r
+            char** value_ptr) {\r
+    return functions->GetSystemProperty(this, property, value_ptr);\r
+  }\r
+\r
+  jvmtiError SetSystemProperty(const char* property,\r
+            const char* value) {\r
+    return functions->SetSystemProperty(this, property, value);\r
+  }\r
+\r
+  jvmtiError GetPhase(jvmtiPhase* phase_ptr) {\r
+    return functions->GetPhase(this, phase_ptr);\r
+  }\r
+\r
+  jvmtiError DisposeEnvironment() {\r
+    return functions->DisposeEnvironment(this);\r
+  }\r
+\r
+  jvmtiError SetEnvironmentLocalStorage(const void* data) {\r
+    return functions->SetEnvironmentLocalStorage(this, data);\r
+  }\r
+\r
+  jvmtiError GetEnvironmentLocalStorage(void** data_ptr) {\r
+    return functions->GetEnvironmentLocalStorage(this, data_ptr);\r
+  }\r
+\r
+  jvmtiError GetVersionNumber(jint* version_ptr) {\r
+    return functions->GetVersionNumber(this, version_ptr);\r
+  }\r
+\r
+  jvmtiError GetErrorName(jvmtiError error,\r
+            char** name_ptr) {\r
+    return functions->GetErrorName(this, error, name_ptr);\r
+  }\r
+\r
+  jvmtiError SetVerboseFlag(jvmtiVerboseFlag flag,\r
+            jboolean value) {\r
+    return functions->SetVerboseFlag(this, flag, value);\r
+  }\r
+\r
+  jvmtiError GetJLocationFormat(jvmtiJlocationFormat* format_ptr) {\r
+    return functions->GetJLocationFormat(this, format_ptr);\r
+  }\r
+\r
+#endif /* __cplusplus */\r
+};\r
+\r
+\r
+#ifdef __cplusplus\r
+} /* extern "C" */\r
+#endif /* __cplusplus */\r
+\r
+#endif /* !_JAVA_JVMTI_H_ */\r
+\r
diff --git a/applications/JavaOpenJPEG/java-jni/include/win32/jawt_md.h b/applications/JavaOpenJPEG/java-jni/include/win32/jawt_md.h
new file mode 100644 (file)
index 0000000..5df3e46
--- /dev/null
@@ -0,0 +1,41 @@
+/*\r
+ * @(#)jawt_md.h       1.7 03/12/19\r
+ *\r
+ * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
+ * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
+ */\r
+\r
+#ifndef _JAVASOFT_JAWT_MD_H_\r
+#define _JAVASOFT_JAWT_MD_H_\r
+\r
+#include <windows.h>\r
+#include "jawt.h"\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+/*\r
+ * Win32-specific declarations for AWT native interface.\r
+ * See notes in jawt.h for an example of use.\r
+ */\r
+typedef struct jawt_Win32DrawingSurfaceInfo {\r
+    /* Native window, DDB, or DIB handle */\r
+    union {\r
+        HWND hwnd;\r
+        HBITMAP hbitmap;\r
+        void* pbits;\r
+    };\r
+    /*\r
+     * This HDC should always be used instead of the HDC returned from\r
+     * BeginPaint() or any calls to GetDC().\r
+     */\r
+    HDC hdc;\r
+    HPALETTE hpalette;\r
+} JAWT_Win32DrawingSurfaceInfo;\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif /* !_JAVASOFT_JAWT_MD_H_ */\r
diff --git a/applications/JavaOpenJPEG/java-jni/include/win32/jni_md.h b/applications/JavaOpenJPEG/java-jni/include/win32/jni_md.h
new file mode 100644 (file)
index 0000000..fdc79a0
--- /dev/null
@@ -0,0 +1,19 @@
+/*\r
+ * @(#)jni_md.h        1.14 03/12/19\r
+ *\r
+ * Copyright 2004 Sun Microsystems, Inc. All rights reserved.\r
+ * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.\r
+ */\r
+\r
+#ifndef _JAVASOFT_JNI_MD_H_\r
+#define _JAVASOFT_JNI_MD_H_\r
+\r
+#define JNIEXPORT __declspec(dllexport)\r
+#define JNIIMPORT __declspec(dllimport)\r
+#define JNICALL __stdcall\r
+\r
+typedef long jint;\r
+typedef __int64 jlong;\r
+typedef signed char jbyte;\r
+\r
+#endif /* !_JAVASOFT_JNI_MD_H_ */\r
diff --git a/applications/JavaOpenJPEG/java-jni/lib/jvm.lib b/applications/JavaOpenJPEG/java-jni/lib/jvm.lib
new file mode 100644 (file)
index 0000000..672855a
Binary files /dev/null and b/applications/JavaOpenJPEG/java-jni/lib/jvm.lib differ
diff --git a/applications/JavaOpenJPEG/java-sources/org/openJpeg/OpenJPEGJavaDecoder.java b/applications/JavaOpenJPEG/java-sources/org/openJpeg/OpenJPEGJavaDecoder.java
new file mode 100644 (file)
index 0000000..0bacc84
--- /dev/null
@@ -0,0 +1,250 @@
+/*\r
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
+ * Copyright (c) 2002-2007, Professor Benoit Macq\r
+ * Copyright (c) 2002-2007, Patrick Piscaglia, Telemis s.a.\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */ \r
+package org.openJpeg;\r
+\r
+import java.util.Vector;\r
+\r
+/** This class decodes one J2K codestream into an image (width + height + depth + pixels[], \r
+ * using the OpenJPEG.org library.\r
+ * To be able to log messages, the called must register a IJavaJ2KDecoderLogger object.\r
+ */\r
+public class OpenJPEGJavaDecoder {\r
+\r
+       public interface IJavaJ2KDecoderLogger {\r
+               public void logDecoderMessage(String message);\r
+               public void logDecoderError(String message);\r
+       }\r
+       \r
+    private static boolean isInitialized = false;\r
+    \r
+       // ===== decompression parameters =============>\r
+       // These value may be changed for each image\r
+    private String[] decoder_arguments = null;\r
+       /** number of resolutions decompositions */\r
+       private int nbResolutions = -1;\r
+       /** the quality layers */\r
+       private int[] layers = null;\r
+\r
+       /** Contains the 8 bpp version of the image. May NOT be filled together with image16 or image24.<P>\r
+        * We store in Java the 8 or 16 bpp version of the image while the decoder uses a 32 bpp version, because <UL>\r
+        * <LI> the storage capacity required is smaller\r
+        * <LI> the transfer Java <-- C will be faster\r
+        * <LI> the conversion byte/short ==> int will be done faster by the C\r
+        * </UL>*/\r
+       private byte[] image8 = null;\r
+       /** Contains the 16 bpp version of the image. May NOT be filled together with image8 or image24*/\r
+       private short[] image16 = null;\r
+       /** Contains the 24 bpp version of the image. May NOT be filled together with image8 or image16 */\r
+       private int[] image24 = null;\r
+       /** Holds the J2K compressed bytecode to decode */\r
+    private byte compressedStream[] = null;\r
+    /** Holds the compressed version of the index file, to be used by the decoder */\r
+    private byte compressedIndex[] = null;\r
+    /** Width and Height of the image */\r
+    private int width = -1;\r
+    private int height = -1;\r
+    private int depth = -1;\r
+    /** This parameter is never used in Java but is read by the C library to know the number of resolutions to skip when decoding, \r
+     * i.e. if there are 5 resolutions and skipped=1 ==> decode until resolution 4.  */\r
+    private int skippedResolutions = 0;\r
+    \r
+    private Vector<IJavaJ2KDecoderLogger> loggers = new Vector();\r
+\r
+\r
+    public OpenJPEGJavaDecoder(String openJPEGlibraryFullPathAndName, IJavaJ2KDecoderLogger messagesAndErrorsLogger) throws ExceptionInInitializerError\r
+    {\r
+       this(openJPEGlibraryFullPathAndName);\r
+       loggers.addElement(messagesAndErrorsLogger);\r
+    }\r
+\r
+    public OpenJPEGJavaDecoder(String openJPEGlibraryFullPathAndName) throws ExceptionInInitializerError\r
+    {\r
+       if (!isInitialized) {\r
+               try {\r
+                       System.load(openJPEGlibraryFullPathAndName);\r
+                       isInitialized = true;\r
+               } catch (Throwable t) {\r
+                       throw new ExceptionInInitializerError("OpenJPEG Java Decoder: probably impossible to find the C library");\r
+               }\r
+       }\r
+    }\r
+    \r
+    public void addLogger(IJavaJ2KDecoderLogger messagesAndErrorsLogger) {\r
+       loggers.addElement(messagesAndErrorsLogger);\r
+    }\r
+    \r
+    public void removeLogger(IJavaJ2KDecoderLogger messagesAndErrorsLogger) {\r
+       loggers.removeElement(messagesAndErrorsLogger);\r
+    }\r
+    \r
+    public int  decodeJ2KtoImage() {\r
+               if ((image16 == null || (image16 != null && image16.length != width*height)) && (depth==-1 || depth==16)) {\r
+                       image16 = new short[width*height];\r
+                       logMessage("OpenJPEGJavaDecoder.decompressImage: image16 length = " + image16.length + " (" + width + " x " + height + ") ");\r
+               }\r
+               if ((image8 == null || (image8 != null && image8.length != width*height)) && (depth==-1 || depth==8)) {\r
+                       image8 = new byte[width*height];\r
+                       logMessage("OpenJPEGJavaDecoder.decompressImage: image8 length = " + image8.length + " (" + width + " x " + height + ") ");\r
+               }\r
+               if ((image24 == null || (image24 != null && image24.length != width*height)) && (depth==-1 || depth==24)) {\r
+                       image24 = new int[width*height];\r
+                       logMessage("OpenJPEGJavaDecoder.decompressImage: image24 length = " + image24.length + " (" + width + " x " + height + ") ");\r
+               }\r
+               \r
+               String[] arguments = new String[0 + (decoder_arguments != null ? decoder_arguments.length : 0)];\r
+               int offset = 0;\r
+               if (decoder_arguments != null) {\r
+                       for (int i=0; i<decoder_arguments.length; i++) {\r
+                               arguments[i+offset] = decoder_arguments[i];\r
+                       }\r
+               }\r
+\r
+               return internalDecodeJ2KtoImage(arguments);\r
+    }\r
+    \r
+    /** \r
+     * Decode the j2k stream given in the codestream byte[] and fills the image8, image16 or image24 array, according to the bit depth.\r
+     */\r
+    private native int internalDecodeJ2KtoImage(String[] parameters);\r
+\r
+    /** Image depth in bpp */\r
+       public int getDepth() {\r
+               return depth;\r
+       }\r
+\r
+    /** Image depth in bpp */\r
+       public void setDepth(int depth) {\r
+               this.depth = depth;\r
+       }\r
+\r
+       /** Image height in pixels */\r
+       public int getHeight() {\r
+               return height;\r
+       }\r
+\r
+       /** Image height in pixels */\r
+       public void setHeight(int height) {\r
+               this.height = height;\r
+       }\r
+\r
+       /** Number of resolutions contained in the image */\r
+       public int getNbResolutions() {\r
+               return nbResolutions;\r
+       }\r
+\r
+       /** Number of resolutions contained in the image */\r
+       public void setNbResolutions(int nbResolutions) {\r
+               this.nbResolutions = nbResolutions;\r
+       }\r
+\r
+       /** Width of the image in pixels */\r
+       public int getWidth() {\r
+               return width;\r
+       }\r
+\r
+       /** Width of the image in pixels */\r
+       public void setWidth(int width) {\r
+               this.width = width;\r
+       }\r
+\r
+       /** Contains the decompressed version of the image, if the depth in is [9,16] bpp.\r
+        * Returns NULL otherwise.\r
+        */\r
+       public short[] getImage16() {\r
+               return image16;\r
+       }\r
+\r
+       /** Contains the decompressed version of the image, if the depth in is [17,24] bpp and the image is in color.\r
+        * Returns NULL otherwise.\r
+        */\r
+       public int[] getImage24() {\r
+               return image24;\r
+       }\r
+\r
+       /** Contains the decompressed version of the image, if the depth in is [1,8] bpp.\r
+        * Returns NULL otherwise.\r
+        */\r
+       public byte[] getImage8() {\r
+               return image8;\r
+       }\r
+\r
+       /** Sets the compressed version of the index file for this image.\r
+        * This index file is used by the decompressor\r
+        */\r
+       public void setCompressedIndex(byte[] compressedIndex) {\r
+               this.compressedIndex = compressedIndex;\r
+       }\r
+\r
+       /** Sets the codestream to be decoded */\r
+       public void setCompressedStream(byte[] compressedStream) {\r
+               this.compressedStream = compressedStream;\r
+       }\r
+\r
+       /** @return the compressed code stream length, or -1 if not defined */\r
+       public long getCodestreamLength() {\r
+               if (compressedStream == null)\r
+                       return -1;\r
+               else return compressedStream.length;\r
+       }\r
+       \r
+       /** This method is called either directly or by the C methods */\r
+       public void logMessage(String message) {\r
+               for (IJavaJ2KDecoderLogger logger:loggers)\r
+                       logger.logDecoderMessage(message);\r
+       }\r
+       \r
+       /** This method is called either directly or by the C methods */\r
+       public void logError(String error) {\r
+               for (IJavaJ2KDecoderLogger logger:loggers)\r
+                       logger.logDecoderError(error);\r
+       }\r
+\r
+       public void reset() {\r
+               nbResolutions = -1;\r
+               layers = null;\r
+               image8 = null;\r
+               image16 = null;\r
+               image24 = null;\r
+               compressedStream = null;\r
+           compressedIndex = null;\r
+           width = -1;\r
+           height = -1;\r
+           depth = -1;\r
+       }\r
+\r
+       public void setSkippedResolutions(int numberOfSkippedResolutions) {\r
+               skippedResolutions = numberOfSkippedResolutions;\r
+       }\r
+\r
+       /** Contains all the decoding arguments other than the input/output file */\r
+       public void setDecoderArguments(String[] argumentsForTheDecoder) {\r
+               decoder_arguments = argumentsForTheDecoder;\r
+       }\r
+\r
+\r
+}\r
diff --git a/applications/JavaOpenJPEG/java-sources/org/openJpeg/OpenJPEGJavaEncoder.java b/applications/JavaOpenJPEG/java-sources/org/openJpeg/OpenJPEGJavaEncoder.java
new file mode 100644 (file)
index 0000000..2c638cf
--- /dev/null
@@ -0,0 +1,338 @@
+/*\r
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
+ * Copyright (c) 2002-2007, Professor Benoit Macq\r
+ * Copyright (c) 2002-2007, Patrick Piscaglia, Telemis s.a.\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */  \r
+package org.openJpeg;\r
+\r
+import java.io.File;\r
+import java.util.Vector;\r
+\r
+/** This class encodes one image into the J2K format, \r
+ * using the OpenJPEG.org library.\r
+ * To be able to log messages, the called must register a IJavaJ2KEncoderLogger object.\r
+ */\r
+public class OpenJPEGJavaEncoder {\r
+\r
+       public interface IJavaJ2KEncoderLogger {\r
+               public void logEncoderMessage(String message);\r
+               public void logEncoderError(String message);\r
+       }\r
+       \r
+    private static boolean isInitialized = false;\r
+    \r
+       // ===== Compression parameters =============>\r
+       // These value may be changed for each image\r
+    private String[] encoder_arguments = null;\r
+       /** number of resolutions decompositions */\r
+       private int nbResolutions = -1;\r
+       /** the quality layers, expressed as compression rate */\r
+       private float[] ratioLayers = null;\r
+       /** the quality layers, expressed as PSNR values. This variable, if defined, has priority over the ratioLayers variable */\r
+       private float[] psnrLayers = null;\r
+       \r
+       /** Contains the 8 bpp version of the image. May NOT be filled together with image16 or image24.<P>\r
+        * We store the 8 or 16 bpp version of the original image while the encoder uses a 32 bpp version, because <UL>\r
+        * <LI> the storage capacity required is smaller\r
+        * <LI> the transfer Java --> C will be faster\r
+        * <LI> the conversion byte/short ==> int will be done faster by the C\r
+        * </UL>*/\r
+       private byte[] image8 = null;\r
+       /** Contains the 16 bpp version of the image. May NOT be filled together with image8 or image24*/\r
+       private short[] image16 = null;\r
+       /** Contains the 24 bpp version of the image. May NOT be filled together with image8 or image16 */\r
+       private int[] image24 = null;\r
+       /** Holds the result of the compression, i.e. the J2K compressed bytecode */\r
+    private byte compressedStream[] = null;\r
+    /** Holds the compressed stream length, which may be smaller than compressedStream.length if this byte[] is pre-allocated */\r
+    private long compressedStreamLength = -1;\r
+    /** Holds the compressed version of the index file, returned by the encoder */\r
+    private byte compressedIndex[] = null;\r
+    /** Width and Height of the image */\r
+    private int width = -1;\r
+    private int height = -1;\r
+    private int depth = -1;\r
+    /** Tile size. We suppose the same size for the horizontal and vertical tiles.\r
+     * If size == -1 ==> no tiling */\r
+    private int tileSize = -1;\r
+    // <===== Compression parameters =============\r
+    \r
+    private Vector<IJavaJ2KEncoderLogger> loggers = new Vector();\r
+\r
+    public OpenJPEGJavaEncoder(String openJPEGlibraryFullPathAndName, IJavaJ2KEncoderLogger messagesAndErrorsLogger) throws ExceptionInInitializerError\r
+    {\r
+       this(openJPEGlibraryFullPathAndName);\r
+       loggers.addElement(messagesAndErrorsLogger);\r
+    }\r
+\r
+    public OpenJPEGJavaEncoder(String openJPEGlibraryFullPathAndName) throws ExceptionInInitializerError\r
+    {\r
+       if (!isInitialized) {\r
+               try {\r
+                       String absolutePath = (new File(openJPEGlibraryFullPathAndName)).getCanonicalPath();\r
+                       System.load(absolutePath);\r
+                       isInitialized = true;\r
+               } catch (Throwable t) {\r
+                       t.printStackTrace();\r
+                       throw new ExceptionInInitializerError("OpenJPEG Java Encoder: probably impossible to find the C library");\r
+               }\r
+       }\r
+    }\r
+    \r
+    public void addLogger(IJavaJ2KEncoderLogger messagesAndErrorsLogger) {\r
+       loggers.addElement(messagesAndErrorsLogger);\r
+    }\r
+    \r
+    public void removeLogger(IJavaJ2KEncoderLogger messagesAndErrorsLogger) {\r
+       loggers.removeElement(messagesAndErrorsLogger);\r
+    }\r
+    \r
+    /** This method compresses the given image.<P>\r
+     * It returns the compressed J2K codestream into the compressedStream byte[].<P>\r
+     * It also returns the compression index as a compressed form, into the compressedIndex byte[].<P>\r
+     * One of the image8, image16 or image24 arrays must be correctly initialized and filled.<P>\r
+     * The width, height and depth variables must be correctly filled.<P>\r
+     * The nbResolutions, nbLayers and if needed the float[] psnrLayers or ratioLayers must also be filled before calling this method.\r
+     */\r
+    public void encodeImageToJ2K() {\r
+               // Need to allocate / reallocate the compressed stream buffer ? (size = max possible size = original image size)\r
+               if (compressedStream== null || (compressedStream.length != width*height*depth/8)) {\r
+                       logMessage("OpenJPEGJavaEncoder.encodeImageToJ2K: (re-)allocating " + (width*height*depth/8) + " bytes for the compressedStream");\r
+                       compressedStream = new byte[width*height*depth/8];\r
+               }\r
+               // Arguments = \r
+               // - number of resolutions "-n 5" : 2\r
+               // - size of tile "-t 512,512" : 2\r
+               // \r
+               // Image width, height, depth and pixels are directly fetched by C from the Java class\r
+               int nbArgs = 2 + (tileSize == -1 ? 0 : 2) + (encoder_arguments != null ? encoder_arguments.length : 0);\r
+               if (psnrLayers != null && psnrLayers.length>0 && psnrLayers[0] != 0)\r
+                       // If psnrLayers is defined and doesn't just express "lossless"\r
+                       nbArgs += 2;\r
+               else if (ratioLayers != null && ratioLayers.length>0 && ratioLayers[0]!=0.0)\r
+                       nbArgs += 2;\r
+               String[] arguments = new String[nbArgs];\r
+               int offset = 0;\r
+               arguments[offset] = "-n"; arguments[offset+1] = "" + nbResolutions; offset += 2;\r
+               if (tileSize!= -1) {\r
+                       arguments[offset++] = "-t"; \r
+                       arguments[offset++] = "" + tileSize + "," + tileSize;\r
+               }\r
+               // If PSNR layers are defined, use them to encode the images\r
+               if (psnrLayers != null && psnrLayers.length>0 && psnrLayers[0]!=-1) {\r
+                       arguments[offset++] = "-q";\r
+                       String s = "";\r
+                       for (int i=0; i<psnrLayers.length; i++)\r
+                               s += psnrLayers[i] + ",";\r
+                       arguments[offset++] = s.substring(0, s.length()-1);\r
+               } else if (ratioLayers != null && ratioLayers.length>0 && ratioLayers[0]!=0.0) {\r
+                       // Specify quality ratioLayers, as compression ratios\r
+                       arguments[offset++] = "-r";\r
+                       String s = "";\r
+                       for (int i=0; i<ratioLayers.length; i++)\r
+                               s += ratioLayers[i] + ",";\r
+                       arguments[offset++] = s.substring(0, s.length()-1);\r
+               }\r
+               if (encoder_arguments != null) {\r
+                       for (int i=0; i<encoder_arguments.length; i++) {\r
+                               arguments[i+offset] = encoder_arguments[i];\r
+                       }\r
+               }\r
+               logMessage("Encoder additional arguments = " + arrayToString(arguments));\r
+               long startTime = (new java.util.Date()).getTime();\r
+               compressedStreamLength = internalEncodeImageToJ2K(arguments);\r
+               logMessage("compression time = " + ((new java.util.Date()).getTime() - startTime) + " msec");\r
+    }\r
+    \r
+    /** \r
+     * Fills the compressedStream byte[] and the compressedIndex byte[]\r
+     * @return the codestream length.\r
+     */\r
+    private native long internalEncodeImageToJ2K(String[] parameters);\r
+\r
+    /** Image depth in bpp */\r
+       public int getDepth() {\r
+               return depth;\r
+       }\r
+\r
+    /** Image depth in bpp */\r
+       public void setDepth(int depth) {\r
+               this.depth = depth;\r
+       }\r
+\r
+       /** Image height in pixels  */\r
+       public int getHeight() {\r
+               return height;\r
+       }\r
+\r
+       /** Image height in pixels  */\r
+       public void setHeight(int height) {\r
+               this.height = height;\r
+       }\r
+\r
+       /** This method must be called in depth in [9,16].\r
+        * @param an array of shorts, containing width*height values\r
+        */\r
+       public void setImage16(short[] image16) {\r
+               this.image16 = image16;\r
+       }\r
+\r
+       /** This method must be called in depth in [17,24] for RGB images.\r
+        * @param an array of int, containing width*height values\r
+        */\r
+       public void setImage24(int[] image24) {\r
+               this.image24 = image24;\r
+       }\r
+\r
+       /** This method must be called in depth in [1,8].\r
+        * @param an array of bytes, containing width*height values\r
+        */\r
+       public void setImage8(byte[] image8) {\r
+               this.image8 = image8;\r
+       }\r
+\r
+       /** Return the ratioLayers, i.e. the compression ratio for each quality layer.\r
+        * If the last value is 0.0, last layer is lossless compressed.\r
+        */\r
+       public float[] getRatioLayers() {\r
+               return ratioLayers;\r
+       }\r
+\r
+       /**\r
+        * sets the quality layers.\r
+        * At least one level.\r
+        * Each level is expressed as a compression ratio (float).\r
+        * If the last value is 0.0, the last layer will be losslessly compressed\r
+        */\r
+       public void setRatioLayers(float[] layers) {\r
+               this.ratioLayers = layers;\r
+       }\r
+\r
+       /** Return the PSNR Layers, i.e. the target PSNR for each quality layer.\r
+        * If the last value is -1, last layer is lossless compressed.\r
+        */\r
+       public float[] getPsnrLayers() {\r
+               return psnrLayers;\r
+       }\r
+\r
+       /**\r
+        * sets the quality layers.\r
+        * At least one level.\r
+        * Each level is expressed as a target PSNR (float).\r
+        * If the last value is -1, the last layer will be losslessly compressed\r
+        */\r
+       public void setPsnrLayers(float[] layers) {\r
+               this.psnrLayers = layers;\r
+       }\r
+\r
+       /** Set the number of resolutions that must be created */\r
+       public void setNbResolutions(int nbResolutions) {\r
+               this.nbResolutions = nbResolutions;\r
+       }\r
+\r
+       public int getWidth() {\r
+               return width;\r
+       }\r
+\r
+       /** Width of the image, in pixels */\r
+       public void setWidth(int width) {\r
+               this.width = width;\r
+       }\r
+\r
+       /** Return the compressed index file.\r
+        * Syntax: TODO PP:\r
+        */\r
+       public byte[] getCompressedIndex() {\r
+               return compressedIndex;\r
+       }\r
+       \r
+       public void setCompressedIndex(byte[] index) {\r
+               compressedIndex = index;\r
+       }\r
+\r
+       public byte[] getCompressedStream() {\r
+               return compressedStream;\r
+       }\r
+\r
+       public void reset() {\r
+               nbResolutions = -1;\r
+               ratioLayers = null;\r
+               psnrLayers = null;\r
+               image8 = null;\r
+               image16 = null;\r
+               image24 = null;\r
+               compressedStream = null;\r
+           compressedIndex = null;\r
+           width = -1;\r
+           height = -1;\r
+           depth = -1;\r
+       }\r
+\r
+       public short[] getImage16() {\r
+               return image16;\r
+       }\r
+\r
+       public int[] getImage24() {\r
+               return image24;\r
+       }\r
+\r
+       public byte[] getImage8() {\r
+               return image8;\r
+       }\r
+       \r
+       /** Sets the size of the tiles. We assume square tiles */\r
+       public void setTileSize(int tileSize) {\r
+               this.tileSize = tileSize;\r
+       }\r
+       \r
+       /** Contains all the encoding arguments other than the input/output file, compression ratio, tile size */\r
+       public void setEncoderArguments(String[] argumentsForTheEncoder) {\r
+               encoder_arguments = argumentsForTheEncoder;\r
+       }\r
+\r
+       public void logMessage(String message) {\r
+               for (IJavaJ2KEncoderLogger logger:loggers)\r
+                       logger.logEncoderMessage(message);\r
+       }\r
+       \r
+       public void logError(String error) {\r
+               for (IJavaJ2KEncoderLogger logger:loggers)\r
+                       logger.logEncoderError(error);\r
+       }\r
+\r
+       public long getCompressedStreamLength() {\r
+               return compressedStreamLength;\r
+       }\r
+       \r
+       private String arrayToString(String[] array) {\r
+               if (array == null)\r
+                       return "NULL";\r
+               StringBuffer sb = new StringBuffer();\r
+               for (int i=0; i<array.length; i++)\r
+                       sb.append(array[i]).append(" ");\r
+               sb.delete(sb.length()-1, sb.length());\r
+               return sb.toString();\r
+       }\r
+}\r
diff --git a/applications/JavaOpenJPEG/org_openJpeg_OpenJPEGJavaDecoder.h b/applications/JavaOpenJPEG/org_openJpeg_OpenJPEGJavaDecoder.h
new file mode 100644 (file)
index 0000000..0e8de2e
--- /dev/null
@@ -0,0 +1,21 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */\r
+#include <jni.h>\r
+/* Header for class org_openJpeg_OpenJPEGJavaDecoder */\r
+\r
+#ifndef _Included_org_openJpeg_OpenJPEGJavaDecoder\r
+#define _Included_org_openJpeg_OpenJPEGJavaDecoder\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+/*\r
+ * Class:     org_openJpeg_OpenJPEGJavaDecoder\r
+ * Method:    internalDecodeJ2KtoImage\r
+ * Signature: ([Ljava/lang/String;)I\r
+ */\r
+JNIEXPORT jint JNICALL Java_org_openJpeg_OpenJPEGJavaDecoder_internalDecodeJ2KtoImage\r
+  (JNIEnv *, jobject, jobjectArray);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
diff --git a/applications/JavaOpenJPEG/org_openJpeg_OpenJPEGJavaEncoder.h b/applications/JavaOpenJPEG/org_openJpeg_OpenJPEGJavaEncoder.h
new file mode 100644 (file)
index 0000000..22b3d95
--- /dev/null
@@ -0,0 +1,21 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */\r
+#include <jni.h>\r
+/* Header for class org_openJpeg_OpenJPEGJavaEncoder */\r
+\r
+#ifndef _Included_org_openJpeg_OpenJPEGJavaEncoder\r
+#define _Included_org_openJpeg_OpenJPEGJavaEncoder\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+/*\r
+ * Class:     org_openJpeg_OpenJPEGJavaEncoder\r
+ * Method:    internalEncodeImageToJ2K\r
+ * Signature: ([Ljava/lang/String;)J\r
+ */\r
+JNIEXPORT jlong JNICALL Java_org_openJpeg_OpenJPEGJavaEncoder_internalEncodeImageToJ2K\r
+  (JNIEnv *, jobject, jobjectArray);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
diff --git a/applications/OPJViewer/Makefile b/applications/OPJViewer/Makefile
new file mode 100644 (file)
index 0000000..b691dc7
--- /dev/null
@@ -0,0 +1,41 @@
+# Makefile for OPJViewer\r
+\r
+# General configuration variables:\r
+CC = $(shell wx-config-2.8 --cxx)\r
+AR = ar\r
+\r
+CFLAGS = -DUSE_JPWL -DwxUSE_LIBOPENJPEG -DwxUSE_GUI=1 -DOPJ_STATIC -DOPJ_HTMLABOUT -DOPJ_INICONFIG -DUSE_JPSEC -DOPJ_MANYFORMATS $(shell wx-config-2.8 --cxxflags) # -g -p -pg -DUSE_JPWL\r
+\r
+OPJV_SRCS = source/imagjpeg2000.cpp source/wxj2kparser.cpp source/OPJViewer.cpp source/wxjp2parser.cpp source/OPJDialogs.cpp source/OPJThreads.cpp source/OPJAbout.cpp ../codec/index.c\r
+\r
+MODULES = $(OPJV_SRCS:.cpp=.o)\r
+\r
+all: opjviewer lib\r
+\r
+.cpp.o:\r
+       $(CC) $(CFLAGS) -c $< -o $@\r
+\r
+lib:\r
+       cd ../jpwl; make\r
+\r
+opjviewer: $(OPJV_SRCS) lib\r
+       $(CC) $(CFLAGS) -I .. -I ../codec -I ../libopenjpeg $(OPJV_SRCS) -o OPJViewer -L ../jpwl -lopenjpeg_JPWL -lm -lstdc++ -ltiff $(shell wx-config-2.8 --libs)\r
+\r
+\r
+clean:\r
+       rm -f OPJViewer *.o *.a\r
+       cd ../libopenjpeg; rm -f *.o\r
+\r
+\r
+\r
+\r
+#.cpp.o :\r
+#       $(CXX) -g -c `wx-config-2.8 --cxxflags` -I ../.. -D wxUSE_LIBOPENJPEG -D wxHACK_BOOLEAN -o $@ $<\r
+\r
+#all:    $(PROGRAM)\r
+\r
+#$(PROGRAM):     $(OBJECTS)\r
+#       $(CXX) -o $(PROGRAM) $(OBJECTS) -lopenjpeg -L ../.. `wx-config-2.8 --libs`\r
+\r
+#clean:\r
+#       rm -f *.o $(PROGRAM)\r
diff --git a/applications/OPJViewer/OPJViewer.dsp b/applications/OPJViewer/OPJViewer.dsp
new file mode 100644 (file)
index 0000000..4939f64
--- /dev/null
@@ -0,0 +1,290 @@
+# Microsoft Developer Studio Project File - Name="OPJViewer" - Package Owner=<4>\r
+# Microsoft Developer Studio Generated Build File, Format Version 6.00\r
+# ** DO NOT EDIT **\r
+\r
+# TARGTYPE "Win32 (x86) Console Application" 0x0103\r
+\r
+CFG=OPJVIEWER - WIN32 RELEASE\r
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r
+!MESSAGE use the Export Makefile command and run\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "OPJViewer.mak".\r
+!MESSAGE \r
+!MESSAGE You can specify a configuration when running NMAKE\r
+!MESSAGE by defining the macro CFG on the command line. For example:\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "OPJViewer.mak" CFG="OPJVIEWER - WIN32 RELEASE"\r
+!MESSAGE \r
+!MESSAGE Possible choices for configuration are:\r
+!MESSAGE \r
+!MESSAGE "OPJViewer - Win32 Release" (based on "Win32 (x86) Console Application")\r
+!MESSAGE "OPJViewer - Win32 Debug" (based on "Win32 (x86) Console Application")\r
+!MESSAGE \r
+\r
+# Begin Project\r
+# PROP AllowPerConfigDependencies 0\r
+# PROP Scc_ProjName ""\r
+# PROP Scc_LocalPath ""\r
+CPP=cl.exe\r
+RSC=rc.exe\r
+\r
+!IF  "$(CFG)" == "OPJViewer - Win32 Release"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 0\r
+# PROP BASE Output_Dir "Release"\r
+# PROP BASE Intermediate_Dir "Release"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 0\r
+# PROP Output_Dir "Release"\r
+# PROP Intermediate_Dir "Release"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
+# ADD CPP /nologo /G6 /MD /W3 /GX /O2 /I "$(WXWIN28)\lib\vc_lib\msw" /I "$(WXWIN28)\include" /I ".." /I "..\libopenjpeg" /I "$(MXFLIB)" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /D WINVER=0x400 /D "_MT" /D wxUSE_GUI=1 /D "wxUSE_LIBOPENJPEG" /D "OPJ_STATIC" /D "USE_JPWL" /D "USE_JPSEC" /D "OPJ_HTMLABOUT" /D "OPJ_MANYFORMATS" /D "OPJ_INICONFIG" /FR /FD /Zm200 /c\r
+# ADD BASE RSC /l 0x410 /d "NDEBUG"\r
+# ADD RSC /l 0x409 /i "$(WXWIN28)\include" /d "NDEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib comctl32.lib rpcrt4.lib wsock32.lib wxzlib.lib wxregex.lib wxpng.lib wxjpeg.lib wxbase28.lib wxmsw28_core.lib wxmsw28_html.lib wxmsw28_adv.lib wxmsw28_core.lib wxbase28.lib wxtiff.lib wxjpeg.lib wxpng.lib wxzlib.lib wxregex.lib wxexpat.lib LibOpenJPEG_JPWL.lib mxflib.lib /nologo /subsystem:windows /machine:I386 /nodefaultlib:"libcmt.lib" /libpath:"$(WXWIN28)\lib\vc_lib" /libpath:"..\jpwl\Release" /libpath:"$(MXFLIB)\build\msvc\Release" /IGNORE:4089\r
+# SUBTRACT LINK32 /pdb:none /nodefaultlib\r
+# Begin Special Build Tool\r
+SOURCE="$(InputPath)"\r
+PostBuild_Desc=Update build number\r
+PostBuild_Cmds=buildupdate.bat\r
+# End Special Build Tool\r
+\r
+!ELSEIF  "$(CFG)" == "OPJViewer - Win32 Debug"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 1\r
+# PROP BASE Output_Dir "OPJViewer___Win32_Debug"\r
+# PROP BASE Intermediate_Dir "OPJViewer___Win32_Debug"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 1\r
+# PROP Output_Dir "Debug"\r
+# PROP Intermediate_Dir "Debug"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c\r
+# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "$(WXWIN28)\INCLUDE" /I "$(WXWIN28)\lib\vc_lib\msw" /I "$(WXWIN28)\include" /I ".." /I "..\libopenjpeg" /I "$(MXFLIB)" /D "_DEBUG" /D "__WXDEBUG__" /D WXDEBUG=1 /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /D WINVER=0x400 /D "_MT" /D wxUSE_GUI=1 /D "wxUSE_LIBOPENJPEG" /D "OPJ_STATIC" /D "USE_JPWL" /D "OPJ_HTMLABOUT" /D "OPJ_INICONFIG" /D "OPJ_MANYFORMATS" /D "USE_JPSEC" /FR /FD /GZ /Zm200 /c\r
+# ADD BASE RSC /l 0x410 /d "_DEBUG"\r
+# ADD RSC /l 0x410 /i "$(WXWIN28)\include" /d "_DEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib comctl32.lib rpcrt4.lib wsock32.lib wxzlibd.lib wxregexd.lib wxpngd.lib wxjpegd.lib wxtiffd.lib wxbase28d.lib wxmsw28d_core.lib wxmsw28d_html.lib wxmsw28d_adv.lib LibOpenJPEG_JPWLd.lib mxflib.lib /nologo /subsystem:windows /debug /machine:I386 /nodefaultlib:"libcmtd.lib" /pdbtype:sept /libpath:"$(WXWIN28)\lib\vc_lib" /libpath:"..\jpwl\Debug" /libpath:"$(MXFLIB)\build\msvc\Debug"\r
+# SUBTRACT LINK32 /pdb:none\r
+\r
+!ENDIF \r
+\r
+# Begin Target\r
+\r
+# Name "OPJViewer - Win32 Release"\r
+# Name "OPJViewer - Win32 Debug"\r
+# Begin Group "Source Files"\r
+\r
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"\r
+# Begin Source File\r
+\r
+SOURCE=.\source\imagjpeg2000.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\imagmxf.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=..\codec\index.c\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\OPJAbout.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\OPJDialogs.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\OPJThreads.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\OPJViewer.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wxj2kparser.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wxjp2parser.cpp\r
+# End Source File\r
+# End Group\r
+# Begin Group "Header Files"\r
+\r
+# PROP Default_Filter "h;hpp;hxx;hm;inl"\r
+# Begin Source File\r
+\r
+SOURCE=.\source\about_htm.h\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\build.h\r
+# PROP Exclude_From_Build 1\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\imagjpeg2000.h\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\imagmxf.h\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=..\codec\index.h\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\OPJViewer.h\r
+# End Source File\r
+# End Group\r
+# Begin Group "Resource Files"\r
+\r
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\blank.cur\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\bullseye.cur\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\cdrom.ico\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\computer.ico\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\cross.cur\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\drive.ico\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\file1.ico\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\floppy.ico\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\folder1.ico\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\folder2.ico\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\hand.cur\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\icon1.xpm\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\icon2.xpm\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\icon3.xpm\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\icon4.xpm\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\icon5.xpm\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\magnif1.cur\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\opj_logo.xpm\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\OPJChild.ico\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\OPJChild16.xpm\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\OPJViewer.ico\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\OPJViewer.rc\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\OPJViewer16.xpm\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\pbrush.cur\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\pencil.cur\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\pntleft.cur\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\pntright.cur\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\removble.ico\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\rightarr.cur\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\roller.cur\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\source\wx\msw\std.ico\r
+# End Source File\r
+# End Group\r
+# End Target\r
+# End Project\r
diff --git a/applications/OPJViewer/OPJViewer.dsw b/applications/OPJViewer/OPJViewer.dsw
new file mode 100644 (file)
index 0000000..772043d
--- /dev/null
@@ -0,0 +1,56 @@
+Microsoft Developer Studio Workspace File, Format Version 6.00\r
+# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!\r
+\r
+###############################################################################\r
+\r
+Project: "LibOpenJPEG_JPWL"=..\jpwl\LibOpenJPEG_JPWL.dsp - Package Owner=<4>\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<4>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
+Project: "OPJViewer"=.\OPJViewer.dsp - Package Owner=<4>\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<4>\r
+{{{\r
+    Begin Project Dependency\r
+    Project_Dep_Name LibOpenJPEG_JPWL\r
+    End Project Dependency\r
+}}}\r
+\r
+###############################################################################\r
+\r
+Project: "mxflib"="..\..\..\..\mxflib-1.0.0\build\msvc\mxflib.dsp" - Package Owner=<4>\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<4>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
+Global:\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<3>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
diff --git a/applications/OPJViewer/OPJViewer.iss b/applications/OPJViewer/OPJViewer.iss
new file mode 100644 (file)
index 0000000..d4cfadb
--- /dev/null
@@ -0,0 +1,48 @@
+; Script generated by the Inno Setup Script Wizard.\r
+; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!\r
+\r
+[Setup]\r
+AppName=OPJViewer\r
+AppVerName=OPJViewer 0.4 beta\r
+AppPublisher=OpenJPEG\r
+AppPublisherURL=http://www.openjpeg.org\r
+AppSupportURL=http://www.openjpeg.org\r
+AppUpdatesURL=http://www.openjpeg.org\r
+DefaultDirName={pf}\OPJViewer\r
+DefaultGroupName=OPJViewer\r
+OutputDir=setup\r
+OutputBaseFilename=OPJViewer04beta_setup\r
+Compression=lzma\r
+SolidCompression=true\r
+InfoBeforeFile=source\readmebefore.txt\r
+InfoAfterFile=source\readmeafter.txt\r
+LicenseFile=source\license.txt\r
+VersionInfoVersion=0.4.0.0\r
+VersionInfoCompany=OpenJPEG\r
+VersionInfoDescription=JPEG 2000 viewer\r
+ShowLanguageDialog=yes\r
+SetupIconFile=source\OPJViewer.ico\r
+\r
+[Languages]\r
+Name: english; MessagesFile: compiler:Default.isl\r
+\r
+[Tasks]\r
+Name: desktopicon; Description: {cm:CreateDesktopIcon}; GroupDescription: {cm:AdditionalIcons}; Flags: unchecked\r
+\r
+[Files]\r
+Source: Release\OPJViewer.exe; DestDir: {app}; Flags: ignoreversion\r
+;Source: about\about.htm; DestDir: {app}/about; Flags: ignoreversion\r
+;Source: about\opj_logo.png; DestDir: {app}/about; Flags: ignoreversion\r
+; NOTE: Don't use "Flags: ignoreversion" on any shared system files\r
+\r
+[Icons]\r
+Name: {group}\OPJViewer; Filename: {app}\OPJViewer.exe; WorkingDir: {app}; IconIndex: 0\r
+Name: {group}\{cm:UninstallProgram,OPJViewer}; Filename: {uninstallexe}\r
+Name: {userdesktop}\OPJViewer; Filename: {app}\OPJViewer.exe; Tasks: desktopicon; WorkingDir: {app}; IconIndex: 0\r
+\r
+[Run]\r
+Filename: {app}\OPJViewer.exe; Description: {cm:LaunchProgram,OPJViewer}; Flags: nowait postinstall skipifsilent; WorkingDir: {app}\r
+\r
+[Registry]\r
+Root: HKCU; Subkey: Software\OpenJPEG; ValueType: none; ValueData: 1; Flags: uninsdeletekey; Tasks: ; Languages: \r
+Root: HKCU; Subkey: Software\OpenJPEG\OPJViewer; ValueType: none; ValueData: 1; Flags: uninsdeletekey; Tasks: ; Languages: \r
diff --git a/applications/OPJViewer/Readme.txt b/applications/OPJViewer/Readme.txt
new file mode 100644 (file)
index 0000000..7eb3e46
--- /dev/null
@@ -0,0 +1,100 @@
+===============================================================================\r
+       JPEG2000 Visualization Software - OPJViewer\r
+\r
+               Version 0.4 beta\r
+===============================================================================\r
+\r
+\r
+1. Scope\r
+=============\r
+\r
+This document describes the installation and use of the OPJViewer in the framework of OpenJPEG library.\r
+\r
+This implementation has been developed using the OpenJPEG library as decoding engine and wxWidgets 2.8 as GUI engine.\r
+\r
+If you find some bugs or if you have problems using the viewer, please send an e-mail to jpwl@diei.unipg.it\r
+\r
+2. Installing the viewer\r
+==========================\r
+\r
+There are two options available, at the moment:\r
+\r
+a) compile from source code\r
+b) download a precompiled binary.\r
+\r
+In order to use option a), it is mandatory to have compiled and built the LibOpenJPEG_JPWL library and the wxWidgets 2.8 framework (you have to download it from http://www.wxwidgets.org/ and compile the wx* libraries).\r
+\r
+2.1. Compiling the source code in Windows\r
+-------------------------------------------\r
+\r
+The steps required to compile the viewer under windows are:\r
+\r
+a) Download at least the libopenjpeg, jpwl, and opjviewer folders from the SVN trunk.\r
+b) Open the OPJViewer.dsw workspace with Visual C++ 6 and activate the "OPJViewer - Win32 Release" configuration.\r
+c) In the configuration settings, go to the C++ tab and modify the wxWidgets paths in order to reflect your wx* install configuration (Preprocessor -> Additional include directories): simply update each instance of the two wx paths, do not remove or add them.\r
+d) In the configuration settings, go to the Link tab and modify the wxWidgets path in order to reflect your wx* install configuration (Input -> Additional library path): simply update the wx path.\r
+e) In the configuration settings, go to the Resources tab and modify the wxWidgets path in order to reflect your wx* install configuration (Additional resource include directories): simply update the wx path.\r
+f) Build!\r
+g) Run!\r
+h) (OPTIONAL) Prepare an installer by compiling the InnoSetup script OPJViewer.iss (you need to download InnoSetup from http://www.jrsoftware.org/isinfo.php).\r
+\r
+2.1.1 Additional libraries\r
+----------------------------\r
+\r
+Since we are also working on the Digital Cinema JPEG 2000, we are integrating the viewer with the MXF library, which is used to prepare the DCPs for digital movies. You can enable its linking in the code by specifying the USE_MXF preprocessor directive but, remember, the integration is at a very early stage.\r
+\r
+2.2. Compiling the source code in Unix-like systems\r
+-----------------------------------------------------\r
+\r
+The porting is possible and under way.\r
+\r
+\r
+3. General information on the viewer\r
+====================================\r
+\r
+This viewer is conceived to open and display information and image content of J2K, JP2, and MJ2 files.\r
+The viewer application interface is divided into three main panels:\r
+- a browsing pane;\r
+- a viewing pane;\r
+- a log/peek pane.\r
+\r
+The browsing pane will present the markers or boxes hierarchy, with position (byte number where marker/box starts and stops) and length information (i.e., inner length as signalled by marker/box and total length, with marker/box sign included), in the following form:\r
+\r
+filename\r
+|\r
+|_ #000: Marker/Box short name (Hex code)\r
+|  |\r
+|  |_ *** Marker/Box long name ***\r
+|  |_ startbyte > stopbyte, inner_length + marker/box sign length (total length)\r
+|  |_ Additional info, depending on the marker/box type\r
+|  |_ ...\r
+|\r
+|_ #001: Marker/Box short name (Hex code)\r
+|  |\r
+|  |_ ...\r
+|\r
+...\r
+\r
+\r
+The viewing pane will display the decoded image contained in the JPEG 2000 file.\r
+It should display correctly images as large as 4000x2000, provided that a couple of GB of RAM are available. Nothing is known about the display of larger sizes: let us know if you manage to get it working.\r
+\r
+\r
+The log/peek pane is shared among two different subpanels:\r
+\r
+- the log panel will report a lot of debugging info coming out from the wx GUI as well as from the openjpeg library\r
+- the peek pane tries to give a peek on the codestream/file portion which is currently selected in the browsing pane. It shows both hex and ascii values corresponding to the marker/box section. \r
+\r
+\r
+4. Known bugs and limitations\r
+===============================\r
+\r
+4.1. Bugs\r
+-----------\r
+\r
+* \r
+\r
+4.2. Limitations\r
+------------------\r
+\r
+* For mj2 files, rendering is only in B/W\r
diff --git a/applications/OPJViewer/about/about.htm b/applications/OPJViewer/about/about.htm
new file mode 100644 (file)
index 0000000..fec6028
--- /dev/null
@@ -0,0 +1,36 @@
+<html>\r
+<body bgcolor="#FFFFFF">\r
+<table cellspacing=7 cellpadding=1 border=0 width="100%">\r
+<tr>\r
+<td rowspan=3 valign=top align=center width=70>\r
+<img src="opj_logo.png"><br><br>\r
+</td>\r
+<td align=center>\r
+<font size=+2 color="#000000"><b>OPJViewer v0.2 alpha</b></font><br>\r
+<font size=+0 color="#000000"><b>A JPEG 2000 image viewer</b></font>\r
+</td>\r
+</tr>\r
+<tr height=3 valign=center>\r
+<td valign=center  bgcolor=#cc3300></td>\r
+</tr>\r
+<tr>\r
+<td align=justify>\r
+<center><font size=+0 color="#000000"><a href="http://www.openjpeg.org/">OpenJPEG</a></font></center>\r
+<font size=-1 color="#000000">The OpenJPEG library is an open-source JPEG 2000 codec written in C language.\r
+In addition to the basic codec, various other features are under development,\r
+among them the JP2 and MJ2 (Motion JPEG 2000) file formats, an indexing tool\r
+useful for the JPIP protocol, JPWL-tools for error-resilience, ...</font>\r
+</td>\r
+</tr>\r
+<tr>\r
+<td colspan=2 bgcolor="#CC3300" height=3 valign=center></td>\r
+</tr>\r
+<tr>\r
+<td colspan=2>\r
+<font size=-2 color="#444444">OpenJPEG is &copy; 2002-2007 <a href="http://www.tele.ucl.ac.be/">TELE</a> - <a href="http://www.uclouvain.be/">Universit� Catholique de Louvain</a></font><br>\r
+<font size=-2 color="#444444">OPJViewer is also &copy; 2005-2007 <a href="http://dsplab.diei.unipg.it/">DSPLab</a> - <a href="http://www.unipg.it/">Universit� degli studi di Perugia</a></font>\r
+</td>\r
+</tr>\r
+</table>\r
+</body>\r
+</html>\r
diff --git a/applications/OPJViewer/about/opj_logo.png b/applications/OPJViewer/about/opj_logo.png
new file mode 100644 (file)
index 0000000..0f43840
Binary files /dev/null and b/applications/OPJViewer/about/opj_logo.png differ
diff --git a/applications/OPJViewer/buildupdate.bat b/applications/OPJViewer/buildupdate.bat
new file mode 100644 (file)
index 0000000..0aae1c1
--- /dev/null
@@ -0,0 +1,15 @@
+::== buildupdate.bat\r
+@echo off\r
+setLocal EnableDelayedExpansion\r
+\r
+for /f "tokens=2,* delims=^(^) " %%a in ('find /v "" ^< .\source\build.h') do (\r
+rem echo %%a\r
+set /A M = %%a + 1\r
+echo Build %%a done^!\r
+echo wxT^("!M!"^) > buildtemp283746825t347\r
+)\r
+\r
+if exist buildtemp283746825t347 move /Y buildtemp283746825t347 .\source\build.h\r
+if exist buildtemp283746825t347 del /F /Q buildtemp283746825t347\r
+\r
+::==
\ No newline at end of file
diff --git a/applications/OPJViewer/source/OPJAbout.cpp b/applications/OPJViewer/source/OPJAbout.cpp
new file mode 100644 (file)
index 0000000..ecc5f45
--- /dev/null
@@ -0,0 +1,87 @@
+/*\r
+ * Copyright (c) 2007, Digital Signal Processing Laboratory, Universita'� degli studi di Perugia (UPG), Italy\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+#ifdef USE_MXF\r
+#include "mxflib/mxflib.h"\r
+#endif // USE_MXF\r
+\r
+#include "OPJViewer.h"\r
+\r
+// about window for the frame\r
+void OPJFrame::OnAbout(wxCommandEvent& WXUNUSED(event))\r
+{\r
+#ifdef OPJ_HTMLABOUT\r
+#include "about_htm.h"\r
+#include "opj_logo.xpm"\r
+\r
+    wxBoxSizer *topsizer;\r
+    wxHtmlWindow *html;\r
+    wxDialog dlg(this, wxID_ANY, wxString(_("About")));\r
+\r
+    wxMemoryFSHandler::AddFile(wxT("opj_logo.xpm"), wxBitmap(opj_logo), wxBITMAP_TYPE_XPM);\r
+\r
+    topsizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+    html = new wxHtmlWindow(&dlg, wxID_ANY, wxDefaultPosition, wxSize(320, 250), wxHW_SCROLLBAR_NEVER);\r
+    html->SetBorders(0);\r
+    //html->LoadPage(wxT("about/about.htm"));\r
+       //html->SetPage("<html><body>Hello, world!</body></html>");\r
+       html->SetPage(htmlaboutpage);\r
+    html->SetSize(html->GetInternalRepresentation()->GetWidth(),\r
+                    html->GetInternalRepresentation()->GetHeight());\r
+\r
+    topsizer->Add(html, 1, wxALL, 10);\r
+\r
+    topsizer->Add(new wxStaticLine(&dlg, wxID_ANY), 0, wxEXPAND | wxLEFT | wxRIGHT, 10);\r
+\r
+    wxButton *bu1 = new wxButton(&dlg, wxID_OK, wxT("OK"));\r
+    bu1->SetDefault();\r
+\r
+    topsizer->Add(bu1, 0, wxALL | wxALIGN_RIGHT, 15);\r
+\r
+    dlg.SetSizer(topsizer);\r
+    topsizer->Fit(&dlg);\r
+\r
+    dlg.ShowModal();\r
+\r
+#else\r
+\r
+       wxMessageBox(wxString::Format(OPJ_APPLICATION_TITLEBAR\r
+                                                                 wxT("\n\n")\r
+                                                                 wxT("Built with %s and OpenJPEG ")\r
+                                                                 wxT(OPENJPEG_VERSION)\r
+                                                                 wxT("\non ") wxT(__DATE__) wxT(", ") wxT(__TIME__)\r
+                                                                 wxT("\nRunning under %s\n\n")\r
+                                                                 OPJ_APPLICATION_COPYRIGHT,\r
+                                                                 wxVERSION_STRING,\r
+                                                                 wxGetOsDescription().c_str()),\r
+                                wxT("About ") OPJ_APPLICATION_NAME,\r
+                                wxOK | wxICON_INFORMATION,\r
+                                this\r
+                                );\r
+\r
+#endif\r
+\r
+}\r
diff --git a/applications/OPJViewer/source/OPJChild.ico b/applications/OPJViewer/source/OPJChild.ico
new file mode 100644 (file)
index 0000000..7a12718
Binary files /dev/null and b/applications/OPJViewer/source/OPJChild.ico differ
diff --git a/applications/OPJViewer/source/OPJChild16.xpm b/applications/OPJViewer/source/OPJChild16.xpm
new file mode 100644 (file)
index 0000000..48e8796
--- /dev/null
@@ -0,0 +1,28 @@
+/* XPM */\r
+static char *OPJChild16[] = {\r
+/* columns rows colors chars-per-pixel */\r
+"16 16 6 1",\r
+"  c black",\r
+". c #008000",\r
+"X c red",\r
+"o c #800080",\r
+"O c gray100",\r
+"+ c None",\r
+/* pixels */\r
+"++++++++++++++++",\r
+"+OOOOOOOOOOOOOO+",\r
+"+OooooooooooooO+",\r
+"+OooooooooooooO+",\r
+"+OooOOOOOOOOOoO+",\r
+"+OooO.......OoO+",\r
+"+OooO.......OoO+",\r
+"+OooO..OOO..OoO+",\r
+"+OooO..OXO..OoO+",\r
+"+OooO..OOO..OoO+",\r
+"+OooO.......OoO+",\r
+"+OooO.......OoO+",\r
+"+OooOOOOOOOOOoO+",\r
+"+OooooooooooooO+",\r
+"+OOOOOOOOOOOOOO+",\r
+"++++++++++++++++"\r
+};\r
diff --git a/applications/OPJViewer/source/OPJDialogs.cpp b/applications/OPJViewer/source/OPJDialogs.cpp
new file mode 100644 (file)
index 0000000..ed68ef3
--- /dev/null
@@ -0,0 +1,1373 @@
+/*\r
+ * Copyright (c) 2007, Digital Signal Processing Laboratory, Universita'� degli studi di Perugia (UPG), Italy\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+#include "OPJViewer.h"\r
+\r
+// ----------------------------------------------------------------------------\r
+// OPJDecoderDialog\r
+// ----------------------------------------------------------------------------\r
+\r
+IMPLEMENT_CLASS(OPJDecoderDialog, wxPropertySheetDialog)\r
+\r
+BEGIN_EVENT_TABLE(OPJDecoderDialog, wxPropertySheetDialog)\r
+       EVT_CHECKBOX(OPJDECO_ENABLEDECO, OPJDecoderDialog::OnEnableDeco)\r
+#ifdef USE_JPWL\r
+       EVT_CHECKBOX(OPJDECO_ENABLEJPWL, OPJDecoderDialog::OnEnableJPWL)\r
+#endif // USE_JPWL\r
+END_EVENT_TABLE()\r
+\r
+OPJDecoderDialog::OPJDecoderDialog(wxWindow* win, int dialogType)\r
+{\r
+       SetExtraStyle(wxDIALOG_EX_CONTEXTHELP|wxWS_EX_VALIDATE_RECURSIVELY);\r
+\r
+       Create(win, wxID_ANY, wxT("Decoder settings"),\r
+               wxDefaultPosition, wxDefaultSize,\r
+               wxDEFAULT_DIALOG_STYLE| (int) wxPlatform::IfNot(wxOS_WINDOWS_CE, wxRESIZE_BORDER)\r
+               );\r
+\r
+       CreateButtons(wxOK | wxCANCEL | (int)wxPlatform::IfNot(wxOS_WINDOWS_CE, wxHELP));\r
+\r
+       m_settingsNotebook = GetBookCtrl();\r
+\r
+       wxPanel* mainSettings = CreateMainSettingsPage(m_settingsNotebook);\r
+       wxPanel* jpeg2000Settings = CreatePart1SettingsPage(m_settingsNotebook);\r
+       if (!wxGetApp().m_enabledeco)\r
+               jpeg2000Settings->Enable(false);\r
+       wxPanel* mjpeg2000Settings = CreatePart3SettingsPage(m_settingsNotebook);\r
+       if (!wxGetApp().m_enabledeco)\r
+               mjpeg2000Settings->Enable(false);\r
+#ifdef USE_JPWL\r
+       wxPanel* jpwlSettings = CreatePart11SettingsPage(m_settingsNotebook);\r
+       if (!wxGetApp().m_enabledeco)\r
+               jpwlSettings->Enable(false);\r
+#endif // USE_JPWL\r
+\r
+       m_settingsNotebook->AddPage(mainSettings, wxT("Display"), false);\r
+       m_settingsNotebook->AddPage(jpeg2000Settings, wxT("JPEG 2000"), false);\r
+       m_settingsNotebook->AddPage(mjpeg2000Settings, wxT("MJPEG 2000"), false);\r
+#ifdef USE_JPWL\r
+       m_settingsNotebook->AddPage(jpwlSettings, wxT("JPWL"), false);\r
+#endif // USE_JPWL\r
+\r
+       LayoutDialog();\r
+}\r
+\r
+OPJDecoderDialog::~OPJDecoderDialog()\r
+{\r
+}\r
+\r
+wxPanel* OPJDecoderDialog::CreateMainSettingsPage(wxWindow* parent)\r
+{\r
+    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
+\r
+       // top sizer\r
+    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+               // sub top sizer\r
+               wxBoxSizer *subtopSizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+               // add decoding enabling check box\r
+               subtopSizer->Add(\r
+                       m_enabledecoCheck = new wxCheckBox(panel, OPJDECO_ENABLEDECO, wxT("Enable decoding"), wxDefaultPosition, wxDefaultSize),\r
+                       0, wxGROW | wxALL, 5);\r
+               m_enabledecoCheck->SetValue(wxGetApp().m_enabledeco);\r
+\r
+               // add parsing enabling check box\r
+               subtopSizer->Add(\r
+                       m_enableparseCheck = new wxCheckBox(panel, OPJDECO_ENABLEPARSE, wxT("Enable parsing"), wxDefaultPosition, wxDefaultSize),\r
+                       0, wxGROW | wxALL, 5);\r
+               m_enableparseCheck->SetValue(wxGetApp().m_enableparse);\r
+\r
+                       // resize settings, column\r
+                       wxString choices[] = {wxT("Don't resize"), wxT("Low quality"), wxT("High quality")};\r
+                       m_resizeBox = new wxRadioBox(panel, OPJDECO_RESMETHOD,\r
+                               wxT("Resize method"),\r
+                               wxDefaultPosition, wxDefaultSize,\r
+                               WXSIZEOF(choices),\r
+                               choices,\r
+                               1,\r
+                               wxRA_SPECIFY_ROWS);\r
+                       m_resizeBox->SetSelection(wxGetApp().m_resizemethod + 1);\r
+\r
+               subtopSizer->Add(m_resizeBox, 0, wxGROW | wxALL, 5);\r
+\r
+       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
+\r
+       // assign top and fit it\r
+    panel->SetSizer(topSizer);\r
+    topSizer->Fit(panel);\r
+\r
+    return panel;\r
+}\r
+\r
+wxPanel* OPJDecoderDialog::CreatePart3SettingsPage(wxWindow* parent)\r
+{\r
+    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
+\r
+       // top sizer\r
+    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+       // add some space\r
+       //topSizer->AddSpacer(5);\r
+\r
+               // sub top sizer\r
+               wxBoxSizer *subtopSizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+                       // frame settings, column\r
+                       wxStaticBox* frameBox = new wxStaticBox(panel, wxID_ANY, wxT("Frame"));\r
+                       wxBoxSizer* frameSizer = new wxStaticBoxSizer(frameBox, wxVERTICAL);\r
+\r
+                               // selected frame number, row\r
+                               wxBoxSizer* framenumSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               framenumSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Displayed frame:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 5);\r
+\r
+                               // add some horizontal space\r
+                               framenumSizer->Add(5, 5, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               framenumSizer->Add(\r
+                                       m_framenumCtrl = new wxSpinCtrl(panel, OPJDECO_FRAMENUM,\r
+                                                               wxString::Format(wxT("%d"), wxGetApp().m_framenum),\r
+                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
+                                                               wxSP_ARROW_KEYS,\r
+                                                               1, 100000, wxGetApp().m_framenum),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\r
+\r
+                       frameSizer->Add(framenumSizer, 0, wxGROW | wxALL, 5);\r
+\r
+               subtopSizer->Add(frameSizer, 0, wxGROW | wxALL, 5);\r
+\r
+       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
+\r
+       // assign top and fit it\r
+    panel->SetSizer(topSizer);\r
+    topSizer->Fit(panel);\r
+\r
+    return panel;\r
+}\r
+\r
+wxPanel* OPJDecoderDialog::CreatePart1SettingsPage(wxWindow* parent)\r
+{\r
+    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
+\r
+       // top sizer\r
+    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+       // add some space\r
+       //topSizer->AddSpacer(5);\r
+\r
+               // sub top sizer\r
+               wxBoxSizer *subtopSizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+                       // resolutions settings, column\r
+                       wxStaticBox* resolutionBox = new wxStaticBox(panel, wxID_ANY, wxT("Resolutions"));\r
+                       wxBoxSizer* resolutionSizer = new wxStaticBoxSizer(resolutionBox, wxVERTICAL);\r
+\r
+                               // reduce factor sizer, row\r
+                               wxBoxSizer* reduceSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               reduceSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Reduce factor:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 5);\r
+\r
+                               // add some horizontal space\r
+                               reduceSizer->Add(5, 5, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               reduceSizer->Add(\r
+                                       m_reduceCtrl = new wxSpinCtrl(panel, OPJDECO_REDUCEFACTOR,\r
+                                       wxString::Format(wxT("%d"), wxGetApp().m_reducefactor),\r
+                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
+                                                               wxSP_ARROW_KEYS,\r
+                                                               0, 10000, wxGetApp().m_reducefactor),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\r
+\r
+                       resolutionSizer->Add(reduceSizer, 0, wxGROW | wxALL, 5);\r
+\r
+               subtopSizer->Add(resolutionSizer, 0, wxGROW | wxALL, 5);\r
+\r
+                       // quality layer settings, column\r
+                       wxStaticBox* layerBox = new wxStaticBox(panel, wxID_ANY, wxT("Layers"));\r
+                       wxBoxSizer* layerSizer = new wxStaticBoxSizer(layerBox, wxVERTICAL);\r
+\r
+                               // quality layers sizer, row\r
+                               wxBoxSizer* qualitySizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               qualitySizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Quality layers:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 5);\r
+\r
+                               // add some horizontal space\r
+                               qualitySizer->Add(5, 5, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               qualitySizer->Add(\r
+                                       m_layerCtrl = new wxSpinCtrl(panel, OPJDECO_QUALITYLAYERS,\r
+                                                               wxString::Format(wxT("%d"), wxGetApp().m_qualitylayers),\r
+                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
+                                                               wxSP_ARROW_KEYS,\r
+                                                               0, 100000, wxGetApp().m_qualitylayers),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\r
+\r
+                       layerSizer->Add(qualitySizer, 0, wxGROW | wxALL, 5);\r
+\r
+               subtopSizer->Add(layerSizer, 0, wxGROW | wxALL, 5);\r
+\r
+                       // component settings, column\r
+                       wxStaticBox* compoBox = new wxStaticBox(panel, wxID_ANY, wxT("Components"));\r
+                       wxBoxSizer* compoSizer = new wxStaticBoxSizer(compoBox, wxVERTICAL);\r
+\r
+                               // quality layers sizer, row\r
+                               wxBoxSizer* numcompsSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               numcompsSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Component displayed:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 5);\r
+\r
+                               // add some horizontal space\r
+                               numcompsSizer->Add(5, 5, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               numcompsSizer->Add(\r
+                                       m_numcompsCtrl = new wxSpinCtrl(panel, OPJDECO_NUMCOMPS,\r
+                                                               wxString::Format(wxT("%d"), wxGetApp().m_components),\r
+                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
+                                                               wxSP_ARROW_KEYS,\r
+                                                               0, 100000, wxGetApp().m_components),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\r
+                               m_numcompsCtrl->Enable(true);\r
+\r
+                       compoSizer->Add(numcompsSizer, 0, wxGROW | wxALL, 5);\r
+\r
+               subtopSizer->Add(compoSizer, 0, wxGROW | wxALL, 5);\r
+\r
+       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
+\r
+       // assign top and fit it\r
+    panel->SetSizer(topSizer);\r
+    topSizer->Fit(panel);\r
+\r
+    return panel;\r
+}\r
+\r
+#ifdef USE_JPWL\r
+wxPanel* OPJDecoderDialog::CreatePart11SettingsPage(wxWindow* parent)\r
+{\r
+    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
+\r
+       // top sizer\r
+    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+       // add some space\r
+       //topSizer->AddSpacer(5);\r
+\r
+               // sub top sizer\r
+               wxBoxSizer *subtopSizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+               // add JPWL enabling check box\r
+               subtopSizer->Add(\r
+                       m_enablejpwlCheck = new wxCheckBox(panel, OPJDECO_ENABLEJPWL, wxT("Enable JPWL"), wxDefaultPosition, wxDefaultSize),\r
+                       0, wxGROW | wxALL, 5);\r
+               m_enablejpwlCheck->SetValue(wxGetApp().m_enablejpwl);\r
+\r
+                       // component settings, column\r
+                       wxStaticBox* compoBox = new wxStaticBox(panel, wxID_ANY, wxT("Components"));\r
+                       wxBoxSizer* compoSizer = new wxStaticBoxSizer(compoBox, wxVERTICAL);\r
+\r
+                               // expected components sizer, row\r
+                               wxBoxSizer* expcompsSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               expcompsSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Expected comps.:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 5);\r
+\r
+                               // add some horizontal space\r
+                               expcompsSizer->Add(5, 5, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               expcompsSizer->Add(\r
+                                       m_expcompsCtrl = new wxSpinCtrl(panel, OPJDECO_EXPCOMPS,\r
+                                                               wxString::Format(wxT("%d"), wxGetApp().m_expcomps),\r
+                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
+                                                               wxSP_ARROW_KEYS,\r
+                                                               1, 100000, wxGetApp().m_expcomps),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\r
+                               m_expcompsCtrl->Enable(wxGetApp().m_enablejpwl);\r
+\r
+                       compoSizer->Add(expcompsSizer, 0, wxGROW | wxALL, 5);\r
+\r
+               subtopSizer->Add(compoSizer, 0, wxGROW | wxALL, 5);\r
+\r
+                       // tiles settings, column\r
+                       wxStaticBox* tileBox = new wxStaticBox(panel, wxID_ANY, wxT("Tiles"));\r
+                       wxBoxSizer* tileSizer = new wxStaticBoxSizer(tileBox, wxVERTICAL);\r
+\r
+                               // maximum tiles sizer, row\r
+                               wxBoxSizer* maxtileSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               maxtileSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Max. no. of tiles:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 5);\r
+\r
+                               // add some horizontal space\r
+                               maxtileSizer->Add(5, 5, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               maxtileSizer->Add(\r
+                                       m_maxtilesCtrl = new wxSpinCtrl(panel, OPJDECO_MAXTILES,\r
+                                                               wxString::Format(wxT("%d"), wxGetApp().m_maxtiles),\r
+                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
+                                                               wxSP_ARROW_KEYS,\r
+                                                               1, 100000, wxGetApp().m_maxtiles),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\r
+                               m_maxtilesCtrl->Enable(wxGetApp().m_enablejpwl);\r
+\r
+                       tileSizer->Add(maxtileSizer, 0, wxGROW | wxALL, 5);\r
+\r
+               subtopSizer->Add(tileSizer, 0, wxGROW | wxALL, 5);\r
+\r
+       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
+\r
+       // assign top and fit it\r
+    panel->SetSizer(topSizer);\r
+    topSizer->Fit(panel);\r
+\r
+    return panel;\r
+}\r
+\r
+void OPJDecoderDialog::OnEnableDeco(wxCommandEvent& event)\r
+{\r
+       size_t pp;\r
+\r
+       if (event.IsChecked()) {\r
+               wxLogMessage(wxT("Decoding enabled"));\r
+               m_resizeBox->Enable(true);\r
+               // enable all tabs except ourselves\r
+               for (pp = 0; pp < m_settingsNotebook->GetPageCount(); pp++) {\r
+                       if (m_settingsNotebook->GetPageText(pp) != wxT("Display"))\r
+                               m_settingsNotebook->GetPage(pp)->Enable(true);\r
+               }\r
+       } else {\r
+               wxLogMessage(wxT("Decoding disabled"));\r
+               m_resizeBox->Enable(false);\r
+               // disable all tabs except ourselves\r
+               for (pp = 0; pp < m_settingsNotebook->GetPageCount(); pp++) {\r
+                       if (m_settingsNotebook->GetPageText(pp) != wxT("Display"))\r
+                               m_settingsNotebook->GetPage(pp)->Enable(false);\r
+               }\r
+       }\r
+\r
+}\r
+\r
+void OPJDecoderDialog::OnEnableJPWL(wxCommandEvent& event)\r
+{\r
+       if (event.IsChecked()) {\r
+               wxLogMessage(wxT("JPWL enabled"));\r
+               m_expcompsCtrl->Enable(true);\r
+               m_maxtilesCtrl->Enable(true);\r
+       } else {\r
+               wxLogMessage(wxT("JPWL disabled"));\r
+               m_expcompsCtrl->Enable(false);\r
+               m_maxtilesCtrl->Enable(false);\r
+       }\r
+\r
+}\r
+\r
+#endif // USE_JPWL\r
+\r
+\r
+\r
+\r
+// ----------------------------------------------------------------------------\r
+// OPJEncoderDialog\r
+// ----------------------------------------------------------------------------\r
+\r
+IMPLEMENT_CLASS(OPJEncoderDialog, wxPropertySheetDialog)\r
+\r
+BEGIN_EVENT_TABLE(OPJEncoderDialog, wxPropertySheetDialog)\r
+       EVT_CHECKBOX(OPJENCO_ENABLECOMM, OPJEncoderDialog::OnEnableComm)\r
+       EVT_CHECKBOX(OPJENCO_ENABLEINDEX, OPJEncoderDialog::OnEnableIdx)\r
+       EVT_CHECKBOX(OPJENCO_ENABLEPOC, OPJEncoderDialog::OnEnablePoc)\r
+       EVT_RADIOBUTTON(OPJENCO_RATERADIO, OPJEncoderDialog::OnRadioQualityRate)\r
+       EVT_RADIOBUTTON(OPJENCO_QUALITYRADIO, OPJEncoderDialog::OnRadioQualityRate)\r
+#ifdef USE_JPWL\r
+       EVT_CHECKBOX(OPJENCO_ENABLEJPWL, OPJEncoderDialog::OnEnableJPWL)\r
+       EVT_CHOICE(OPJENCO_HPROT, OPJEncoderDialog::OnHprotSelect)\r
+       EVT_CHOICE(OPJENCO_PPROT, OPJEncoderDialog::OnPprotSelect)\r
+       EVT_CHOICE(OPJENCO_SENSI, OPJEncoderDialog::OnSensiSelect)\r
+#endif // USE_JPWL\r
+END_EVENT_TABLE()\r
+\r
+OPJEncoderDialog::OPJEncoderDialog(wxWindow* win, int dialogType)\r
+{\r
+       SetExtraStyle(wxDIALOG_EX_CONTEXTHELP|wxWS_EX_VALIDATE_RECURSIVELY);\r
+\r
+       Create(win, wxID_ANY, wxT("Encoder settings"),\r
+               wxDefaultPosition, wxDefaultSize,\r
+               wxDEFAULT_DIALOG_STYLE| (int) wxPlatform::IfNot(wxOS_WINDOWS_CE, wxRESIZE_BORDER)\r
+               );\r
+\r
+       CreateButtons(wxOK | wxCANCEL | (int)wxPlatform::IfNot(wxOS_WINDOWS_CE, wxHELP));\r
+\r
+       m_settingsNotebook = GetBookCtrl();\r
+\r
+       wxPanel* jpeg2000_1Settings = CreatePart1_1SettingsPage(m_settingsNotebook);\r
+       wxPanel* jpeg2000_2Settings = CreatePart1_2SettingsPage(m_settingsNotebook);\r
+       wxPanel* mainSettings = CreateMainSettingsPage(m_settingsNotebook);\r
+#ifdef USE_JPWL\r
+       wxPanel* jpwlSettings = CreatePart11SettingsPage(m_settingsNotebook);\r
+#endif // USE_JPWL\r
+\r
+#ifdef USE_JPWL\r
+       m_settingsNotebook->AddPage(jpwlSettings, wxT("JPWL"), false);\r
+#endif // USE_JPWL\r
+       m_settingsNotebook->AddPage(jpeg2000_1Settings, wxT("JPEG 2000 - 1"), false);\r
+       m_settingsNotebook->AddPage(jpeg2000_2Settings, wxT("JPEG 2000 - 2"), false);\r
+       m_settingsNotebook->AddPage(mainSettings, wxT("General"), false);\r
+\r
+       LayoutDialog();\r
+}\r
+\r
+OPJEncoderDialog::~OPJEncoderDialog()\r
+{\r
+}\r
+\r
+wxPanel* OPJEncoderDialog::CreateMainSettingsPage(wxWindow* parent)\r
+{\r
+    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
+\r
+       // top sizer\r
+    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+               // sub top sizer\r
+               wxBoxSizer *subtopSizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
+\r
+       // assign top and fit it\r
+    panel->SetSizer(topSizer);\r
+    topSizer->Fit(panel);\r
+\r
+    return panel;\r
+}\r
+\r
+#ifdef USE_JPWL\r
+wxPanel* OPJEncoderDialog::CreatePart11SettingsPage(wxWindow* parent)\r
+{\r
+    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
+       int specno;\r
+\r
+       // top sizer\r
+    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+               // add JPWL enabling check box\r
+               topSizer->Add(\r
+                       m_enablejpwlCheck = new wxCheckBox(panel, OPJENCO_ENABLEJPWL, wxT("Enable JPWL"),\r
+                       wxDefaultPosition, wxDefaultSize),\r
+                       0, wxGROW | wxALL | wxALIGN_CENTER, 5);\r
+               m_enablejpwlCheck->SetValue(wxGetApp().m_enablejpwle);\r
+\r
+               // sub top sizer\r
+               wxFlexGridSizer *subtopSizer = new wxFlexGridSizer(2, 3, 3);\r
+\r
+                       // header settings, column\r
+                       wxStaticBox* headerBox = new wxStaticBox(panel, wxID_ANY, wxT("Header protection"));\r
+                       wxBoxSizer* headerSizer = new wxStaticBoxSizer(headerBox, wxVERTICAL);\r
+\r
+                               // info sizer, row\r
+                               wxBoxSizer* info1Sizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               info1Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
+                                                               wxT("Type")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
+\r
+                               // add some horizontal space\r
+                               info1Sizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add some text\r
+                               info1Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
+                                                               wxT("Tile part")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
+\r
+                       headerSizer->Add(info1Sizer, 0, wxGROW | wxALL, 0);\r
+\r
+                       // specify specs\r
+                       wxString hprotvalues[] = {wxT("None"), wxT("Pred."), wxT("CRC16"), wxT("CRC32"),\r
+                               wxT("RS37"), wxT("RS38"), wxT("RS40"), wxT("RS43"), wxT("RS45"), wxT("RS48"),\r
+                               wxT("RS51"), wxT("RS53"), wxT("RS56"), wxT("RS64"), wxT("RS75"), wxT("RS80"),\r
+                               wxT("RS85"), wxT("RS96"), wxT("RS112"), wxT("RS128")};\r
+                       for (specno = 0; specno < MYJPWL_MAX_NO_TILESPECS; specno++) {\r
+\r
+                                       // tile+hprot sizer, row\r
+                                       wxBoxSizer* tilehprotSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                                       // add the value selection\r
+                                       tilehprotSizer->Add(\r
+                                               m_hprotChoice[specno] = new wxChoice(panel, OPJENCO_HPROT,\r
+                                                       wxDefaultPosition, wxSize(60, wxDefaultCoord),\r
+                                                       WXSIZEOF(hprotvalues), hprotvalues),\r
+                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
+                                       m_hprotChoice[specno]->SetSelection(wxGetApp().m_hprotsel[specno]);\r
+\r
+                                       // add some horizontal space\r
+                                       tilehprotSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                                       // add the value control\r
+                                       tilehprotSizer->Add(\r
+                                               m_htileCtrl[specno] = new wxSpinCtrl(panel, OPJENCO_HTILE,\r
+                                                       wxString::Format(wxT("%d"), wxGetApp().m_htileval[specno]),\r
+                                                       wxDefaultPosition, wxSize(45, wxDefaultCoord),\r
+                                                       wxSP_ARROW_KEYS,\r
+                                                       0, JPWL_MAXIMUM_TILES - 1, 0),\r
+                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
+\r
+                               headerSizer->Add(tilehprotSizer, 0, wxGROW | wxALL, 0);\r
+                       }\r
+\r
+                       wxCommandEvent event1;\r
+                       OnHprotSelect(event1);\r
+\r
+               subtopSizer->Add(headerSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                       // packet settings, column\r
+                       wxStaticBox* packetBox = new wxStaticBox(panel, wxID_ANY, wxT("Packet protection"));\r
+                       wxBoxSizer* packetSizer = new wxStaticBoxSizer(packetBox, wxVERTICAL);\r
+\r
+                               // info sizer, row\r
+                               wxBoxSizer* info2Sizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               info2Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
+                                                               wxT("Type")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
+\r
+                               // add some horizontal space\r
+                               info2Sizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add some text\r
+                               info2Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
+                                                               wxT("Tile part")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
+\r
+                               // add some horizontal space\r
+                               info2Sizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add some text\r
+                               info2Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
+                                                               wxT("Packet")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
+\r
+                       packetSizer->Add(info2Sizer, 0, wxGROW | wxALL, 0);\r
+\r
+                       // specify specs\r
+                       wxString pprotvalues[] = {wxT("None"), wxT("Pred."), wxT("CRC16"), wxT("CRC32"),\r
+                               wxT("RS37"), wxT("RS38"), wxT("RS40"), wxT("RS43"), wxT("RS45"), wxT("RS48"),\r
+                               wxT("RS51"), wxT("RS53"), wxT("RS56"), wxT("RS64"), wxT("RS75"), wxT("RS80"),\r
+                               wxT("RS85"), wxT("RS96"), wxT("RS112"), wxT("RS128")};\r
+                       for (specno = 0; specno < MYJPWL_MAX_NO_TILESPECS; specno++) {\r
+\r
+                                       // tile+pprot sizer, row\r
+                                       wxBoxSizer* tilepprotSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                                       // add the value selection\r
+                                       tilepprotSizer->Add(\r
+                                               m_pprotChoice[specno] = new wxChoice(panel, OPJENCO_PPROT,\r
+                                                       wxDefaultPosition, wxSize(60, wxDefaultCoord),\r
+                                                       WXSIZEOF(pprotvalues), pprotvalues),\r
+                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
+                                       m_pprotChoice[specno]->SetSelection(wxGetApp().m_pprotsel[specno]);\r
+\r
+                                       // add some horizontal space\r
+                                       tilepprotSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                                       // add the value control\r
+                                       tilepprotSizer->Add(\r
+                                               m_ptileCtrl[specno] = new wxSpinCtrl(panel, OPJENCO_PTILE,\r
+                                                       wxString::Format(wxT("%d"), wxGetApp().m_ptileval[specno]),\r
+                                                       wxDefaultPosition, wxSize(45, wxDefaultCoord),\r
+                                                       wxSP_ARROW_KEYS,\r
+                                                       0, JPWL_MAXIMUM_TILES - 1, 0),\r
+                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
+\r
+                                       // add some horizontal space\r
+                                       tilepprotSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                                       // add the value control\r
+                                       tilepprotSizer->Add(\r
+                                               m_ppackCtrl[specno] = new wxSpinCtrl(panel, OPJENCO_PPACK,\r
+                                                       wxString::Format(wxT("%d"), wxGetApp().m_ppackval[specno]),\r
+                                                       wxDefaultPosition, wxSize(50, wxDefaultCoord),\r
+                                                       wxSP_ARROW_KEYS,\r
+                                                       0, 2047, 0),\r
+                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
+\r
+                               packetSizer->Add(tilepprotSizer, 0, wxGROW | wxALL, 0);\r
+                       }\r
+\r
+                       wxCommandEvent event2;\r
+                       OnPprotSelect(event2);\r
+\r
+               subtopSizer->Add(packetSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                       // sensitivity settings, column\r
+                       wxStaticBox* sensiBox = new wxStaticBox(panel, wxID_ANY, wxT("Sensitivity"));\r
+                       wxBoxSizer* sensiSizer = new wxStaticBoxSizer(sensiBox, wxVERTICAL);\r
+\r
+                               // info sizer, row\r
+                               wxBoxSizer* info3Sizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               info3Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
+                                                               wxT("Type")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
+\r
+                               // add some horizontal space\r
+                               info3Sizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add some text\r
+                               info3Sizer->Add(new wxStaticText(panel, wxID_ANY,\r
+                                                               wxT("Tile part")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 1);\r
+\r
+                       sensiSizer->Add(info3Sizer, 0, wxGROW | wxALL, 0);\r
+\r
+                       // specify specs\r
+                       wxString sensivalues[] = {wxT("None"), wxT("RELATIVE ERROR"), wxT("MSE"),\r
+                               wxT("MSE REDUCTION"), wxT("PSNR INCREMENT"), wxT("MAXERR"), wxT("TSE")};\r
+                       for (specno = 0; specno < MYJPWL_MAX_NO_TILESPECS; specno++) {\r
+\r
+                                       // tile+sensi sizer, row\r
+                                       wxBoxSizer* tilesensiSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                                       // add the value selection\r
+                                       tilesensiSizer->Add(\r
+                                               m_sensiChoice[specno] = new wxChoice(panel, OPJENCO_SENSI,\r
+                                                       wxDefaultPosition, wxSize(110, wxDefaultCoord),\r
+                                                       WXSIZEOF(sensivalues), sensivalues),\r
+                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
+                                       m_sensiChoice[specno]->SetSelection(wxGetApp().m_sensisel[specno]);\r
+\r
+                                       // add some horizontal space\r
+                                       tilesensiSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                                       // add the value control\r
+                                       tilesensiSizer->Add(\r
+                                               m_stileCtrl[specno] = new wxSpinCtrl(panel, OPJENCO_STILE,\r
+                                                       wxString::Format(wxT("%d"), wxGetApp().m_stileval[specno]),\r
+                                                       wxDefaultPosition, wxSize(45, wxDefaultCoord),\r
+                                                       wxSP_ARROW_KEYS,\r
+                                                       0, JPWL_MAXIMUM_TILES - 1, 0),\r
+                                               0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 1);\r
+\r
+                               sensiSizer->Add(tilesensiSizer, 0, wxGROW | wxALL, 0);\r
+                       }\r
+\r
+                       wxCommandEvent event3;\r
+                       OnSensiSelect(event3);\r
+\r
+               subtopSizer->Add(sensiSizer, 0, wxGROW | wxALL, 3);\r
+\r
+       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
+\r
+       // assign top and fit it\r
+    panel->SetSizer(topSizer);\r
+    topSizer->Fit(panel);\r
+\r
+    return panel;\r
+}\r
+#endif // USE_JPWL\r
+\r
+wxPanel* OPJEncoderDialog::CreatePart1_1SettingsPage(wxWindow* parent)\r
+{\r
+    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
+\r
+       // top sizer\r
+    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+       // add some space\r
+       //topSizer->AddSpacer(5);\r
+\r
+               // sub top sizer\r
+               wxFlexGridSizer *subtopSizer = new wxFlexGridSizer(2, 3, 3);\r
+\r
+                       // image settings, column\r
+                       wxStaticBox* imageBox = new wxStaticBox(panel, wxID_ANY, wxT("Image"));\r
+                       wxBoxSizer* imageSizer = new wxStaticBoxSizer(imageBox, wxVERTICAL);\r
+\r
+                               // subsampling factor sizer, row\r
+                               wxBoxSizer* subsSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               subsSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Subsampling:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                               // add some horizontal space\r
+                               subsSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               subsSizer->Add(\r
+                                       m_subsamplingCtrl = new wxTextCtrl(panel, OPJENCO_SUBSAMPLING,\r
+                                                               wxGetApp().m_subsampling,\r
+                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
+                                                               wxTE_LEFT),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                       imageSizer->Add(subsSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                               // origin sizer, row\r
+                               wxBoxSizer* imorigSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               imorigSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Origin:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                               // add some horizontal space\r
+                               imorigSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               imorigSizer->Add(\r
+                                       m_originCtrl = new wxTextCtrl(panel, OPJENCO_IMORIG,\r
+                                                               wxGetApp().m_origin,\r
+                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
+                                                               wxTE_LEFT),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                       imageSizer->Add(imorigSizer, 0, wxGROW | wxALL, 3);\r
+\r
+               subtopSizer->Add(imageSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                       // layer settings, column\r
+                       wxStaticBox* layerBox = new wxStaticBox(panel, wxID_ANY, wxT("Layers/compression"));\r
+                       wxBoxSizer* layerSizer = new wxStaticBoxSizer(layerBox, wxVERTICAL);\r
+\r
+                               // rate factor sizer, row\r
+                               wxBoxSizer* rateSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               /*rateSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Rate values:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);*/\r
+\r
+                               // add the radio button\r
+                               rateSizer->Add(\r
+                                       m_rateRadio = new wxRadioButton(panel, OPJENCO_RATERADIO, wxT("&Rate values"),\r
+                                                               wxDefaultPosition, wxDefaultSize,\r
+                                                               wxRB_GROUP),\r
+                                                               0, wxALL | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL\r
+                                                               );\r
+                               m_rateRadio->SetValue(!(wxGetApp().m_enablequality));\r
+\r
+                               // add some horizontal space\r
+                               rateSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               rateSizer->Add(\r
+                                       m_rateCtrl = new wxTextCtrl(panel, OPJENCO_RATEFACTOR,\r
+                                                               wxGetApp().m_rates,\r
+                                                               wxDefaultPosition, wxSize(100, wxDefaultCoord),\r
+                                                               wxTE_LEFT),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+                               if (wxGetApp().m_enablequality == true)\r
+                                       m_rateCtrl->Enable(false);\r
+\r
+                       layerSizer->Add(rateSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                               // quality factor sizer, row\r
+                               wxBoxSizer* qualitySizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               /*qualitySizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Quality values:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);*/\r
+\r
+                               // add the radio button\r
+                               qualitySizer->Add(\r
+                                       m_qualityRadio = new wxRadioButton(panel, OPJENCO_QUALITYRADIO, wxT("&Quality values"),\r
+                                                               wxDefaultPosition, wxDefaultSize),\r
+                                                               0, wxALL | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL\r
+                                                               );\r
+                               m_qualityRadio->SetValue(wxGetApp().m_enablequality);\r
+\r
+                               // add some horizontal space\r
+                               qualitySizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               qualitySizer->Add(\r
+                                       m_qualityCtrl = new wxTextCtrl(panel, OPJENCO_QUALITYFACTOR,\r
+                                                               wxGetApp().m_quality,\r
+                                                               wxDefaultPosition, wxSize(100, wxDefaultCoord),\r
+                                                               wxTE_LEFT),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+                               if (wxGetApp().m_enablequality == false)\r
+                                       m_qualityCtrl->Enable(false);\r
+\r
+                       layerSizer->Add(qualitySizer, 0, wxGROW | wxALL, 3);\r
+\r
+               subtopSizer->Add(layerSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                       // wavelet settings, column\r
+                       wxStaticBox* transformBox = new wxStaticBox(panel, wxID_ANY, wxT("Transforms"));\r
+                       wxBoxSizer* transformSizer = new wxStaticBoxSizer(transformBox, wxVERTICAL);\r
+\r
+                       // multiple component check box\r
+                       transformSizer->Add(\r
+                               m_mctCheck = new wxCheckBox(panel, OPJENCO_ENABLEMCT, wxT("Multiple component"),\r
+                               wxDefaultPosition, wxDefaultSize),\r
+                               0, wxGROW | wxALL, 3);\r
+                       m_mctCheck->SetValue(wxGetApp().m_multicomp);\r
+\r
+                       // irreversible wavelet check box\r
+                       transformSizer->Add(\r
+                               m_irrevCheck = new wxCheckBox(panel, OPJENCO_ENABLEIRREV, wxT("Irreversible wavelet"),\r
+                               wxDefaultPosition, wxDefaultSize),\r
+                               0, wxGROW | wxALL, 3);\r
+                       m_irrevCheck->SetValue(wxGetApp().m_irreversible);\r
+\r
+                               // resolution number sizer, row\r
+                               wxBoxSizer* resnumSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               resnumSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Resolutions:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                               // add some horizontal space\r
+                               resnumSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               resnumSizer->Add(\r
+                                       m_resolutionsCtrl = new wxSpinCtrl(panel, OPJENCO_RESNUMBER,\r
+                                                               wxString::Format(wxT("%d"), wxGetApp().m_resolutions),\r
+                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
+                                                               wxSP_ARROW_KEYS,\r
+                                                               1, 256, 6),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                       transformSizer->Add(resnumSizer, 0, wxGROW | wxALL, 3);\r
+\r
+               subtopSizer->Add(transformSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                       // codestream settings, column\r
+                       wxStaticBox* codestreamBox = new wxStaticBox(panel, wxID_ANY, wxT("Codestream"));\r
+                       wxBoxSizer* codestreamSizer = new wxStaticBoxSizer(codestreamBox, wxVERTICAL);\r
+\r
+                               // codeblock sizer, row\r
+                               wxBoxSizer* codeblockSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               codeblockSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Codeblocks size:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                               // add some horizontal space\r
+                               codeblockSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               codeblockSizer->Add(\r
+                                       m_cbsizeCtrl = new wxTextCtrl(panel, OPJENCO_CODEBLOCKSIZE,\r
+                                                               wxGetApp().m_cbsize,\r
+                                                               wxDefaultPosition, wxSize(100, wxDefaultCoord),\r
+                                                               wxTE_LEFT),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                       codestreamSizer->Add(codeblockSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                               // precinct sizer, row\r
+                               wxBoxSizer* precinctSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               precinctSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Precincts size:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                               // add some horizontal space\r
+                               precinctSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               precinctSizer->Add(\r
+                                       m_prsizeCtrl = new wxTextCtrl(panel, OPJENCO_PRECINCTSIZE,\r
+                                                               wxGetApp().m_prsize,\r
+                                                               wxDefaultPosition, wxSize(100, wxDefaultCoord),\r
+                                                               wxTE_LEFT),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                       codestreamSizer->Add(precinctSizer, 0, wxGROW | wxALL, 3);\r
+\r
+               subtopSizer->Add(codestreamSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                       // tile settings, column\r
+                       wxStaticBox* tileBox = new wxStaticBox(panel, wxID_ANY, wxT("Tiles"));\r
+                       wxBoxSizer* tileSizer = new wxStaticBoxSizer(tileBox, wxVERTICAL);\r
+\r
+                               // tile size sizer, row\r
+                               wxBoxSizer* tilesizeSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               tilesizeSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Size:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                               // add some horizontal space\r
+                               tilesizeSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               tilesizeSizer->Add(\r
+                                       m_tsizeCtrl = new wxTextCtrl(panel, OPJENCO_TILESIZE,\r
+                                                               wxGetApp().m_tsize,\r
+                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
+                                                               wxTE_LEFT),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                       tileSizer->Add(tilesizeSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                               // tile origin sizer, row\r
+                               wxBoxSizer* tilorigSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               tilorigSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Origin:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                               // add some horizontal space\r
+                               tilorigSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               tilorigSizer->Add(\r
+                                       m_toriginCtrl = new wxTextCtrl(panel, OPJENCO_TILORIG,\r
+                                                               wxGetApp().m_torigin,\r
+                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
+                                                               wxTE_LEFT),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                       tileSizer->Add(tilorigSizer, 0, wxGROW | wxALL, 3);\r
+\r
+               subtopSizer->Add(tileSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                       // progression and profile settings, column\r
+                       wxString choices[] = {wxT("LRCP"), wxT("RLCP"), wxT("RPCL"), wxT("PCRL"), wxT("CPRL"),\r
+                               wxT("DCI2K24"), wxT("DCI2K48"), wxT("DCI4K")};\r
+                       progressionBox = new wxRadioBox(panel, OPJENCO_PROGRESSION,\r
+                               wxT("Progression order/profile"),\r
+                               wxDefaultPosition, wxDefaultSize,\r
+                               WXSIZEOF(choices),\r
+                               choices,\r
+                               3,\r
+                               wxRA_SPECIFY_COLS);\r
+                       progressionBox->SetSelection(wxGetApp().m_progression);\r
+\r
+               subtopSizer->Add(progressionBox, 0, wxGROW | wxALL, 3);\r
+\r
+       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
+\r
+       // assign top and fit it\r
+    panel->SetSizer(topSizer);\r
+    topSizer->Fit(panel);\r
+\r
+    return panel;\r
+}\r
+\r
+wxPanel* OPJEncoderDialog::CreatePart1_2SettingsPage(wxWindow* parent)\r
+{\r
+    wxPanel* panel = new wxPanel(parent, wxID_ANY);\r
+\r
+       // top sizer\r
+    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);\r
+\r
+       // add some space\r
+       //topSizer->AddSpacer(5);\r
+\r
+               // sub top sizer\r
+               wxFlexGridSizer *subtopSizer = new wxFlexGridSizer(2, 3, 3);\r
+                       \r
+                       // resilience settings, column\r
+                       wxStaticBox* resilBox = new wxStaticBox(panel, wxID_ANY, wxT("Error resilience"));\r
+                       wxBoxSizer* resilSizer = new wxStaticBoxSizer(resilBox, wxVERTICAL);\r
+\r
+                               // resil2 sizer, row\r
+                               wxBoxSizer* resil2Sizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // SOP check box\r
+                               resil2Sizer->Add(\r
+                                       m_sopCheck = new wxCheckBox(panel, OPJENCO_ENABLESOP, wxT("SOP"),\r
+                                               wxDefaultPosition, wxDefaultSize),\r
+                                               0, wxGROW | wxALL, 3);\r
+                               m_sopCheck->SetValue(wxGetApp().m_enablesop);\r
+\r
+                               // EPH check box\r
+                               resil2Sizer->Add(\r
+                                       m_ephCheck = new wxCheckBox(panel, OPJENCO_ENABLEEPH, wxT("EPH"),\r
+                                               wxDefaultPosition, wxDefaultSize),\r
+                                               0, wxGROW | wxALL, 3);\r
+                               m_ephCheck->SetValue(wxGetApp().m_enableeph);\r
+\r
+                       resilSizer->Add(resil2Sizer, 0, wxGROW | wxALL, 3);\r
+\r
+                       // separation\r
+                       resilSizer->Add(new wxStaticLine(panel, wxID_ANY), 0, wxEXPAND | wxLEFT | wxRIGHT, 3);\r
+\r
+                               // resil3 sizer, row\r
+                               wxFlexGridSizer* resil3Sizer = new wxFlexGridSizer(3, 3, 3);\r
+\r
+                               // BYPASS check box\r
+                               resil3Sizer->Add(\r
+                                       m_enablebypassCheck = new wxCheckBox(panel, OPJENCO_ENABLEBYPASS, wxT("BYPASS"),\r
+                                       wxDefaultPosition, wxDefaultSize),\r
+                                       0, wxGROW | wxALL, 3);\r
+                               m_enablebypassCheck->SetValue(wxGetApp().m_enablebypass);\r
+\r
+                               // RESET check box\r
+                               resil3Sizer->Add(\r
+                                       m_enableresetCheck = new wxCheckBox(panel, OPJENCO_ENABLERESET, wxT("RESET"),\r
+                                       wxDefaultPosition, wxDefaultSize),\r
+                                       0, wxGROW | wxALL, 3);\r
+                               m_enableresetCheck->SetValue(wxGetApp().m_enablereset);\r
+\r
+                               // RESTART check box\r
+                               resil3Sizer->Add(\r
+                                       m_enablerestartCheck = new wxCheckBox(panel, OPJENCO_ENABLERESTART, wxT("RESTART"),\r
+                                       wxDefaultPosition, wxDefaultSize),\r
+                                       0, wxGROW | wxALL, 3);\r
+                               m_enablerestartCheck->SetValue(wxGetApp().m_enablerestart);\r
+\r
+                               // VSC check box\r
+                               resil3Sizer->Add(\r
+                                       m_enablevscCheck = new wxCheckBox(panel, OPJENCO_ENABLEVSC, wxT("VSC"),\r
+                                       wxDefaultPosition, wxDefaultSize),\r
+                                       0, wxGROW | wxALL, 3);\r
+                               m_enablevscCheck->SetValue(wxGetApp().m_enablevsc);\r
+\r
+                               // ERTERM check box\r
+                               resil3Sizer->Add(\r
+                                       m_enableertermCheck = new wxCheckBox(panel, OPJENCO_ENABLEERTERM, wxT("ERTERM"),\r
+                                       wxDefaultPosition, wxDefaultSize),\r
+                                       0, wxGROW | wxALL, 3);\r
+                               m_enableertermCheck->SetValue(wxGetApp().m_enableerterm);\r
+\r
+                               // SEGMARK check box\r
+                               resil3Sizer->Add(\r
+                                       m_enablesegmarkCheck = new wxCheckBox(panel, OPJENCO_ENABLESEGMARK, wxT("SEGMARK"),\r
+                                       wxDefaultPosition, wxDefaultSize),\r
+                                       0, wxGROW | wxALL, 3);\r
+                               m_enablesegmarkCheck->SetValue(wxGetApp().m_enablesegmark);\r
+\r
+                       resilSizer->Add(resil3Sizer, 0, wxGROW | wxALL, 3);\r
+\r
+               subtopSizer->Add(resilSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                       // ROI settings, column\r
+                       wxStaticBox* roiBox = new wxStaticBox(panel, wxID_ANY, wxT("Region Of Interest"));\r
+                       wxBoxSizer* roiSizer = new wxStaticBoxSizer(roiBox, wxVERTICAL);\r
+\r
+                               // component number sizer, row\r
+                               wxBoxSizer* roicompSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               roicompSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Component:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                               // add some horizontal space\r
+                               roicompSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               roicompSizer->Add(\r
+                                       /*m_layerCtrl =*/ new wxSpinCtrl(panel, OPJENCO_ROICOMP,\r
+                                                               wxT("0"),\r
+                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
+                                                               wxSP_ARROW_KEYS,\r
+                                                               0, 256, 0),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                       roiSizer->Add(roicompSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                               // upshift sizer, row\r
+                               wxBoxSizer* roishiftSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               roishiftSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Upshift:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                               // add some horizontal space\r
+                               roishiftSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               roishiftSizer->Add(\r
+                                       /*m_layerCtrl =*/ new wxSpinCtrl(panel, OPJENCO_ROISHIFT,\r
+                                                               wxT("0"),\r
+                                                               wxDefaultPosition, wxSize(80, wxDefaultCoord),\r
+                                                               wxSP_ARROW_KEYS,\r
+                                                               0, 37, 0),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                       roiSizer->Add(roishiftSizer, 0, wxGROW | wxALL, 3);\r
+\r
+               subtopSizer->Add(roiSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                       // POC settings, column\r
+                       wxStaticBox* pocBox = new wxStaticBox(panel, wxID_ANY, wxT("POC"));\r
+                       wxBoxSizer* pocSizer = new wxStaticBoxSizer(pocBox, wxVERTICAL);\r
+\r
+                       // POC check box\r
+                       pocSizer->Add(\r
+                               m_enablepocCheck = new wxCheckBox(panel, OPJENCO_ENABLEPOC, wxT("Enabled (tn=rs,cs,le,re,ce,pr)"),\r
+                               wxDefaultPosition, wxDefaultSize),\r
+                               0, wxGROW | wxALL, 3);\r
+                       m_enablepocCheck->SetValue(wxGetApp().m_enablepoc);\r
+\r
+                               // POC sizer, row\r
+                               wxBoxSizer* pocspecSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               pocspecSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&Changes:")),\r
+                                                               0, wxALL | wxALIGN_TOP, 3);\r
+\r
+                               // add some horizontal space\r
+                               pocspecSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               pocspecSizer->Add(\r
+                                       m_pocCtrl = new wxTextCtrl(panel, OPJENCO_POCSPEC,\r
+                                                               wxGetApp().m_poc,\r
+                                                               wxDefaultPosition, wxSize(140, 60),\r
+                                                               wxTE_LEFT | wxTE_MULTILINE),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+                               m_pocCtrl->Enable(wxGetApp().m_enablepoc);\r
+\r
+                       pocSizer->Add(pocspecSizer, 0, wxGROW | wxALL, 3);\r
+\r
+               subtopSizer->Add(pocSizer, 0, wxGROW | wxALL, 3);\r
+                       \r
+                       // Comment settings, column\r
+                       wxStaticBox* commentBox = new wxStaticBox(panel, wxID_ANY, wxT("Comment"));\r
+                       wxBoxSizer* commentSizer = new wxStaticBoxSizer(commentBox, wxVERTICAL);\r
+\r
+                       // commenting check box\r
+                       commentSizer->Add(\r
+                               m_enablecommCheck = new wxCheckBox(panel, OPJENCO_ENABLECOMM, wxT("Enabled (empty to reset)"),\r
+                               wxDefaultPosition, wxDefaultSize),\r
+                               0, wxGROW | wxALL, 3);\r
+                       m_enablecommCheck->SetValue(wxGetApp().m_enablecomm);\r
+\r
+                       // add some horizontal space\r
+                       commentSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                       // add the value control\r
+                       commentSizer->Add(\r
+                               m_commentCtrl = new wxTextCtrl(panel, OPJENCO_COMMENTTEXT,\r
+                                                       wxGetApp().m_comment,\r
+                                                       wxDefaultPosition, wxSize(wxDefaultCoord, 60),\r
+                                                       wxTE_LEFT | wxTE_MULTILINE),\r
+                               0, wxGROW | wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+                       m_commentCtrl->Enable(wxGetApp().m_enablecomm);\r
+\r
+               subtopSizer->Add(commentSizer, 0, wxGROW | wxALL, 3);\r
+\r
+                       // Index file settings, column\r
+                       wxStaticBox* indexBox = new wxStaticBox(panel, wxID_ANY, wxT("Indexing"));\r
+                       wxBoxSizer* indexSizer = new wxStaticBoxSizer(indexBox, wxVERTICAL);\r
+\r
+                       // indexing check box\r
+                       indexSizer->Add(\r
+                               m_enableidxCheck = new wxCheckBox(panel, OPJENCO_ENABLEINDEX, wxT("Enabled"),\r
+                               wxDefaultPosition, wxDefaultSize),\r
+                               0, wxGROW | wxALL, 3);\r
+                       m_enableidxCheck->SetValue(wxGetApp().m_enableidx);\r
+\r
+                               // index file sizer, row\r
+                               wxBoxSizer* indexnameSizer = new wxBoxSizer(wxHORIZONTAL);\r
+\r
+                               // add some text\r
+                               indexnameSizer->Add(new wxStaticText(panel, wxID_ANY, wxT("&File name:")),\r
+                                                               0, wxALL | wxALIGN_CENTER_VERTICAL, 3);\r
+\r
+                               // add some horizontal space\r
+                               indexnameSizer->Add(3, 3, 1, wxALL, 0);\r
+\r
+                               // add the value control\r
+                               indexnameSizer->Add(\r
+                                       m_indexCtrl = new wxTextCtrl(panel, OPJENCO_INDEXNAME,\r
+                                                               wxGetApp().m_index,\r
+                                                               wxDefaultPosition, wxSize(120, wxDefaultCoord),\r
+                                                               wxTE_LEFT),\r
+                                       0, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 3);\r
+                               m_indexCtrl->Enable(wxGetApp().m_enableidx);\r
+\r
+                       indexSizer->Add(indexnameSizer, 0, wxGROW | wxALL, 3);\r
+\r
+               subtopSizer->Add(indexSizer, 0, wxGROW | wxALL, 3);\r
+\r
+       topSizer->Add(subtopSizer, 1, wxGROW | wxALIGN_CENTRE | wxALL, 5);\r
+\r
+       // assign top and fit it\r
+    panel->SetSizer(topSizer);\r
+    topSizer->Fit(panel);\r
+\r
+    return panel;\r
+}\r
+\r
+void OPJEncoderDialog::OnEnableComm(wxCommandEvent& event)\r
+{\r
+       if (event.IsChecked()) {\r
+               wxLogMessage(wxT("Comment enabled"));\r
+               m_commentCtrl->Enable(true);\r
+       } else {\r
+               wxLogMessage(wxT("Comment disabled"));\r
+               m_commentCtrl->Enable(false);\r
+       }\r
+\r
+}\r
+\r
+void OPJEncoderDialog::OnEnableIdx(wxCommandEvent& event)\r
+{\r
+       if (event.IsChecked()) {\r
+               wxLogMessage(wxT("Index enabled"));\r
+               m_indexCtrl->Enable(true);\r
+       } else {\r
+               wxLogMessage(wxT("Index disabled"));\r
+               m_indexCtrl->Enable(false);\r
+       }\r
+\r
+}\r
+\r
+void OPJEncoderDialog::OnEnablePoc(wxCommandEvent& event)\r
+{\r
+       if (event.IsChecked()) {\r
+               wxLogMessage(wxT("POC enabled"));\r
+               m_pocCtrl->Enable(true);\r
+       } else {\r
+               wxLogMessage(wxT("POC disabled"));\r
+               m_pocCtrl->Enable(false);\r
+       }\r
+\r
+}\r
+\r
+void OPJEncoderDialog::OnRadioQualityRate(wxCommandEvent& event)\r
+{\r
+       if (event.GetId() == OPJENCO_QUALITYRADIO) {\r
+               wxLogMessage(wxT("Quality selected"));\r
+               m_rateCtrl->Enable(false);\r
+               m_qualityCtrl->Enable(true);\r
+       } else {\r
+               wxLogMessage(wxT("Rate selected"));\r
+               m_rateCtrl->Enable(true);\r
+               m_qualityCtrl->Enable(false);\r
+       }\r
+}\r
+\r
+#ifdef USE_JPWL\r
+void OPJEncoderDialog::OnEnableJPWL(wxCommandEvent& event)\r
+{\r
+       int specno;\r
+\r
+       if (event.IsChecked()) {\r
+               wxLogMessage(wxT("JPWL enabled"));\r
+               for (specno = 0; specno < MYJPWL_MAX_NO_TILESPECS; specno++) {\r
+                       m_hprotChoice[specno]->Enable(true);\r
+                       m_htileCtrl[specno]->Enable(true);\r
+                       m_pprotChoice[specno]->Enable(true);\r
+                       m_ptileCtrl[specno]->Enable(true);\r
+                       m_ppackCtrl[specno]->Enable(true);\r
+                       m_sensiChoice[specno]->Enable(true);\r
+                       m_stileCtrl[specno]->Enable(true);\r
+               }\r
+               OnHprotSelect(event);\r
+               OnPprotSelect(event);\r
+               OnSensiSelect(event);\r
+       } else {\r
+               wxLogMessage(wxT("JPWL disabled"));\r
+               for (specno = 0; specno < MYJPWL_MAX_NO_TILESPECS; specno++) {\r
+                       m_hprotChoice[specno]->Enable(false);\r
+                       m_htileCtrl[specno]->Enable(false);\r
+                       m_pprotChoice[specno]->Enable(false);\r
+                       m_ptileCtrl[specno]->Enable(false);\r
+                       m_ppackCtrl[specno]->Enable(false);\r
+                       m_sensiChoice[specno]->Enable(false);\r
+                       m_stileCtrl[specno]->Enable(false);\r
+               }\r
+       }\r
+\r
+}\r
+\r
+void OPJEncoderDialog::OnHprotSelect(wxCommandEvent& event)\r
+{\r
+       int specno;\r
+\r
+       // deactivate properly\r
+       for (specno = MYJPWL_MAX_NO_TILESPECS - 1; specno >= 0; specno--) {\r
+               if (!m_hprotChoice[specno]->GetSelection()) {\r
+                       m_hprotChoice[specno]->Enable(false);\r
+                       m_htileCtrl[specno]->Enable(false);\r
+               } else\r
+                       break;\r
+       }\r
+       if (specno < (MYJPWL_MAX_NO_TILESPECS - 1)) {\r
+               m_hprotChoice[specno + 1]->Enable(true);\r
+               m_htileCtrl[specno + 1]->Enable(true);\r
+       }\r
+\r
+       //wxLogMessage(wxT("hprot changed: %d"), specno);\r
+}\r
+\r
+void OPJEncoderDialog::OnPprotSelect(wxCommandEvent& event)\r
+{\r
+       int specno;\r
+\r
+       // deactivate properly\r
+       for (specno = MYJPWL_MAX_NO_TILESPECS - 1; specno >= 0; specno--) {\r
+               if (!m_pprotChoice[specno]->GetSelection()) {\r
+                       m_pprotChoice[specno]->Enable(false);\r
+                       m_ptileCtrl[specno]->Enable(false);\r
+                       m_ppackCtrl[specno]->Enable(false);\r
+               } else\r
+                       break;\r
+       }\r
+       if (specno < (MYJPWL_MAX_NO_TILESPECS - 1)) {\r
+               m_pprotChoice[specno + 1]->Enable(true);\r
+               m_ptileCtrl[specno + 1]->Enable(true);\r
+               m_ppackCtrl[specno + 1]->Enable(true);\r
+       }\r
+\r
+       //wxLogMessage(wxT("pprot changed: %d"), specno);\r
+}\r
+\r
+void OPJEncoderDialog::OnSensiSelect(wxCommandEvent& event)\r
+{\r
+       int specno;\r
+\r
+       // deactivate properly\r
+       for (specno = MYJPWL_MAX_NO_TILESPECS - 1; specno >= 0; specno--) {\r
+               if (!m_sensiChoice[specno]->GetSelection()) {\r
+                       m_sensiChoice[specno]->Enable(false);\r
+                       m_stileCtrl[specno]->Enable(false);\r
+               } else\r
+                       break;\r
+       }\r
+       if (specno < (MYJPWL_MAX_NO_TILESPECS - 1)) {\r
+               m_sensiChoice[specno + 1]->Enable(true);\r
+               m_stileCtrl[specno + 1]->Enable(true);\r
+       }\r
+\r
+       //wxLogMessage(wxT("sprot changed: %d"), specno);\r
+}\r
+\r
+\r
+#endif // USE_JPWL\r
+\r
diff --git a/applications/OPJViewer/source/OPJThreads.cpp b/applications/OPJViewer/source/OPJThreads.cpp
new file mode 100644 (file)
index 0000000..3c93ee2
--- /dev/null
@@ -0,0 +1,1268 @@
+/*\r
+ * Copyright (c) 2007, Digital Signal Processing Laboratory, Universita'� degli studi di Perugia (UPG), Italy\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+#include "OPJViewer.h"\r
+\r
+\r
+/////////////////////////////////////////////////////////////////////\r
+// Encoding thread class\r
+/////////////////////////////////////////////////////////////////////\r
+\r
+OPJEncoThread::OPJEncoThread(OPJCanvas *canvas)\r
+        : wxThread()\r
+{\r
+    m_count = 0;\r
+    m_canvas = canvas;\r
+}\r
+\r
+void OPJEncoThread::WriteText(const wxString& text)\r
+{\r
+    wxString msg;\r
+\r
+    // before doing any GUI calls we must ensure that this thread is the only\r
+    // one doing it!\r
+\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiEnter();\r
+#endif // __WXGTK__\r
+\r
+    msg << text;\r
+    m_canvas->WriteText(msg);\r
+\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiLeave();\r
+#endif // __WXGTK__\r
+}\r
+\r
+void OPJEncoThread::OnExit()\r
+{\r
+    wxCriticalSectionLocker locker(wxGetApp().m_enco_critsect);\r
+\r
+    wxArrayThread& ethreads = wxGetApp().m_enco_threads;\r
+    ethreads.Remove(this);\r
+\r
+    if (ethreads.IsEmpty() )\r
+    {\r
+        // signal the main thread that there are no more threads left if it is\r
+        // waiting for us\r
+        if (wxGetApp().m_enco_waitingUntilAllDone) {\r
+            wxGetApp().m_enco_waitingUntilAllDone = false;\r
+            wxGetApp().m_enco_semAllDone.Post();\r
+        }\r
+    }\r
+}\r
+\r
+void *OPJEncoThread::Entry()\r
+{\r
+    wxString text;\r
+\r
+       srand(GetId());\r
+       //int m_countnum = rand() % 9;\r
+    //text.Printf(wxT("Deco thread 0x%lx started (priority = %u, time = %d)."),\r
+    //            GetId(), GetPriority(), m_countnum);\r
+    text.Printf(wxT("Enco thread %d started"), m_canvas->m_childframe->m_winnumber);\r
+    WriteText(text);\r
+\r
+       // set handler properties\r
+       wxJPEG2000Handler *jpeg2000handler = (wxJPEG2000Handler *) wxImage::FindHandler(wxBITMAP_TYPE_JPEG2000);\r
+       jpeg2000handler->m_subsampling = wxGetApp().m_subsampling;\r
+       jpeg2000handler->m_origin = wxGetApp().m_origin;\r
+       jpeg2000handler->m_rates = wxGetApp().m_rates;\r
+       jpeg2000handler->m_quality = wxGetApp().m_quality;\r
+       jpeg2000handler->m_enablequality = wxGetApp().m_enablequality;\r
+       jpeg2000handler->m_multicomp = wxGetApp().m_multicomp;\r
+       jpeg2000handler->m_irreversible = wxGetApp().m_irreversible;\r
+       jpeg2000handler->m_resolutions = wxGetApp().m_resolutions;\r
+       jpeg2000handler->m_progression = wxGetApp().m_progression;\r
+       jpeg2000handler->m_cbsize = wxGetApp().m_cbsize;\r
+       jpeg2000handler->m_prsize = wxGetApp().m_prsize;\r
+       jpeg2000handler->m_tsize = wxGetApp().m_tsize;\r
+       jpeg2000handler->m_torigin = wxGetApp().m_torigin;\r
+       jpeg2000handler->m_enablesop = wxGetApp().m_enablesop;\r
+       jpeg2000handler->m_enableeph = wxGetApp().m_enableeph;\r
+       jpeg2000handler->m_enablebypass = wxGetApp().m_enablebypass;\r
+       jpeg2000handler->m_enablerestart = wxGetApp().m_enablerestart;\r
+       jpeg2000handler->m_enablereset = wxGetApp().m_enablereset;\r
+       jpeg2000handler->m_enablesegmark = wxGetApp().m_enablesegmark;\r
+       jpeg2000handler->m_enableerterm = wxGetApp().m_enableerterm;\r
+       jpeg2000handler->m_enablevsc = wxGetApp().m_enablevsc;\r
+       jpeg2000handler->m_enableidx = wxGetApp().m_enableidx;\r
+       jpeg2000handler->m_index = m_canvas->m_savename.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR) + wxGetApp().m_index;\r
+       jpeg2000handler->m_enablecomm = wxGetApp().m_enablecomm;\r
+       jpeg2000handler->m_comment = wxGetApp().m_comment;\r
+       jpeg2000handler->m_enablepoc = wxGetApp().m_enablepoc;\r
+       jpeg2000handler->m_poc = wxGetApp().m_poc;\r
+\r
+       // save the file\r
+       if (!m_canvas->m_image100.SaveFile(m_canvas->m_savename.GetFullPath(), (wxBitmapType) wxBITMAP_TYPE_JPEG2000)) {\r
+               WriteText(wxT("Can't save image"));\r
+               return NULL;\r
+       }\r
+\r
+    text.Printf(wxT("Enco thread %d finished"), m_canvas->m_childframe->m_winnumber);\r
+    WriteText(text);\r
+    return NULL;\r
+}\r
+\r
+\r
+/////////////////////////////////////////////////////////////////////\r
+// Decoding thread class\r
+/////////////////////////////////////////////////////////////////////\r
+OPJDecoThread::OPJDecoThread(OPJCanvas *canvas)\r
+        : wxThread()\r
+{\r
+    m_count = 0;\r
+    m_canvas = canvas;\r
+}\r
+\r
+void OPJDecoThread::WriteText(const wxString& text)\r
+{\r
+    wxString msg;\r
+       \r
+       // we use a fake event and post it for inter-thread gui communication\r
+    wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, OPJFRAME_THREADLOGMSG);\r
+    event.SetInt(-1); \r
+       msg << text;\r
+       event.SetString(msg);\r
+    wxPostEvent(this->m_canvas->m_childframe->m_frame, event);\r
+\r
+/*\r
+    // before doing any GUI calls we must ensure that this thread is the only\r
+    // one doing it!\r
+\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiEnter();\r
+#endif // __WXGTK__\r
+\r
+    msg << text;\r
+    m_canvas->WriteText(msg);\r
+\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiLeave();\r
+#endif // __WXGTK__\r
+*/\r
+}\r
+\r
+void OPJDecoThread::OnExit()\r
+{\r
+    wxCriticalSectionLocker locker(wxGetApp().m_deco_critsect);\r
+\r
+    wxArrayThread& dthreads = wxGetApp().m_deco_threads;\r
+    dthreads.Remove(this);\r
+\r
+    if (dthreads.IsEmpty() )\r
+    {\r
+        // signal the main thread that there are no more threads left if it is\r
+        // waiting for us\r
+        if (wxGetApp().m_deco_waitingUntilAllDone) {\r
+            wxGetApp().m_deco_waitingUntilAllDone = false;\r
+            wxGetApp().m_deco_semAllDone.Post();\r
+        }\r
+    }\r
+}\r
+\r
+void *OPJDecoThread::Entry()\r
+{\r
+\r
+    wxString text;\r
+\r
+       //srand(GetId());\r
+       //int m_countnum = rand() % 9;\r
+    //text.Printf(wxT("Deco thread 0x%lx started (priority = %u, time = %d)."),\r
+    //            GetId(), GetPriority(), m_countnum);\r
+\r
+       // we have started\r
+    text.Printf(wxT("Deco thread %d started"), m_canvas->m_childframe->m_winnumber);\r
+    WriteText(text);\r
+\r
+       // prepare dummy wximage\r
+    wxBitmap bitmap(100, 100);\r
+    wxImage image(100, 100, true); //= bitmap.ConvertToImage();\r
+    image.Destroy();\r
+\r
+       // show image full name\r
+       WriteText(m_canvas->m_fname.GetFullPath());\r
+\r
+       // set handler properties\r
+       wxJPEG2000Handler *jpeg2000handler = (wxJPEG2000Handler *) wxImage::FindHandler(wxBITMAP_TYPE_JPEG2000);\r
+       jpeg2000handler->m_reducefactor = wxGetApp().m_reducefactor;\r
+       jpeg2000handler->m_qualitylayers = wxGetApp().m_qualitylayers;\r
+       jpeg2000handler->m_components = wxGetApp().m_components;\r
+       jpeg2000handler->m_framenum = wxGetApp().m_framenum;\r
+#ifdef USE_JPWL\r
+       jpeg2000handler->m_enablejpwl = wxGetApp().m_enablejpwl;\r
+       jpeg2000handler->m_expcomps = wxGetApp().m_expcomps;\r
+       jpeg2000handler->m_maxtiles = wxGetApp().m_maxtiles;\r
+#endif // USE_JPWL\r
+\r
+#ifdef USE_MXF\r
+       wxMXFHandler *mxfffhandler = (wxMXFHandler *) wxImage::FindHandler(wxBITMAP_TYPE_MXF);\r
+       mxfffhandler->m_reducefactor = wxGetApp().m_reducefactor;\r
+       mxfffhandler->m_qualitylayers = wxGetApp().m_qualitylayers;\r
+       mxfffhandler->m_components = wxGetApp().m_components;\r
+       mxfffhandler->m_framenum = wxGetApp().m_framenum;\r
+       mxfffhandler->m_filename = m_canvas->m_fname;\r
+#ifdef USE_JPWL\r
+       mxfffhandler->m_enablejpwl = wxGetApp().m_enablejpwl;\r
+       mxfffhandler->m_expcomps = wxGetApp().m_expcomps;\r
+       mxfffhandler->m_maxtiles = wxGetApp().m_maxtiles;\r
+#endif // USE_JPWL\r
+#endif // USE_MXF\r
+\r
+       // if decoding is enabled...\r
+       if (wxGetApp().m_enabledeco) {\r
+\r
+               // load the file\r
+               if (!image.LoadFile(m_canvas->m_fname.GetFullPath(), wxBITMAP_TYPE_ANY, 0)) {\r
+                       WriteText(wxT("Can't load image!"));\r
+                       return NULL;\r
+               }\r
+\r
+       } else {\r
+\r
+               // display a warning\r
+               if (!image.Create(300, 5, false)) {\r
+                       WriteText(wxT("Can't create image!"));\r
+                       return NULL;\r
+               }\r
+\r
+       }\r
+\r
+       // assign 100% image\r
+    m_canvas->m_image100 = wxBitmap(image);\r
+\r
+       // signal the frame to refresh the canvas\r
+    wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, OPJFRAME_VIEWFIT);\r
+       event.SetString(wxT("Fit me"));\r
+    event.SetInt(m_canvas->m_childframe->m_winnumber); \r
+    wxPostEvent(m_canvas->m_childframe->m_frame, event);\r
+\r
+       // find a fit-to-width zoom\r
+       /*int zooml, wzooml, hzooml;\r
+       wxSize clientsize = m_canvas->GetClientSize();\r
+       wzooml = (int) floor(100.0 * (double) clientsize.GetWidth() / (double) (2 * OPJ_CANVAS_BORDER + image.GetWidth()));\r
+       hzooml = (int) floor(100.0 * (double) clientsize.GetHeight() / (double) (2 * OPJ_CANVAS_BORDER + image.GetHeight()));\r
+       zooml = wxMin(100, wxMin(wzooml, hzooml));*/\r
+\r
+       // fit to width\r
+#ifndef __WXGTK__\r
+       //m_canvas->m_childframe->m_frame->Rescale(zooml, m_canvas->m_childframe);\r
+#endif // __WXGTK__\r
+\r
+       //m_canvas->m_image = m_canvas->m_image100;\r
+       //m_canvas->Refresh();\r
+       //m_canvas->SetScrollbars(20, 20, (int)(0.5 + (double) image.GetWidth() / 20.0), (int)(0.5 + (double) image.GetHeight() / 20.0));\r
+\r
+    //text.Printf(wxT("Deco thread 0x%lx finished."), GetId());\r
+    text.Printf(wxT("Deco thread %d finished"), m_canvas->m_childframe->m_winnumber);\r
+    WriteText(text);\r
+    return NULL;\r
+\r
+}\r
+\r
+/////////////////////////////////////////////////////////////////////\r
+// Parsing thread class\r
+/////////////////////////////////////////////////////////////////////\r
+\r
+OPJParseThread::OPJParseThread(OPJMarkerTree *tree, wxTreeItemId parentid)\r
+        : wxThread()\r
+{\r
+    m_count = 0;\r
+    m_tree = tree;\r
+       m_parentid = parentid;\r
+}\r
+\r
+void OPJParseThread::WriteText(const wxString& text)\r
+{\r
+    wxString msg;\r
+       \r
+       // we use a fake event and post it for inter-thread gui communication\r
+    wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, OPJFRAME_THREADLOGMSG);\r
+    event.SetInt(-1); \r
+       msg << text;\r
+       event.SetString(msg);\r
+    wxPostEvent(this->m_tree->m_childframe->m_frame, event);\r
+\r
+/*    // before doing any GUI calls we must ensure that this thread is the only\r
+    // one doing it!\r
+\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiEnter();\r
+#endif // __WXGTK\r
+\r
+    msg << text;\r
+    m_tree->WriteText(msg);\r
+\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiLeave();\r
+#endif // __WXGTK*/\r
+}\r
+\r
+void OPJParseThread::OnExit()\r
+{\r
+    wxCriticalSectionLocker locker(wxGetApp().m_parse_critsect);\r
+\r
+    wxArrayThread& threads = wxGetApp().m_parse_threads;\r
+    threads.Remove(this);\r
+\r
+    if (threads.IsEmpty()) {\r
+        // signal the main thread that there are no more threads left if it is\r
+        // waiting for us\r
+        if (wxGetApp().m_parse_waitingUntilAllDone) {\r
+            wxGetApp().m_parse_waitingUntilAllDone = false;\r
+            wxGetApp().m_parse_semAllDone.Post();\r
+        }\r
+    }\r
+}\r
+\r
+void *OPJParseThread::Entry()\r
+{\r
+\r
+       printf("Entering\n\n");\r
+\r
+    wxString text;\r
+\r
+       srand(GetId());\r
+       int m_countnum = rand() % 9;\r
+    text.Printf(wxT("Parse thread 0x%lx started (priority = %u, time = %d)."),\r
+            GetId(), GetPriority(), m_countnum);\r
+    WriteText(text);\r
+    LoadFile(m_tree->m_fname);\r
+    text.Printf(wxT("Parse thread 0x%lx finished."), GetId());\r
+    WriteText(text);\r
+\r
+\r
+    //wxLogMessage(wxT("Entering\n")); //test wxLog thread safeness\r
+\r
+       //wxBusyCursor wait;\r
+       //wxBusyInfo wait(wxT("Decoding image ..."));\r
+\r
+\r
+    /*for ( m_count = 0; m_count < m_countnum; m_count++ )\r
+    {\r
+        // check if we were asked to exit\r
+        if ( TestDestroy() )\r
+            break;\r
+\r
+        text.Printf(wxT("[%u] Parse thread 0x%lx here."), m_count, GetId());\r
+        WriteText(text);\r
+\r
+        // wxSleep() can't be called from non-GUI thread!\r
+        wxThread::Sleep(10);\r
+    }*/\r
+\r
+    // wxLogMessage(text); -- test wxLog thread safeness\r
+\r
+       printf("Exiting\n\n");\r
+\r
+    return NULL;\r
+}\r
+\r
+\r
+///////////////////////////////////////////\r
+// Parsing hread and related\r
+///////////////////////////////////////////\r
+\r
+#if USE_GENERIC_TREECTRL\r
+BEGIN_EVENT_TABLE(OPJMarkerTree, wxGenericTreeCtrl)\r
+#else\r
+BEGIN_EVENT_TABLE(OPJMarkerTree, wxTreeCtrl)\r
+#endif\r
+    /*EVT_TREE_BEGIN_DRAG(TreeTest_Ctrl, OPJMarkerTree::OnBeginDrag)\r
+    EVT_TREE_BEGIN_RDRAG(TreeTest_Ctrl, OPJMarkerTree::OnBeginRDrag)\r
+    EVT_TREE_END_DRAG(TreeTest_Ctrl, OPJMarkerTree::OnEndDrag)*/\r
+    /*EVT_TREE_BEGIN_LABEL_EDIT(TreeTest_Ctrl, OPJMarkerTree::OnBeginLabelEdit)\r
+    EVT_TREE_END_LABEL_EDIT(TreeTest_Ctrl, OPJMarkerTree::OnEndLabelEdit)*/\r
+    /*EVT_TREE_DELETE_ITEM(TreeTest_Ctrl, OPJMarkerTree::OnDeleteItem)*/\r
+#if 0       // there are so many of those that logging them causes flicker\r
+    /*EVT_TREE_GET_INFO(TreeTest_Ctrl, OPJMarkerTree::OnGetInfo)*/\r
+#endif\r
+    /*EVT_TREE_SET_INFO(TreeTest_Ctrl, OPJMarkerTree::OnSetInfo)\r
+    EVT_TREE_ITEM_EXPANDED(TreeTest_Ctrl, OPJMarkerTree::OnItemExpanded)*/\r
+    EVT_TREE_ITEM_EXPANDING(TreeTest_Ctrl, OPJMarkerTree::OnItemExpanding)\r
+    /*EVT_TREE_ITEM_COLLAPSED(TreeTest_Ctrl, OPJMarkerTree::OnItemCollapsed)\r
+    EVT_TREE_ITEM_COLLAPSING(TreeTest_Ctrl, OPJMarkerTree::OnItemCollapsing)*/\r
+\r
+    EVT_TREE_SEL_CHANGED(TreeTest_Ctrl, OPJMarkerTree::OnSelChanged)\r
+    /*EVT_TREE_SEL_CHANGING(TreeTest_Ctrl, OPJMarkerTree::OnSelChanging)*/\r
+    /*EVT_TREE_KEY_DOWN(TreeTest_Ctrl, OPJMarkerTree::OnTreeKeyDown)*/\r
+    /*EVT_TREE_ITEM_ACTIVATED(TreeTest_Ctrl, OPJMarkerTree::OnItemActivated)*/\r
+\r
+    // so many differents ways to handle right mouse button clicks...\r
+    /*EVT_CONTEXT_MENU(OPJMarkerTree::OnContextMenu)*/\r
+    // EVT_TREE_ITEM_MENU is the preferred event for creating context menus\r
+    // on a tree control, because it includes the point of the click or item,\r
+    // meaning that no additional placement calculations are required.\r
+    EVT_TREE_ITEM_MENU(TreeTest_Ctrl, OPJMarkerTree::OnItemMenu)\r
+    /*EVT_TREE_ITEM_RIGHT_CLICK(TreeTest_Ctrl, OPJMarkerTree::OnItemRClick)*/\r
+\r
+    /*EVT_RIGHT_DOWN(OPJMarkerTree::OnRMouseDown)\r
+    EVT_RIGHT_UP(OPJMarkerTree::OnRMouseUp)\r
+    EVT_RIGHT_DCLICK(OPJMarkerTree::OnRMouseDClick)*/\r
+END_EVENT_TABLE()\r
+\r
+// OPJMarkerTree implementation\r
+#if USE_GENERIC_TREECTRL\r
+IMPLEMENT_DYNAMIC_CLASS(OPJMarkerTree, wxGenericTreeCtrl)\r
+#else\r
+IMPLEMENT_DYNAMIC_CLASS(OPJMarkerTree, wxTreeCtrl)\r
+#endif\r
+\r
+OPJMarkerTree::OPJMarkerTree(wxWindow *parent, OPJChildFrame *subframe, wxFileName fname, wxString name, const wxWindowID id,\r
+           const wxPoint& pos, const wxSize& size, long style)\r
+          : wxTreeCtrl(parent, id, pos, size, style)\r
+{\r
+    m_reverseSort = false;\r
+       m_fname = fname;\r
+\r
+       m_peektextCtrl = ((OPJFrame *) (parent->GetParent()->GetParent()))->m_textCtrlbrowse;\r
+    CreateImageList();\r
+\r
+    // Add some items to the tree\r
+    //AddTestItemsToTree(5, 5);\r
+    int image = wxGetApp().ShowImages() ? OPJMarkerTree::TreeCtrlIcon_Folder : -1;\r
+    wxTreeItemId rootId = AddRoot(name,\r
+                                  image, image,\r
+                                  new OPJMarkerData(name));\r
+\r
+    OPJParseThread *pthread = CreateParseThread(0x00, subframe);\r
+    if (pthread->Run() != wxTHREAD_NO_ERROR)\r
+        wxLogMessage(wxT("Can't start parse thread!"));\r
+    else\r
+               wxLogMessage(wxT("New parse thread started."));\r
+\r
+       m_childframe = subframe;\r
+}\r
+\r
+void OPJMarkerTree::CreateImageList(int size)\r
+{\r
+    if (size == -1) {\r
+        SetImageList(NULL);\r
+        return;\r
+    }\r
+    if (size == 0)\r
+        size = m_imageSize;\r
+    else\r
+        m_imageSize = size;\r
+\r
+    // Make an image list containing small icons\r
+    wxImageList *images = new wxImageList(size, size, true);\r
+\r
+    // should correspond to TreeCtrlIcon_xxx enum\r
+    wxBusyCursor wait;\r
+    wxIcon icons[5];\r
+    icons[0] = wxIcon(icon1_xpm);\r
+    icons[1] = wxIcon(icon2_xpm);\r
+    icons[2] = wxIcon(icon3_xpm);\r
+    icons[3] = wxIcon(icon4_xpm);\r
+    icons[4] = wxIcon(icon5_xpm);\r
+\r
+    int sizeOrig = icons[0].GetWidth();\r
+    for (size_t i = 0; i < WXSIZEOF(icons); i++) {\r
+        if (size == sizeOrig) {\r
+            images->Add(icons[i]);\r
+        } else {\r
+            images->Add(wxBitmap(wxBitmap(icons[i]).ConvertToImage().Rescale(size, size)));\r
+        }\r
+    }\r
+\r
+    AssignImageList(images);\r
+}\r
+\r
+#if USE_GENERIC_TREECTRL || !defined(__WXMSW__)\r
+void OPJMarkerTree::CreateButtonsImageList(int size)\r
+{\r
+    if ( size == -1 ) {\r
+        SetButtonsImageList(NULL);\r
+        return;\r
+    }\r
+\r
+    // Make an image list containing small icons\r
+    wxImageList *images = new wxImageList(size, size, true);\r
+\r
+    // should correspond to TreeCtrlIcon_xxx enum\r
+    wxBusyCursor wait;\r
+    wxIcon icons[4];\r
+    icons[0] = wxIcon(icon3_xpm);   // closed\r
+    icons[1] = wxIcon(icon3_xpm);   // closed, selected\r
+    icons[2] = wxIcon(icon5_xpm);   // open\r
+    icons[3] = wxIcon(icon5_xpm);   // open, selected\r
+\r
+    for ( size_t i = 0; i < WXSIZEOF(icons); i++ ) {\r
+        int sizeOrig = icons[i].GetWidth();\r
+        if ( size == sizeOrig ) {\r
+            images->Add(icons[i]);\r
+        } else {\r
+            images->Add(wxBitmap(wxBitmap(icons[i]).ConvertToImage().Rescale(size, size)));\r
+        }\r
+    }\r
+\r
+    AssignButtonsImageList(images);\r
+#else\r
+void OPJMarkerTree::CreateButtonsImageList(int WXUNUSED(size))\r
+{\r
+#endif\r
+}\r
+\r
+void OPJParseThread::LoadFile(wxFileName fname)\r
+{\r
+       wxTreeItemId rootid;\r
+\r
+       // this is the root node\r
+       int image = wxGetApp().ShowImages() ? m_tree->TreeCtrlIcon_Folder : -1;\r
+\r
+       if (this->m_parentid) {\r
+               // leaf of a tree\r
+               rootid = m_parentid;\r
+               m_tree->SetItemText(rootid, wxT("Parsing..."));\r
+\r
+       } else {\r
+\r
+               // delete the existing tree hierarchy\r
+               m_tree->DeleteAllItems();\r
+\r
+               // new tree\r
+               rootid = m_tree->AddRoot(wxT("Parsing..."),\r
+                       image,\r
+                       image,\r
+                       new OPJMarkerData(fname.GetFullPath())\r
+                       );\r
+               //m_tree->SetItemFont(rootid, *wxITALIC_FONT);\r
+               m_tree->SetItemBold(rootid);\r
+       }\r
+\r
+       // open the file\r
+       wxFile m_file(fname.GetFullPath().c_str(), wxFile::read);\r
+\r
+       // parsing enabled?\r
+       if (wxGetApp().m_enableparse) {\r
+\r
+               // what is the extension?\r
+               if ((fname.GetExt() == wxT("j2k")) || (fname.GetExt() == wxT("j2c"))) {\r
+\r
+                       // parse the file\r
+                       ParseJ2KFile(&m_file, 0, m_file.Length(), rootid);\r
+\r
+               } else if ((fname.GetExt() == wxT("jp2")) || (fname.GetExt() == wxT("mj2"))) {\r
+\r
+                       // parse the file\r
+                       if (this->m_parentid) {\r
+                               //WriteText(wxT("Only a subsection of jp2"));\r
+                               OPJMarkerData *data = (OPJMarkerData *) m_tree->GetItemData(rootid);\r
+                               ParseJ2KFile(&m_file, data->m_start, data->m_length, rootid);\r
+                               m_tree->Expand(rootid);\r
+\r
+                       } else {\r
+                               // as usual\r
+                               ParseJP2File(&m_file, 0, m_file.Length(), rootid);\r
+                       }\r
+\r
+               } else {\r
+\r
+                       // unknown extension\r
+                       WriteText(wxT("Unknown file format!"));\r
+\r
+               }\r
+\r
+       }\r
+\r
+       // this is the root node\r
+       if (this->m_parentid)\r
+               m_tree->SetItemText(rootid, wxT("Codestream"));\r
+       else\r
+               //m_tree->SetItemText(rootid, wxString::Format(wxT("%s (%d B)"), fname.GetFullName(), m_file.Length()));\r
+               m_tree->SetItemText(rootid, fname.GetFullName());\r
+\r
+       // close the file\r
+       m_file.Close();\r
+\r
+       WriteText(wxT("Parsing finished!"));\r
+}\r
+\r
+/*int OPJMarkerTree::OnCompareItems(const wxTreeItemId& item1,\r
+                               const wxTreeItemId& item2)\r
+{\r
+    if ( m_reverseSort )\r
+    {\r
+        // just exchange 1st and 2nd items\r
+        return wxTreeCtrl::OnCompareItems(item2, item1);\r
+    }\r
+    else\r
+    {\r
+        return wxTreeCtrl::OnCompareItems(item1, item2);\r
+    }\r
+}*/\r
+\r
+/*void OPJMarkerTree::AddItemsRecursively(const wxTreeItemId& idParent,\r
+                                     size_t numChildren,\r
+                                     size_t depth,\r
+                                     size_t folder)\r
+{\r
+    if ( depth > 0 )\r
+    {\r
+        bool hasChildren = depth > 1;\r
+\r
+        wxString str;\r
+        for ( size_t n = 0; n < numChildren; n++ )\r
+        {\r
+            // at depth 1 elements won't have any more children\r
+            if ( hasChildren )\r
+                str.Printf(wxT("%s child %u"), wxT("Folder"), unsigned(n + 1));\r
+            else\r
+                str.Printf(wxT("%s child %u.%u"), wxT("File"), unsigned(folder), unsigned(n + 1));\r
+\r
+            // here we pass to AppendItem() normal and selected item images (we\r
+            // suppose that selected image follows the normal one in the enum)\r
+            int image, imageSel;\r
+            if ( wxGetApp().ShowImages() )\r
+            {\r
+                image = depth == 1 ? TreeCtrlIcon_File : TreeCtrlIcon_Folder;\r
+                imageSel = image + 1;\r
+            }\r
+            else\r
+            {\r
+                image = imageSel = -1;\r
+            }\r
+            wxTreeItemId id = AppendItem(idParent, str, image, imageSel,\r
+                                         new OPJMarkerData(str));\r
+\r
+            // and now we also set the expanded one (only for the folders)\r
+            if ( hasChildren && wxGetApp().ShowImages() )\r
+            {\r
+                SetItemImage(id, TreeCtrlIcon_FolderOpened,\r
+                             wxTreeItemIcon_Expanded);\r
+            }\r
+\r
+            // remember the last child for OnEnsureVisible()\r
+            if ( !hasChildren && n == numChildren - 1 )\r
+            {\r
+                m_lastItem = id;\r
+            }\r
+\r
+            AddItemsRecursively(id, numChildren, depth - 1, n + 1);\r
+        }\r
+    }\r
+    //else: done!\r
+}*/\r
+\r
+/*void OPJMarkerTree::AddTestItemsToTree(size_t numChildren,\r
+                                    size_t depth)\r
+{\r
+    int image = wxGetApp().ShowImages() ? OPJMarkerTree::TreeCtrlIcon_Folder : -1;\r
+    wxTreeItemId rootId = AddRoot(wxT("Root"),\r
+                                  image, image,\r
+                                  new OPJMarkerData(wxT("Root item")));\r
+    if ( image != -1 )\r
+    {\r
+        SetItemImage(rootId, TreeCtrlIcon_FolderOpened, wxTreeItemIcon_Expanded);\r
+    }\r
+\r
+    AddItemsRecursively(rootId, numChildren, depth, 0);\r
+\r
+    // set some colours/fonts for testing\r
+    SetItemFont(rootId, *wxITALIC_FONT);\r
+\r
+    wxTreeItemIdValue cookie;\r
+    wxTreeItemId id = GetFirstChild(rootId, cookie);\r
+    SetItemTextColour(id, *wxBLUE);\r
+\r
+    id = GetNextChild(rootId, cookie);\r
+    id = GetNextChild(rootId, cookie);\r
+    SetItemTextColour(id, *wxRED);\r
+    SetItemBackgroundColour(id, *wxLIGHT_GREY);\r
+}*/\r
+\r
+/*void OPJMarkerTree::GetItemsRecursively(const wxTreeItemId& idParent,\r
+                                     wxTreeItemIdValue cookie)\r
+{\r
+    wxTreeItemId id;\r
+\r
+    if ( !cookie )\r
+        id = GetFirstChild(idParent, cookie);\r
+    else\r
+        id = GetNextChild(idParent, cookie);\r
+\r
+    if ( !id.IsOk() )\r
+        return;\r
+\r
+    wxString text = GetItemText(id);\r
+    wxLogMessage(text);\r
+\r
+    if (ItemHasChildren(id))\r
+        GetItemsRecursively(id);\r
+\r
+    GetItemsRecursively(idParent, cookie);\r
+}*/\r
+\r
+/*void OPJMarkerTree::DoToggleIcon(const wxTreeItemId& item)\r
+{\r
+    int image = (GetItemImage(item) == TreeCtrlIcon_Folder)\r
+                    ? TreeCtrlIcon_File\r
+                    : TreeCtrlIcon_Folder;\r
+    SetItemImage(item, image, wxTreeItemIcon_Normal);\r
+\r
+    image = (GetItemImage(item) == TreeCtrlIcon_FolderSelected)\r
+                    ? TreeCtrlIcon_FileSelected\r
+                    : TreeCtrlIcon_FolderSelected;\r
+    SetItemImage(item, image, wxTreeItemIcon_Selected);\r
+}*/\r
+\r
+void OPJMarkerTree::LogEvent(const wxChar *name, const wxTreeEvent& event)\r
+{\r
+    wxTreeItemId item = event.GetItem();\r
+    wxString text;\r
+    if ( item.IsOk() )\r
+        text << wxT('"') << GetItemText(item).c_str() << wxT('"');\r
+    else\r
+        text = wxT("invalid item");\r
+    wxLogMessage(wxT("%s(%s)"), name, text.c_str());\r
+}\r
+\r
+OPJParseThread *OPJMarkerTree::CreateParseThread(wxTreeItemId parentid, OPJChildFrame *subframe)\r
+{\r
+    OPJParseThread *pthread = new OPJParseThread(this, parentid);\r
+\r
+    if (pthread->Create() != wxTHREAD_NO_ERROR)\r
+               wxLogError(wxT("Can't create parse thread!"));\r
+\r
+    wxCriticalSectionLocker enter(wxGetApp().m_parse_critsect);\r
+    wxGetApp().m_parse_threads.Add(pthread);\r
+\r
+    return pthread;\r
+}\r
+\r
+\r
+/*// avoid repetition\r
+#define TREE_EVENT_HANDLER(name)                                 \\r
+void OPJMarkerTree::name(wxTreeEvent& event)                        \\r
+{                                                                \\r
+    LogEvent(_T(#name), event);                                  \\r
+    SetLastItem(wxTreeItemId());                                 \\r
+    event.Skip();                                                \\r
+}*/\r
+\r
+/*TREE_EVENT_HANDLER(OnBeginRDrag)*/\r
+/*TREE_EVENT_HANDLER(OnDeleteItem)*/\r
+/*TREE_EVENT_HANDLER(OnGetInfo)\r
+TREE_EVENT_HANDLER(OnSetInfo)*/\r
+/*TREE_EVENT_HANDLER(OnItemExpanded)\r
+TREE_EVENT_HANDLER(OnItemExpanding)*/\r
+/*TREE_EVENT_HANDLER(OnItemCollapsed)*/\r
+/*TREE_EVENT_HANDLER(OnSelChanged)\r
+TREE_EVENT_HANDLER(OnSelChanging)*/\r
+\r
+/*#undef TREE_EVENT_HANDLER*/\r
+\r
+void OPJMarkerTree::OnItemExpanding(wxTreeEvent& event)\r
+{\r
+       wxTreeItemId item = event.GetItem();\r
+       OPJMarkerData* data = (OPJMarkerData *) GetItemData(item);\r
+       wxString text;\r
+\r
+       if (item.IsOk())\r
+               text << wxT('"') << GetItemText(item).c_str() << wxT('"');\r
+       else\r
+               text = wxT("invalid item");\r
+\r
+       if (wxStrcmp(data->GetDesc1(), wxT("INFO-CSTREAM")))\r
+               return;\r
+\r
+       wxLogMessage(wxT("Expanding... (%s -> %s, %s, %d, %d)"),\r
+               text.c_str(), data->GetDesc1(), data->GetDesc2(),\r
+               data->m_start, data->m_length);\r
+\r
+       // the codestream box is being asked for expansion\r
+       wxTreeItemIdValue cookie;\r
+       if (!GetFirstChild(item, cookie).IsOk()) {\r
+               OPJParseThread *pthread = CreateParseThread(item);\r
+               if (pthread->Run() != wxTHREAD_NO_ERROR)\r
+                       wxLogMessage(wxT("Can't start parse thread!"));\r
+               else\r
+                       wxLogMessage(wxT("New parse thread started."));\r
+       }\r
+}\r
+\r
+void OPJMarkerTree::OnSelChanged(wxTreeEvent& event)\r
+{\r
+       int bunch_linesize = 16;\r
+       int bunch_numlines = 7;\r
+\r
+       wxTreeItemId item = event.GetItem();\r
+       OPJMarkerData* data = (OPJMarkerData *) GetItemData(item);\r
+       wxString text;\r
+       int l, c, pos = 0, pre_pos;\r
+\r
+       m_peektextCtrl->Clear();\r
+\r
+       /*text << wxString::Format(wxT("Selected... (%s -> %s, %s, %d, %d)"),\r
+               text.c_str(), data->GetDesc1(), data->GetDesc2(),\r
+               data->m_start, data->m_length) << wxT("\n");*/\r
+\r
+       // open the file and browse a little\r
+       wxFile *fp = new wxFile(m_fname.GetFullPath().c_str(), wxFile::read);\r
+\r
+       // go to position claimed\r
+       fp->Seek(data->m_start, wxFromStart);\r
+\r
+       // read a bunch\r
+       int max_read = wxMin(wxFileOffset(bunch_linesize * bunch_numlines), data->m_length - data->m_start + 1);\r
+       if (data->m_desc == wxT("MARK (65380)")) {\r
+               /*wxLogMessage(data->m_desc);*/\r
+               max_read = data->m_length - data->m_start + 1;\r
+               bunch_numlines = (int) ceil((float) max_read / (float) bunch_linesize);\r
+       }\r
+       unsigned char *buffer = new unsigned char[bunch_linesize * bunch_numlines];\r
+       fp->Read(buffer, max_read);\r
+\r
+       // write the file data between start and stop\r
+       pos = 0;\r
+       for (l = 0; l < bunch_numlines; l++) {\r
+\r
+               text << wxString::Format(wxT("%010d:"), data->m_start + pos);\r
+\r
+               pre_pos = pos;\r
+\r
+               // add hex browsing text\r
+               for (c = 0; c < bunch_linesize; c++) {\r
+\r
+                       if (!(c % 8))\r
+                               text << wxT(" ");\r
+\r
+                       if (pos < max_read) {\r
+                               text << wxString::Format(wxT("%02X "), buffer[pos]);\r
+                       } else\r
+                               text << wxT("   ");\r
+                       pos++;\r
+               }\r
+\r
+               text << wxT("    ");\r
+\r
+               // add char browsing text\r
+               for (c = 0; c < bunch_linesize; c++) {\r
+\r
+                       if (pre_pos < max_read) {\r
+                               if ((buffer[pre_pos] == '\n') ||\r
+                                       (buffer[pre_pos] == '\t') ||\r
+                                       (buffer[pre_pos] == '\0') ||\r
+                                       (buffer[pre_pos] == 0x0D) ||\r
+                                       (buffer[pre_pos] == 0x0B))\r
+                                       buffer[pre_pos] = ' ';\r
+                               text << wxString::FromAscii((char) buffer[pre_pos]) << wxT(".");\r
+                       } else\r
+                               text << wxT("  ");\r
+                       pre_pos++;\r
+               }\r
+\r
+               text << wxT("\n");\r
+\r
+       }\r
+\r
+       // close the file\r
+       fp->Close();\r
+\r
+       m_peektextCtrl->WriteText(text);\r
+\r
+       delete buffer;\r
+}\r
+\r
+/*void LogKeyEvent(const wxChar *name, const wxKeyEvent& event)\r
+{\r
+    wxString key;\r
+    long keycode = event.GetKeyCode();\r
+    {\r
+        switch ( keycode )\r
+        {\r
+            case WXK_BACK: key = wxT("BACK"); break;\r
+            case WXK_TAB: key = wxT("TAB"); break;\r
+            case WXK_RETURN: key = wxT("RETURN"); break;\r
+            case WXK_ESCAPE: key = wxT("ESCAPE"); break;\r
+            case WXK_SPACE: key = wxT("SPACE"); break;\r
+            case WXK_DELETE: key = wxT("DELETE"); break;\r
+            case WXK_START: key = wxT("START"); break;\r
+            case WXK_LBUTTON: key = wxT("LBUTTON"); break;\r
+            case WXK_RBUTTON: key = wxT("RBUTTON"); break;\r
+            case WXK_CANCEL: key = wxT("CANCEL"); break;\r
+            case WXK_MBUTTON: key = wxT("MBUTTON"); break;\r
+            case WXK_CLEAR: key = wxT("CLEAR"); break;\r
+            case WXK_SHIFT: key = wxT("SHIFT"); break;\r
+            case WXK_ALT: key = wxT("ALT"); break;\r
+            case WXK_CONTROL: key = wxT("CONTROL"); break;\r
+            case WXK_MENU: key = wxT("MENU"); break;\r
+            case WXK_PAUSE: key = wxT("PAUSE"); break;\r
+            case WXK_CAPITAL: key = wxT("CAPITAL"); break;\r
+            case WXK_END: key = wxT("END"); break;\r
+            case WXK_HOME: key = wxT("HOME"); break;\r
+            case WXK_LEFT: key = wxT("LEFT"); break;\r
+            case WXK_UP: key = wxT("UP"); break;\r
+            case WXK_RIGHT: key = wxT("RIGHT"); break;\r
+            case WXK_DOWN: key = wxT("DOWN"); break;\r
+            case WXK_SELECT: key = wxT("SELECT"); break;\r
+            case WXK_PRINT: key = wxT("PRINT"); break;\r
+            case WXK_EXECUTE: key = wxT("EXECUTE"); break;\r
+            case WXK_SNAPSHOT: key = wxT("SNAPSHOT"); break;\r
+            case WXK_INSERT: key = wxT("INSERT"); break;\r
+            case WXK_HELP: key = wxT("HELP"); break;\r
+            case WXK_NUMPAD0: key = wxT("NUMPAD0"); break;\r
+            case WXK_NUMPAD1: key = wxT("NUMPAD1"); break;\r
+            case WXK_NUMPAD2: key = wxT("NUMPAD2"); break;\r
+            case WXK_NUMPAD3: key = wxT("NUMPAD3"); break;\r
+            case WXK_NUMPAD4: key = wxT("NUMPAD4"); break;\r
+            case WXK_NUMPAD5: key = wxT("NUMPAD5"); break;\r
+            case WXK_NUMPAD6: key = wxT("NUMPAD6"); break;\r
+            case WXK_NUMPAD7: key = wxT("NUMPAD7"); break;\r
+            case WXK_NUMPAD8: key = wxT("NUMPAD8"); break;\r
+            case WXK_NUMPAD9: key = wxT("NUMPAD9"); break;\r
+            case WXK_MULTIPLY: key = wxT("MULTIPLY"); break;\r
+            case WXK_ADD: key = wxT("ADD"); break;\r
+            case WXK_SEPARATOR: key = wxT("SEPARATOR"); break;\r
+            case WXK_SUBTRACT: key = wxT("SUBTRACT"); break;\r
+            case WXK_DECIMAL: key = wxT("DECIMAL"); break;\r
+            case WXK_DIVIDE: key = wxT("DIVIDE"); break;\r
+            case WXK_F1: key = wxT("F1"); break;\r
+            case WXK_F2: key = wxT("F2"); break;\r
+            case WXK_F3: key = wxT("F3"); break;\r
+            case WXK_F4: key = wxT("F4"); break;\r
+            case WXK_F5: key = wxT("F5"); break;\r
+            case WXK_F6: key = wxT("F6"); break;\r
+            case WXK_F7: key = wxT("F7"); break;\r
+            case WXK_F8: key = wxT("F8"); break;\r
+            case WXK_F9: key = wxT("F9"); break;\r
+            case WXK_F10: key = wxT("F10"); break;\r
+            case WXK_F11: key = wxT("F11"); break;\r
+            case WXK_F12: key = wxT("F12"); break;\r
+            case WXK_F13: key = wxT("F13"); break;\r
+            case WXK_F14: key = wxT("F14"); break;\r
+            case WXK_F15: key = wxT("F15"); break;\r
+            case WXK_F16: key = wxT("F16"); break;\r
+            case WXK_F17: key = wxT("F17"); break;\r
+            case WXK_F18: key = wxT("F18"); break;\r
+            case WXK_F19: key = wxT("F19"); break;\r
+            case WXK_F20: key = wxT("F20"); break;\r
+            case WXK_F21: key = wxT("F21"); break;\r
+            case WXK_F22: key = wxT("F22"); break;\r
+            case WXK_F23: key = wxT("F23"); break;\r
+            case WXK_F24: key = wxT("F24"); break;\r
+            case WXK_NUMLOCK: key = wxT("NUMLOCK"); break;\r
+            case WXK_SCROLL: key = wxT("SCROLL"); break;\r
+            case WXK_PAGEUP: key = wxT("PAGEUP"); break;\r
+            case WXK_PAGEDOWN: key = wxT("PAGEDOWN"); break;\r
+            case WXK_NUMPAD_SPACE: key = wxT("NUMPAD_SPACE"); break;\r
+            case WXK_NUMPAD_TAB: key = wxT("NUMPAD_TAB"); break;\r
+            case WXK_NUMPAD_ENTER: key = wxT("NUMPAD_ENTER"); break;\r
+            case WXK_NUMPAD_F1: key = wxT("NUMPAD_F1"); break;\r
+            case WXK_NUMPAD_F2: key = wxT("NUMPAD_F2"); break;\r
+            case WXK_NUMPAD_F3: key = wxT("NUMPAD_F3"); break;\r
+            case WXK_NUMPAD_F4: key = wxT("NUMPAD_F4"); break;\r
+            case WXK_NUMPAD_HOME: key = wxT("NUMPAD_HOME"); break;\r
+            case WXK_NUMPAD_LEFT: key = wxT("NUMPAD_LEFT"); break;\r
+            case WXK_NUMPAD_UP: key = wxT("NUMPAD_UP"); break;\r
+            case WXK_NUMPAD_RIGHT: key = wxT("NUMPAD_RIGHT"); break;\r
+            case WXK_NUMPAD_DOWN: key = wxT("NUMPAD_DOWN"); break;\r
+            case WXK_NUMPAD_PAGEUP: key = wxT("NUMPAD_PAGEUP"); break;\r
+            case WXK_NUMPAD_PAGEDOWN: key = wxT("NUMPAD_PAGEDOWN"); break;\r
+            case WXK_NUMPAD_END: key = wxT("NUMPAD_END"); break;\r
+            case WXK_NUMPAD_BEGIN: key = wxT("NUMPAD_BEGIN"); break;\r
+            case WXK_NUMPAD_INSERT: key = wxT("NUMPAD_INSERT"); break;\r
+            case WXK_NUMPAD_DELETE: key = wxT("NUMPAD_DELETE"); break;\r
+            case WXK_NUMPAD_EQUAL: key = wxT("NUMPAD_EQUAL"); break;\r
+            case WXK_NUMPAD_MULTIPLY: key = wxT("NUMPAD_MULTIPLY"); break;\r
+            case WXK_NUMPAD_ADD: key = wxT("NUMPAD_ADD"); break;\r
+            case WXK_NUMPAD_SEPARATOR: key = wxT("NUMPAD_SEPARATOR"); break;\r
+            case WXK_NUMPAD_SUBTRACT: key = wxT("NUMPAD_SUBTRACT"); break;\r
+            case WXK_NUMPAD_DECIMAL: key = wxT("NUMPAD_DECIMAL"); break;\r
+\r
+            default:\r
+            {\r
+               if ( keycode < 128 && wxIsprint((int)keycode) )\r
+                   key.Printf(wxT("'%c'"), (char)keycode);\r
+               else if ( keycode > 0 && keycode < 27 )\r
+                   key.Printf(_("Ctrl-%c"), wxT('A') + keycode - 1);\r
+               else\r
+                   key.Printf(wxT("unknown (%ld)"), keycode);\r
+            }\r
+        }\r
+    }\r
+\r
+    wxLogMessage(wxT("%s event: %s (flags = %c%c%c%c)"),\r
+                  name,\r
+                  key.c_str(),\r
+                  event.ControlDown() ? wxT('C') : wxT('-'),\r
+                  event.AltDown() ? wxT('A') : wxT('-'),\r
+                  event.ShiftDown() ? wxT('S') : wxT('-'),\r
+                  event.MetaDown() ? wxT('M') : wxT('-'));\r
+}\r
+\r
+void OPJMarkerTree::OnTreeKeyDown(wxTreeEvent& event)\r
+{\r
+    LogKeyEvent(wxT("Tree key down "), event.GetKeyEvent());\r
+\r
+    event.Skip();\r
+}*/\r
+\r
+/*void OPJMarkerTree::OnBeginDrag(wxTreeEvent& event)\r
+{\r
+    // need to explicitly allow drag\r
+    if ( event.GetItem() != GetRootItem() )\r
+    {\r
+        m_draggedItem = event.GetItem();\r
+\r
+        wxLogMessage(wxT("OnBeginDrag: started dragging %s"),\r
+                     GetItemText(m_draggedItem).c_str());\r
+\r
+        event.Allow();\r
+    }\r
+    else\r
+    {\r
+        wxLogMessage(wxT("OnBeginDrag: this item can't be dragged."));\r
+    }\r
+}\r
+\r
+void OPJMarkerTree::OnEndDrag(wxTreeEvent& event)\r
+{\r
+    wxTreeItemId itemSrc = m_draggedItem,\r
+                 itemDst = event.GetItem();\r
+    m_draggedItem = (wxTreeItemId)0l;\r
+\r
+    // where to copy the item?\r
+    if ( itemDst.IsOk() && !ItemHasChildren(itemDst) )\r
+    {\r
+        // copy to the parent then\r
+        itemDst = GetItemParent(itemDst);\r
+    }\r
+\r
+    if ( !itemDst.IsOk() )\r
+    {\r
+        wxLogMessage(wxT("OnEndDrag: can't drop here."));\r
+\r
+        return;\r
+    }\r
+\r
+    wxString text = GetItemText(itemSrc);\r
+    wxLogMessage(wxT("OnEndDrag: '%s' copied to '%s'."),\r
+                 text.c_str(), GetItemText(itemDst).c_str());\r
+\r
+    // just do append here - we could also insert it just before/after the item\r
+    // on which it was dropped, but this requires slightly more work... we also\r
+    // completely ignore the client data and icon of the old item but could\r
+    // copy them as well.\r
+    //\r
+    // Finally, we only copy one item here but we might copy the entire tree if\r
+    // we were dragging a folder.\r
+    int image = wxGetApp().ShowImages() ? TreeCtrlIcon_File : -1;\r
+    AppendItem(itemDst, text, image);\r
+}*/\r
+\r
+/*void OPJMarkerTree::OnBeginLabelEdit(wxTreeEvent& event)\r
+{\r
+    wxLogMessage(wxT("OnBeginLabelEdit"));\r
+\r
+    // for testing, prevent this item's label editing\r
+    wxTreeItemId itemId = event.GetItem();\r
+    if ( IsTestItem(itemId) )\r
+    {\r
+        wxMessageBox(wxT("You can't edit this item."));\r
+\r
+        event.Veto();\r
+    }\r
+    else if ( itemId == GetRootItem() )\r
+    {\r
+        // test that it is possible to change the text of the item being edited\r
+        SetItemText(itemId, _T("Editing root item"));\r
+    }\r
+}\r
+\r
+void OPJMarkerTree::OnEndLabelEdit(wxTreeEvent& event)\r
+{\r
+    wxLogMessage(wxT("OnEndLabelEdit"));\r
+\r
+    // don't allow anything except letters in the labels\r
+    if ( !event.GetLabel().IsWord() )\r
+    {\r
+        wxMessageBox(wxT("The new label should be a single word."));\r
+\r
+        event.Veto();\r
+    }\r
+}*/\r
+\r
+/*void OPJMarkerTree::OnItemCollapsing(wxTreeEvent& event)\r
+{\r
+    wxLogMessage(wxT("OnItemCollapsing"));\r
+\r
+    // for testing, prevent the user from collapsing the first child folder\r
+    wxTreeItemId itemId = event.GetItem();\r
+    if ( IsTestItem(itemId) )\r
+    {\r
+        wxMessageBox(wxT("You can't collapse this item."));\r
+\r
+        event.Veto();\r
+    }\r
+}*/\r
+\r
+/*void OPJMarkerTree::OnItemActivated(wxTreeEvent& event)\r
+{\r
+    // show some info about this item\r
+    wxTreeItemId itemId = event.GetItem();\r
+    OPJMarkerData *item = (OPJMarkerData *)GetItemData(itemId);\r
+\r
+    if ( item != NULL )\r
+    {\r
+        item->ShowInfo(this);\r
+    }\r
+\r
+    wxLogMessage(wxT("OnItemActivated"));\r
+}*/\r
+\r
+void OPJMarkerTree::OnItemMenu(wxTreeEvent& event)\r
+{\r
+    /*wxTreeItemId itemId = event.GetItem();\r
+    OPJMarkerData *item = itemId.IsOk() ? (OPJMarkerData *)GetItemData(itemId)\r
+                                         : NULL;\r
+\r
+    wxLogMessage(wxT("OnItemMenu for item \"%s\""), item ? item->GetDesc()\r
+                                                         : _T(""));*/\r
+\r
+       //wxLogMessage(wxT("EEEEEEEEEE"));\r
+\r
+    //event.Skip();\r
+}\r
+\r
+/*void OPJMarkerTree::OnContextMenu(wxContextMenuEvent& event)\r
+{\r
+    wxPoint pt = event.GetPosition();\r
+    wxTreeItemId item;\r
+    wxLogMessage(wxT("OnContextMenu at screen coords (%i, %i)"), pt.x, pt.y);\r
+\r
+    // check if event was generated by keyboard (MSW-specific?)\r
+    if ( pt.x == -1 && pt.y == -1 ) //(this is how MSW indicates it)\r
+    {\r
+        if ( !HasFlag(wxTR_MULTIPLE) )\r
+            item = GetSelection();\r
+\r
+        // attempt to guess where to show the menu\r
+        if ( item.IsOk() )\r
+        {\r
+            // if an item was clicked, show menu to the right of it\r
+            wxRect rect;\r
+            GetBoundingRect(item, rect, true );// only the label\r
+            pt = wxPoint(rect.GetRight(), rect.GetTop());\r
+        }\r
+        else\r
+        {\r
+            pt = wxPoint(0, 0);\r
+        }\r
+    }\r
+    else // event was generated by mouse, use supplied coords\r
+    {\r
+        pt = ScreenToClient(pt);\r
+        item = HitTest(pt);\r
+    }\r
+\r
+    ShowMenu(item, pt);\r
+}*/\r
+\r
+/*void OPJMarkerTree::ShowMenu(wxTreeItemId id, const wxPoint& pt)\r
+{\r
+    wxString title;\r
+    if ( id.IsOk() )\r
+    {\r
+        title << wxT("Menu for ") << GetItemText(id);\r
+    }\r
+    else\r
+    {\r
+        title = wxT("Menu for no particular item");\r
+    }\r
+\r
+#if wxUSE_MENUS\r
+    wxMenu menu(title);\r
+    menu.Append(TreeTest_About, wxT("&About..."));\r
+    menu.AppendSeparator();\r
+    menu.Append(TreeTest_Highlight, wxT("&Highlight item"));\r
+    menu.Append(TreeTest_Dump, wxT("&Dump"));\r
+\r
+    PopupMenu(&menu, pt);\r
+#endif // wxUSE_MENUS\r
+}*/\r
+\r
+/*void OPJMarkerTree::OnItemRClick(wxTreeEvent& event)\r
+{\r
+    wxTreeItemId itemId = event.GetItem();\r
+    OPJMarkerData *item = itemId.IsOk() ? (OPJMarkerData *)GetItemData(itemId)\r
+                                         : NULL;\r
+\r
+    wxLogMessage(wxT("Item \"%s\" right clicked"), item ? item->GetDesc()\r
+                                                        : _T(""));\r
+\r
+    event.Skip();\r
+}*/\r
+\r
+/*\r
+void OPJMarkerTree::OnRMouseDown(wxMouseEvent& event)\r
+{\r
+    wxLogMessage(wxT("Right mouse button down"));\r
+\r
+    event.Skip();\r
+}\r
+\r
+void OPJMarkerTree::OnRMouseUp(wxMouseEvent& event)\r
+{\r
+    wxLogMessage(wxT("Right mouse button up"));\r
+\r
+    event.Skip();\r
+}\r
+\r
+void OPJMarkerTree::OnRMouseDClick(wxMouseEvent& event)\r
+{\r
+    wxTreeItemId id = HitTest(event.GetPosition());\r
+    if ( !id )\r
+        wxLogMessage(wxT("No item under mouse"));\r
+    else\r
+    {\r
+        OPJMarkerData *item = (OPJMarkerData *)GetItemData(id);\r
+        if ( item )\r
+            wxLogMessage(wxT("Item '%s' under mouse"), item->GetDesc());\r
+    }\r
+\r
+    event.Skip();\r
+}\r
+*/\r
+\r
+static inline const wxChar *Bool2String(bool b)\r
+{\r
+    return b ? wxT("") : wxT("not ");\r
+}\r
+\r
+void OPJMarkerData::ShowInfo(wxTreeCtrl *tree)\r
+{\r
+    wxLogMessage(wxT("Item '%s': %sselected, %sexpanded, %sbold,\n")\r
+                 wxT("%u children (%u immediately under this item)."),\r
+                 m_desc.c_str(),\r
+                 Bool2String(tree->IsSelected(GetId())),\r
+                 Bool2String(tree->IsExpanded(GetId())),\r
+                 Bool2String(tree->IsBold(GetId())),\r
+                 unsigned(tree->GetChildrenCount(GetId())),\r
+                 unsigned(tree->GetChildrenCount(GetId(), false)));\r
+}\r
+\r
+\r
diff --git a/applications/OPJViewer/source/OPJViewer.cpp b/applications/OPJViewer/source/OPJViewer.cpp
new file mode 100644 (file)
index 0000000..8f2c86e
--- /dev/null
@@ -0,0 +1,1664 @@
+/*\r
+ * Copyright (c) 2007, Digital Signal Processing Laboratory, Universita' degli studi di Perugia (UPG), Italy\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        sashtest.cpp\r
+// Purpose:     Layout/sash sample\r
+// Author:      Julian Smart\r
+// Modified by:\r
+// Created:     04/01/98\r
+// RCS-ID:      $Id: sashtest.cpp,v 1.18 2005/08/23 15:54:35 ABX Exp $\r
+// Copyright:   (c) Julian Smart\r
+// Licence:     wxWindows license\r
+/////////////////////////////////////////////////////////////////////////////\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        treetest.cpp\r
+// Purpose:     wxTreeCtrl sample\r
+// Author:      Julian Smart\r
+// Modified by:\r
+// Created:     04/01/98\r
+// RCS-ID:      $Id: treetest.cpp,v 1.110 2006/11/04 11:26:51 VZ Exp $\r
+// Copyright:   (c) Julian Smart\r
+// Licence:     wxWindows license\r
+/////////////////////////////////////////////////////////////////////////////\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        dialogs.cpp\r
+// Purpose:     Common dialogs demo\r
+// Author:      Julian Smart\r
+// Modified by: ABX (2004) - adjustements for conditional building + new menu\r
+// Created:     04/01/98\r
+// RCS-ID:      $Id: dialogs.cpp,v 1.163 2006/11/04 10:57:24 VZ Exp $\r
+// Copyright:   (c) Julian Smart\r
+// Licence:     wxWindows license\r
+/////////////////////////////////////////////////////////////////////////////\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        thread.cpp\r
+// Purpose:     wxWidgets thread sample\r
+// Author:      Guilhem Lavaux, Vadim Zeitlin\r
+// Modified by:\r
+// Created:     06/16/98\r
+// RCS-ID:      $Id: thread.cpp,v 1.26 2006/10/02 05:36:28 PC Exp $\r
+// Copyright:   (c) 1998-2002 wxWidgets team\r
+// Licence:     wxWindows license\r
+/////////////////////////////////////////////////////////////////////////////\r
+///////////////////////////////////////////////////////////////////////////////\r
+// Name:        samples/image/image.cpp\r
+// Purpose:     sample showing operations with wxImage\r
+// Author:      Robert Roebling\r
+// Modified by:\r
+// Created:     1998\r
+// RCS-ID:      $Id: image.cpp,v 1.120 2006/12/06 17:13:11 VZ Exp $\r
+// Copyright:   (c) 1998-2005 Robert Roebling\r
+// License:     wxWindows licence\r
+///////////////////////////////////////////////////////////////////////////////\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        samples/console/console.cpp\r
+// Purpose:     A sample console (as opposed to GUI) program using wxWidgets\r
+// Author:      Vadim Zeitlin\r
+// Modified by:\r
+// Created:     04.10.99\r
+// RCS-ID:      $Id: console.cpp,v 1.206 2006/11/12 19:55:19 VZ Exp $\r
+// Copyright:   (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>\r
+// Licence:     wxWindows license\r
+/////////////////////////////////////////////////////////////////////////////\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        samples/notebook/notebook.cpp\r
+// Purpose:     a sample demonstrating notebook usage\r
+// Author:      Julian Smart\r
+// Modified by: Dimitri Schoolwerth\r
+// Created:     26/10/98\r
+// RCS-ID:      $Id: notebook.cpp,v 1.49 2006/11/04 18:24:07 RR Exp $\r
+// Copyright:   (c) 1998-2002 wxWidgets team\r
+// License:     wxWindows license\r
+/////////////////////////////////////////////////////////////////////////////\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        dialogs.cpp\r
+// Purpose:     Common dialogs demo\r
+// Author:      Julian Smart\r
+// Modified by: ABX (2004) - adjustements for conditional building + new menu\r
+// Created:     04/01/98\r
+// RCS-ID:      $Id: dialogs.cpp,v 1.163 2006/11/04 10:57:24 VZ Exp $\r
+// Copyright:   (c) Julian Smart\r
+// Licence:     wxWindows license\r
+/////////////////////////////////////////////////////////////////////////////\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        dnd.cpp\r
+// Purpose:     Drag and drop sample\r
+// Author:      Vadim Zeitlin\r
+// Modified by:\r
+// Created:     04/01/98\r
+// RCS-ID:      $Id: dnd.cpp,v 1.107 2006/10/30 20:23:41 VZ Exp $\r
+// Copyright:\r
+// Licence:     wxWindows licence\r
+/////////////////////////////////////////////////////////////////////////////\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        test.cpp\r
+// Purpose:     wxHtml testing example\r
+/////////////////////////////////////////////////////////////////////////////\r
+\r
+\r
+#include "OPJViewer.h"\r
+\r
+IMPLEMENT_APP(OPJViewerApp)\r
+\r
+// For drawing lines in a canvas\r
+long xpos = -1;\r
+long ypos = -1;\r
+\r
+int winNumber = 1;\r
+\r
+// Initialise this in OnInit, not statically\r
+bool OPJViewerApp::OnInit(void)\r
+{\r
+       int n;\r
+#if wxUSE_UNICODE\r
+\r
+    wxChar **wxArgv = new wxChar *[argc + 1];\r
+\r
+    for (n = 0; n < argc; n++ ) {\r
+        wxMB2WXbuf warg = wxConvertMB2WX((char *) argv[n]);\r
+        wxArgv[n] = wxStrdup(warg);\r
+    }\r
+\r
+    wxArgv[n] = NULL;\r
+\r
+#else // !wxUSE_UNICODE\r
+\r
+    #define wxArgv argv\r
+\r
+#endif // wxUSE_UNICODE/!wxUSE_UNICODE\r
+\r
+#if wxUSE_CMDLINE_PARSER\r
+\r
+    static const wxCmdLineEntryDesc cmdLineDesc[] =\r
+    {\r
+        { wxCMD_LINE_SWITCH, _T("h"), _T("help"), _T("show this help message"),\r
+            wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },\r
+\r
+        { wxCMD_LINE_PARAM,  NULL, NULL, _T("input file"),\r
+            wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE },\r
+\r
+        { wxCMD_LINE_NONE }\r
+    };\r
+\r
+    wxCmdLineParser parser(cmdLineDesc, argc, wxArgv);\r
+\r
+    switch (parser.Parse()) {\r
+    case -1:\r
+        wxLogMessage(wxT("Help was given, terminating."));\r
+        break;\r
+\r
+    case 0:\r
+        ShowCmdLine(parser);\r
+        break;\r
+\r
+    default:\r
+        wxLogMessage(wxT("Syntax error detected."));\r
+        break;\r
+    }\r
+\r
+#endif // wxUSE_CMDLINE_PARSER\r
+\r
+    //wxInitAllImageHandlers();\r
+#if wxUSE_LIBJPEG\r
+  wxImage::AddHandler( new wxJPEGHandler );\r
+#endif\r
+#if wxUSE_LIBOPENJPEG\r
+  wxImage::AddHandler( new wxJPEG2000Handler );\r
+#endif\r
+#if USE_MXF\r
+  wxImage::AddHandler( new wxMXFHandler );\r
+#endif // USE_MXF\r
+#if OPJ_MANYFORMATS\r
+  wxImage::AddHandler( new wxBMPHandler );\r
+  wxImage::AddHandler( new wxPNGHandler );\r
+  wxImage::AddHandler( new wxGIFHandler );\r
+  wxImage::AddHandler( new wxPNMHandler );\r
+  wxImage::AddHandler( new wxTIFFHandler );\r
+#endif\r
+    // we use a XPM image in our HTML page\r
+    wxImage::AddHandler(new wxXPMHandler);\r
+\r
+       // memory file system\r
+    wxFileSystem::AddHandler(new wxMemoryFSHandler);\r
+\r
+#ifdef OPJ_INICONFIG\r
+       //load decoding engine parameters\r
+       OPJconfig = new wxConfig(OPJ_APPLICATION, OPJ_APPLICATION_VENDOR);\r
+\r
+       OPJconfig->Read(wxT("decode/enabledeco"), &m_enabledeco, (bool) true);\r
+       OPJconfig->Read(wxT("decode/enableparse"), &m_enableparse, (bool) true);\r
+       OPJconfig->Read(wxT("decode/resizemethod"), &m_resizemethod, (long) 0);\r
+       OPJconfig->Read(wxT("decode/xxxreducefactor"), &m_reducefactor, (long) 0);\r
+       OPJconfig->Read(wxT("decode/xxxqualitylayers"), &m_qualitylayers, (long) 0);\r
+       OPJconfig->Read(wxT("decode/xxxcomponents"), &m_components, (long) 0);\r
+       OPJconfig->Read(wxT("decode/xxxframenum"), &m_framenum, (long) 0);\r
+#ifdef USE_JPWL\r
+       OPJconfig->Read(wxT("decode/enablejpwl"), &m_enablejpwl, (bool) true);\r
+       OPJconfig->Read(wxT("decode/expcomps"), &m_expcomps, (long) JPWL_EXPECTED_COMPONENTS);\r
+       OPJconfig->Read(wxT("decode/maxtiles"), &m_maxtiles, (long) JPWL_MAXIMUM_TILES);\r
+#endif // USE_JPWL\r
+\r
+       OPJconfig->Write(wxT("teststring"), wxT("This is a test value"));\r
+       OPJconfig->Write(wxT("testbool"), (bool) true);\r
+       OPJconfig->Write(wxT("testlong"), (long) 245);\r
+\r
+       OPJconfig->Read(wxT("showtoolbar"), &m_showtoolbar, (bool) true);\r
+       OPJconfig->Read(wxT("showbrowser"), &m_showbrowser, (bool) true);\r
+       OPJconfig->Read(wxT("showpeeker"), &m_showpeeker, (bool) true);\r
+       OPJconfig->Read(wxT("browserwidth"), &m_browserwidth, (long) OPJ_BROWSER_WIDTH);\r
+       OPJconfig->Read(wxT("peekerheight"), &m_peekerheight, (long) OPJ_PEEKER_HEIGHT);\r
+       OPJconfig->Read(wxT("framewidth"), &m_framewidth, (long) OPJ_FRAME_WIDTH);\r
+       OPJconfig->Read(wxT("frameheight"), &m_frameheight, (long) OPJ_FRAME_HEIGHT);\r
+\r
+       // load encoding engine parameters\r
+       OPJconfig->Read(wxT("encode/subsampling"), &m_subsampling, (wxString) wxT("1,1"));\r
+       OPJconfig->Read(wxT("encode/origin"), &m_origin, (wxString) wxT("0,0"));\r
+       OPJconfig->Read(wxT("encode/rates"), &m_rates, (wxString) wxT("20,10,5"));\r
+       OPJconfig->Read(wxT("encode/quality"), &m_quality, (wxString) wxT("30,35,40"));\r
+       OPJconfig->Read(wxT("encode/enablequality"), &m_enablequality, (bool) false);\r
+       OPJconfig->Read(wxT("encode/multicomp"), &m_multicomp, (bool) false);   \r
+       OPJconfig->Read(wxT("encode/irreversible"), &m_irreversible, (bool) false);     \r
+       OPJconfig->Read(wxT("encode/resolutions"), &m_resolutions, (int) 6);    \r
+       OPJconfig->Read(wxT("encode/progression"), &m_progression, (int) 0);    \r
+       OPJconfig->Read(wxT("encode/cbsize"), &m_cbsize, (wxString) wxT("32,32"));\r
+       OPJconfig->Read(wxT("encode/prsize"), &m_prsize, (wxString) wxT("[128,128],[128,128]"));\r
+       OPJconfig->Read(wxT("encode/tsize"), &m_tsize, (wxString) wxT(""));\r
+       OPJconfig->Read(wxT("encode/torigin"), &m_torigin, (wxString) wxT("0,0"));\r
+       OPJconfig->Read(wxT("encode/enablesop"), &m_enablesop, (bool) false);   \r
+       OPJconfig->Read(wxT("encode/enableeph"), &m_enableeph, (bool) false);   \r
+       OPJconfig->Read(wxT("encode/enablebypass"), &m_enablebypass, (bool) false);     \r
+       OPJconfig->Read(wxT("encode/enablereset"), &m_enablereset, (bool) false);       \r
+       OPJconfig->Read(wxT("encode/enablerestart"), &m_enablerestart, (bool) false);   \r
+       OPJconfig->Read(wxT("encode/enablevsc"), &m_enablevsc, (bool) false);   \r
+       OPJconfig->Read(wxT("encode/enableerterm"), &m_enableerterm, (bool) false);     \r
+       OPJconfig->Read(wxT("encode/enablesegmark"), &m_enablesegmark, (bool) false);   \r
+       OPJconfig->Read(wxT("encode/enablecomm"), &m_enablecomm, (bool) true);  \r
+       OPJconfig->Read(wxT("encode/enablepoc"), &m_enablepoc, (bool) false);   \r
+       OPJconfig->Read(wxT("encode/comment"), &m_comment, (wxString) wxT(""));\r
+       OPJconfig->Read(wxT("encode/poc"), &m_poc, (wxString) wxT("T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL"));\r
+       OPJconfig->Read(wxT("encode/enableidx"), &m_enableidx, (bool) false);   \r
+       OPJconfig->Read(wxT("encode/index"), &m_index, (wxString) wxT("index.txt"));\r
+#ifdef USE_JPWL\r
+       OPJconfig->Read(wxT("encode/enablejpwl"), &m_enablejpwle, (bool) true);\r
+       for (n = 0; n < MYJPWL_MAX_NO_TILESPECS; n++) {\r
+               OPJconfig->Read(wxT("encode/jpwl/hprotsel") + wxString::Format(wxT("%02d"), n), &m_hprotsel[n], 0);\r
+               OPJconfig->Read(wxT("encode/jpwl/htileval") + wxString::Format(wxT("%02d"), n), &m_htileval[n], 0);\r
+               OPJconfig->Read(wxT("encode/jpwl/pprotsel") + wxString::Format(wxT("%02d"), n), &m_pprotsel[n], 0);\r
+               OPJconfig->Read(wxT("encode/jpwl/ptileval") + wxString::Format(wxT("%02d"), n), &m_ptileval[n], 0);\r
+               OPJconfig->Read(wxT("encode/jpwl/ppackval") + wxString::Format(wxT("%02d"), n), &m_ppackval[n], 0);\r
+               OPJconfig->Read(wxT("encode/jpwl/sensisel") + wxString::Format(wxT("%02d"), n), &m_sensisel[n], 0);\r
+               OPJconfig->Read(wxT("encode/jpwl/stileval") + wxString::Format(wxT("%02d"), n), &m_stileval[n], 0);\r
+       }\r
+#endif // USE_JPWL\r
+\r
+#else\r
+       // set decoding engine parameters\r
+       m_enabledeco = true;\r
+       m_enableparse = true;\r
+       m_resizemethod = 0;\r
+       m_reducefactor = 0;\r
+       m_qualitylayers = 0;\r
+       m_components = 0;\r
+       m_framenum = 0;\r
+#ifdef USE_JPWL\r
+       m_enablejpwl = true;\r
+       m_expcomps = JPWL_EXPECTED_COMPONENTS;\r
+       m_maxtiles = JPWL_MAXIMUM_TILES;\r
+#endif // USE_JPWL\r
+       m_showtoolbar = true;\r
+       m_showbrowser = true;\r
+       m_showpeeker = true;\r
+       m_browserwidth = OPJ_BROWSER_WIDTH;\r
+       m_peekerheight = OPJ_PEEKER_HEIGHT;\r
+       m_framewidth = OPJ_FRAME_WIDTH;\r
+       m_frameheight = OPJ_FRAME_HEIGHT;\r
+\r
+       // set encoding engine parameters\r
+       m_subsampling = wxT("1,1");\r
+       m_origin = wxT("0,0");\r
+       m_rates = wxT("20,10,5");\r
+       m_quality = wxT("30,35,40");\r
+       m_enablequality = false;\r
+       m_multicomp = false;\r
+       m_irreversible = false;\r
+       m_resolutions = 6;\r
+       m_progression = 0;\r
+       m_cbsize= wxT("32,32");\r
+       m_prsize= wxT("[128,128],[128,128]");\r
+       m_tsize = wxT("");\r
+       m_torigin = wxT("0,0");\r
+       m_enablesop = false;\r
+       m_enableeph = false;\r
+       m_enablebypass = false;\r
+       m_enablereset = false;\r
+       m_enablerestart = false;\r
+       m_enablevsc = false;\r
+       m_enableerterm = false;\r
+       m_enablesegmark = false;\r
+       m_enableidx = false;\r
+       m_index = wxT("index.txt");\r
+       m_enablecomm = true;\r
+       m_comment = wxT("");\r
+       m_enablepoc = false;\r
+       m_poc = wxT("T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL");\r
+#ifdef USE_JPWL\r
+       m_enablejpwle = true;\r
+       for (n = 0; n < MYJPWL_MAX_NO_TILESPECS; n++) {\r
+               m_hprotsel[n] = 0;\r
+               m_htileval[n] = 0;\r
+               m_pprotsel[n] = 0;\r
+               m_ptileval[n] = 0;\r
+               m_sensisel[n] = 0;\r
+               m_stileval[n] = 0;\r
+       }\r
+#endif // USE_JPWL\r
+\r
+#endif // OPJ_INICONFIG\r
+\r
+       if (m_comment == wxT("")) {\r
+#if defined __WXMSW__\r
+               m_comment = wxT("Created by OPJViewer Win32 - OpenJPEG  version ");\r
+#elif defined __WXGTK__\r
+               m_comment = wxT("Created by OPJViewer Lin32 - OpenJPEG version ");\r
+#else\r
+               m_comment = wxT("Created by OPJViewer - OpenJPEG version ");\r
+#endif\r
+\r
+#ifdef USE_JPWL\r
+               m_comment += wxString::Format(wxT("%s with JPWL"), (char *) opj_version());\r
+#else\r
+               m_comment += wxString::Format(wxT("%s"), (char *) opj_version());\r
+#endif\r
+       }\r
+\r
+       // Create the main frame window\r
+  OPJFrame *frame = new OPJFrame(NULL, wxID_ANY, OPJ_APPLICATION_TITLEBAR,\r
+                                         wxDefaultPosition, wxSize(wxGetApp().m_framewidth, wxGetApp().m_frameheight),\r
+                      wxDEFAULT_FRAME_STYLE | wxNO_FULL_REPAINT_ON_RESIZE |\r
+                      wxHSCROLL | wxVSCROLL);\r
+\r
+  // Give it an icon (this is ignored in MDI mode: uses resources)\r
+#ifdef __WXMSW__\r
+  frame->SetIcon(wxIcon(wxT("OPJViewer16")));\r
+#endif\r
+\r
+  frame->Show(true);\r
+\r
+  SetTopWindow(frame);\r
+\r
+       // if there are files on the command line, open them\r
+       if (!(m_filelist.IsEmpty())) {\r
+               //wxLogMessage(wxT("Habemus files!!!"));\r
+               wxArrayString paths, filenames;\r
+               for (unsigned int f = 0; f < wxGetApp().m_filelist.GetCount(); f++) {\r
+                       paths.Add(wxFileName(wxGetApp().m_filelist[f]).GetFullPath());\r
+                       filenames.Add(wxFileName(wxGetApp().m_filelist[f]).GetFullName());\r
+               }\r
+               //wxLogMessage(paths[0]);\r
+               frame->OpenFiles(paths, filenames);\r
+       }\r
+\r
+  return true;\r
+}\r
+\r
+int OPJViewerApp::OnExit()\r
+{\r
+       int n;\r
+\r
+#ifdef OPJ_INICONFIG\r
+       OPJconfig->Write(wxT("decode/enabledeco"), m_enabledeco);\r
+       OPJconfig->Write(wxT("decode/enableparse"), m_enableparse);\r
+       OPJconfig->Write(wxT("decode/resizemethod"), m_resizemethod);\r
+       OPJconfig->Write(wxT("decode/reducefactor"), m_reducefactor);\r
+       OPJconfig->Write(wxT("decode/qualitylayers"), m_qualitylayers);\r
+       OPJconfig->Write(wxT("decode/components"), m_components);\r
+       OPJconfig->Write(wxT("decode/framenum"), m_framenum);\r
+#ifdef USE_JPWL\r
+       OPJconfig->Write(wxT("decode/enablejpwl"), m_enablejpwl);\r
+       OPJconfig->Write(wxT("decode/expcomps"), m_expcomps);\r
+       OPJconfig->Write(wxT("decode/maxtiles"), m_maxtiles);\r
+#endif // USE_JPWL\r
+       OPJconfig->Write(wxT("showtoolbar"), m_showtoolbar);\r
+       OPJconfig->Write(wxT("showbrowser"), m_showbrowser);\r
+       OPJconfig->Write(wxT("showpeeker"), m_showpeeker);\r
+       OPJconfig->Write(wxT("browserwidth"), m_browserwidth);\r
+       OPJconfig->Write(wxT("peekerheight"), m_peekerheight);\r
+       OPJconfig->Write(wxT("framewidth"), m_framewidth);\r
+       OPJconfig->Write(wxT("frameheight"), m_frameheight);\r
+\r
+       OPJconfig->Write(wxT("encode/subsampling"), m_subsampling);\r
+       OPJconfig->Write(wxT("encode/origin"), m_origin);\r
+       OPJconfig->Write(wxT("encode/rates"), m_rates);\r
+       OPJconfig->Write(wxT("encode/quality"), m_quality);\r
+       OPJconfig->Write(wxT("encode/enablequality"), m_enablequality);\r
+       OPJconfig->Write(wxT("encode/multicomp"), m_multicomp);\r
+       OPJconfig->Write(wxT("encode/irreversible"), m_irreversible);\r
+       OPJconfig->Write(wxT("encode/resolutions"), m_resolutions);\r
+       OPJconfig->Write(wxT("encode/progression"), m_progression);\r
+       OPJconfig->Write(wxT("encode/cbsize"), m_cbsize);\r
+       OPJconfig->Write(wxT("encode/prsize"), m_prsize);\r
+       OPJconfig->Write(wxT("encode/tiles"), m_tsize);\r
+       OPJconfig->Write(wxT("encode/torigin"), m_torigin);\r
+       OPJconfig->Write(wxT("encode/enablesop"), m_enablesop);\r
+       OPJconfig->Write(wxT("encode/enableeph"), m_enableeph);\r
+       OPJconfig->Write(wxT("encode/enablebypass"), m_enablebypass);\r
+       OPJconfig->Write(wxT("encode/enablereset"), m_enablereset);\r
+       OPJconfig->Write(wxT("encode/enablerestart"), m_enablerestart);\r
+       OPJconfig->Write(wxT("encode/enablevsc"), m_enablevsc);\r
+       OPJconfig->Write(wxT("encode/enableerterm"), m_enableerterm);\r
+       OPJconfig->Write(wxT("encode/enablesegmark"), m_enablesegmark);\r
+       OPJconfig->Write(wxT("encode/enableidx"), m_enableidx);\r
+       OPJconfig->Write(wxT("encode/index"), m_index);\r
+       OPJconfig->Write(wxT("encode/enablecomm"), m_enablecomm);\r
+       OPJconfig->Write(wxT("encode/comment"), m_comment);\r
+       OPJconfig->Write(wxT("encode/enablepoc"), m_enablepoc);\r
+       OPJconfig->Write(wxT("encode/poc"), m_poc);\r
+#ifdef USE_JPWL\r
+       OPJconfig->Write(wxT("encode/enablejpwl"), m_enablejpwle);\r
+       for (n = 0; n < MYJPWL_MAX_NO_TILESPECS; n++) {\r
+               OPJconfig->Write(wxT("encode/jpwl/hprotsel") + wxString::Format(wxT("%02d"), n), m_hprotsel[n]);\r
+               OPJconfig->Write(wxT("encode/jpwl/htileval") + wxString::Format(wxT("%02d"), n), m_htileval[n]);\r
+               OPJconfig->Write(wxT("encode/jpwl/pprotsel") + wxString::Format(wxT("%02d"), n), m_pprotsel[n]);\r
+               OPJconfig->Write(wxT("encode/jpwl/ptileval") + wxString::Format(wxT("%02d"), n), m_ptileval[n]);\r
+               OPJconfig->Write(wxT("encode/jpwl/ppackval") + wxString::Format(wxT("%02d"), n), m_ppackval[n]);\r
+               OPJconfig->Write(wxT("encode/jpwl/sensisel") + wxString::Format(wxT("%02d"), n), m_sensisel[n]);\r
+               OPJconfig->Write(wxT("encode/jpwl/stileval") + wxString::Format(wxT("%02d"), n), m_stileval[n]);\r
+       }\r
+#endif // USE_JPWL\r
+\r
+#endif // OPJ_INICONFIG\r
+\r
+       return 1;\r
+}\r
+\r
+void OPJViewerApp::ShowCmdLine(const wxCmdLineParser& parser)\r
+{\r
+    wxString s = wxT("Command line parsed successfully:\nInput files: ");\r
+\r
+    size_t count = parser.GetParamCount();\r
+    for (size_t param = 0; param < count; param++) {\r
+        s << parser.GetParam(param) << ';';\r
+               m_filelist.Add(parser.GetParam(param));\r
+    }\r
+\r
+    //wxLogMessage(s);\r
+}\r
+\r
+// OPJFrame events\r
+\r
+// Event class for sending text messages between worker and GUI threads\r
+BEGIN_EVENT_TABLE(OPJFrame, wxMDIParentFrame)\r
+    EVT_MENU(OPJFRAME_HELPABOUT, OPJFrame::OnAbout)\r
+    EVT_MENU(OPJFRAME_FILEOPEN, OPJFrame::OnFileOpen)\r
+    EVT_MENU(OPJFRAME_FILESAVEAS, OPJFrame::OnFileSaveAs)\r
+    EVT_MENU(OPJFRAME_MEMORYOPEN, OPJFrame::OnMemoryOpen)\r
+    EVT_SIZE(OPJFrame::OnSize)\r
+    EVT_MENU(OPJFRAME_FILEEXIT, OPJFrame::OnQuit)\r
+    EVT_MENU(OPJFRAME_FILECLOSE, OPJFrame::OnClose)\r
+    EVT_MENU(OPJFRAME_VIEWZOOM, OPJFrame::OnZoom)\r
+    EVT_MENU(OPJFRAME_VIEWFIT, OPJFrame::OnFit)\r
+    EVT_MENU(OPJFRAME_VIEWRELOAD, OPJFrame::OnReload)\r
+    EVT_MENU(OPJFRAME_VIEWPREVFRAME, OPJFrame::OnPrevFrame)\r
+    EVT_MENU(OPJFRAME_VIEWHOMEFRAME, OPJFrame::OnHomeFrame)\r
+    EVT_MENU(OPJFRAME_VIEWNEXTFRAME, OPJFrame::OnNextFrame)\r
+    EVT_MENU(OPJFRAME_VIEWLESSLAYERS, OPJFrame::OnLessLayers)\r
+    EVT_MENU(OPJFRAME_VIEWALLLAYERS, OPJFrame::OnAllLayers)\r
+    EVT_MENU(OPJFRAME_VIEWMORELAYERS, OPJFrame::OnMoreLayers)\r
+    EVT_MENU(OPJFRAME_VIEWLESSRES, OPJFrame::OnLessRes)\r
+    EVT_MENU(OPJFRAME_VIEWFULLRES, OPJFrame::OnFullRes)\r
+    EVT_MENU(OPJFRAME_VIEWMORERES, OPJFrame::OnMoreRes)\r
+    EVT_MENU(OPJFRAME_VIEWPREVCOMP, OPJFrame::OnPrevComp)\r
+    EVT_MENU(OPJFRAME_VIEWALLCOMPS, OPJFrame::OnAllComps)\r
+    EVT_MENU(OPJFRAME_VIEWNEXTCOMP, OPJFrame::OnNextComp)\r
+    EVT_MENU(OPJFRAME_FILETOGGLEB, OPJFrame::OnToggleBrowser)\r
+    EVT_MENU(OPJFRAME_FILETOGGLEP, OPJFrame::OnTogglePeeker)\r
+    EVT_MENU(OPJFRAME_FILETOGGLET, OPJFrame::OnToggleToolbar)\r
+    EVT_MENU(OPJFRAME_SETSENCO, OPJFrame::OnSetsEnco)\r
+    EVT_MENU(OPJFRAME_SETSDECO, OPJFrame::OnSetsDeco)\r
+    EVT_SASH_DRAGGED_RANGE(OPJFRAME_BROWSEWIN, OPJFRAME_LOGWIN, OPJFrame::OnSashDrag)\r
+    EVT_NOTEBOOK_PAGE_CHANGED(LEFT_NOTEBOOK_ID, OPJFrame::OnNotebook)\r
+    EVT_MENU(OPJFRAME_THREADLOGMSG, OPJFrame::OnThreadLogmsg)\r
+END_EVENT_TABLE()\r
+\r
+// this is the frame constructor\r
+OPJFrame::OPJFrame(wxWindow *parent, const wxWindowID id, const wxString& title,\r
+                                  const wxPoint& pos, const wxSize& size, const long style)\r
+               : wxMDIParentFrame(parent, id, title, pos, size, style)\r
+{\r
+       // file menu and its items\r
+       wxMenu *file_menu = new wxMenu;\r
+\r
+       file_menu->Append(OPJFRAME_FILEOPEN, wxT("&Open\tCtrl+O"));\r
+       file_menu->SetHelpString(OPJFRAME_FILEOPEN, wxT("Open one or more files"));\r
+\r
+       file_menu->Append(OPJFRAME_MEMORYOPEN, wxT("&Memory\tCtrl+M"));\r
+       file_menu->SetHelpString(OPJFRAME_MEMORYOPEN, wxT("Open a memory buffer"));\r
+\r
+       file_menu->Append(OPJFRAME_FILECLOSE, wxT("&Close\tCtrl+C"));\r
+       file_menu->SetHelpString(OPJFRAME_FILECLOSE, wxT("Close current image"));\r
+\r
+       file_menu->AppendSeparator();\r
+\r
+       file_menu->Append(OPJFRAME_FILESAVEAS, wxT("&Save as\tCtrl+S"));\r
+       file_menu->SetHelpString(OPJFRAME_FILESAVEAS, wxT("Save the current image"));\r
+       //file_menu->Enable(OPJFRAME_FILESAVEAS, false);\r
+\r
+       file_menu->AppendSeparator();\r
+\r
+       file_menu->Append(OPJFRAME_FILETOGGLEB, wxT("Toggle &browser\tCtrl+B"));\r
+       file_menu->SetHelpString(OPJFRAME_FILETOGGLEB, wxT("Toggle the left browsing pane"));\r
+\r
+       file_menu->Append(OPJFRAME_FILETOGGLEP, wxT("Toggle &peeker\tCtrl+P"));\r
+       file_menu->SetHelpString(OPJFRAME_FILETOGGLEP, wxT("Toggle the bottom peeking pane"));\r
+\r
+       file_menu->Append(OPJFRAME_FILETOGGLET, wxT("Toggle &toolbar\tCtrl+T"));\r
+       file_menu->SetHelpString(OPJFRAME_FILETOGGLET, wxT("Toggle the toolbar"));\r
+\r
+       file_menu->AppendSeparator();\r
+\r
+       file_menu->Append(OPJFRAME_FILEEXIT, wxT("&Exit\tCtrl+Q"));\r
+       file_menu->SetHelpString(OPJFRAME_FILEEXIT, wxT("Quit this program"));\r
+\r
+       // view menu and its items\r
+       wxMenu *view_menu = new wxMenu;\r
+\r
+       view_menu->Append(OPJFRAME_VIEWZOOM, wxT("&Zoom\tCtrl+Z"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWZOOM, wxT("Rescale the image"));\r
+\r
+       view_menu->Append(OPJFRAME_VIEWFIT, wxT("Zoom to &fit\tCtrl+F"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWFIT, wxT("Fit the image in canvas"));\r
+\r
+       view_menu->Append(OPJFRAME_VIEWRELOAD, wxT("&Reload image\tCtrl+R"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWRELOAD, wxT("Reload the current image"));\r
+\r
+       view_menu->AppendSeparator();\r
+\r
+       view_menu->Append(OPJFRAME_VIEWPREVFRAME, wxT("&Prev frame\tLeft"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWPREVFRAME, wxT("View previous frame"));\r
+\r
+       view_menu->Append(OPJFRAME_VIEWHOMEFRAME, wxT("&Start frame\tHome"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWHOMEFRAME, wxT("View starting frame"));\r
+\r
+       view_menu->Append(OPJFRAME_VIEWNEXTFRAME, wxT("&Next frame\tRight"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWNEXTFRAME, wxT("View next frame"));\r
+\r
+       view_menu->AppendSeparator();\r
+\r
+       view_menu->Append(OPJFRAME_VIEWLESSLAYERS, wxT("&Less layers\t-"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWLESSLAYERS, wxT("Remove a layer"));\r
+\r
+       view_menu->Append(OPJFRAME_VIEWALLLAYERS, wxT("&All layers\t0"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWALLLAYERS, wxT("Show all layers"));\r
+\r
+       view_menu->Append(OPJFRAME_VIEWMORELAYERS, wxT("&More layers\t+"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWMORELAYERS, wxT("Add a layer"));\r
+\r
+       view_menu->AppendSeparator();\r
+\r
+       view_menu->Append(OPJFRAME_VIEWLESSRES, wxT("&Less resolution\t<"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWLESSRES, wxT("Reduce the resolution"));\r
+\r
+       view_menu->Append(OPJFRAME_VIEWFULLRES, wxT("&Full resolution\tf"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWFULLRES, wxT("Full resolution"));\r
+\r
+       view_menu->Append(OPJFRAME_VIEWMORERES, wxT("&More resolution\t>"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWMORERES, wxT("Increase the resolution"));\r
+\r
+       view_menu->AppendSeparator();\r
+\r
+       view_menu->Append(OPJFRAME_VIEWPREVCOMP, wxT("&Prev component\tDown"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWPREVCOMP, wxT("View previous component"));\r
+\r
+       view_menu->Append(OPJFRAME_VIEWALLCOMPS, wxT("&All components\ta"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWALLCOMPS, wxT("View all components"));\r
+\r
+       view_menu->Append(OPJFRAME_VIEWNEXTCOMP, wxT("&Next component\tUp"));\r
+       view_menu->SetHelpString(OPJFRAME_VIEWNEXTCOMP, wxT("View next component"));\r
+\r
+\r
+       // settings menu and its items\r
+       wxMenu *sets_menu = new wxMenu;\r
+\r
+       sets_menu->Append(OPJFRAME_SETSENCO, wxT("&Encoder\tCtrl+E"));\r
+       sets_menu->SetHelpString(OPJFRAME_SETSENCO, wxT("Encoder settings"));\r
+\r
+       sets_menu->Append(OPJFRAME_SETSDECO, wxT("&Decoder\tCtrl+D"));\r
+       sets_menu->SetHelpString(OPJFRAME_SETSDECO, wxT("Decoder settings"));\r
+\r
+       // help menu and its items\r
+       wxMenu *help_menu = new wxMenu;\r
+\r
+       help_menu->Append(OPJFRAME_HELPABOUT, wxT("&About\tF1"));\r
+       help_menu->SetHelpString(OPJFRAME_HELPABOUT, wxT("Basic info on the program"));\r
+\r
+       // the whole menubar\r
+       wxMenuBar *menu_bar = new wxMenuBar;\r
+       menu_bar->Append(file_menu, wxT("&File"));\r
+       menu_bar->Append(view_menu, wxT("&View"));\r
+       menu_bar->Append(sets_menu, wxT("&Settings"));\r
+       menu_bar->Append(help_menu, wxT("&Help"));\r
+\r
+       // Associate the menu bar with the frame\r
+       SetMenuBar(menu_bar);\r
+\r
+       // the status bar\r
+       CreateStatusBar();\r
+\r
+       // the toolbar\r
+       tool_bar = new wxToolBar(this, OPJFRAME_TOOLBAR,\r
+                                                               wxDefaultPosition, wxDefaultSize,\r
+                                                               wxTB_HORIZONTAL | wxNO_BORDER);\r
+       wxBitmap bmpOpen = wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR,\r
+                                                                                               wxDefaultSize);\r
+       wxBitmap bmpSaveAs = wxArtProvider::GetBitmap(wxART_FILE_SAVE_AS, wxART_TOOLBAR,\r
+                                                                                               wxDefaultSize);\r
+       wxBitmap bmpZoom = wxArtProvider::GetBitmap(wxART_FIND, wxART_TOOLBAR,\r
+                                                                                               wxDefaultSize);\r
+       wxBitmap bmpFit = wxArtProvider::GetBitmap(wxART_FIND_AND_REPLACE, wxART_TOOLBAR,\r
+                                                                                               wxDefaultSize);\r
+       wxBitmap bmpReload = wxArtProvider::GetBitmap(wxART_EXECUTABLE_FILE, wxART_TOOLBAR,\r
+                                                                                               wxDefaultSize);\r
+       wxBitmap bmpDecosettings = wxArtProvider::GetBitmap(wxART_REPORT_VIEW, wxART_TOOLBAR,\r
+                                                                                               wxDefaultSize);\r
+       wxBitmap bmpEncosettings = wxArtProvider::GetBitmap(wxART_LIST_VIEW, wxART_TOOLBAR,\r
+                                                                                               wxDefaultSize);\r
+       wxBitmap bmpPrevframe = wxArtProvider::GetBitmap(wxART_GO_BACK, wxART_TOOLBAR,\r
+                                                                                               wxDefaultSize);\r
+       wxBitmap bmpHomeframe = wxArtProvider::GetBitmap(wxART_GO_HOME, wxART_TOOLBAR,\r
+                                                                                               wxDefaultSize);\r
+       wxBitmap bmpNextframe = wxArtProvider::GetBitmap(wxART_GO_FORWARD, wxART_TOOLBAR,\r
+                                                                                               wxDefaultSize);\r
+       wxBitmap bmpLesslayers = bmpPrevframe;\r
+       wxBitmap bmpAlllayers = wxArtProvider::GetBitmap(wxART_GO_TO_PARENT, wxART_TOOLBAR,\r
+                                                                                               wxDefaultSize);\r
+       wxBitmap bmpMorelayers = bmpNextframe;\r
+       wxBitmap bmpLessres = bmpPrevframe;\r
+       wxBitmap bmpFullres = wxArtProvider::GetBitmap(wxART_GO_TO_PARENT, wxART_TOOLBAR,\r
+                                                                                               wxDefaultSize);\r
+       wxBitmap bmpMoreres = bmpNextframe;\r
+       wxBitmap bmpPrevcomp = bmpPrevframe;\r
+       wxBitmap bmpAllcomps = wxArtProvider::GetBitmap(wxART_GO_TO_PARENT, wxART_TOOLBAR,\r
+                                                                                               wxDefaultSize);\r
+       wxBitmap bmpNextcomp = bmpNextframe;\r
+\r
+       tool_bar->AddTool(OPJFRAME_FILEOPEN, bmpOpen, wxT("Open"));\r
+       tool_bar->AddTool(OPJFRAME_FILESAVEAS, bmpSaveAs, wxT("Save as "));\r
+       //tool_bar->EnableTool(OPJFRAME_FILESAVEAS, false);\r
+       tool_bar->AddSeparator();\r
+       tool_bar->AddTool(OPJFRAME_VIEWZOOM, bmpZoom, wxT("Zoom"));\r
+       tool_bar->AddTool(OPJFRAME_VIEWFIT, bmpFit, wxT("Zoom to fit"));\r
+       tool_bar->AddTool(OPJFRAME_VIEWRELOAD, bmpReload, wxT("Reload"));\r
+       tool_bar->AddSeparator();\r
+       tool_bar->AddTool(OPJFRAME_SETSDECO, bmpDecosettings, wxT("Decoder settings"));\r
+       tool_bar->AddTool(OPJFRAME_SETSENCO, bmpEncosettings, wxT("Encoder settings"));\r
+       tool_bar->AddSeparator();\r
+       tool_bar->AddTool(OPJFRAME_VIEWPREVFRAME, bmpPrevframe, wxT("Previous frame"));\r
+       tool_bar->AddTool(OPJFRAME_VIEWHOMEFRAME, bmpHomeframe, wxT("Starting frame"));\r
+       tool_bar->AddTool(OPJFRAME_VIEWNEXTFRAME, bmpNextframe, wxT("Next frame"));\r
+       tool_bar->AddSeparator();\r
+       tool_bar->AddTool(OPJFRAME_VIEWLESSLAYERS, bmpLesslayers, wxT("Remove a layer"));\r
+       tool_bar->AddTool(OPJFRAME_VIEWALLLAYERS, bmpAlllayers, wxT("Show all layers"));\r
+       tool_bar->AddTool(OPJFRAME_VIEWMORELAYERS, bmpMorelayers, wxT("Add a layer"));\r
+       tool_bar->AddSeparator();\r
+       tool_bar->AddTool(OPJFRAME_VIEWLESSRES, bmpLessres, wxT("Reduce the resolution"));\r
+       tool_bar->AddTool(OPJFRAME_VIEWFULLRES, bmpFullres, wxT("Full resolution"));\r
+       tool_bar->AddTool(OPJFRAME_VIEWMORERES, bmpMoreres, wxT("Increase the resolution"));\r
+       tool_bar->AddSeparator();\r
+       tool_bar->AddTool(OPJFRAME_VIEWPREVCOMP, bmpPrevcomp, wxT("Previous component"));\r
+       tool_bar->AddTool(OPJFRAME_VIEWALLCOMPS, bmpAllcomps, wxT("All components"));\r
+       tool_bar->AddTool(OPJFRAME_VIEWNEXTCOMP, bmpNextcomp, wxT("Next component"));\r
+       tool_bar->Realize();\r
+       \r
+       // associate the toolbar with the frame\r
+       SetToolBar(tool_bar);\r
+\r
+       // show the toolbar?\r
+       if (!wxGetApp().m_showtoolbar)\r
+               tool_bar->Show(false);\r
+       else\r
+               tool_bar->Show(true);\r
+\r
+       // the logging window\r
+       loggingWindow = new wxSashLayoutWindow(this, OPJFRAME_LOGWIN,\r
+                                                                                       wxDefaultPosition, wxSize(400, wxGetApp().m_peekerheight),\r
+                                                                                       wxNO_BORDER | wxSW_3D | wxCLIP_CHILDREN\r
+                                                                                       );\r
+       loggingWindow->SetDefaultSize(wxSize(1000, wxGetApp().m_peekerheight));\r
+       loggingWindow->SetOrientation(wxLAYOUT_HORIZONTAL);\r
+       loggingWindow->SetAlignment(wxLAYOUT_BOTTOM);\r
+       //loggingWindow->SetBackgroundColour(wxColour(0, 0, 255));\r
+       loggingWindow->SetSashVisible(wxSASH_TOP, true);\r
+\r
+       // show the logging?\r
+       if (!wxGetApp().m_showpeeker)\r
+               loggingWindow->Show(false);\r
+       else\r
+               loggingWindow->Show(true);\r
+\r
+       // create the bottom notebook\r
+       m_bookCtrlbottom = new wxNotebook(loggingWindow, BOTTOM_NOTEBOOK_ID,\r
+                                                               wxDefaultPosition, wxDefaultSize,\r
+                                                               wxBK_LEFT);\r
+\r
+       // create the text control of the logger\r
+       m_textCtrl = new wxTextCtrl(m_bookCtrlbottom, wxID_ANY, wxT(""),\r
+                                                               wxDefaultPosition, wxDefaultSize,\r
+                                                               wxTE_MULTILINE | wxSUNKEN_BORDER | wxTE_READONLY\r
+                                                               );\r
+       m_textCtrl->SetValue(_T("Logging window\n"));\r
+\r
+       // add it to the notebook\r
+       m_bookCtrlbottom->AddPage(m_textCtrl, wxT("Log"));\r
+\r
+       // create the text control of the browser\r
+       m_textCtrlbrowse = new wxTextCtrl(m_bookCtrlbottom, wxID_ANY, wxT(""),\r
+                                                               wxDefaultPosition, wxDefaultSize,\r
+                                                               wxTE_MULTILINE | wxSUNKEN_BORDER | wxTE_READONLY | wxTE_RICH\r
+                                                               );\r
+       wxFont *browsefont = new wxFont(wxNORMAL_FONT->GetPointSize(),\r
+               wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);\r
+    m_textCtrlbrowse->SetDefaultStyle(wxTextAttr(wxNullColour, wxNullColour, *browsefont));\r
+       m_textCtrlbrowse->AppendText(wxT("Browsing window\n"));\r
+\r
+       // add it the notebook\r
+       m_bookCtrlbottom->AddPage(m_textCtrlbrowse, wxT("Peek"), false);\r
+\r
+       // the browser window\r
+       markerTreeWindow = new wxSashLayoutWindow(this, OPJFRAME_BROWSEWIN,\r
+                                                                                         wxDefaultPosition, wxSize(wxGetApp().m_browserwidth, 30),\r
+                                                                                         wxNO_BORDER | wxSW_3D | wxCLIP_CHILDREN\r
+                                                                                         );\r
+       markerTreeWindow->SetDefaultSize(wxSize(wxGetApp().m_browserwidth, 1000));\r
+       markerTreeWindow->SetOrientation(wxLAYOUT_VERTICAL);\r
+       markerTreeWindow->SetAlignment(wxLAYOUT_LEFT);\r
+       //markerTreeWindow->SetBackgroundColour(wxColour(0, 255, 0));\r
+       markerTreeWindow->SetSashVisible(wxSASH_RIGHT, true);\r
+       markerTreeWindow->SetExtraBorderSize(0);\r
+\r
+       // create the browser notebook\r
+       m_bookCtrl = new wxNotebook(markerTreeWindow, LEFT_NOTEBOOK_ID,\r
+                                                               wxDefaultPosition, wxDefaultSize,\r
+                                                               wxBK_TOP);\r
+\r
+       // show the browser?\r
+       if (!wxGetApp().m_showbrowser)\r
+               markerTreeWindow->Show(false);\r
+       else\r
+               markerTreeWindow->Show(true);\r
+\r
+#ifdef __WXMOTIF__\r
+       // For some reason, we get a memcpy crash in wxLogStream::DoLogStream\r
+       // on gcc/wxMotif, if we use wxLogTextCtl. Maybe it's just gcc?\r
+       delete wxLog::SetActiveTarget(new wxLogStderr);\r
+#else\r
+       // set our text control as the log target\r
+       wxLogTextCtrl *logWindow = new wxLogTextCtrl(m_textCtrl);\r
+       delete wxLog::SetActiveTarget(logWindow);\r
+#endif\r
+\r
+       // associate drop targets with the controls\r
+       SetDropTarget(new OPJDnDFile(this));\r
+\r
+}\r
+\r
+// this is the frame destructor\r
+OPJFrame::~OPJFrame(void)\r
+{\r
+       // save size settings\r
+       GetSize(&(wxGetApp().m_framewidth), &(wxGetApp().m_frameheight));\r
+\r
+       // delete all possible things\r
+       delete m_bookCtrl;\r
+       m_bookCtrl = NULL;\r
+\r
+       delete markerTreeWindow;\r
+       markerTreeWindow = NULL;\r
+\r
+       delete m_textCtrl;\r
+       m_textCtrl = NULL;\r
+\r
+       delete m_bookCtrlbottom;\r
+       m_bookCtrlbottom = NULL;\r
+\r
+       delete loggingWindow;\r
+       loggingWindow = NULL;\r
+}\r
+\r
+void OPJFrame::OnNotebook(wxNotebookEvent& event)\r
+{\r
+       int sel = event.GetSelection();\r
+       long childnum;\r
+\r
+       m_bookCtrl->GetPageText(sel).ToLong(&childnum);\r
+\r
+       if (m_childhash[childnum])\r
+               m_childhash[childnum]->Activate();\r
+\r
+       //wxLogMessage(wxT("Selection changed (now %d --> %d)"), childnum, m_childhash[childnum]->m_winnumber);\r
+\r
+}\r
+\r
+\r
+void OPJFrame::Resize(int number)\r
+{\r
+       wxSize size = GetClientSize();\r
+}\r
+\r
+void OPJFrame::OnSetsEnco(wxCommandEvent& event)\r
+{\r
+       int n;\r
+\r
+    OPJEncoderDialog dialog(this, event.GetId());\r
+\r
+    if (dialog.ShowModal() == wxID_OK) {\r
+\r
+               // load settings\r
+               wxGetApp().m_subsampling = dialog.m_subsamplingCtrl->GetValue();\r
+               wxGetApp().m_origin = dialog.m_originCtrl->GetValue();\r
+               wxGetApp().m_rates = dialog.m_rateCtrl->GetValue();\r
+               wxGetApp().m_quality = dialog.m_qualityCtrl->GetValue();\r
+               wxGetApp().m_enablequality = dialog.m_qualityRadio->GetValue();\r
+               wxGetApp().m_multicomp = dialog.m_mctCheck->GetValue();\r
+               wxGetApp().m_irreversible = dialog.m_irrevCheck->GetValue();\r
+               wxGetApp().m_resolutions = dialog.m_resolutionsCtrl->GetValue();\r
+               wxGetApp().m_cbsize = dialog.m_cbsizeCtrl->GetValue();\r
+               wxGetApp().m_prsize = dialog.m_prsizeCtrl->GetValue();\r
+               wxGetApp().m_tsize = dialog.m_tsizeCtrl->GetValue();\r
+               wxGetApp().m_torigin = dialog.m_toriginCtrl->GetValue();\r
+               wxGetApp().m_progression = dialog.progressionBox->GetSelection();\r
+               wxGetApp().m_enablesop = dialog.m_sopCheck->GetValue();\r
+               wxGetApp().m_enableeph = dialog.m_ephCheck->GetValue();\r
+               wxGetApp().m_enablebypass = dialog.m_enablebypassCheck->GetValue();\r
+               wxGetApp().m_enablereset = dialog.m_enableresetCheck->GetValue();\r
+               wxGetApp().m_enablerestart = dialog.m_enablerestartCheck->GetValue();\r
+               wxGetApp().m_enablevsc = dialog.m_enablevscCheck->GetValue();\r
+               wxGetApp().m_enableerterm = dialog.m_enableertermCheck->GetValue();\r
+               wxGetApp().m_enablesegmark = dialog.m_enablesegmarkCheck->GetValue();\r
+               wxGetApp().m_enableidx = dialog.m_enableidxCheck->GetValue();\r
+               wxGetApp().m_index = dialog.m_indexCtrl->GetValue();\r
+               wxGetApp().m_enablecomm = dialog.m_enablecommCheck->GetValue();\r
+               wxGetApp().m_comment = dialog.m_commentCtrl->GetValue();\r
+               wxGetApp().m_enablepoc = dialog.m_enablepocCheck->GetValue();\r
+               wxGetApp().m_poc = dialog.m_pocCtrl->GetValue();\r
+#ifdef USE_JPWL\r
+               wxGetApp().m_enablejpwle = dialog.m_enablejpwlCheck->GetValue();\r
+               for (n = 0; n < MYJPWL_MAX_NO_TILESPECS; n++) {\r
+                       wxGetApp().m_hprotsel[n] = dialog.m_hprotChoice[n]->GetSelection();\r
+                       wxGetApp().m_htileval[n] = dialog.m_htileCtrl[n]->GetValue();\r
+                       wxGetApp().m_pprotsel[n] = dialog.m_pprotChoice[n]->GetSelection();\r
+                       wxGetApp().m_ptileval[n] = dialog.m_ptileCtrl[n]->GetValue();\r
+                       wxGetApp().m_ppackval[n] = dialog.m_ppackCtrl[n]->GetValue();\r
+                       wxGetApp().m_sensisel[n] = dialog.m_sensiChoice[n]->GetSelection();\r
+                       wxGetApp().m_stileval[n] = dialog.m_stileCtrl[n]->GetValue();\r
+               }\r
+#endif // USE_JPWL\r
+       };\r
+}\r
+\r
+void OPJFrame::OnSetsDeco(wxCommandEvent& event)\r
+{\r
+    OPJDecoderDialog dialog(this, event.GetId());\r
+\r
+    if (dialog.ShowModal() == wxID_OK) {\r
+\r
+               // load settings\r
+               wxGetApp().m_enabledeco = dialog.m_enabledecoCheck->GetValue();\r
+               wxGetApp().m_enableparse = dialog.m_enableparseCheck->GetValue();\r
+               wxGetApp().m_resizemethod = dialog.m_resizeBox->GetSelection() - 1;\r
+               wxGetApp().m_reducefactor = dialog.m_reduceCtrl->GetValue();\r
+               wxGetApp().m_qualitylayers = dialog.m_layerCtrl->GetValue();\r
+               wxGetApp().m_components = dialog.m_numcompsCtrl->GetValue();\r
+               wxGetApp().m_framenum = dialog.m_framenumCtrl->GetValue();\r
+#ifdef USE_JPWL\r
+               wxGetApp().m_enablejpwl = dialog.m_enablejpwlCheck->GetValue();\r
+               wxGetApp().m_expcomps = dialog.m_expcompsCtrl->GetValue();\r
+               wxGetApp().m_maxtiles = dialog.m_maxtilesCtrl->GetValue();\r
+#endif // USE_JPWL\r
+\r
+       };\r
+}\r
+\r
+void OPJFrame::OnQuit(wxCommandEvent& WXUNUSED(event))\r
+{\r
+       Close(true);\r
+}\r
+\r
+void OPJFrame::OnClose(wxCommandEvent& WXUNUSED(event))\r
+{\r
+       // current frame\r
+       OPJChildFrame *currframe = (OPJChildFrame *) GetActiveChild();\r
+\r
+       if (!currframe)\r
+               return;\r
+\r
+       wxCloseEvent e;\r
+       currframe->OnClose(e);\r
+}\r
+\r
+void OPJFrame::OnFit(wxCommandEvent& event)\r
+{\r
+       OPJChildFrame *currchild;\r
+       wxString eventstring = event.GetString();\r
+\r
+       //wxLogMessage(wxT("OnFit:%d:%s"), event.GetInt(), eventstring);\r
+\r
+       // current child\r
+       if (event.GetInt() >= 1) {\r
+               currchild = m_childhash[event.GetInt()];\r
+       } else {\r
+               currchild = (OPJChildFrame *) GetActiveChild();\r
+       }\r
+\r
+       // problems\r
+       if (!currchild)\r
+               return;\r
+\r
+       // current canvas\r
+       OPJCanvas *currcanvas = currchild->m_canvas;\r
+\r
+       // find a fit-to-width zoom\r
+       /*int zooml, wzooml, hzooml;\r
+       wxSize clientsize = currcanvas->GetClientSize();\r
+       wzooml = (int) ceil(100.0 * (double) (clientsize.GetWidth() - 2 * OPJ_CANVAS_BORDER) / (double) (currcanvas->m_image100.GetWidth()));\r
+       hzooml = (int) ceil(100.0 * (double) (clientsize.GetHeight() - 2 * OPJ_CANVAS_BORDER) / (double) (currcanvas->m_image100.GetHeight()));\r
+       zooml = wxMin(100, wxMin(wzooml, hzooml));*/\r
+\r
+       // fit to width\r
+       Rescale(-1, currchild);\r
+}\r
+\r
+void OPJFrame::OnZoom(wxCommandEvent& WXUNUSED(event))\r
+{\r
+       // current frame\r
+       OPJChildFrame *currframe = (OPJChildFrame *) GetActiveChild();\r
+\r
+       if (!currframe)\r
+               return;\r
+\r
+       // get the preferred zoom\r
+       long zooml = wxGetNumberFromUser(wxT("Choose a scale between 5% and 300%"),\r
+               wxT("Zoom (%)"),\r
+               wxT("Image scale"),\r
+               currframe->m_canvas->m_zooml, 5, 300, NULL, wxDefaultPosition);\r
+\r
+       // rescale current frame image if necessary\r
+       if (zooml >= 5) {\r
+               Rescale(zooml, currframe);\r
+               wxLogMessage(wxT("zoom to %d%%"), zooml);\r
+       }\r
+}\r
+\r
+void OPJFrame::Rescale(int zooml, OPJChildFrame *currframe)\r
+{\r
+       wxImage new_image = currframe->m_canvas->m_image100.ConvertToImage();\r
+\r
+       // resizing enabled?\r
+       if (wxGetApp().m_resizemethod == -1) {\r
+\r
+               zooml = 100;\r
+\r
+       } else {\r
+\r
+               if (zooml < 0) {\r
+                       // find a fit-to-width zoom\r
+                       int wzooml, hzooml;\r
+                       //wxSize clientsize = currframe->m_canvas->GetClientSize();\r
+                       wxSize clientsize = currframe->m_frame->GetActiveChild()->GetClientSize();\r
+                       wzooml = (int) floor(100.0 * (double) clientsize.GetWidth() / (double) (2 * OPJ_CANVAS_BORDER + currframe->m_canvas->m_image100.GetWidth()));\r
+                       hzooml = (int) floor(100.0 * (double) clientsize.GetHeight() / (double) (2 * OPJ_CANVAS_BORDER + currframe->m_canvas->m_image100.GetHeight()));\r
+                       zooml = wxMin(100, wxMin(wzooml, hzooml));\r
+               }\r
+       }\r
+\r
+       if (zooml != 100)\r
+               new_image.Rescale((int) ((double) zooml * (double) new_image.GetWidth() / 100.0),\r
+                       (int) ((double) zooml * (double) new_image.GetHeight() / 100.0),\r
+                       wxGetApp().m_resizemethod ? wxIMAGE_QUALITY_HIGH : wxIMAGE_QUALITY_NORMAL);\r
+       currframe->m_canvas->m_image = wxBitmap(new_image);\r
+       currframe->m_canvas->SetScrollbars(20,\r
+                                                                               20,\r
+                                                                               (int)(0.5 + (double) new_image.GetWidth() / 20.0),\r
+                                                                               (int)(0.5 + (double) new_image.GetHeight() / 20.0)\r
+                                                                               );\r
+\r
+       currframe->m_canvas->Refresh();\r
+\r
+       wxLogMessage(wxT("Rescale said %d%%"), zooml);\r
+\r
+       // update zoom\r
+       currframe->m_canvas->m_zooml = zooml;\r
+}\r
+\r
+\r
+void OPJFrame::OnReload(wxCommandEvent& event)\r
+{\r
+       OPJChildFrame *currframe = (OPJChildFrame *) GetActiveChild();\r
+\r
+       if (currframe) {\r
+               OPJDecoThread *dthread = currframe->m_canvas->CreateDecoThread();\r
+\r
+               if (dthread->Run() != wxTHREAD_NO_ERROR)\r
+                       wxLogMessage(wxT("Can't start deco thread!"));\r
+               else\r
+                       wxLogMessage(wxT("New deco thread started."));\r
+\r
+               currframe->m_canvas->Refresh();\r
+\r
+               // update zoom\r
+               //currframe->m_canvas->m_zooml = zooml;\r
+       }\r
+}\r
+\r
+void OPJFrame::OnPrevFrame(wxCommandEvent& event)\r
+{\r
+       if (--wxGetApp().m_framenum < 0)\r
+               wxGetApp().m_framenum = 0;\r
+\r
+       wxCommandEvent e;\r
+       OnReload(e);\r
+}\r
+\r
+void OPJFrame::OnHomeFrame(wxCommandEvent& event)\r
+{\r
+       wxGetApp().m_framenum = 0;\r
+\r
+       wxCommandEvent e;\r
+       OnReload(e);\r
+}\r
+\r
+void OPJFrame::OnNextFrame(wxCommandEvent& event)\r
+{\r
+       ++wxGetApp().m_framenum;\r
+\r
+       wxCommandEvent e;\r
+       OnReload(e);\r
+}\r
+\r
+void OPJFrame::OnLessLayers(wxCommandEvent& event)\r
+{\r
+       if (--wxGetApp().m_qualitylayers < 1)\r
+               wxGetApp().m_qualitylayers = 1;\r
+\r
+       wxCommandEvent e;\r
+       OnReload(e);\r
+}\r
+\r
+void OPJFrame::OnAllLayers(wxCommandEvent& event)\r
+{\r
+       wxGetApp().m_qualitylayers = 0;\r
+\r
+       wxCommandEvent e;\r
+       OnReload(e);\r
+}\r
+\r
+void OPJFrame::OnMoreLayers(wxCommandEvent& event)\r
+{\r
+       ++wxGetApp().m_qualitylayers;\r
+\r
+       wxCommandEvent e;\r
+       OnReload(e);\r
+}\r
+\r
+void OPJFrame::OnLessRes(wxCommandEvent& event)\r
+{\r
+       ++wxGetApp().m_reducefactor;\r
+\r
+       wxCommandEvent e;\r
+       OnReload(e);\r
+}\r
+\r
+void OPJFrame::OnFullRes(wxCommandEvent& event)\r
+{\r
+       wxGetApp().m_reducefactor = 0;\r
+\r
+       wxCommandEvent e;\r
+       OnReload(e);\r
+}\r
+\r
+void OPJFrame::OnMoreRes(wxCommandEvent& event)\r
+{\r
+       if (--wxGetApp().m_reducefactor < 0)\r
+               wxGetApp().m_reducefactor = 0;\r
+\r
+       wxCommandEvent e;\r
+       OnReload(e);\r
+}\r
+\r
+void OPJFrame::OnPrevComp(wxCommandEvent& event)\r
+{\r
+       if (--wxGetApp().m_components < 1)\r
+               wxGetApp().m_components = 1;\r
+\r
+       wxCommandEvent e;\r
+       OnReload(e);\r
+}\r
+\r
+void OPJFrame::OnAllComps(wxCommandEvent& event)\r
+{\r
+       wxGetApp().m_components = 0;\r
+\r
+       wxCommandEvent e;\r
+       OnReload(e);\r
+}\r
+\r
+void OPJFrame::OnNextComp(wxCommandEvent& event)\r
+{\r
+       ++wxGetApp().m_components;\r
+\r
+       wxCommandEvent e;\r
+       OnReload(e);\r
+}\r
+\r
+void OPJFrame::OnToggleBrowser(wxCommandEvent& WXUNUSED(event))\r
+{\r
+    if (markerTreeWindow->IsShown())\r
+        markerTreeWindow->Show(false);\r
+    else\r
+        markerTreeWindow->Show(true);\r
+\r
+    wxLayoutAlgorithm layout;\r
+    layout.LayoutMDIFrame(this);\r
+\r
+       wxGetApp().m_showbrowser = markerTreeWindow->IsShown();\r
+\r
+    // Leaves bits of itself behind sometimes\r
+    GetClientWindow()->Refresh();\r
+}\r
+\r
+void OPJFrame::OnTogglePeeker(wxCommandEvent& WXUNUSED(event))\r
+{\r
+    if (loggingWindow->IsShown())\r
+        loggingWindow->Show(false);\r
+    else\r
+        loggingWindow->Show(true);\r
+\r
+    wxLayoutAlgorithm layout;\r
+    layout.LayoutMDIFrame(this);\r
+\r
+       wxGetApp().m_showpeeker = loggingWindow->IsShown();\r
+\r
+    // Leaves bits of itself behind sometimes\r
+    GetClientWindow()->Refresh();\r
+}\r
+\r
+void OPJFrame::OnToggleToolbar(wxCommandEvent& WXUNUSED(event))\r
+{\r
+    if (tool_bar->IsShown())\r
+        tool_bar->Show(false);\r
+    else\r
+        tool_bar->Show(true);\r
+\r
+    wxLayoutAlgorithm layout;\r
+    layout.LayoutMDIFrame(this);\r
+\r
+       wxGetApp().m_showtoolbar = tool_bar->IsShown();\r
+\r
+    // Leaves bits of itself behind sometimes\r
+    GetClientWindow()->Refresh();\r
+}\r
+\r
+void OPJFrame::OnSashDrag(wxSashEvent& event)\r
+{\r
+       int wid, hei;\r
+\r
+    if (event.GetDragStatus() == wxSASH_STATUS_OUT_OF_RANGE)\r
+        return;\r
+\r
+    switch (event.GetId()) {\r
+               case OPJFRAME_BROWSEWIN:\r
+               {\r
+                       markerTreeWindow->SetDefaultSize(wxSize(event.GetDragRect().width, 1000));\r
+                       break;\r
+               }\r
+               case OPJFRAME_LOGWIN:\r
+               {\r
+                       loggingWindow->SetDefaultSize(wxSize(1000, event.GetDragRect().height));\r
+                       break;\r
+               }\r
+    }\r
+\r
+    wxLayoutAlgorithm layout;\r
+    layout.LayoutMDIFrame(this);\r
+\r
+    // Leaves bits of itself behind sometimes\r
+    GetClientWindow()->Refresh();\r
+\r
+       // update dimensions\r
+       markerTreeWindow->GetSize(&wid, &hei);\r
+       wxGetApp().m_browserwidth = wid;\r
+\r
+       loggingWindow->GetSize(&wid, &hei);\r
+       wxGetApp().m_peekerheight = hei;\r
+\r
+}\r
+\r
+void OPJFrame::OnThreadLogmsg(wxCommandEvent& event)\r
+{\r
+#if 1\r
+    wxLogMessage(wxT("Frame got message from worker thread: %d"), event.GetInt());\r
+    wxLogMessage(event.GetString());\r
+#else\r
+    int n = event.GetInt();\r
+    if ( n == -1 )\r
+    {\r
+        m_dlgProgress->Destroy();\r
+        m_dlgProgress = (wxProgressDialog *)NULL;\r
+\r
+        // the dialog is aborted because the event came from another thread, so\r
+        // we may need to wake up the main event loop for the dialog to be\r
+        // really closed\r
+        wxWakeUpIdle();\r
+    }\r
+    else\r
+    {\r
+        if ( !m_dlgProgress->Update(n) )\r
+        {\r
+            wxCriticalSectionLocker lock(m_critsectWork);\r
+\r
+            m_cancelled = true;\r
+        }\r
+    }\r
+#endif\r
+}\r
+\r
+\r
+// physically save the file\r
+void OPJFrame::SaveFile(wxArrayString paths, wxArrayString filenames)\r
+{\r
+       size_t count = paths.GetCount();\r
+       wxString msg, s;\r
+\r
+       if (wxFile::Exists(paths[0].c_str())) {\r
+\r
+               s.Printf(wxT("File %s already exists. Do you want to overwrite it?\n"), filenames[0].c_str());\r
+               wxMessageDialog dialog3(this, s, _T("File exists"), wxYES_NO);\r
+               if (dialog3.ShowModal() == wxID_NO)\r
+                       return;\r
+       }\r
+\r
+       /*s.Printf(_T("File %d: %s (%s)\n"), (int)0, paths[0].c_str(), filenames[0].c_str());\r
+       msg += s;\r
+\r
+       wxMessageDialog dialog2(this, msg, _T("Selected files"));\r
+       dialog2.ShowModal();*/\r
+\r
+       if (!GetActiveChild())\r
+               return;\r
+\r
+       ((OPJChildFrame *) GetActiveChild())->m_canvas->m_savename = paths[0];\r
+\r
+       OPJEncoThread *ethread = ((OPJChildFrame *) GetActiveChild())->m_canvas->CreateEncoThread();\r
+\r
+    if (ethread->Run() != wxTHREAD_NO_ERROR)\r
+        wxLogMessage(wxT("Can't start enco thread!"));\r
+    else\r
+               wxLogMessage(wxT("New enco thread started."));\r
+\r
+\r
+}\r
+\r
+// physically open the files\r
+void OPJFrame::OpenFiles(wxArrayString paths, wxArrayString filenames)\r
+{\r
+\r
+       size_t count = paths.GetCount();\r
+       for (size_t n = 0; n < count; n++) {\r
+\r
+               wxString msg, s;\r
+               s.Printf(_T("File %d: %s (%s)\n"), (int)n, paths[n].c_str(), filenames[n].c_str());\r
+\r
+               msg += s;\r
+\r
+               /*wxMessageDialog dialog2(this, msg, _T("Selected files"));\r
+               dialog2.ShowModal();*/\r
+\r
+               // Make another frame, containing a canvas\r
+               OPJChildFrame *subframe = new OPJChildFrame(this,\r
+                                                                                                       paths[n],\r
+                                                                                                       winNumber,\r
+                                                                                                       wxT("Canvas Frame"),\r
+                                                                                                       wxDefaultPosition, wxSize(300, 300),\r
+                                                                                                       wxDEFAULT_FRAME_STYLE | wxNO_FULL_REPAINT_ON_RESIZE\r
+                                                                                                       );\r
+               m_childhash[winNumber] = subframe;\r
+\r
+               // create own marker tree\r
+               m_treehash[winNumber] = new OPJMarkerTree(m_bookCtrl, subframe, paths[n], wxT("Parsing..."), TreeTest_Ctrl,\r
+                                                                                                 wxDefaultPosition, wxDefaultSize,\r
+                                                                                                 wxTR_DEFAULT_STYLE | wxSUNKEN_BORDER\r
+                                                                                                 );\r
+\r
+               m_bookCtrl->AddPage(m_treehash[winNumber], wxString::Format(wxT("%u"), winNumber), false);\r
+\r
+               for (unsigned int p = 0; p < m_bookCtrl->GetPageCount(); p++) {\r
+                       if (m_bookCtrl->GetPageText(p) == wxString::Format(wxT("%u"), winNumber)) {\r
+                               m_bookCtrl->ChangeSelection(p);\r
+                               break;\r
+                       }\r
+               }\r
+\r
+               winNumber++;\r
+       }\r
+}\r
+\r
+void OPJFrame::OnFileOpen(wxCommandEvent& WXUNUSED(event))\r
+{\r
+    wxString wildcards =\r
+#ifdef __WXMOTIF__\r
+       wxT("JPEG 2000 files (*.jp2,*.j2k,*.j2c,*.mj2)|*.*j*2*");\r
+#else\r
+#if wxUSE_LIBOPENJPEG\r
+       wxT("JPEG 2000 files (*.jp2,*.j2k,*.j2c,*.mj2)|*.jp2;*.j2k;*.j2c;*.mj2")\r
+#endif\r
+#if USE_MXF\r
+       wxT("|MXF JPEG 2000 video (*.mxf)|*.mxf")\r
+#endif // USE_MXF\r
+#if wxUSE_LIBJPEG\r
+               wxT("|JPEG files (*.jpg)|*.jpg")\r
+#endif\r
+#if OPJ_MANYFORMATS\r
+               wxT("|BMP files (*.bmp)|*.bmp")\r
+               wxT("|PNG files (*.png)|*.png")\r
+               wxT("|GIF files (*.gif)|*.gif")\r
+               wxT("|PNM files (*.pnm)|*.pnm")\r
+               wxT("|TIFF files (*.tif,*.tiff)|*.tif*")\r
+#endif\r
+               wxT("|All files|*");\r
+#endif\r
+    wxFileDialog dialog(this, _T("Open image file(s)"),\r
+                        wxEmptyString, wxEmptyString, wildcards,\r
+                        wxFD_OPEN|wxFD_MULTIPLE);\r
+\r
+    if (dialog.ShowModal() == wxID_OK) {\r
+        wxArrayString paths, filenames;\r
+\r
+        dialog.GetPaths(paths);\r
+        dialog.GetFilenames(filenames);\r
+\r
+               OpenFiles(paths, filenames);\r
+    }\r
+\r
+}\r
+\r
+void OPJFrame::OnFileSaveAs(wxCommandEvent& WXUNUSED(event))\r
+{\r
+    wxString wildcards =\r
+#ifdef wxUSE_LIBOPENJPEG\r
+#ifdef __WXMOTIF__\r
+       wxT("JPEG 2000 codestream (*.j2k)|*.*j*2*");\r
+#else\r
+       wxT("JPEG 2000 codestream (*.j2k)|*.j2k")\r
+       wxT("|JPEG 2000 file format (*.jp2)|*.jp2");\r
+#endif\r
+#endif\r
+\r
+    wxFileDialog dialog(this, _T("Save image file"),\r
+                        wxEmptyString, wxEmptyString, wildcards,\r
+                        wxFD_SAVE);\r
+\r
+    if (dialog.ShowModal() == wxID_OK) {\r
+        wxArrayString paths, filenames;\r
+\r
+        dialog.GetPaths(paths);\r
+        dialog.GetFilenames(filenames);\r
+\r
+               SaveFile(paths, filenames);\r
+    }\r
+\r
+\r
+}\r
+\r
+void OPJFrame::OnMemoryOpen(wxCommandEvent& WXUNUSED(event))\r
+{\r
+       // do nothing\r
+       return;\r
+       \r
+       wxTextEntryDialog dialog(this, wxT("Memory HEX address range: start_address-stop_address"),\r
+                                                       wxT("Decode a memory buffer"),\r
+                                                       wxT("0x-0x"),\r
+                                                       wxOK | wxCANCEL | wxCENTRE,\r
+                                                       wxDefaultPosition);\r
+\r
+       if (dialog.ShowModal() == wxID_OK) {\r
+\r
+       }\r
+\r
+}\r
+\r
+BEGIN_EVENT_TABLE(OPJCanvas, wxScrolledWindow)\r
+    EVT_MOUSE_EVENTS(OPJCanvas::OnEvent)\r
+    EVT_MENU(OPJCANVAS_THREADSIGNAL, OPJCanvas::OnThreadSignal)\r
+END_EVENT_TABLE()\r
+\r
+// Define a constructor for my canvas\r
+OPJCanvas::OPJCanvas(wxFileName fname, wxWindow *parent, const wxPoint& pos, const wxSize& size)\r
+        : wxScrolledWindow(parent, wxID_ANY, pos, size,\r
+                           wxSUNKEN_BORDER | wxNO_FULL_REPAINT_ON_RESIZE)\r
+{\r
+    SetBackgroundColour(OPJ_CANVAS_COLOUR);\r
+\r
+       m_fname = fname;\r
+       m_childframe = (OPJChildFrame *) parent;\r
+       // 100% zoom\r
+       m_zooml = 100;\r
+\r
+\r
+    OPJDecoThread *dthread = CreateDecoThread();\r
+\r
+    if (dthread->Run() != wxTHREAD_NO_ERROR)\r
+        wxLogMessage(wxT("Can't start deco thread!"));\r
+    else\r
+               wxLogMessage(wxT("New deco thread started."));\r
+\r
+       // 100% zoom\r
+       //m_zooml = 100;\r
+\r
+}\r
+\r
+OPJDecoThread *OPJCanvas::CreateDecoThread(void)\r
+{\r
+    OPJDecoThread *dthread = new OPJDecoThread(this);\r
+\r
+    if (dthread->Create() != wxTHREAD_NO_ERROR)\r
+               wxLogError(wxT("Can't create deco thread!"));\r
+\r
+    wxCriticalSectionLocker enter(wxGetApp().m_deco_critsect);\r
+    wxGetApp().m_deco_threads.Add(dthread);\r
+\r
+    return dthread;\r
+}\r
+\r
+OPJEncoThread *OPJCanvas::CreateEncoThread(void)\r
+{\r
+    OPJEncoThread *ethread = new OPJEncoThread(this);\r
+\r
+    if (ethread->Create() != wxTHREAD_NO_ERROR)\r
+               wxLogError(wxT("Can't create enco thread!"));\r
+\r
+    wxCriticalSectionLocker enter(wxGetApp().m_enco_critsect);\r
+    wxGetApp().m_enco_threads.Add(ethread);\r
+\r
+    return ethread;\r
+}\r
+\r
+#define activeoverlay 0\r
+// Define the repainting behaviour\r
+void OPJCanvas::OnDraw(wxDC& dc)\r
+{\r
+       if (m_image.Ok()) {\r
+               dc.DrawBitmap(m_image, OPJ_CANVAS_BORDER, OPJ_CANVAS_BORDER);\r
+\r
+               if (activeoverlay) {\r
+                       dc.SetPen(*wxRED_PEN);\r
+                       dc.SetBrush(*wxTRANSPARENT_BRUSH);\r
+                       //int tw, th;\r
+                       dc.DrawRectangle(OPJ_CANVAS_BORDER, OPJ_CANVAS_BORDER,\r
+                               (unsigned long int) (0.5 + (double) m_zooml * (double) m_childframe->m_twidth / 100.0),\r
+                               (unsigned long int) (0.5 + (double) m_zooml * (double) m_childframe->m_theight / 100.0));\r
+               }\r
+\r
+       } else {\r
+               dc.SetFont(*wxSWISS_FONT);\r
+               dc.SetPen(*wxBLACK_PEN);\r
+#ifdef __WXGTK__\r
+               dc.DrawText(_T("Decoding image, please wait... (press \"Zoom to Fit\" to show the image)"), 40, 50);\r
+#else\r
+               dc.DrawText(_T("Decoding image, please wait..."), 40, 50);\r
+#endif\r
+       }\r
+}\r
+\r
+// This implements a tiny doodling program! Drag the mouse using\r
+// the left button.\r
+void OPJCanvas::OnEvent(wxMouseEvent& event)\r
+{\r
+#if USE_PENCIL_ON_CANVAS\r
+  wxClientDC dc(this);\r
+  PrepareDC(dc);\r
+\r
+  wxPoint pt(event.GetLogicalPosition(dc));\r
+\r
+  if ((xpos > -1) && (ypos > -1) && event.Dragging()) {\r
+    dc.SetPen(*wxRED_PEN);\r
+    dc.DrawLine(xpos, ypos, pt.x, pt.y);\r
+  }\r
+  xpos = pt.x;\r
+  ypos = pt.y;\r
+#endif\r
+}\r
+\r
+void OPJFrame::OnSize(wxSizeEvent& WXUNUSED(event))\r
+{\r
+    wxLayoutAlgorithm layout;\r
+    layout.LayoutMDIFrame(this);\r
+}\r
+\r
+void OPJCanvas::OnThreadSignal(wxCommandEvent& event)\r
+{\r
+#if 1\r
+    wxLogMessage(wxT("Canvas got signal from deco thread: %d"), event.GetInt());\r
+    wxLogMessage(event.GetString());\r
+#else\r
+    int n = event.GetInt();\r
+    if ( n == -1 )\r
+    {\r
+        m_dlgProgress->Destroy();\r
+        m_dlgProgress = (wxProgressDialog *)NULL;\r
+\r
+        // the dialog is aborted because the event came from another thread, so\r
+        // we may need to wake up the main event loop for the dialog to be\r
+        // really closed\r
+        wxWakeUpIdle();\r
+    }\r
+    else\r
+    {\r
+        if ( !m_dlgProgress->Update(n) )\r
+        {\r
+            wxCriticalSectionLocker lock(m_critsectWork);\r
+\r
+            m_cancelled = true;\r
+        }\r
+    }\r
+#endif\r
+}\r
+\r
+\r
+// Note that OPJFRAME_FILEOPEN and OPJFRAME_HELPABOUT commands get passed\r
+// to the parent window for processing, so no need to\r
+// duplicate event handlers here.\r
+\r
+BEGIN_EVENT_TABLE(OPJChildFrame, wxMDIChildFrame)\r
+  /*EVT_MENU(SASHTEST_CHILD_QUIT, OPJChildFrame::OnQuit)*/\r
+  EVT_CLOSE(OPJChildFrame::OnClose)\r
+  EVT_SET_FOCUS(OPJChildFrame::OnGotFocus)\r
+  EVT_KILL_FOCUS(OPJChildFrame::OnLostFocus)\r
+END_EVENT_TABLE()\r
+\r
+OPJChildFrame::OPJChildFrame(OPJFrame *parent, wxFileName fname, int winnumber, const wxString& title, const wxPoint& pos, const wxSize& size,\r
+const long style):\r
+  wxMDIChildFrame(parent, wxID_ANY, title, pos, size, style)\r
+{\r
+       m_frame = (OPJFrame  *) parent;\r
+       m_canvas = NULL;\r
+       //my_children.Append(this);\r
+       m_fname = fname;\r
+       m_winnumber = winnumber;\r
+       SetTitle(wxString::Format(_T("%d: "), m_winnumber) + m_fname.GetFullName());\r
+\r
+         // Give it an icon (this is ignored in MDI mode: uses resources)\r
+#ifdef __WXMSW__\r
+       SetIcon(wxIcon(wxT("OPJChild16")));\r
+#endif\r
+\r
+       // Give it a status line\r
+       /*CreateStatusBar();*/\r
+\r
+       int width, height;\r
+       GetClientSize(&width, &height);\r
+\r
+       OPJCanvas *canvas = new OPJCanvas(fname, this, wxPoint(0, 0), wxSize(width, height));\r
+#if USE_PENCIL_ON_CANVAS\r
+       canvas->SetCursor(wxCursor(wxCURSOR_PENCIL));\r
+#endif\r
+       m_canvas = canvas;\r
+\r
+       // Give it scrollbars\r
+       canvas->SetScrollbars(20, 20, 5, 5);\r
+\r
+       Show(true);\r
+       Maximize(true);\r
+\r
+       /*wxLogError(wxString::Format(wxT("Created tree %d (0x%x)"), m_winnumber, m_frame->m_treehash[m_winnumber]));*/\r
+\r
+}\r
+\r
+OPJChildFrame::~OPJChildFrame(void)\r
+{\r
+  //my_children.DeleteObject(this);\r
+}\r
+\r
+\r
+void OPJChildFrame::OnClose(wxCloseEvent& event)\r
+{\r
+       for (unsigned int p = 0; p < m_frame->m_bookCtrl->GetPageCount(); p++) {\r
+               if (m_frame->m_bookCtrl->GetPageText(p) == wxString::Format(wxT("%u"), m_winnumber)) {\r
+                       m_frame->m_bookCtrl->DeletePage(p);\r
+                       break;\r
+               }\r
+       }\r
+       Destroy();\r
+\r
+       wxLogMessage(wxT("Closed: %d"), m_winnumber);\r
+}\r
+\r
+void OPJChildFrame::OnActivate(wxActivateEvent& event)\r
+{\r
+  /*if (event.GetActive() && m_canvas)\r
+    m_canvas->SetFocus();*/\r
+}\r
+\r
+void OPJChildFrame::OnGotFocus(wxFocusEvent& event)\r
+{\r
+       // we need to check if the notebook is being destroyed or not\r
+       if (!m_frame->m_bookCtrl)\r
+               return;\r
+\r
+       for (unsigned int p = 0; p < m_frame->m_bookCtrl->GetPageCount(); p++) {\r
+\r
+               if (m_frame->m_bookCtrl->GetPageText(p) == wxString::Format(wxT("%u"), m_winnumber)) {\r
+                       m_frame->m_bookCtrl->ChangeSelection(p);\r
+                       break;\r
+               }\r
+\r
+       }\r
+\r
+       //wxLogMessage(wxT("Got focus: %d (%x)"), m_winnumber, event.GetWindow());\r
+}\r
+\r
+void OPJChildFrame::OnLostFocus(wxFocusEvent& event)\r
+{\r
+       //wxLogMessage(wxT("Lost focus: %d (%x)"), m_winnumber, event.GetWindow());\r
+}\r
+\r
+\r
+////////////////////////////////\r
+// drag and drop \r
+////////////////////////////////\r
+\r
+bool OPJDnDFile::OnDropFiles(wxCoord, wxCoord, const wxArrayString& filenames)\r
+{\r
+    /*size_t nFiles = filenames.GetCount();\r
+    wxString str;\r
+    str.Printf( _T("%d files dropped\n"), (int)nFiles);\r
+    for ( size_t n = 0; n < nFiles; n++ ) {\r
+        str << filenames[n] << wxT("\n");\r
+    }\r
+    wxLogMessage(str);*/\r
+       m_pOwner->OpenFiles(filenames, filenames);\r
+\r
+    return true;\r
+}\r
+\r
diff --git a/applications/OPJViewer/source/OPJViewer.h b/applications/OPJViewer/source/OPJViewer.h
new file mode 100644 (file)
index 0000000..3574dac
--- /dev/null
@@ -0,0 +1,811 @@
+/*\r
+ * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        sashtest.h\r
+// Purpose:     Layout window/sash sample\r
+// Author:      Julian Smart\r
+// Modified by:\r
+// Created:     04/01/98\r
+// RCS-ID:      $Id: sashtest.h,v 1.5 2005/06/02 12:04:24 JS Exp $\r
+// Copyright:   (c) Julian Smart\r
+// Licence:     wxWindows license\r
+/////////////////////////////////////////////////////////////////////////////\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        treectrl.h\r
+// Purpose:     wxTreeCtrl sample\r
+// Author:      Julian Smart\r
+// Modified by:\r
+// Created:     04/01/98\r
+// RCS-ID:      $Id: treetest.h,v 1.50 2006/11/04 11:26:51 VZ Exp $\r
+// Copyright:   (c) Julian Smart\r
+// Licence:     wxWindows license\r
+/////////////////////////////////////////////////////////////////////////////\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        dialogs.h\r
+// Purpose:     Common dialogs demo\r
+// Author:      Julian Smart\r
+// Modified by: ABX (2004) - adjustementd for conditional building\r
+// Created:     04/01/98\r
+// RCS-ID:      $Id: dialogs.h,v 1.50 2006/10/08 14:12:59 VZ Exp $\r
+// Copyright:   (c) Julian Smart\r
+// Licence:     wxWindows license\r
+/////////////////////////////////////////////////////////////////////////////\r
+\r
+#ifndef __OPJ_VIEWER_H__\r
+#define __OPJ_VIEWER_H__\r
+\r
+// For compilers that support precompilation, includes "wx/wx.h".\r
+#include "wx/wxprec.h"\r
+\r
+#ifdef __BORLANDC__\r
+#pragma hdrstop\r
+#endif\r
+\r
+#ifndef WX_PRECOMP\r
+#include "wx/wx.h"\r
+#include "wx/mdi.h"\r
+#endif\r
+\r
+#include "wx/toolbar.h"\r
+#include "wx/laywin.h"\r
+#include "wx/treectrl.h"\r
+\r
+#include "icon1.xpm"\r
+#include "icon2.xpm"\r
+#include "icon3.xpm"\r
+#include "icon4.xpm"\r
+#include "icon5.xpm"\r
+\r
+#include "wx/filedlg.h"\r
+#include "wx/toolbar.h"\r
+#include <wx/filename.h>\r
+#include <wx/busyinfo.h>\r
+#include <wx/cmdline.h>\r
+#include <wx/file.h>\r
+#include "wx/notebook.h"\r
+#include <wx/numdlg.h>\r
+\r
+#include "wx/propdlg.h"\r
+#include "wx/spinctrl.h"\r
+\r
+#include <wx/dnd.h>\r
+#include "wx/wxhtml.h"\r
+#include "wx/statline.h"\r
+#include <wx/fs_mem.h>\r
+\r
+#include <wx/imaglist.h>\r
+\r
+#include "wx/toolbar.h"\r
+#include "wx/artprov.h"\r
+\r
+#include "libopenjpeg/openjpeg.h"\r
+\r
+//#include "imagj2k.h"\r
+//#include "imagjp2.h"\r
+//#include "imagmj2.h"\r
+#include "imagjpeg2000.h"\r
+#ifdef USE_MXF\r
+#include "imagmxf.h"\r
+#endif // USE_MXF\r
+\r
+#ifdef __WXMSW__\r
+typedef unsigned __int64 int8byte;\r
+#endif // __WXMSW__\r
+\r
+#ifdef __WXGTK__\r
+typedef unsigned long long int8byte;\r
+#endif // __WXGTK__\r
+\r
+#define USE_GENERIC_TREECTRL 0\r
+#define USE_PENCIL_ON_CANVAS 0\r
+\r
+#if USE_GENERIC_TREECTRL\r
+#include "wx/generic/treectlg.h"\r
+#ifndef wxTreeCtrl\r
+#define wxTreeCtrl wxGenericTreeCtrl\r
+#define sm_classwxTreeCtrl sm_classwxGenericTreeCtrl\r
+#endif\r
+#endif\r
+\r
+#define OPJ_APPLICATION             wxT("OPJViewer")\r
+#define OPJ_APPLICATION_NAME           wxT("OpenJPEG Viewer")\r
+#define OPJ_APPLICATION_VERSION                wxT("0.4 beta")\r
+#define OPJ_APPLICATION_TITLEBAR       OPJ_APPLICATION_NAME wxT(" ") OPJ_APPLICATION_VERSION\r
+#define OPJ_APPLICATION_COPYRIGHT      wxT("(C) 2007-2008, Giuseppe Baruffa")\r
+#define OPJ_APPLICATION_VENDOR      wxT("OpenJPEG")\r
+\r
+#ifdef __WXMSW__\r
+#define OPJ_APPLICATION_PLATFORM    wxT("Windows")\r
+#endif\r
+\r
+#ifdef __WXGTK__\r
+#define OPJ_APPLICATION_PLATFORM    wxT("Linux")\r
+#endif\r
+\r
+#define OPJ_FRAME_WIDTH   800\r
+#define OPJ_FRAME_HEIGHT  600\r
+\r
+#define OPJ_BROWSER_WIDTH 300\r
+#define OPJ_PEEKER_HEIGHT 130\r
+\r
+#define OPJ_CANVAS_BORDER 10\r
+#define OPJ_CANVAS_COLOUR *wxWHITE\r
+\r
+\r
+\r
+#ifdef USE_JPWL\r
+\r
+//#define MYJPWL_MAX_NO_TILESPECS JPWL_MAX_NO_TILESPECS\r
+#define MYJPWL_MAX_NO_TILESPECS 4\r
+\r
+#endif // USE_JPWL\r
+\r
+\r
+class OPJDecoThread;\r
+class OPJEncoThread;\r
+class OPJParseThread;\r
+WX_DEFINE_ARRAY_PTR(wxThread *, wxArrayThread);\r
+class OPJChildFrame;\r
+\r
+//////////////////////////////////\r
+// this is our main application //\r
+//////////////////////////////////\r
+class OPJViewerApp: public wxApp\r
+{\r
+       // public methods and variables\r
+       public:\r
+\r
+               // class constructor\r
+               OPJViewerApp() { m_showImages = true; m_showButtons = false; }\r
+\r
+               // other methods\r
+               bool OnInit(void);\r
+               int OnExit(void);\r
+               void SetShowImages(bool show) { m_showImages = show; }\r
+               bool ShowImages() const { return m_showImages; }\r
+               void ShowCmdLine(const wxCmdLineParser& parser);\r
+\r
+               // all the threads currently alive - as soon as the thread terminates, it's\r
+               // removed from the array\r
+               wxArrayThread m_deco_threads, m_parse_threads, m_enco_threads;\r
+\r
+               // crit section protects access to all of the arrays below\r
+               wxCriticalSection m_deco_critsect, m_parse_critsect, m_enco_critsect;\r
+\r
+               // semaphore used to wait for the threads to exit, see OPJFrame::OnQuit()\r
+               wxSemaphore m_deco_semAllDone, m_parse_semAllDone, m_enco_semAllDone;\r
+\r
+               // the last exiting thread should post to m_semAllDone if this is true\r
+               // (protected by the same m_critsect)\r
+               bool m_deco_waitingUntilAllDone, m_parse_waitingUntilAllDone, m_enco_waitingUntilAllDone;\r
+\r
+               // the list of all filenames written in the command line\r
+               wxArrayString m_filelist;\r
+\r
+               // displaying engine parameters\r
+               int m_resizemethod;\r
+\r
+               // decoding engine parameters\r
+               bool m_enabledeco, m_enableparse;\r
+               int m_reducefactor, m_qualitylayers, m_components, m_framenum;\r
+#ifdef USE_JPWL\r
+               bool m_enablejpwl, m_enablejpwle;\r
+               int m_expcomps, m_maxtiles;\r
+               int m_framewidth, m_frameheight;\r
+#endif // USE_JPWL\r
+\r
+               // encoding engine parameters\r
+               wxString m_subsampling, m_origin, m_rates, m_comment, m_index, m_quality;\r
+               wxString m_cbsize, m_prsize, m_tsize, m_torigin, m_poc;\r
+               bool m_enablecomm, m_enableidx, m_multicomp, m_irreversible, m_enablesop, m_enableeph;\r
+               bool m_enablebypass, m_enablereset, m_enablerestart, m_enablevsc, m_enableerterm;\r
+               bool m_enablesegmark, m_enablepoc;\r
+               bool m_enablequality;\r
+               int m_resolutions, m_progression;\r
+#ifdef USE_JPWL\r
+               int m_hprotsel[MYJPWL_MAX_NO_TILESPECS], m_pprotsel[MYJPWL_MAX_NO_TILESPECS];\r
+               int m_htileval[MYJPWL_MAX_NO_TILESPECS], m_ptileval[MYJPWL_MAX_NO_TILESPECS],\r
+                       m_ppackval[MYJPWL_MAX_NO_TILESPECS];\r
+               int m_sensisel[MYJPWL_MAX_NO_TILESPECS], m_stileval[MYJPWL_MAX_NO_TILESPECS];\r
+#endif // USE_JPWL\r
+\r
+               // some layout settings\r
+               bool m_showtoolbar, m_showbrowser, m_showpeeker;\r
+               int m_browserwidth, m_peekerheight;\r
+\r
+               // application configuration\r
+               wxConfig *OPJconfig; \r
+\r
+       // private methods and variables\r
+       private:\r
+               bool m_showImages, m_showButtons;\r
+\r
+};\r
+\r
+DECLARE_APP(OPJViewerApp)\r
+\r
+///////////////////////////////////////////\r
+// this canvas is used to draw the image //\r
+///////////////////////////////////////////\r
+class OPJCanvas: public wxScrolledWindow\r
+{\r
+       // public methods and variables\r
+       public:\r
+\r
+               // class constructor\r
+               OPJCanvas(wxFileName fname, wxWindow *parent, const wxPoint& pos, const wxSize& size);\r
+\r
+               virtual void OnDraw(wxDC& dc);\r
+               void OnEvent(wxMouseEvent& event);\r
+               void WriteText(const wxString& text) {\r
+#ifndef __WXGTK__ \r
+                       wxMutexGuiEnter();\r
+#endif //__WXGTK__\r
+                       wxLogMessage(text);\r
+#ifndef __WXGTK__ \r
+                       wxMutexGuiLeave();\r
+#endif //__WXGTK__\r
+               }\r
+\r
+               void OnThreadSignal(wxCommandEvent& event);\r
+\r
+               OPJDecoThread *CreateDecoThread(void);\r
+               OPJEncoThread *CreateEncoThread(void);\r
+\r
+\r
+               OPJChildFrame *m_childframe;\r
+\r
+               wxBitmap  m_image, m_image100;\r
+               wxFileName m_fname, m_savename;\r
+               long m_zooml;\r
+\r
+       DECLARE_EVENT_TABLE()\r
+};\r
+\r
+///////////////////////////////////////////////////\r
+// the data associated to each tree leaf or node //\r
+///////////////////////////////////////////////////\r
+class OPJMarkerData : public wxTreeItemData\r
+{\r
+       // public methods and variables\r
+       public:\r
+\r
+               // class constructor\r
+               OPJMarkerData(const wxString& desc, const wxString& fname = wxT(""), wxFileOffset start = 0, wxFileOffset length = 0) : m_desc(desc), m_filestring(fname) { m_start = start; m_length = length; }\r
+\r
+               void ShowInfo(wxTreeCtrl *tree);\r
+               const wxChar *GetDesc1() const { return m_desc.c_str(); }\r
+               const wxChar *GetDesc2() const { return m_filestring.c_str(); }\r
+               wxFileOffset m_start, m_length;\r
+               wxString m_desc;\r
+\r
+       // private methods and variables\r
+       private:\r
+               wxString m_filestring;\r
+};\r
+\r
+\r
+class OPJMarkerTree : public wxTreeCtrl\r
+{\r
+public:\r
+    enum\r
+    {\r
+        TreeCtrlIcon_File,\r
+        TreeCtrlIcon_FileSelected,\r
+        TreeCtrlIcon_Folder,\r
+        TreeCtrlIcon_FolderSelected,\r
+        TreeCtrlIcon_FolderOpened\r
+    };\r
+\r
+    OPJMarkerTree() { };\r
+    OPJMarkerTree(wxWindow *parent, OPJChildFrame *subframe, wxFileName fname, wxString name, const wxWindowID id,\r
+               const wxPoint& pos, const wxSize& size,\r
+               long style);\r
+    virtual ~OPJMarkerTree(){};\r
+       OPJParseThread *CreateParseThread(wxTreeItemId parentid = 0x00, OPJChildFrame *subframe = NULL);\r
+    void WriteText(const wxString& text) { wxMutexGuiEnter(); wxLogMessage(text); wxMutexGuiLeave(); }\r
+\r
+       wxFileName m_fname;\r
+       wxTextCtrl *m_peektextCtrl;\r
+       OPJChildFrame *m_childframe;\r
+\r
+    /*void OnBeginDrag(wxTreeEvent& event);\r
+    void OnBeginRDrag(wxTreeEvent& event);\r
+    void OnEndDrag(wxTreeEvent& event);*/\r
+    /*void OnBeginLabelEdit(wxTreeEvent& event);\r
+    void OnEndLabelEdit(wxTreeEvent& event);*/\r
+    /*void OnDeleteItem(wxTreeEvent& event);*/\r
+    /*void OnContextMenu(wxContextMenuEvent& event);*/\r
+    void OnItemMenu(wxTreeEvent& event);\r
+    /*void OnGetInfo(wxTreeEvent& event);\r
+    void OnSetInfo(wxTreeEvent& event);*/\r
+    /*void OnItemExpanded(wxTreeEvent& event);*/\r
+    void OnItemExpanding(wxTreeEvent& event);\r
+    /*void OnItemCollapsed(wxTreeEvent& event);\r
+    void OnItemCollapsing(wxTreeEvent& event);*/\r
+    void OnSelChanged(wxTreeEvent& event);\r
+    /*void OnSelChanging(wxTreeEvent& event);*/\r
+    /*void OnTreeKeyDown(wxTreeEvent& event);*/\r
+    /*void OnItemActivated(wxTreeEvent& event);*/\r
+    /*void OnItemRClick(wxTreeEvent& event);*/\r
+    /*void OnRMouseDown(wxMouseEvent& event);\r
+    void OnRMouseUp(wxMouseEvent& event);\r
+    void OnRMouseDClick(wxMouseEvent& event);*/\r
+    /*void GetItemsRecursively(const wxTreeItemId& idParent,\r
+                             wxTreeItemIdValue cookie = 0);*/\r
+\r
+    void CreateImageList(int size = 16);\r
+    void CreateButtonsImageList(int size = 11);\r
+\r
+    /*void AddTestItemsToTree(size_t numChildren, size_t depth);*/\r
+    /*void DoSortChildren(const wxTreeItemId& item, bool reverse = false)\r
+        { m_reverseSort = reverse; wxTreeCtrl::SortChildren(item); }*/\r
+    /*void DoEnsureVisible() { if (m_lastItem.IsOk()) EnsureVisible(m_lastItem); }*/\r
+    /*void DoToggleIcon(const wxTreeItemId& item);*/\r
+    /*void ShowMenu(wxTreeItemId id, const wxPoint& pt);*/\r
+\r
+    int ImageSize(void) const { return m_imageSize; }\r
+\r
+    void SetLastItem(wxTreeItemId id) { m_lastItem = id; }\r
+\r
+protected:\r
+    /*virtual int OnCompareItems(const wxTreeItemId& i1, const wxTreeItemId& i2);*/\r
+\r
+    // is this the test item which we use in several event handlers?\r
+    /*bool IsTestItem(const wxTreeItemId& item)\r
+    {\r
+        // the test item is the first child folder\r
+        return GetItemParent(item) == GetRootItem() && !GetPrevSibling(item);\r
+    }*/\r
+\r
+private:\r
+    /*void AddItemsRecursively(const wxTreeItemId& idParent,\r
+                             size_t nChildren,\r
+                             size_t depth,\r
+                             size_t folder);*/\r
+\r
+    void LogEvent(const wxChar *name, const wxTreeEvent& event);\r
+\r
+    int          m_imageSize;               // current size of images\r
+    bool         m_reverseSort;             // flag for OnCompareItems\r
+    wxTreeItemId m_lastItem,                // for OnEnsureVisible()\r
+                 m_draggedItem;             // item being dragged right now\r
+\r
+    // NB: due to an ugly wxMSW hack you _must_ use DECLARE_DYNAMIC_CLASS()\r
+    //     if you want your overloaded OnCompareItems() to be called.\r
+    //     OTOH, if you don't want it you may omit the next line - this will\r
+    //     make default (alphabetical) sorting much faster under wxMSW.\r
+    DECLARE_DYNAMIC_CLASS(OPJMarkerTree)\r
+    DECLARE_EVENT_TABLE()\r
+};\r
+\r
+// this hash map stores all the trees of currently opened images, with an integer key\r
+WX_DECLARE_HASH_MAP(int, OPJMarkerTree*, wxIntegerHash, wxIntegerEqual, OPJMarkerTreeHash);\r
+\r
+// this hash map stores all the children of currently opened images, with an integer key\r
+WX_DECLARE_HASH_MAP(int, OPJChildFrame*, wxIntegerHash, wxIntegerEqual, OPJChildFrameHash);\r
+\r
+// Define a new frame\r
+class OPJFrame: public wxMDIParentFrame\r
+{\r
+  public:\r
+\r
+    OPJFrame(wxWindow *parent, const wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, const long style);\r
+\r
+    ~OPJFrame(void);\r
+       void OnSize(wxSizeEvent& WXUNUSED(event));\r
+    void OnAbout(wxCommandEvent& WXUNUSED(event));\r
+    void OnFileOpen(wxCommandEvent& WXUNUSED(event));\r
+    void OnFileSaveAs(wxCommandEvent& WXUNUSED(event));\r
+    void OnMemoryOpen(wxCommandEvent& WXUNUSED(event));\r
+    void OnQuit(wxCommandEvent& WXUNUSED(event));\r
+    void OnClose(wxCommandEvent& WXUNUSED(event));\r
+    void OnZoom(wxCommandEvent& WXUNUSED(event));\r
+       void OnFit(wxCommandEvent& event);\r
+       void OnToggleBrowser(wxCommandEvent& WXUNUSED(event));\r
+       void OnTogglePeeker(wxCommandEvent& WXUNUSED(event));\r
+       void OnToggleToolbar(wxCommandEvent& WXUNUSED(event));\r
+       void OnReload(wxCommandEvent& event);\r
+       void OnPrevFrame(wxCommandEvent& event);\r
+       void OnHomeFrame(wxCommandEvent& event);\r
+       void OnNextFrame(wxCommandEvent& event);\r
+       void OnLessLayers(wxCommandEvent& event);\r
+       void OnAllLayers(wxCommandEvent& event);\r
+       void OnMoreLayers(wxCommandEvent& event);\r
+       void OnLessRes(wxCommandEvent& event);\r
+       void OnFullRes(wxCommandEvent& event);\r
+       void OnMoreRes(wxCommandEvent& event);\r
+       void OnPrevComp(wxCommandEvent& event);\r
+       void OnAllComps(wxCommandEvent& event);\r
+       void OnNextComp(wxCommandEvent& event);\r
+       void OnSetsEnco(wxCommandEvent& event);\r
+       void OnSetsDeco(wxCommandEvent& event);\r
+       void OnSashDrag(wxSashEvent& event);\r
+       void OpenFiles(wxArrayString paths, wxArrayString filenames);\r
+       void SaveFile(wxArrayString paths, wxArrayString filenames);\r
+       void OnNotebook(wxNotebookEvent& event);\r
+       void Rescale(int scale, OPJChildFrame *child);\r
+       void OnThreadLogmsg(wxCommandEvent& event);\r
+\r
+       OPJMarkerTreeHash m_treehash;\r
+       OPJChildFrameHash m_childhash;\r
+    wxSashLayoutWindow* markerTreeWindow;\r
+    wxSashLayoutWindow* loggingWindow;\r
+       wxToolBar* tool_bar;\r
+    void Resize(int number);\r
+       wxNotebook *m_bookCtrl;\r
+       wxNotebook *m_bookCtrlbottom;\r
+    wxTextCtrl *m_textCtrlbrowse;\r
+\r
+  private:\r
+    void TogStyle(int id, long flag);\r
+\r
+    void DoSort(bool reverse = false);\r
+\r
+    wxPanel *m_panel;\r
+    wxTextCtrl *m_textCtrl;\r
+\r
+    void DoSetBold(bool bold = true);\r
+\r
+protected:\r
+    wxSashLayoutWindow* m_topWindow;\r
+    wxSashLayoutWindow* m_leftWindow2;\r
+\r
+DECLARE_EVENT_TABLE()\r
+};\r
+\r
+class OPJChildFrame: public wxMDIChildFrame\r
+{\r
+  public:\r
+    OPJCanvas *m_canvas;\r
+    OPJChildFrame(OPJFrame *parent, wxFileName fname, int winnumber, const wxString& title, const wxPoint& pos, const wxSize& size, const long style);\r
+    ~OPJChildFrame(void);\r
+    void OnActivate(wxActivateEvent& event);\r
+       /*void OnQuit(wxCommandEvent& WXUNUSED(event));*/\r
+       void OnClose(wxCloseEvent& event);\r
+       void OnGotFocus(wxFocusEvent& event);\r
+       void OnLostFocus(wxFocusEvent& event);\r
+    OPJFrame *m_frame;\r
+       wxFileName m_fname;\r
+       int m_winnumber;\r
+\r
+       unsigned long  m_twidth, m_theight, m_tx, m_ty;\r
+\r
+       DECLARE_EVENT_TABLE()\r
+};\r
+\r
+// frame and main menu ids\r
+enum {\r
+       OPJFRAME_FILEEXIT = wxID_EXIT,\r
+       OPJFRAME_HELPABOUT = wxID_ABOUT,\r
+       OPJFRAME_FILEOPEN,\r
+       OPJFRAME_MEMORYOPEN,\r
+       OPJFRAME_FILESAVEAS,\r
+       OPJFRAME_FILETOGGLEB,\r
+       OPJFRAME_FILETOGGLEP,\r
+       OPJFRAME_FILETOGGLET,\r
+       OPJFRAME_VIEWZOOM,\r
+       OPJFRAME_VIEWFIT,\r
+       OPJFRAME_VIEWRELOAD,\r
+       OPJFRAME_VIEWPREVFRAME,\r
+       OPJFRAME_VIEWHOMEFRAME,\r
+       OPJFRAME_VIEWNEXTFRAME,\r
+       OPJFRAME_VIEWLESSLAYERS,\r
+       OPJFRAME_VIEWALLLAYERS,\r
+       OPJFRAME_VIEWMORELAYERS,\r
+       OPJFRAME_VIEWLESSRES,\r
+       OPJFRAME_VIEWFULLRES,\r
+       OPJFRAME_VIEWMORERES,\r
+       OPJFRAME_VIEWPREVCOMP,\r
+       OPJFRAME_VIEWALLCOMPS,\r
+       OPJFRAME_VIEWNEXTCOMP,\r
+       OPJFRAME_FILECLOSE,\r
+       OPJFRAME_SETSENCO,\r
+       OPJFRAME_SETSDECO,\r
+\r
+       OPJFRAME_BROWSEWIN = 10000,\r
+       OPJFRAME_LOGWIN,\r
+       OPJFRAME_TOOLBAR,\r
+\r
+       OPJFRAME_THREADLOGMSG,\r
+       OPJCANVAS_THREADSIGNAL\r
+};\r
+\r
+\r
+// menu and control ids\r
+enum\r
+{\r
+    TreeTest_Quit = wxID_EXIT,\r
+    TreeTest_About = wxID_ABOUT,\r
+    TreeTest_TogButtons = wxID_HIGHEST,\r
+    TreeTest_TogTwist,\r
+    TreeTest_TogLines,\r
+    TreeTest_TogEdit,\r
+    TreeTest_TogHideRoot,\r
+    TreeTest_TogRootLines,\r
+    TreeTest_TogBorder,\r
+    TreeTest_TogFullHighlight,\r
+    TreeTest_SetFgColour,\r
+    TreeTest_SetBgColour,\r
+    TreeTest_ResetStyle,\r
+    TreeTest_Highlight,\r
+    TreeTest_Dump,\r
+    TreeTest_DumpSelected,\r
+    TreeTest_Count,\r
+    TreeTest_CountRec,\r
+    TreeTest_Sort,\r
+    TreeTest_SortRev,\r
+    TreeTest_SetBold,\r
+    TreeTest_ClearBold,\r
+    TreeTest_Rename,\r
+    TreeTest_Delete,\r
+    TreeTest_DeleteChildren,\r
+    TreeTest_DeleteAll,\r
+    TreeTest_Recreate,\r
+    TreeTest_ToggleImages,\r
+    TreeTest_ToggleButtons,\r
+    TreeTest_SetImageSize,\r
+    TreeTest_ToggleSel,\r
+    TreeTest_CollapseAndReset,\r
+    TreeTest_EnsureVisible,\r
+    TreeTest_AddItem,\r
+    TreeTest_InsertItem,\r
+    TreeTest_IncIndent,\r
+    TreeTest_DecIndent,\r
+    TreeTest_IncSpacing,\r
+    TreeTest_DecSpacing,\r
+    TreeTest_ToggleIcon,\r
+    TreeTest_Select,\r
+    TreeTest_Unselect,\r
+    TreeTest_SelectRoot,\r
+    TreeTest_Ctrl = 1000,\r
+       BOTTOM_NOTEBOOK_ID,\r
+       LEFT_NOTEBOOK_ID\r
+};\r
+\r
+class OPJEncoThread : public wxThread\r
+{\r
+public:\r
+    OPJEncoThread(OPJCanvas *canvas);\r
+\r
+    // thread execution starts here\r
+    virtual void *Entry();\r
+\r
+    // called when the thread exits - whether it terminates normally or is\r
+    // stopped with Delete() (but not when it is Kill()ed!)\r
+    virtual void OnExit();\r
+\r
+    // write something to the text control\r
+    void WriteText(const wxString& text);\r
+\r
+public:\r
+    unsigned m_count;\r
+    OPJCanvas *m_canvas;\r
+};\r
+\r
+class OPJDecoThread : public wxThread\r
+{\r
+public:\r
+    OPJDecoThread(OPJCanvas *canvas);\r
+\r
+    // thread execution starts here\r
+    virtual void *Entry();\r
+\r
+    // called when the thread exits - whether it terminates normally or is\r
+    // stopped with Delete() (but not when it is Kill()ed!)\r
+    virtual void OnExit();\r
+\r
+    // write something to the text control\r
+    void WriteText(const wxString& text);\r
+\r
+public:\r
+    unsigned m_count;\r
+    OPJCanvas *m_canvas;\r
+};\r
+\r
+class OPJParseThread : public wxThread\r
+{\r
+public:\r
+    OPJParseThread(OPJMarkerTree *tree, wxTreeItemId parentid = 0x00);\r
+\r
+    // thread execution starts here\r
+    virtual void *Entry();\r
+\r
+    // called when the thread exits - whether it terminates normally or is\r
+    // stopped with Delete() (but not when it is Kill()ed!)\r
+    virtual void OnExit();\r
+\r
+    // write something to the text control\r
+    void WriteText(const wxString& text);\r
+       void LoadFile(wxFileName fname);\r
+       void ParseJ2KFile(wxFile *m_file, wxFileOffset offset, wxFileOffset length, wxTreeItemId parentid);\r
+       void ParseJP2File(wxFile *fileid, wxFileOffset filepoint, wxFileOffset filelimit, wxTreeItemId parentid);\r
+\r
+    unsigned m_count;\r
+    OPJMarkerTree *m_tree;\r
+       wxTreeItemId m_parentid;\r
+\r
+private:\r
+       int jpeg2000parse(wxFile *fileid, wxFileOffset filepoint, wxFileOffset filelimit,\r
+                       wxTreeItemId parentid, int level, char *scansign, unsigned long int *scanpoint);\r
+       int box_handler_function(int boxtype, wxFile *fileid, wxFileOffset filepoint, wxFileOffset filelimit,\r
+                       wxTreeItemId parentid, int level, char *scansign, unsigned long int *scanpoint);\r
+\r
+};\r
+\r
+\r
+// Drag and drop files target\r
+class OPJDnDFile: public wxFileDropTarget\r
+{\r
+public:\r
+    OPJDnDFile(OPJFrame *pOwner) { m_pOwner = pOwner; }\r
+    virtual bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames);\r
+\r
+private:\r
+    OPJFrame *m_pOwner;\r
+};\r
+\r
+\r
+\r
+// Property sheet dialog: encoder\r
+class OPJEncoderDialog: public wxPropertySheetDialog\r
+{\r
+DECLARE_CLASS(OPJEncoderDialog)\r
+public:\r
+    OPJEncoderDialog(wxWindow* parent, int dialogType);\r
+    ~OPJEncoderDialog();\r
+\r
+       wxBookCtrlBase* m_settingsNotebook;\r
+\r
+    wxPanel* CreateMainSettingsPage(wxWindow* parent);\r
+    wxPanel* CreatePart1_1SettingsPage(wxWindow* parent);\r
+    wxPanel* CreatePart1_2SettingsPage(wxWindow* parent);\r
+/*    wxPanel* CreatePart3SettingsPage(wxWindow* parent);*/\r
+       void OnEnableComm(wxCommandEvent& event);\r
+       void OnEnableIdx(wxCommandEvent& event);\r
+       void OnEnablePoc(wxCommandEvent& event);\r
+       void OnRadioQualityRate(wxCommandEvent& event);\r
+#ifdef USE_JPWL\r
+       void OnEnableJPWL(wxCommandEvent& event);\r
+       wxPanel* CreatePart11SettingsPage(wxWindow* parent);\r
+       /*wxCheckBox *m_enablejpwlCheck;*/\r
+       wxChoice *m_hprotChoice[MYJPWL_MAX_NO_TILESPECS];\r
+       wxSpinCtrl *m_htileCtrl[MYJPWL_MAX_NO_TILESPECS];\r
+       wxChoice *m_pprotChoice[MYJPWL_MAX_NO_TILESPECS];\r
+       wxSpinCtrl *m_ptileCtrl[MYJPWL_MAX_NO_TILESPECS];\r
+       wxSpinCtrl *m_ppackCtrl[MYJPWL_MAX_NO_TILESPECS];\r
+       wxChoice *m_sensiChoice[MYJPWL_MAX_NO_TILESPECS];\r
+       wxSpinCtrl *m_stileCtrl[MYJPWL_MAX_NO_TILESPECS];\r
+       void OnHprotSelect(wxCommandEvent& event);\r
+       void OnPprotSelect(wxCommandEvent& event);\r
+       void OnSensiSelect(wxCommandEvent& event);\r
+#endif // USE_JPWL\r
+\r
+       wxTextCtrl *m_subsamplingCtrl, *m_originCtrl, *m_rateCtrl, *m_commentCtrl;\r
+       wxRadioButton *m_rateRadio, *m_qualityRadio;\r
+       wxTextCtrl *m_indexCtrl, *m_qualityCtrl, *m_cbsizeCtrl, *m_prsizeCtrl, *m_pocCtrl;\r
+       wxTextCtrl *m_tsizeCtrl, *m_toriginCtrl;\r
+       wxRadioBox *progressionBox;\r
+       wxCheckBox *m_enablecommCheck, *m_enableidxCheck, *m_mctCheck, *m_irrevCheck;\r
+       wxCheckBox *m_sopCheck, *m_ephCheck, *m_enablebypassCheck, *m_enableresetCheck,\r
+               *m_enablerestartCheck, *m_enablevscCheck, *m_enableertermCheck, *m_enablesegmarkCheck;\r
+       wxCheckBox *m_enablepocCheck, *m_enablejpwlCheck;\r
+       wxSpinCtrl *m_resolutionsCtrl;\r
+\r
+protected:\r
+\r
+    enum {\r
+               OPJENCO_ENABLEJPWL = 100,\r
+               OPJENCO_RATEFACTOR,\r
+               OPJENCO_RATERADIO,\r
+               OPJENCO_QUALITYFACTOR,\r
+               OPJENCO_QUALITYRADIO,\r
+               OPJENCO_RESNUMBER,\r
+               OPJENCO_CODEBLOCKSIZE,\r
+               OPJENCO_PRECINCTSIZE,\r
+               OPJENCO_TILESIZE,\r
+               OPJENCO_PROGRESSION,\r
+               OPJENCO_SUBSAMPLING,\r
+               OPJENCO_ENABLESOP,\r
+               OPJENCO_ENABLEEPH,\r
+               OPJENCO_ENABLEBYPASS,\r
+               OPJENCO_ENABLERESET,\r
+               OPJENCO_ENABLERESTART,\r
+               OPJENCO_ENABLEVSC,\r
+               OPJENCO_ENABLEERTERM,\r
+               OPJENCO_ENABLESEGMARK,\r
+               OPJENCO_ENABLEPOC,\r
+               OPJENCO_ROICOMP,\r
+               OPJENCO_ROISHIFT,\r
+               OPJENCO_IMORIG,\r
+               OPJENCO_TILORIG,\r
+               OPJENCO_ENABLEMCT,\r
+               OPJENCO_ENABLEIRREV,\r
+               OPJENCO_ENABLEINDEX,\r
+               OPJENCO_INDEXNAME,\r
+               OPJENCO_POCSPEC,\r
+               OPJENCO_ENABLECOMM,\r
+               OPJENCO_COMMENTTEXT,\r
+               OPJENCO_HPROT,\r
+               OPJENCO_HTILE,\r
+               OPJENCO_PPROT,\r
+               OPJENCO_PTILE,\r
+               OPJENCO_PPACK,\r
+               OPJENCO_SENSI,\r
+               OPJENCO_STILE\r
+    };\r
+\r
+DECLARE_EVENT_TABLE()\r
+};\r
+\r
+// Property sheet dialog: decoder\r
+class OPJDecoderDialog: public wxPropertySheetDialog\r
+{\r
+DECLARE_CLASS(OPJDecoderDialog)\r
+public:\r
+    OPJDecoderDialog(wxWindow* parent, int dialogType);\r
+    ~OPJDecoderDialog();\r
+\r
+       wxBookCtrlBase* m_settingsNotebook;\r
+       wxCheckBox *m_enabledecoCheck, *m_enableparseCheck;\r
+       wxSpinCtrl *m_reduceCtrl, *m_layerCtrl, *m_numcompsCtrl;\r
+       wxRadioBox* m_resizeBox;\r
+\r
+       void OnEnableDeco(wxCommandEvent& event);\r
+\r
+    wxPanel* CreateMainSettingsPage(wxWindow* parent);\r
+    wxPanel* CreatePart1SettingsPage(wxWindow* parent);\r
+    wxPanel* CreatePart3SettingsPage(wxWindow* parent);\r
+#ifdef USE_JPWL\r
+       void OnEnableJPWL(wxCommandEvent& event);\r
+    wxPanel* CreatePart11SettingsPage(wxWindow* parent);\r
+       wxSpinCtrl *m_expcompsCtrl, *m_framenumCtrl, *m_maxtilesCtrl;\r
+       wxCheckBox *m_enablejpwlCheck;\r
+#endif // USE_JPWL\r
+\r
+\r
+protected:\r
+\r
+    enum {\r
+               OPJDECO_RESMETHOD = 100,\r
+               OPJDECO_REDUCEFACTOR,\r
+               OPJDECO_QUALITYLAYERS,\r
+               OPJDECO_NUMCOMPS,\r
+               OPJDECO_ENABLEDECO,\r
+               OPJDECO_ENABLEPARSE,\r
+               OPJDECO_ENABLEJPWL,\r
+               OPJDECO_EXPCOMPS,\r
+               OPJDECO_MAXTILES,\r
+               OPJDECO_FRAMENUM\r
+    };\r
+\r
+DECLARE_EVENT_TABLE()\r
+};\r
+\r
+#endif //__OPJ_VIEWER_H__\r
+\r
+\r
+\r
diff --git a/applications/OPJViewer/source/OPJViewer.ico b/applications/OPJViewer/source/OPJViewer.ico
new file mode 100644 (file)
index 0000000..931d5e0
Binary files /dev/null and b/applications/OPJViewer/source/OPJViewer.ico differ
diff --git a/applications/OPJViewer/source/OPJViewer.rc b/applications/OPJViewer/source/OPJViewer.rc
new file mode 100644 (file)
index 0000000..fb5a5de
--- /dev/null
@@ -0,0 +1,3 @@
+OPJChild16 ICON OPJChild.ico\r
+OPJViewer16 ICON OPJViewer.ico\r
+#include "wx/msw/wx.rc"
\ No newline at end of file
diff --git a/applications/OPJViewer/source/OPJViewer16.xpm b/applications/OPJViewer/source/OPJViewer16.xpm
new file mode 100644 (file)
index 0000000..27e522b
--- /dev/null
@@ -0,0 +1,26 @@
+/* XPM */\r
+static char *OPJViewer16[] = {\r
+/* columns rows colors chars-per-pixel */\r
+"16 16 4 1",\r
+"  c black",\r
+". c #800000",\r
+"X c red",\r
+"o c None",\r
+/* pixels */\r
+"oooooooooooooooo",\r
+"ooo.XXXXoooooooo",\r
+"ooXXoo .Xooooooo",\r
+"o..oooo .ooooooo",\r
+"oX.oooo  ooooooo",\r
+"oX.oooo .ooooooo",\r
+"oXXoooo .ooooooo",\r
+"o.XXoo .oooooooo",\r
+"oo.XXXXooooooooo",\r
+"ooooooooo.Xo .oo",\r
+"ooooooooo X. ooo",\r
+"oooooooooo...ooo",\r
+"oooooooooo XXooo",\r
+"oooooooooo .Xooo",\r
+"oooooooooooooooo",\r
+"oooooooooooooooo"\r
+};\r
diff --git a/applications/OPJViewer/source/about_htm.h b/applications/OPJViewer/source/about_htm.h
new file mode 100644 (file)
index 0000000..c39fdc5
--- /dev/null
@@ -0,0 +1,54 @@
+wxString htmlaboutpage = wxT(\r
+"<html>"\r
+"<body bgcolor=#FFFFFF>"\r
+"<table cellspacing=7 cellpadding=1 border=0 width=100%>"   \r
+"<tr>"\r
+"<td rowspan=3 valign=top align=center width=70>"\r
+"<img src=\"memory:opj_logo.xpm\"><br><br>" \r
+"</td>"\r
+"<td align=center>"\r
+"<font size=+0 color=#000000><b>" \r
+OPJ_APPLICATION " " OPJ_APPLICATION_VERSION \r
+"</b></font><br>"\r
+"<font size=-1 color=#000000><b>A JPEG 2000 image viewer</b></font><br>"  \r
+"<font size=-2 color=#000000><b>" OPJ_APPLICATION_PLATFORM " version</b></font>"  \r
+"</td>"\r
+"</tr>"\r
+"<tr height=3 valign=center>"  \r
+"<td valign=center  bgcolor=#cc3300></td>"   \r
+"</tr>"\r
+"<tr>"\r
+"<td align=justify>"\r
+"<center><font size=+0 color=#000000><a href=\"http://www.openjpeg.org/\">OpenJPEG</a></font></center>"\r
+"<p><font size=-1 color=#000000>The OpenJPEG library is an open-source JPEG 2000 codec written in C language. "\r
+"In addition to the basic codec, various other features are under development.</font></p><br>"\r
+"<font size=-2 color=red>* Build: ")\r
+#include "build.h"\r
+wxT(", " __DATE__ ", " __TIME__ "</font><br>")\r
+wxT("<font size=-2 color=red>* " wxVERSION_STRING "</font><br>")\r
+wxT("<font size=-2 color=red>* OpenJPEG " OPENJPEG_VERSION " (")\r
+#ifdef USE_JPWL\r
+wxT("<font size=-2 color=green>JPWL</font> ")\r
+#endif // USE_JPWL\r
+#ifdef USE_JPSEC\r
+wxT("<font size=-2 color=green>JPSEC</font> ")\r
+#endif // USE_JPSEC\r
+wxT(")</font><br>")\r
+#ifdef USE_MXF\r
+wxT("<font size=-2 color=red>* MXFLib " MXFLIB_VERSION_MAJOR "." MXFLIB_VERSION_MINOR "." MXFLIB_VERSION_TWEAK " (" MXFLIB_VERSION_BUILD ")</font><br>")\r
+#endif // USE_MXF\r
+wxT("</td>"\r
+"</tr>"\r
+"<tr>"\r
+"<td colspan=2 bgcolor=#CC3300 height=3 valign=center></td>" \r
+"</tr>"\r
+"<tr>"\r
+"<td colspan=2>"\r
+"<font size=-2 color=#444444>OpenJPEG is &copy; 2002-2008 <a href=\"http://www.tele.ucl.ac.be/\">TELE</a> - <a href=\"http://www.uclouvain.be/\">Universite' Catholique de Louvain</a></font><br>"\r
+"<font size=-2 color=#444444>OPJViewer is &copy; 2007-2008 <a href=\"http://dsplab.diei.unipg.it/\">DSPLab</a> - <a href=\"http://www.unipg.it/\">Universita' degli studi di Perugia</a></font>"\r
+"</td>"\r
+"</tr>"\r
+"</table>"\r
+"</body>"\r
+"</html>"\r
+);\r
diff --git a/applications/OPJViewer/source/build.h b/applications/OPJViewer/source/build.h
new file mode 100644 (file)
index 0000000..9858dff
--- /dev/null
@@ -0,0 +1 @@
+wxT("491") \r
diff --git a/applications/OPJViewer/source/icon1.xpm b/applications/OPJViewer/source/icon1.xpm
new file mode 100644 (file)
index 0000000..fbc605b
--- /dev/null
@@ -0,0 +1,79 @@
+/* XPM */
+static char *icon1_xpm[] = {
+/* columns rows colors chars-per-pixel */
+"32 32 41 1",
+"> c #97C4E7",
+"# c #4381AA",
+"d c #FFFFFF",
+"< c #71B2DE",
+"+ c #538BB1",
+"& c #D1E5F5",
+"q c #63B3DE",
+"6 c #F1F4F7",
+"* c #CAE1F3",
+"y c #7AC4E5",
+"= c #C3DDF1",
+"X c #74A1BD",
+"- c #BCD9EF",
+"5 c #619BC4",
+"3 c #E6EAF1",
+"2 c #4B8EBF",
+"o c #6B97B6",
+". c #4B82A8",
+"  c None",
+"w c #54A6D8",
+"1 c #71A8D1",
+", c #85BBE2",
+"t c #EFF6FC",
+"7 c #DEEDF8",
+"@ c #4388B4",
+"a c #F7FBFD",
+"$ c #D7E0E9",
+"r c #FAFCFE",
+"4 c #DAEAF7",
+"e c #E9F3FA",
+"0 c #76BAE2",
+"% c #7FA6C0",
+"s c #FDFDFE",
+"O c #5896BE",
+"p c #B6D5EE",
+"8 c #87ABC3",
+": c #A5CCEA",
+"9 c #E5F0F9",
+"; c #AFD1EC",
+"i c #F4F9FD",
+"u c #8FB0C3",
+/* pixels */
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"        .XXXooOO++@#$           ",
+"        %&*=-;:>>,<123          ",
+"        %4&*=-;:>>,1>56         ",
+"        %74&*=-;:>>1*>56        ",
+"        89700qqqqwq1e*>X        ",
+"        8e974&*=-;:1re*>8       ",
+"        8te974&*=-;11111#       ",
+"        8tty000qqqqqww>,+       ",
+"        uitte974&*=-p:>>+       ",
+"        uaitte974&*=-p:>O       ",
+"        uaayyyy000qqqqp:O       ",
+"        uraaitte974&*=-po       ",
+"        urraaitte974&*=-o       ",
+"        usryyyyyyy000q*=X       ",
+"        ussrraaitte974&*X       ",
+"        udssrraaitte974&X       ",
+"        uddyyyyyyyyyy074%       ",
+"        udddssrraaitte97%       ",
+"        uddddssrraaitte9%       ",
+"        udddddssrraaitte8       ",
+"        uddddddssrraaitt8       ",
+"        uuuuuuuuuuuuuu88u       ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                "
+};
diff --git a/applications/OPJViewer/source/icon2.xpm b/applications/OPJViewer/source/icon2.xpm
new file mode 100644 (file)
index 0000000..7ae8c92
--- /dev/null
@@ -0,0 +1,53 @@
+/* XPM */
+static char *icon2_xpm[] = {
+/* columns rows colors chars-per-pixel */
+"32 32 15 1",
+". c Black",
+"O c #97C4E7",
+"$ c #63B3DE",
+"@ c #CAE1F3",
+"; c #7AC4E5",
+"* c #74A1BD",
+"+ c #619BC4",
+"o c #4B8EBF",
+"  c None",
+"% c #54A6D8",
+"= c #FAFCFE",
+"& c #E9F3FA",
+"# c #76BAE2",
+"X c #C00000",
+"- c #87ABC3",
+/* pixels */
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"        .............           ",
+"        .XXXXXXXXXX.o.          ",
+"        .XXXXXXXXXX.O+.         ",
+"        .XXXXXXXXXX.@O+.        ",
+"        .XX##$$$$%$.&@O*        ",
+"        .XXXXXXXXXX.=&@O-       ",
+"        .XXXXXXXXXX......       ",
+"        .XX;###$$$$$%%XX.       ",
+"        .XXXXXXXXXXXXXXX.       ",
+"        .XXXXXXXXXXXXXXX.       ",
+"        .XX;;;;###$$$$XX.       ",
+"        .XXXXXXXXXXXXXXX.       ",
+"        .XXXXXXXXXXXXXXX.       ",
+"        .XX;;;;;;;###$XX.       ",
+"        .XXXXXXXXXXXXXXX.       ",
+"        .XXXXXXXXXXXXXXX.       ",
+"        .XX;;;;;;;;;;#XX.       ",
+"        .XXXXXXXXXXXXXXX.       ",
+"        .XXXXXXXXXXXXXXX.       ",
+"        .XXXXXXXXXXXXXXX.       ",
+"        .XXXXXXXXXXXXXXX.       ",
+"        .................       ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                "
+};
diff --git a/applications/OPJViewer/source/icon3.xpm b/applications/OPJViewer/source/icon3.xpm
new file mode 100644 (file)
index 0000000..722de6b
--- /dev/null
@@ -0,0 +1,79 @@
+/* XPM */
+static char *icon3_xpm[] = {
+/* columns rows colors chars-per-pixel */
+"32 32 41 1",
+"6 c #EDF2FB",
+"- c #AAC1E8",
+": c #B9CDED",
+"X c #295193",
+", c #C6D6F0",
+"a c #4A7CCE",
+"u c #779DDB",
+"y c #7FA2DD",
+"$ c #3263B4",
+"5 c #EAF0FA",
+". c #2D59A3",
+"o c #6E96D8",
+"* c #356AC1",
+"r c #F7F9FD",
+"> c #BED0EE",
+"3 c #E1E9F7",
+"7 c #F0F5FC",
+"< c #CBD9F1",
+"2 c #DAE5F6",
+"# c #3161B1",
+"  c None",
+"0 c #FDFEFF",
+"= c #9FB9E5",
+"e c #AEC5EA",
+"t c #89A9DF",
+"q c #98B5E4",
+"p c #5584D1",
+"d c #3A70CA",
+"@ c #305FAC",
+"i c #5D89D3",
+"1 c #D2DFF4",
+"% c #3366B9",
+"9 c #FAFCFE",
+"8 c #F5F8FD",
+"s c #4075CC",
+"O c #638ED5",
+"w c #90AFE2",
+"& c #3467BC",
+"+ c #2F5DA9",
+"; c #B3C8EB",
+"4 c #E5EDF9",
+/* pixels */
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"      ......X                   ",
+"      .oooooO+                  ",
+"      .ooooooo.                 ",
+"      .+@@@##$%%&&&&&****.      ",
+"      .=-;:>,<12345678900.      ",
+"      .q=-;:>,<1234567890.      ",
+"      .wq=-e:>,<12345678r.      ",
+"      .twq=-e:>,<12345678.      ",
+"      .ytwq=-e:>,<1234567.      ",
+"      .uytwq=-e:>,<123456.      ",
+"      .ouytwq=-e:>,<12345.      ",
+"      .Oouytwq=-e;>,<1234.      ",
+"      .iOouytwq=-e;>,<123.      ",
+"      .piOouytwq=-e;>,<12.      ",
+"      .apiOouytwq=-e;>,<1.      ",
+"      .sapiOouytwq=-e;>,<.      ",
+"      .dsapiOouytwq=-e;>,.      ",
+"      ...................#      ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                "
+};
diff --git a/applications/OPJViewer/source/icon4.xpm b/applications/OPJViewer/source/icon4.xpm
new file mode 100644 (file)
index 0000000..a18e1a7
--- /dev/null
@@ -0,0 +1,43 @@
+/* XPM */
+static char *icon4_xpm[] = {
+/* columns rows colors chars-per-pixel */
+"32 32 5 1",
+". c Black",
+"o c #8399B4",
+"X c #8DA0B9",
+"  c None",
+"O c #800000",
+/* pixels */
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"      .......                   ",
+"      .XXXXXo.                  ",
+"      .XXXXXXX.                 ",
+"      ....................      ",
+"      .OOOOOOOOOOOOOOOOOO.      ",
+"      .OOOOOOOOOOOOOOOOOO.      ",
+"      .OOOOOOOOOOOOOOOOOO.      ",
+"      .OOOOOOOOOOOOOOOOOO.      ",
+"      .OOOOOOOOOOOOOOOOOO.      ",
+"      .OOOOOOOOOOOOOOOOOO.      ",
+"      .OOOOOOOOOOOOOOOOOO.      ",
+"      .OOOOOOOOOOOOOOOOOO.      ",
+"      .OOOOOOOOOOOOOOOOOO.      ",
+"      .OOOOOOOOOOOOOOOOOO.      ",
+"      .OOOOOOOOOOOOOOOOOO.      ",
+"      .OOOOOOOOOOOOOOOOOO.      ",
+"      .OOOOOOOOOOOOOOOOOO.      ",
+"      ....................      ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                "
+};
diff --git a/applications/OPJViewer/source/icon5.xpm b/applications/OPJViewer/source/icon5.xpm
new file mode 100644 (file)
index 0000000..9f63c31
--- /dev/null
@@ -0,0 +1,79 @@
+/* XPM */
+static char *icon5_xpm[] = {
+/* columns rows colors chars-per-pixel */
+"32 32 41 1",
+"0 c #AAC1E8",
+"q c #B9CDED",
+"X c #295193",
+"e c #C6D6F0",
+"a c #4A7CCE",
+"& c #779DDB",
+"* c #7FA2DD",
+"2 c #EAF0FA",
+"@ c #2D59A3",
+"o c #6E96D8",
+"y c #356AC1",
+"d c #214279",
+"w c #BED0EE",
+"= c #85A7DF",
+"< c #E1E9F7",
+"3 c #F0F5FC",
+"s c #CBD9F1",
+", c #DAE5F6",
+"7 c #3161B1",
+"  c None",
+". c #274D8B",
+"6 c #FDFEFF",
+"i c #E7EEF9",
+"9 c #9FB9E5",
+"- c #89A9DF",
+"8 c #98B5E4",
+"$ c #5584D1",
+"+ c #3569BF",
+"% c #305FAC",
+"O c #5D89D3",
+"> c #D2DFF4",
+"p c #3366B9",
+"5 c #FAFCFE",
+"4 c #F5F8FD",
+"t c #4075CC",
+"u c #638ED5",
+"r c #CEDCF2",
+"; c #90AFE2",
+"# c #2F5DA9",
+": c #B3C8EB",
+"1 c #E5EDF9",
+/* pixels */
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"     ......X                    ",
+"     XoooooO.                   ",
+"     Xoooooo+.                  ",
+"     Xooooooo@XXXXXXXXXX#       ",
+"     Xoooooooooooooooooo#       ",
+"     Xoooooooooooooooooo#       ",
+"     Xoo$###################    ",
+"     Xoo%O&*=-;:>,<123445667    ",
+"     XooX890:qwer>,<123445q#    ",
+"     Xoty;890:qwer>,<12344#     ",
+"     Xo%u-;890:qwer>,<i234#     ",
+"     XoX&*-;890:qwer>,<i2r#     ",
+"     Xtpo&*-;890:qwer>,<i#      ",
+"     X%auo&*-;890:qwer>,<#      ",
+"     XX$Ouo&*-;890:qwer>s#      ",
+"     d%a$Ouo&*-;890:qwer#       ",
+"     d+ta$Ouo&*-;890:qwe#       ",
+"     d..................#       ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                ",
+"                                "
+};
diff --git a/applications/OPJViewer/source/imagjpeg2000.cpp b/applications/OPJViewer/source/imagjpeg2000.cpp
new file mode 100644 (file)
index 0000000..66e1146
--- /dev/null
@@ -0,0 +1,1464 @@
+/*\r
+ * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        imagjpeg2000.cpp\r
+// Purpose:     wxImage JPEG 2000 family file format handler\r
+// Author:      Giuseppe Baruffa - based on imagjpeg.cpp, Vaclav Slavik\r
+// RCS-ID:      $Id: imagjpeg2000.cpp,v 0.00 2008/01/31 10:58:00 MW Exp $\r
+// Copyright:   (c) Giuseppe Baruffa\r
+// Licence:     wxWindows licence\r
+/////////////////////////////////////////////////////////////////////////////\r
+\r
+// For compilers that support precompilation, includes "wx.h".\r
+#include "wx/wxprec.h"\r
+\r
+#ifdef __BORLANDC__\r
+    #pragma hdrstop\r
+#endif\r
+\r
+#if wxUSE_IMAGE && wxUSE_LIBOPENJPEG\r
+\r
+#include "imagjpeg2000.h"\r
+\r
+#ifndef WX_PRECOMP\r
+    #include "wx/log.h"\r
+    #include "wx/app.h"\r
+    #include "wx/intl.h"\r
+    #include "wx/bitmap.h"\r
+    #include "wx/module.h"\r
+#endif\r
+\r
+#include "libopenjpeg/openjpeg.h"\r
+\r
+#include "wx/filefn.h"\r
+#include "wx/wfstream.h"\r
+\r
+// ----------------------------------------------------------------------------\r
+// types\r
+// ----------------------------------------------------------------------------\r
+\r
+\r
+//-----------------------------------------------------------------------------\r
+// wxJPEG2000Handler\r
+//-----------------------------------------------------------------------------\r
+\r
+IMPLEMENT_DYNAMIC_CLASS(wxJPEG2000Handler,wxImageHandler)\r
+\r
+#if wxUSE_STREAMS\r
+\r
+//------------- JPEG 2000 Data Source Manager\r
+\r
+#define J2K_CFMT 0\r
+#define JP2_CFMT 1\r
+#define JPT_CFMT 2\r
+#define MJ2_CFMT 3\r
+#define PXM_DFMT 0\r
+#define PGX_DFMT 1\r
+#define BMP_DFMT 2\r
+#define YUV_DFMT 3\r
+\r
+#define MAX_MESSAGE_LEN 200\r
+\r
+/* check file type */\r
+int\r
+jpeg2000familytype(unsigned char *hdr, int hdr_len)\r
+{\r
+       // check length\r
+    if (hdr_len < 24)\r
+        return -1;\r
+\r
+       // check format\r
+       if (hdr[0] == 0x00 &&\r
+                       hdr[1] == 0x00 &&\r
+                       hdr[2] == 0x00 &&\r
+                       hdr[3] == 0x0C &&\r
+                       hdr[4] == 0x6A &&\r
+                       hdr[5] == 0x50 &&\r
+                       hdr[6] == 0x20 &&\r
+                       hdr[7] == 0x20 &&\r
+                       hdr[20] == 0x6A &&\r
+                       hdr[21] == 0x70 &&\r
+                       hdr[22] == 0x32)\r
+               // JP2 file format\r
+               return JP2_CFMT;\r
+       else if (hdr[0] == 0x00 &&\r
+                       hdr[1] == 0x00 &&\r
+                       hdr[2] == 0x00 &&\r
+                       hdr[3] == 0x0C &&\r
+                       hdr[4] == 0x6A &&\r
+                       hdr[5] == 0x50 &&\r
+                       hdr[6] == 0x20 &&\r
+                       hdr[7] == 0x20 &&\r
+                       hdr[20] == 0x6D &&\r
+                       hdr[21] == 0x6A &&\r
+                       hdr[22] == 0x70 &&\r
+                       hdr[23] == 0x32)\r
+               // MJ2 file format\r
+               return MJ2_CFMT;\r
+       else if (hdr[0] == 0xFF &&\r
+                       hdr[1] == 0x4F)\r
+               // J2K file format\r
+               return J2K_CFMT;\r
+       else\r
+               // unknown format\r
+               return -1;\r
+\r
+}\r
+\r
+/* we have to use this to avoid GUI-noGUI threads crashing */\r
+void printevent(const char *msg)\r
+{\r
+#ifndef __WXGTK__ \r
+       wxMutexGuiEnter();\r
+#endif /* __WXGTK__ */\r
+       wxLogMessage(wxT("%s"), msg);\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiLeave();\r
+#endif /* __WXGTK__ */\r
+}\r
+\r
+/* sample error callback expecting a FILE* client object */\r
+void jpeg2000_error_callback(const char *msg, void *client_data) {\r
+       char mess[MAX_MESSAGE_LEN + 20];\r
+       int message_len = strlen(msg);\r
+\r
+       if (message_len > MAX_MESSAGE_LEN)\r
+               message_len = MAX_MESSAGE_LEN;\r
+       \r
+       if (msg[message_len - 1] == '\n')\r
+               message_len--;\r
+\r
+       sprintf(mess, "[ERROR] %.*s", message_len, msg);\r
+       printevent(mess);\r
+}\r
+\r
+/* sample warning callback expecting a FILE* client object */\r
+void jpeg2000_warning_callback(const char *msg, void *client_data) {\r
+       char mess[MAX_MESSAGE_LEN + 20];\r
+       int message_len = strlen(msg);\r
+\r
+       if (message_len > MAX_MESSAGE_LEN)\r
+               message_len = MAX_MESSAGE_LEN;\r
+       \r
+       if (msg[message_len - 1] == '\n')\r
+               message_len--;\r
+\r
+       sprintf(mess, "[WARNING] %.*s", message_len, msg);\r
+       printevent(mess);\r
+}\r
+\r
+/* sample debug callback expecting no client object */\r
+void jpeg2000_info_callback(const char *msg, void *client_data) {\r
+       char mess[MAX_MESSAGE_LEN + 20];\r
+       int message_len = strlen(msg);\r
+\r
+       if (message_len > MAX_MESSAGE_LEN)\r
+               message_len = MAX_MESSAGE_LEN;\r
+       \r
+       if (msg[message_len - 1] == '\n')\r
+               message_len--;\r
+\r
+       sprintf(mess, "[INFO] %.*s", message_len, msg);\r
+       printevent(mess);\r
+}\r
+\r
+/* macro functions */\r
+/* From little endian to big endian, 2 and 4 bytes */\r
+#define        BYTE_SWAP2(X)   ((X & 0x00FF) << 8) | ((X & 0xFF00) >> 8)\r
+#define        BYTE_SWAP4(X)   ((X & 0x000000FF) << 24) | ((X & 0x0000FF00) << 8) | ((X & 0x00FF0000) >> 8) | ((X & 0xFF000000) >> 24)\r
+\r
+#ifdef __WXGTK__\r
+#define        BYTE_SWAP8(X)   ((X & 0x00000000000000FFULL) << 56) | ((X & 0x000000000000FF00ULL) << 40) | \\r
+                        ((X & 0x0000000000FF0000ULL) << 24) | ((X & 0x00000000FF000000ULL) << 8) | \\r
+                                               ((X & 0x000000FF00000000ULL) >> 8)  | ((X & 0x0000FF0000000000ULL) >> 24) | \\r
+                                               ((X & 0x00FF000000000000ULL) >> 40) | ((X & 0xFF00000000000000ULL) >> 56)\r
+#else\r
+#define        BYTE_SWAP8(X)   ((X & 0x00000000000000FF) << 56) | ((X & 0x000000000000FF00) << 40) | \\r
+                        ((X & 0x0000000000FF0000) << 24) | ((X & 0x00000000FF000000) << 8) | \\r
+                                               ((X & 0x000000FF00000000) >> 8)  | ((X & 0x0000FF0000000000) >> 24) | \\r
+                                               ((X & 0x00FF000000000000) >> 40) | ((X & 0xFF00000000000000) >> 56)\r
+#endif\r
+\r
+/* From codestream to int values */\r
+#define STREAM_TO_UINT32(C, P) (((unsigned long int) (C)[(P) + 0] << 24) + \\r
+                                                               ((unsigned long int) (C)[(P) + 1] << 16) + \\r
+                                                               ((unsigned long int) (C)[(P) + 2] << 8) + \\r
+                                                               ((unsigned long int) (C)[(P) + 3] << 0))\r
+\r
+#define STREAM_TO_UINT16(C, P) (((unsigned long int) (C)[(P) + 0] << 8) + \\r
+                                                               ((unsigned long int) (C)[(P) + 1] << 0))\r
+\r
+/* defines */\r
+#define SHORT_DESCR_LEN        32\r
+#define LONG_DESCR_LEN         256\r
+\r
+/* enumeration for file formats */\r
+#define JPEG2000FILENUM              4\r
+typedef enum {\r
+\r
+        JP2_FILE,\r
+        J2K_FILE,\r
+               MJ2_FILE,\r
+               UNK_FILE\r
+\r
+} jpeg2000filetype;\r
+\r
+/* enumeration for the box types */\r
+#define JPEG2000BOXNUM                23\r
+typedef enum {\r
+\r
+                       FILE_BOX,\r
+                       JP_BOX,\r
+                       FTYP_BOX,\r
+                       JP2H_BOX,\r
+                       IHDR_BOX,\r
+                       COLR_BOX,\r
+                       JP2C_BOX,\r
+                       JP2I_BOX,\r
+                       XML_BOX,\r
+                       UUID_BOX,\r
+                       UINF_BOX,\r
+                       MOOV_BOX,\r
+                       MVHD_BOX,\r
+                       TRAK_BOX,\r
+                       TKHD_BOX,\r
+                       MDIA_BOX,\r
+                       MINF_BOX,\r
+                       STBL_BOX,\r
+                       STSD_BOX,\r
+                       MJP2_BOX,\r
+                       MDAT_BOX,\r
+                       ANY_BOX,\r
+                       UNK_BOX\r
+\r
+} jpeg2000boxtype;\r
+\r
+/* jpeg2000 family box signatures */\r
+#define FILE_SIGN           ""\r
+#define JP_SIGN             "jP\040\040"\r
+#define FTYP_SIGN           "ftyp"\r
+#define JP2H_SIGN           "jp2h"\r
+#define IHDR_SIGN           "ihdr"\r
+#define COLR_SIGN           "colr"\r
+#define JP2C_SIGN           "jp2c"\r
+#define JP2I_SIGN           "jp2i"\r
+#define XML_SIGN            "xml\040"\r
+#define UUID_SIGN           "uuid"\r
+#define UINF_SIGN           "uinf"\r
+#define MOOV_SIGN           "moov"\r
+#define MVHD_SIGN           "mvhd"\r
+#define TRAK_SIGN           "trak"\r
+#define TKHD_SIGN           "tkhd"\r
+#define MDIA_SIGN           "mdia"\r
+#define MINF_SIGN           "minf"\r
+#define VMHD_SIGN           "vmhd"\r
+#define STBL_SIGN           "stbl"\r
+#define STSD_SIGN           "stsd"\r
+#define MJP2_SIGN           "mjp2"\r
+#define MDAT_SIGN           "mdat"\r
+#define ANY_SIGN                       ""\r
+#define UNK_SIGN            ""\r
+\r
+/* the box structure itself */\r
+struct jpeg2000boxdef {\r
+\r
+        char                  value[5];                 /* hexadecimal value/string*/\r
+               char                  name[SHORT_DESCR_LEN];    /* short description       */\r
+               char                  descr[LONG_DESCR_LEN];    /* long  description       */\r
+               int                   sbox;                     /* is it a superbox?       */\r
+               int                   req[JPEG2000FILENUM];     /* mandatory box           */\r
+               jpeg2000boxtype       ins;                      /* contained in box...     */\r
+\r
+};\r
+\r
+/* the possible boxes */\r
+struct jpeg2000boxdef jpeg2000box[] =\r
+{\r
+/* sign */     {FILE_SIGN,\r
+/* short */    "placeholder for nothing",\r
+/* long */     "Nothing to say",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {JP_SIGN,\r
+/* short */    "JPEG 2000 Signature box",\r
+/* long */     "This box uniquely identifies the file as being part of the JPEG 2000 family of files",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {FTYP_SIGN,\r
+/* short */    "File Type box",\r
+/* long */     "This box specifies file type, version and compatibility information, including specifying if this file "\r
+                       "is a conforming JP2 file or if it can be read by a conforming JP2 reader",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {JP2H_SIGN,\r
+/* short */    "JP2 Header box",\r
+/* long */     "This box contains a series of boxes that contain header-type information about the file",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {IHDR_SIGN,\r
+/* short */    "Image Header box",\r
+/* long */     "This box specifies the size of the image and other related fields",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      JP2H_BOX},\r
+\r
+/* sign */     {COLR_SIGN,\r
+/* short */    "Colour Specification box",\r
+/* long */     "This box specifies the colourspace of the image",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      JP2H_BOX},\r
+\r
+/* sign */     {JP2C_SIGN,\r
+/* short */    "Contiguous Codestream box",\r
+/* long */     "This box contains the codestream as defined by Annex A",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {JP2I_SIGN,\r
+/* short */    "Intellectual Property box",\r
+/* long */     "This box contains intellectual property information about the image",\r
+/* sbox */     0,\r
+/* req */      {0, 0, 0},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {XML_SIGN,\r
+/* short */    "XML box",\r
+/* long */     "This box provides a tool by which vendors can add XML formatted information to a JP2 file",\r
+/* sbox */     0,\r
+/* req */      {0, 0, 0},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {UUID_SIGN,\r
+/* short */    "UUID box",\r
+/* long */     "This box provides a tool by which vendors can add additional information to a file "\r
+                       "without risking conflict with other vendors",\r
+/* sbox */     0,\r
+/* req */      {0, 0, 0},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {UINF_SIGN,\r
+/* short */    "UUID Info box",\r
+/* long */     "This box provides a tool by which a vendor may provide access to additional information associated with a UUID",\r
+/* sbox */     0,\r
+/* req */      {0, 0, 0},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {MOOV_SIGN,\r
+/* short */    "Movie box",\r
+/* long */     "This box contains the media data. In video tracks, this box would contain JPEG2000 video frames",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {MVHD_SIGN,\r
+/* short */    "Movie Header box",\r
+/* long */     "This box defines overall information which is media-independent, and relevant to the entire presentation "\r
+                       "considered as a whole",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MOOV_BOX},\r
+\r
+/* sign */     {TRAK_SIGN,\r
+/* short */    "Track box",\r
+/* long */     "This is a container box for a single track of a presentation. A presentation may consist of one or more tracks",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MOOV_BOX},\r
+\r
+/* sign */     {TKHD_SIGN,\r
+/* short */    "Track Header box",\r
+/* long */     "This box specifies the characteristics of a single track. Exactly one Track Header Box is contained in a track",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      TRAK_BOX},\r
+\r
+/* sign */     {MDIA_SIGN,\r
+/* short */    "Media box",\r
+/* long */     "The media declaration container contains all the objects which declare information about the media data "\r
+                       "within a track",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      TRAK_BOX},\r
+\r
+/* sign */     {MINF_SIGN,\r
+/* short */    "Media Information box",\r
+/* long */     "This box contains all the objects which declare characteristic information of the media in the track",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MDIA_BOX},\r
+\r
+/* sign */     {STBL_SIGN,\r
+/* short */    "Sample Table box",\r
+/* long */     "The sample table contains all the time and data indexing of the media samples in a track",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MINF_BOX},\r
+\r
+/* sign */     {STSD_SIGN,\r
+/* short */    "Sample Description box",\r
+/* long */     "The sample description table gives detailed information about the coding type used, and any initialization "\r
+                       "information needed for that coding",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MINF_BOX},\r
+\r
+/* sign */     {MJP2_SIGN,\r
+/* short */    "MJP2 Sample Description box",\r
+/* long */     "The MJP2 sample description table gives detailed information about the coding type used, and any initialization "\r
+                       "information needed for that coding",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MINF_BOX},\r
+\r
+/* sign */     {MDAT_SIGN,\r
+/* short */    "Media Data box",\r
+/* long */     "The meta-data for a presentation is stored in the single Movie Box which occurs at the top-level of a file",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {ANY_SIGN,\r
+/* short */    "Any box",\r
+/* long */     "All the existing boxes",\r
+/* sbox */     0,\r
+/* req */      {0, 0, 0},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {UNK_SIGN,\r
+/* short */    "Unknown Type box",\r
+/* long */     "The signature is not recognised to be that of an existing box",\r
+/* sbox */     0,\r
+/* req */      {0, 0, 0},\r
+/* ins */      ANY_BOX}\r
+\r
+};\r
+\r
+/* declaration */\r
+int\r
+jpeg2000_box_handler_function(jpeg2000boxtype boxtype, wxInputStream& stream, unsigned long int filepoint,\r
+                                                         unsigned long int filelimit, int level, char *scansign,\r
+                                                         unsigned long int *scanpoint);\r
+\r
+#ifdef __WXMSW__\r
+typedef unsigned __int64 int8byte;\r
+#endif // __WXMSW__\r
+\r
+#ifdef __WXGTK__\r
+typedef unsigned long long int8byte;\r
+#endif // __WXGTK__\r
+\r
+/* internal mini-search for a box signature */\r
+int\r
+jpeg2000_file_parse(wxInputStream& stream, unsigned long int filepoint, unsigned long int filelimit, int level,\r
+                                       char *scansign, unsigned long int *scanpoint)\r
+{\r
+       unsigned long int       LBox = 0x00000000;\r
+       char                    TBox[5] = "\0\0\0\0";\r
+       int8byte                XLBox = 0x0000000000000000;\r
+       unsigned long int       box_length = 0;\r
+       int                     last_box = 0, box_num = 0;\r
+       int                     box_type = ANY_BOX;\r
+       unsigned char           fourbytes[4];\r
+       int                     box_number = 0;\r
+\r
+       /* cycle all over the file */\r
+       box_num = 0;\r
+       last_box = 0;\r
+       while (!last_box) {\r
+\r
+               /* do not exceed file limit */\r
+               if (filepoint >= filelimit)\r
+                       return (0);\r
+\r
+               /* seek on file */\r
+               if (stream.SeekI(filepoint, wxFromStart) == wxInvalidOffset)\r
+                       return (-1);\r
+\r
+               /* read the mandatory LBox, 4 bytes */\r
+               if (!stream.Read(fourbytes, 4)) {\r
+                       wxLogError(wxT("Problem reading LBox from the file (file ended?)"));\r
+                       return -1;\r
+               };\r
+               LBox = STREAM_TO_UINT32(fourbytes, 0);\r
+\r
+               /* read the mandatory TBox, 4 bytes */\r
+               if (!stream.Read(TBox, 4)) {\r
+                       wxLogError(wxT("Problem reading TBox from the file (file ended?)"));\r
+                       return -1;\r
+               };\r
+\r
+               /* look if scansign is got */\r
+               if ((scansign != NULL) && (memcmp(TBox, scansign, 4) == 0)) {\r
+                       /* hack/exploit */\r
+                       // stop as soon as you find the level-th codebox\r
+                       if (box_number == level) {\r
+                               memcpy(scansign, "    ", 4);\r
+                               *scanpoint = filepoint;\r
+                               return (0);\r
+                       } else\r
+                               box_number++;\r
+\r
+               };\r
+\r
+               /* determine the box type */\r
+               for (box_type = JP_BOX; box_type < UNK_BOX; box_type++)\r
+                       if (memcmp(TBox, jpeg2000box[box_type].value, 4) == 0)\r
+                               break;  \r
+\r
+               /* read the optional XLBox, 8 bytes */\r
+               if (LBox == 1) {\r
+\r
+                       if (!stream.Read(&XLBox, 8)) {\r
+                               wxLogError(wxT("Problem reading XLBox from the file (file ended?)"));\r
+                               return -1;\r
+                       };\r
+                       box_length = (unsigned long int) BYTE_SWAP8(XLBox);\r
+\r
+               } else if (LBox == 0x00000000) {\r
+\r
+                       /* last box in file */\r
+                       last_box = 1; \r
+                       box_length = filelimit - filepoint;\r
+\r
+               } else\r
+\r
+                       box_length = LBox;\r
+\r
+\r
+               /* go deep in the box */\r
+               jpeg2000_box_handler_function((jpeg2000boxtype) box_type,\r
+                       stream, (LBox == 1) ? (filepoint + 16) : (filepoint + 8),\r
+                       filepoint + box_length, level, scansign, scanpoint);\r
+\r
+               /* if it's a superbox go inside it */\r
+               if (jpeg2000box[box_type].sbox)\r
+                       jpeg2000_file_parse(stream, (LBox == 1) ? (filepoint + 16) : (filepoint + 8), filepoint + box_length,\r
+                               level, scansign, scanpoint);\r
+\r
+               /* increment box number and filepoint*/\r
+               box_num++;\r
+               filepoint += box_length;\r
+\r
+       };\r
+\r
+       /* all good */\r
+       return (0);\r
+}\r
+\r
+// search first contiguos codestream box in an mj2 file\r
+unsigned long int\r
+searchjpeg2000c(wxInputStream& stream, unsigned long int fsize, int number)\r
+{\r
+       char scansign[] = "jp2c";\r
+       unsigned long int scanpoint = 0L;\r
+\r
+       wxLogMessage(wxT("Searching jp2c box... "));\r
+\r
+       /* do the parsing */\r
+       if (jpeg2000_file_parse(stream, 0, fsize, number, scansign, &scanpoint) < 0)            \r
+               wxLogMessage(wxT("Unrecoverable error during JPEG 2000 box parsing: stopping"));\r
+\r
+       if (strcmp(scansign, "    "))\r
+               wxLogMessage(wxT("Box not found"));\r
+       else {\r
+\r
+               wxLogMessage(wxString::Format(wxT("Box found at byte %d"), scanpoint));\r
+\r
+       };\r
+\r
+       return (scanpoint);\r
+}\r
+\r
+// search the jp2h box in the file\r
+unsigned long int\r
+searchjpeg2000headerbox(wxInputStream& stream, unsigned long int fsize)\r
+{\r
+       char scansign[] = "jp2h";\r
+       unsigned long int scanpoint = 0L;\r
+\r
+       wxLogMessage(wxT("Searching jp2h box... "));\r
+\r
+       /* do the parsing */\r
+       if (jpeg2000_file_parse(stream, 0, fsize, 0, scansign, &scanpoint) < 0)         \r
+               wxLogMessage(wxT("Unrecoverable error during JPEG 2000 box parsing: stopping"));\r
+\r
+       if (strcmp(scansign, "    "))\r
+               wxLogMessage(wxT("Box not found"));\r
+       else\r
+               wxLogMessage(wxString::Format(wxT("Box found at byte %d"), scanpoint));\r
+\r
+       return (scanpoint);\r
+}\r
+\r
+/* handling functions */\r
+#define ITEM_PER_ROW   10\r
+\r
+/* Box handler function */\r
+int\r
+jpeg2000_box_handler_function(jpeg2000boxtype boxtype, wxInputStream& stream, unsigned long int filepoint,\r
+                                                         unsigned long int filelimit, int level,\r
+                                                         char *scansign, unsigned long int *scanpoint)\r
+{\r
+       switch (boxtype) {\r
+\r
+       /* Sample Description box */\r
+       case (STSD_BOX):\r
+               jpeg2000_file_parse(stream, filepoint + 8, filelimit, level, scansign, scanpoint);\r
+               break;\r
+\r
+       /* MJP2 Sample Description box */\r
+       case (MJP2_BOX):\r
+               jpeg2000_file_parse(stream, filepoint + 78, filelimit, level, scansign, scanpoint);\r
+               break;\r
+               \r
+       /* not yet implemented */\r
+       default:\r
+               break;\r
+\r
+       };\r
+\r
+       return (0);\r
+}\r
+\r
+// the jP and ftyp parts of the header\r
+#define jpeg2000headSIZE       32\r
+unsigned char jpeg2000head[jpeg2000headSIZE] = {\r
+               0x00, 0x00, 0x00, 0x0C,  'j',  'P',  ' ',  ' ',\r
+               0x0D, 0x0A, 0x87, 0x0A, 0x00, 0x00, 0x00, 0x14,\r
+                'f',  't',  'y',  'p',  'j',  'p',  '2',  ' ',\r
+               0x00, 0x00, 0x00, 0x00,  'j',  'p',  '2',  ' '                  \r
+};\r
+\r
+/////////////////////////////////////////////////\r
+/////////////////////////////////////////////////\r
+\r
+// load the jpeg2000 file format\r
+bool wxJPEG2000Handler::LoadFile(wxImage *image, wxInputStream& stream, bool verbose, int index)\r
+{\r
+       opj_dparameters_t parameters;   /* decompression parameters */\r
+       opj_event_mgr_t event_mgr;              /* event manager */\r
+       opj_image_t *opjimage = NULL;\r
+       unsigned char *src = NULL;\r
+    unsigned char *ptr;\r
+       int file_length, jp2c_point, jp2h_point;\r
+       unsigned long int jp2hboxlen, jp2cboxlen;\r
+       opj_codestream_info_t cstr_info;  /* Codestream information structure */\r
+    unsigned char hdr[24];\r
+       int jpfamform;\r
+\r
+       // destroy the image\r
+    image->Destroy();\r
+\r
+       /* read the beginning of the file to check the type */ \r
+    if (!stream.Read(hdr, WXSIZEOF(hdr)))\r
+        return false;\r
+       if ((jpfamform = jpeg2000familytype(hdr, WXSIZEOF(hdr))) < 0)\r
+               return false;\r
+       stream.SeekI(0, wxFromStart);\r
+\r
+       /* handle to a decompressor */\r
+       opj_dinfo_t* dinfo = NULL;      \r
+       opj_cio_t *cio = NULL;\r
+\r
+       /* configure the event callbacks */\r
+       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));\r
+       event_mgr.error_handler = jpeg2000_error_callback;\r
+       event_mgr.warning_handler = jpeg2000_warning_callback;\r
+       event_mgr.info_handler = jpeg2000_info_callback;\r
+\r
+       /* set decoding parameters to default values */\r
+       opj_set_default_decoder_parameters(&parameters);\r
+\r
+       /* prepare parameters */\r
+       strncpy(parameters.infile, "", sizeof(parameters.infile) - 1);\r
+       strncpy(parameters.outfile, "", sizeof(parameters.outfile) - 1);\r
+       parameters.decod_format = jpfamform;\r
+       parameters.cod_format = BMP_DFMT;\r
+       if (m_reducefactor)\r
+               parameters.cp_reduce = m_reducefactor;\r
+       if (m_qualitylayers)\r
+               parameters.cp_layer = m_qualitylayers;\r
+       /*if (n_components)\r
+               parameters. = n_components;*/\r
+\r
+       /* JPWL only */\r
+#ifdef USE_JPWL\r
+       parameters.jpwl_exp_comps = m_expcomps;\r
+       parameters.jpwl_max_tiles = m_maxtiles;\r
+       parameters.jpwl_correct = m_enablejpwl;\r
+#endif /* USE_JPWL */\r
+\r
+       /* get a decoder handle */\r
+       if (jpfamform == JP2_CFMT || jpfamform == MJ2_CFMT)\r
+               dinfo = opj_create_decompress(CODEC_JP2);\r
+       else if (jpfamform == J2K_CFMT)\r
+               dinfo = opj_create_decompress(CODEC_J2K);\r
+       else\r
+               return false;\r
+\r
+       /* find length of the stream */\r
+       stream.SeekI(0, wxFromEnd);\r
+       file_length = (int) stream.TellI();\r
+\r
+       /* it's a movie */\r
+       if (jpfamform == MJ2_CFMT) {\r
+               /* search for the first codestream box and the movie header box  */\r
+               jp2c_point = searchjpeg2000c(stream, file_length, m_framenum);\r
+               jp2h_point = searchjpeg2000headerbox(stream, file_length);\r
+\r
+               // read the jp2h box and store it\r
+               stream.SeekI(jp2h_point, wxFromStart);\r
+               stream.Read(&jp2hboxlen, sizeof(unsigned long int));\r
+               jp2hboxlen = BYTE_SWAP4(jp2hboxlen);\r
+\r
+               // read the jp2c box and store it\r
+               stream.SeekI(jp2c_point, wxFromStart);\r
+               stream.Read(&jp2cboxlen, sizeof(unsigned long int));\r
+               jp2cboxlen = BYTE_SWAP4(jp2cboxlen);\r
+\r
+               // malloc memory source\r
+               src = (unsigned char *) malloc(jpeg2000headSIZE + jp2hboxlen + jp2cboxlen);\r
+\r
+               // copy the jP and ftyp\r
+               memcpy(src, jpeg2000head, jpeg2000headSIZE);\r
+\r
+               // copy the jp2h\r
+               stream.SeekI(jp2h_point, wxFromStart);\r
+               stream.Read(&src[jpeg2000headSIZE], jp2hboxlen);\r
+\r
+               // copy the jp2c\r
+               stream.SeekI(jp2c_point, wxFromStart);\r
+               stream.Read(&src[jpeg2000headSIZE + jp2hboxlen], jp2cboxlen);\r
+       } else  if (jpfamform == JP2_CFMT || jpfamform == J2K_CFMT) {\r
+               /* It's a plain image */\r
+               /* get data */\r
+               stream.SeekI(0, wxFromStart);\r
+               src = (unsigned char *) malloc(file_length);\r
+               stream.Read(src, file_length);\r
+       } else\r
+               return false;\r
+\r
+       /* catch events using our callbacks and give a local context */\r
+       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);\r
+\r
+       /* setup the decoder decoding parameters using user parameters */\r
+       opj_setup_decoder(dinfo, &parameters);\r
+\r
+       /* open a byte stream */\r
+       if (jpfamform == MJ2_CFMT)\r
+               cio = opj_cio_open((opj_common_ptr)dinfo, src, jpeg2000headSIZE + jp2hboxlen + jp2cboxlen);\r
+       else if (jpfamform == JP2_CFMT || jpfamform == J2K_CFMT)\r
+               cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);\r
+       else {\r
+               free(src);\r
+               return false;\r
+       }\r
+\r
+       /* decode the stream and fill the image structure */\r
+       opjimage = opj_decode_with_info(dinfo, cio, &cstr_info);\r
+       if (!opjimage) {\r
+               wxMutexGuiEnter();\r
+               wxLogError(wxT("JPEG 2000 failed to decode image!"));\r
+               wxMutexGuiLeave();\r
+               opj_destroy_decompress(dinfo);\r
+               opj_cio_close(cio);\r
+               free(src);\r
+               return false;\r
+       }\r
+\r
+       /* close the byte stream */\r
+       opj_cio_close(cio);\r
+\r
+       /*\r
+\r
+       - At this point, we have the structure "opjimage" that is filled with decompressed\r
+         data, as processed by the OpenJPEG decompression engine\r
+\r
+       - We need to fill the class "image" with the proper pixel sample values\r
+\r
+       */\r
+       {\r
+               int shiftbpp;\r
+               int c, tempcomps;\r
+\r
+               // check components number\r
+               if (m_components > opjimage->numcomps)\r
+                       m_components = opjimage->numcomps;\r
+\r
+               // check image depth (only on the first one, for now)\r
+               if (m_components)\r
+                       shiftbpp = opjimage->comps[m_components - 1].prec - 8;\r
+               else\r
+                       shiftbpp = opjimage->comps[0].prec - 8;\r
+\r
+               // prepare image size\r
+               if (m_components)\r
+                       image->Create(opjimage->comps[m_components - 1].w, opjimage->comps[m_components - 1].h, true);\r
+               else\r
+                       image->Create(opjimage->comps[0].w, opjimage->comps[0].h, true);\r
+\r
+               // access image raw data\r
+               image->SetMask(false);\r
+               ptr = image->GetData();\r
+\r
+               // workaround for components different from 1 or 3\r
+               if ((opjimage->numcomps != 1) && (opjimage->numcomps != 3)) {\r
+#ifndef __WXGTK__ \r
+                       wxMutexGuiEnter();\r
+#endif /* __WXGTK__ */\r
+                       wxLogMessage(wxT("JPEG2000: weird number of components"));\r
+#ifndef __WXGTK__ \r
+                       wxMutexGuiLeave();\r
+#endif /* __WXGTK__ */\r
+                       tempcomps = 1;\r
+               } else\r
+                       tempcomps = opjimage->numcomps;\r
+\r
+               // workaround for subsampled components\r
+               for (c = 1; c < tempcomps; c++) {\r
+                       if ((opjimage->comps[c].w != opjimage->comps[c - 1].w) || (opjimage->comps[c].h != opjimage->comps[c - 1].h)) {\r
+                               tempcomps = 1;\r
+                               break;\r
+                       }\r
+               }\r
+\r
+               // workaround for different precision components\r
+               for (c = 1; c < tempcomps; c++) {\r
+                       if (opjimage->comps[c].bpp != opjimage->comps[c - 1].bpp) {\r
+                               tempcomps = 1;\r
+                               break;\r
+                       }\r
+               }\r
+\r
+               // only one component selected\r
+               if (m_components)\r
+                       tempcomps = 1;\r
+\r
+               // RGB color picture\r
+               if (tempcomps == 3) {\r
+                       int row, col;\r
+                       int *r = opjimage->comps[0].data;\r
+                       int *g = opjimage->comps[1].data;\r
+                       int *b = opjimage->comps[2].data;\r
+                       if (shiftbpp > 0) {\r
+                               for (row = 0; row < opjimage->comps[0].h; row++) {\r
+                                       for (col = 0; col < opjimage->comps[0].w; col++) {\r
+                                               \r
+                                               *(ptr++) = (*(r++)) >> shiftbpp;\r
+                                               *(ptr++) = (*(g++)) >> shiftbpp;\r
+                                               *(ptr++) = (*(b++)) >> shiftbpp;\r
+\r
+                                       }\r
+                               }\r
+\r
+                       } else if (shiftbpp < 0) {\r
+                               for (row = 0; row < opjimage->comps[0].h; row++) {\r
+                                       for (col = 0; col < opjimage->comps[0].w; col++) {\r
+                                               \r
+                                               *(ptr++) = (*(r++)) << -shiftbpp;\r
+                                               *(ptr++) = (*(g++)) << -shiftbpp;\r
+                                               *(ptr++) = (*(b++)) << -shiftbpp;\r
+\r
+                                       }\r
+                               }\r
+                               \r
+                       } else {\r
+                               for (row = 0; row < opjimage->comps[0].h; row++) {\r
+                                       for (col = 0; col < opjimage->comps[0].w; col++) {\r
+\r
+                                               *(ptr++) = *(r++);\r
+                                               *(ptr++) = *(g++);\r
+                                               *(ptr++) = *(b++);\r
+                                       \r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+\r
+               // B/W picture\r
+               if (tempcomps == 1) {\r
+                       int row, col;\r
+                       int selcomp;\r
+\r
+                       if (m_components)\r
+                               selcomp = m_components - 1;\r
+                       else\r
+                               selcomp = 0;\r
+\r
+                       int *y = opjimage->comps[selcomp].data;\r
+                       if (shiftbpp > 0) {\r
+                               for (row = 0; row < opjimage->comps[selcomp].h; row++) {\r
+                                       for (col = 0; col < opjimage->comps[selcomp].w; col++) {\r
+                                               \r
+                                               *(ptr++) = (*(y)) >> shiftbpp;\r
+                                               *(ptr++) = (*(y)) >> shiftbpp;\r
+                                               *(ptr++) = (*(y++)) >> shiftbpp;\r
+\r
+                                       }\r
+                               }\r
+                       } else if (shiftbpp < 0) {\r
+                               for (row = 0; row < opjimage->comps[selcomp].h; row++) {\r
+                                       for (col = 0; col < opjimage->comps[selcomp].w; col++) {\r
+                                               \r
+                                               *(ptr++) = (*(y)) << -shiftbpp;\r
+                                               *(ptr++) = (*(y)) << -shiftbpp;\r
+                                               *(ptr++) = (*(y++)) << -shiftbpp;\r
+\r
+                                       }\r
+                               }\r
+                       } else {\r
+                               for (row = 0; row < opjimage->comps[selcomp].h; row++) {\r
+                                       for (col = 0; col < opjimage->comps[selcomp].w; col++) {\r
+                                               \r
+                                               *(ptr++) = *(y);\r
+                                               *(ptr++) = *(y);\r
+                                               *(ptr++) = *(y++);\r
+\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+\r
+\r
+       }\r
+\r
+    wxMutexGuiEnter();\r
+    wxLogMessage(wxT("JPEG 2000 image loaded."));\r
+    wxMutexGuiLeave();\r
+\r
+       /* close openjpeg structs */\r
+       opj_destroy_decompress(dinfo);\r
+       opj_image_destroy(opjimage);\r
+       free(src);\r
+\r
+       if (!image->Ok())\r
+               return false;\r
+       else\r
+               return true;\r
+\r
+}\r
+\r
+#define CINEMA_24_CS 1302083   /* Codestream length for 24fps */\r
+#define CINEMA_48_CS 651041            /* Codestream length for 48fps */\r
+#define COMP_24_CS 1041666             /* Maximum size per color component for 2K & 4K @ 24fps */\r
+#define COMP_48_CS 520833              /* Maximum size per color component for 2K @ 48fps */\r
+\r
+// save the j2k codestream\r
+bool wxJPEG2000Handler::SaveFile( wxImage *wimage, wxOutputStream& stream, bool verbose )\r
+{\r
+        opj_cparameters_t parameters;  /* compression parameters */\r
+        opj_event_mgr_t event_mgr;             /* event manager */\r
+        opj_image_t *oimage = NULL;\r
+        opj_image_cmptparm_t *cmptparm;        \r
+        opj_cio_t *cio = NULL;\r
+        opj_codestream_info_t cstr_info;\r
+        int codestream_length;\r
+        bool bSuccess;\r
+        int i;\r
+        char indexfilename[OPJ_PATH_LEN] = ""; /* index file name */\r
+\r
+        /*\r
+        configure the event callbacks (not required)\r
+        setting of each callback is optionnal\r
+        */\r
+        memset(&event_mgr, 0, sizeof(opj_event_mgr_t));\r
+        event_mgr.error_handler = jpeg2000_error_callback;\r
+        event_mgr.warning_handler = jpeg2000_warning_callback;\r
+        event_mgr.info_handler = jpeg2000_info_callback;\r
+\r
+        /* set encoding parameters to default values */\r
+        opj_set_default_encoder_parameters(&parameters);\r
+\r
+        /* load parameters */\r
+        parameters.cp_cinema = OFF;\r
+\r
+        /* subsampling */\r
+        if (sscanf(m_subsampling.ToAscii(), "%d,%d", &(parameters.subsampling_dx), &(parameters.subsampling_dy)) != 2) {\r
+                wxLogError(wxT("Wrong sub-sampling encoder setting: dx,dy"));\r
+                return false;\r
+        }\r
+\r
+        /* compression rates */\r
+        if ((m_rates != wxT("")) && (!m_enablequality)) {\r
+                const char *s1 = m_rates.ToAscii();\r
+                wxLogMessage(wxT("rates %s"), s1);\r
+                while (sscanf(s1, "%f", &(parameters.tcp_rates[parameters.tcp_numlayers])) == 1) {\r
+                        parameters.tcp_numlayers++;\r
+                        while (*s1 && *s1 != ',') {\r
+                                s1++;\r
+                        }\r
+                        if (!*s1)\r
+                                break;\r
+                        s1++;\r
+                }\r
+                wxLogMessage(wxT("%d layers"), parameters.tcp_numlayers);\r
+                parameters.cp_disto_alloc = 1;\r
+        }\r
+\r
+        /* image quality, dB */\r
+        if ((m_quality != wxT("")) && (m_enablequality)) {\r
+                const char *s2 = m_quality.ToAscii();\r
+                wxLogMessage(wxT("qualities %s"), s2);\r
+                while (sscanf(s2, "%f", &parameters.tcp_distoratio[parameters.tcp_numlayers]) == 1) {\r
+                        parameters.tcp_numlayers++;\r
+                        while (*s2 && *s2 != ',') {\r
+                                s2++;\r
+                        }\r
+                        if (!*s2)\r
+                                break;\r
+                        s2++;\r
+                }\r
+                wxLogMessage(wxT("%d layers"), parameters.tcp_numlayers);\r
+                parameters.cp_fixed_quality = 1;\r
+        }\r
+\r
+        /* image origin */\r
+        if (sscanf(m_origin.ToAscii(), "%d,%d", &parameters.image_offset_x0, &parameters.image_offset_y0) != 2) {\r
+                wxLogError(wxT("bad coordinate of the image origin: x0,y0"));\r
+                return false;\r
+        }\r
+                                \r
+        /* Create comment for codestream */\r
+        if(m_enablecomm) {\r
+                parameters.cp_comment = (char *) malloc(strlen(m_comment.ToAscii()) + 1);\r
+                if(parameters.cp_comment) {\r
+                        strcpy(parameters.cp_comment, m_comment.ToAscii());\r
+                }\r
+        } else {\r
+                parameters.cp_comment = NULL;\r
+        }\r
+\r
+        /* indexing file */\r
+        if (m_enableidx) {\r
+                strncpy(indexfilename, m_index.ToAscii(), OPJ_PATH_LEN);\r
+                wxLogMessage(wxT("index file is %s"), indexfilename);\r
+        }\r
+\r
+        /* if no rate entered, lossless by default */\r
+        if (parameters.tcp_numlayers == 0) {\r
+                parameters.tcp_rates[0] = 0;   /* MOD antonin : losslessbug */\r
+                parameters.tcp_numlayers++;\r
+                parameters.cp_disto_alloc = 1;\r
+        }\r
+\r
+        /* irreversible transform */\r
+        parameters.irreversible = (m_irreversible == true) ? 1 : 0;\r
+\r
+        /* resolutions */\r
+        parameters.numresolution = m_resolutions;\r
+\r
+        /* codeblocks size */\r
+        if (m_cbsize != wxT("")) {\r
+                int cblockw_init = 0, cblockh_init = 0;\r
+                sscanf(m_cbsize.ToAscii(), "%d,%d", &cblockw_init, &cblockh_init);\r
+                if (cblockw_init * cblockh_init > 4096 || cblockw_init > 1024 || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {\r
+                        wxLogError(wxT("!! Size of code_block error !! Restrictions:\n  width*height<=4096\n  4<=width,height<= 1024"));\r
+                        return false;\r
+                }\r
+                parameters.cblockw_init = cblockw_init;\r
+                parameters.cblockh_init = cblockh_init;\r
+        }\r
+\r
+        /* precincts size */\r
+        if (m_prsize != wxT("")) {\r
+                char sep;\r
+                int res_spec = 0;\r
+                char *s = (char *) m_prsize.c_str();\r
+                do {\r
+                        sep = 0;\r
+                        sscanf(s, "[%d,%d]%c", &parameters.prcw_init[res_spec], &parameters.prch_init[res_spec], &sep);\r
+                        parameters.csty |= 0x01;\r
+                        res_spec++;\r
+                        s = strpbrk(s, "]") + 2;\r
+                } while (sep == ',');\r
+                parameters.res_spec = res_spec;\r
+        }\r
+\r
+        /* tiles */\r
+        if (m_tsize != wxT("")) {\r
+                sscanf(m_tsize.ToAscii(), "%d,%d", &parameters.cp_tdx, &parameters.cp_tdy);\r
+                parameters.tile_size_on = true;\r
+        }\r
+\r
+        /* tile origin */\r
+        if (sscanf(m_torigin.ToAscii(), "%d,%d", &parameters.cp_tx0, &parameters.cp_ty0) != 2) {\r
+                wxLogError(wxT("tile offset setting error: X0,Y0"));\r
+                return false;\r
+        }\r
+\r
+        /* use SOP */\r
+        if (m_enablesop)\r
+                parameters.csty |= 0x02;\r
+\r
+        /* use EPH */\r
+        if (m_enableeph)\r
+                parameters.csty |= 0x04;\r
+\r
+        /* multiple component transform */\r
+        if (m_multicomp)\r
+                parameters.tcp_mct = 1;\r
+        else\r
+                parameters.tcp_mct = 0;\r
+\r
+        /* mode switch */\r
+        parameters.mode = (m_enablebypass ? 1 : 0) + (m_enablereset ? 2 : 0)\r
+                + (m_enablerestart ? 4 : 0) + (m_enablevsc ? 8 : 0)\r
+                + (m_enableerterm ? 16 : 0) + (m_enablesegmark ? 32 : 0);\r
+\r
+        /* progression order */\r
+        switch (m_progression) {\r
+\r
+                /* LRCP */\r
+        case 0:\r
+                parameters.prog_order = LRCP;\r
+                break;\r
+\r
+                /* RLCP */\r
+        case 1:\r
+                parameters.prog_order = RLCP;\r
+                break;\r
+\r
+                /* RPCL */\r
+        case 2:\r
+                parameters.prog_order = RPCL;\r
+                break;\r
+\r
+                /* PCRL */\r
+        case 3:\r
+                parameters.prog_order = PCRL;\r
+                break;\r
+\r
+                /* CPRL */\r
+        case 4:\r
+                parameters.prog_order = CPRL;\r
+                break;\r
+\r
+                /* DCI2K24 */\r
+        case 5:\r
+                parameters.cp_cinema = CINEMA2K_24;\r
+                parameters.cp_rsiz = CINEMA2K;\r
+                break;\r
+\r
+                /* DCI2K48 */\r
+        case 6:\r
+                parameters.cp_cinema = CINEMA2K_48;\r
+                parameters.cp_rsiz = CINEMA2K;\r
+                break;\r
+\r
+                /* DCI4K */\r
+        case 7:\r
+                parameters.cp_cinema = CINEMA4K_24;\r
+                parameters.cp_rsiz = CINEMA4K;\r
+                break;\r
+\r
+        default:\r
+                break;\r
+        }\r
+\r
+        /* check cinema */\r
+        if (parameters.cp_cinema) {\r
+\r
+                /* set up */\r
+                parameters.tile_size_on = false;\r
+                parameters.cp_tdx=1;\r
+                parameters.cp_tdy=1;\r
+                \r
+                /*Tile part*/\r
+                parameters.tp_flag = 'C';\r
+                parameters.tp_on = 1;\r
+\r
+                /*Tile and Image shall be at (0,0)*/\r
+                parameters.cp_tx0 = 0;\r
+                parameters.cp_ty0 = 0;\r
+                parameters.image_offset_x0 = 0;\r
+                parameters.image_offset_y0 = 0;\r
+\r
+                /*Codeblock size= 32*32*/\r
+                parameters.cblockw_init = 32;  \r
+                parameters.cblockh_init = 32;\r
+                parameters.csty |= 0x01;\r
+\r
+                /*The progression order shall be CPRL*/\r
+                parameters.prog_order = CPRL;\r
+\r
+                /* No ROI */\r
+                parameters.roi_compno = -1;\r
+\r
+                parameters.subsampling_dx = 1;\r
+                parameters.subsampling_dy = 1;\r
+\r
+                /* 9-7 transform */\r
+                parameters.irreversible = 1;\r
+\r
+        }                              \r
+\r
+        /* convert wx image into opj image */\r
+        cmptparm = (opj_image_cmptparm_t*) malloc(3 * sizeof(opj_image_cmptparm_t));\r
+\r
+        /* initialize opj image components */  \r
+        memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));\r
+        for(i = 0; i < 3; i++) {               \r
+                cmptparm[i].prec = 8;\r
+                cmptparm[i].bpp = 8;\r
+                cmptparm[i].sgnd = false;\r
+                cmptparm[i].dx = parameters.subsampling_dx;\r
+                cmptparm[i].dy = parameters.subsampling_dy;\r
+                cmptparm[i].w = wimage->GetWidth();\r
+                cmptparm[i].h = wimage->GetHeight();\r
+        }\r
+\r
+        /* create the image */\r
+        oimage = opj_image_create(3, &cmptparm[0], CLRSPC_SRGB);\r
+        if(!oimage) {\r
+                if (cmptparm)\r
+                        free(cmptparm);\r
+                return false;\r
+        }\r
+\r
+        /* set image offset and reference grid */\r
+        oimage->x0 = parameters.image_offset_x0;\r
+        oimage->y0 = parameters.image_offset_y0;\r
+        oimage->x1 = parameters.image_offset_x0 + (wimage->GetWidth() - 1) * 1 + 1;\r
+        oimage->y1 = parameters.image_offset_y0 + (wimage->GetHeight() - 1) * 1 + 1;\r
+\r
+        /* load image data */\r
+        unsigned char *value = wimage->GetData(); \r
+        int area = wimage->GetWidth() * wimage->GetHeight();\r
+        for (i = 0; i < area; i++) {\r
+                        oimage->comps[0].data[i] = *(value++);\r
+                        oimage->comps[1].data[i] = *(value++);\r
+                        oimage->comps[2].data[i] = *(value++);\r
+        }\r
+\r
+        /* check cinema again */\r
+        if (parameters.cp_cinema) {\r
+                int i;\r
+                float temp_rate;\r
+                opj_poc_t *POC = NULL;\r
+\r
+                switch (parameters.cp_cinema) {\r
+\r
+                case CINEMA2K_24:\r
+                case CINEMA2K_48:\r
+                        if (parameters.numresolution > 6) {\r
+                                parameters.numresolution = 6;\r
+                        }\r
+                        if (!((oimage->comps[0].w == 2048) | (oimage->comps[0].h == 1080))) {\r
+                                wxLogWarning(wxT("Image coordinates %d x %d is not 2K compliant. JPEG Digital Cinema Profile-3 "\r
+                                        "(2K profile) compliance requires that at least one of coordinates match 2048 x 1080"),\r
+                                        oimage->comps[0].w, oimage->comps[0].h);\r
+                                parameters.cp_rsiz = STD_RSIZ;\r
+                        }\r
+                break;\r
+                \r
+                case CINEMA4K_24:\r
+                        if (parameters.numresolution < 1) {\r
+                                        parameters.numresolution = 1;\r
+                        } else if (parameters.numresolution > 7) {\r
+                                        parameters.numresolution = 7;\r
+                        }\r
+                        if (!((oimage->comps[0].w == 4096) | (oimage->comps[0].h == 2160))) {\r
+                                wxLogWarning(wxT("Image coordinates %d x %d is not 4K compliant. JPEG Digital Cinema Profile-4" \r
+                                        "(4K profile) compliance requires that at least one of coordinates match 4096 x 2160"),\r
+                                        oimage->comps[0].w, oimage->comps[0].h);\r
+                                parameters.cp_rsiz = STD_RSIZ;\r
+                        }\r
+                        parameters.POC[0].tile  = 1; \r
+                        parameters.POC[0].resno0  = 0; \r
+                        parameters.POC[0].compno0 = 0;\r
+                        parameters.POC[0].layno1  = 1;\r
+                        parameters.POC[0].resno1  = parameters.numresolution - 1;\r
+                        parameters.POC[0].compno1 = 3;\r
+                        parameters.POC[0].prg1 = CPRL;\r
+                        parameters.POC[1].tile  = 1;\r
+                        parameters.POC[1].resno0  = parameters.numresolution - 1; \r
+                        parameters.POC[1].compno0 = 0;\r
+                        parameters.POC[1].layno1  = 1;\r
+                        parameters.POC[1].resno1  = parameters.numresolution;\r
+                        parameters.POC[1].compno1 = 3;\r
+                        parameters.POC[1].prg1 = CPRL;\r
+                        parameters.numpocs = 2;\r
+                        break;\r
+                }\r
+\r
+                switch (parameters.cp_cinema) {\r
+                case CINEMA2K_24:\r
+                case CINEMA4K_24:\r
+                        for (i = 0 ; i < parameters.tcp_numlayers; i++) {\r
+                                temp_rate = 0;\r
+                                if (parameters.tcp_rates[i] == 0) {\r
+                                        parameters.tcp_rates[0] = ((float) (oimage->numcomps * oimage->comps[0].w * oimage->comps[0].h * oimage->comps[0].prec)) / \r
+                                        (CINEMA_24_CS * 8 * oimage->comps[0].dx * oimage->comps[0].dy);\r
+                                }else{\r
+                                        temp_rate = ((float) (oimage->numcomps * oimage->comps[0].w * oimage->comps[0].h * oimage->comps[0].prec)) / \r
+                                                (parameters.tcp_rates[i] * 8 * oimage->comps[0].dx * oimage->comps[0].dy);\r
+                                        if (temp_rate > CINEMA_24_CS ) {\r
+                                                parameters.tcp_rates[i]= ((float) (oimage->numcomps * oimage->comps[0].w * oimage->comps[0].h * oimage->comps[0].prec)) / \r
+                                                (CINEMA_24_CS * 8 * oimage->comps[0].dx * oimage->comps[0].dy);\r
+                                        } else {\r
+                                                /* do nothing */\r
+                                        }\r
+                                }\r
+                        }\r
+                        parameters.max_comp_size = COMP_24_CS;\r
+                        break;\r
+                        \r
+                case CINEMA2K_48:\r
+                        for (i = 0; i < parameters.tcp_numlayers; i++) {\r
+                                temp_rate = 0 ;\r
+                                if (parameters.tcp_rates[i] == 0) {\r
+                                        parameters.tcp_rates[0] = ((float) (oimage->numcomps * oimage->comps[0].w * oimage->comps[0].h * oimage->comps[0].prec)) / \r
+                                        (CINEMA_48_CS * 8 * oimage->comps[0].dx * oimage->comps[0].dy);\r
+                                }else{\r
+                                        temp_rate =((float) (oimage->numcomps * oimage->comps[0].w * oimage->comps[0].h * oimage->comps[0].prec)) / \r
+                                                (parameters.tcp_rates[i] * 8 * oimage->comps[0].dx * oimage->comps[0].dy);\r
+                                        if (temp_rate > CINEMA_48_CS ){\r
+                                                parameters.tcp_rates[0]= ((float) (oimage->numcomps * oimage->comps[0].w * oimage->comps[0].h * oimage->comps[0].prec)) / \r
+                                                (CINEMA_48_CS * 8 * oimage->comps[0].dx * oimage->comps[0].dy);\r
+                                        }else{\r
+                                                /* do nothing */\r
+                                        }\r
+                                }\r
+                        }\r
+                        parameters.max_comp_size = COMP_48_CS;\r
+                        break;\r
+                }\r
+\r
+                parameters.cp_disto_alloc = 1;\r
+        }\r
+        \r
+        /* get a J2K compressor handle */\r
+        opj_cinfo_t* cinfo = opj_create_compress(CODEC_J2K);\r
+\r
+        /* catch events using our callbacks and give a local context */\r
+        opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);\r
+\r
+        /* setup the encoder parameters using the current image and user parameters */\r
+        opj_setup_encoder(cinfo, &parameters, oimage);\r
+\r
+        /* open a byte stream for writing */\r
+        /* allocate memory for all tiles */\r
+        cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);\r
+\r
+        /* encode the image */\r
+        bSuccess = opj_encode_with_info(cinfo, cio, oimage, &cstr_info);\r
+        if (!bSuccess) {\r
+\r
+                opj_cio_close(cio);\r
+                opj_destroy_compress(cinfo);\r
+                opj_image_destroy(oimage);\r
+                if (cmptparm)\r
+                        free(cmptparm);\r
+                if(parameters.cp_comment)\r
+                        free(parameters.cp_comment);\r
+                if(parameters.cp_matrice)\r
+                        free(parameters.cp_matrice);\r
+\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiEnter();\r
+#endif /* __WXGTK__ */\r
+\r
+                wxLogError(wxT("failed to encode image"));\r
+\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiLeave();\r
+#endif /* __WXGTK__ */\r
+\r
+                return false;\r
+        }\r
+        codestream_length = cio_tell(cio);\r
+        wxLogMessage(wxT("Codestream: %d bytes"), codestream_length);\r
+\r
+        /* write the buffer to stream */\r
+        stream.Write(cio->buffer, codestream_length);\r
+\r
+        /* close and free the byte stream */\r
+        opj_cio_close(cio);\r
+\r
+        /* Write the index to disk */\r
+        if (*indexfilename) {\r
+                if (write_index_file(&cstr_info, indexfilename)) {\r
+                        wxLogError(wxT("Failed to output index file"));\r
+                }\r
+        }\r
+\r
+        /* free remaining compression structures */\r
+        opj_destroy_compress(cinfo);\r
+\r
+        /* free image data */\r
+        opj_image_destroy(oimage);\r
+\r
+        if (cmptparm)\r
+                free(cmptparm);\r
+        if(parameters.cp_comment)\r
+                free(parameters.cp_comment);\r
+        if(parameters.cp_matrice)\r
+                free(parameters.cp_matrice);\r
+\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiEnter();\r
+#endif /* __WXGTK__ */\r
+\r
+    wxLogMessage(wxT("J2K: Image encoded!"));\r
+\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiLeave();\r
+#endif /* __WXGTK__ */\r
+\r
+    return true;\r
+}\r
+\r
+#ifdef __VISUALC__\r
+    #pragma warning(default:4611)\r
+#endif /* VC++ */\r
+\r
+// recognize the JPEG 2000 family starting box or the 0xFF4F JPEG 2000 SOC marker\r
+bool wxJPEG2000Handler::DoCanRead(wxInputStream& stream)\r
+{\r
+    unsigned char hdr[24];\r
+       int jpfamform;\r
+\r
+    if ( !stream.Read(hdr, WXSIZEOF(hdr)) )\r
+        return false;\r
+\r
+       jpfamform = jpeg2000familytype(hdr, WXSIZEOF(hdr));\r
+\r
+       return ((jpfamform == JP2_CFMT) || (jpfamform == MJ2_CFMT) || (jpfamform == J2K_CFMT));\r
+}\r
+\r
+#endif   // wxUSE_STREAMS\r
+\r
+#endif   // wxUSE_LIBOPENJPEG\r
diff --git a/applications/OPJViewer/source/imagjpeg2000.h b/applications/OPJViewer/source/imagjpeg2000.h
new file mode 100644 (file)
index 0000000..2fea20a
--- /dev/null
@@ -0,0 +1,177 @@
+/*\r
+ * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        imagalljpeg2000.h\r
+// Purpose:     wxImage JPEG 2000 family file format handler\r
+// Author:      G. Baruffa - based on imagjpeg.h, Vaclav Slavik\r
+// RCS-ID:      $Id: imagalljpeg2000.h,v 0.0 2008/01/31 11:22:00 VZ Exp $\r
+// Copyright:   (c) Giuseppe Baruffa\r
+// Licence:     wxWindows licence\r
+/////////////////////////////////////////////////////////////////////////////\r
+\r
+#ifndef _WX_IMAGJPEG2000_H_\r
+#define _WX_IMAGJPEG2000_H_\r
+\r
+#include "wx/defs.h"\r
+\r
+//-----------------------------------------------------------------------------\r
+// wxJPEG2000Handler\r
+//-----------------------------------------------------------------------------\r
+\r
+#if wxUSE_LIBOPENJPEG\r
+\r
+#include "wx/image.h"\r
+#include "libopenjpeg/openjpeg.h"\r
+#include "codec/index.h"\r
+\r
+#define wxBITMAP_TYPE_JPEG2000 50\r
+\r
+class WXDLLEXPORT wxJPEG2000Handler: public wxImageHandler\r
+{\r
+public:\r
+    inline wxJPEG2000Handler()\r
+    {\r
+        m_name = wxT("JPEG 2000 family file format");\r
+        m_extension = wxT("mj2");\r
+        m_type = wxBITMAP_TYPE_JPEG2000;\r
+        m_mime = wxT("image/mj2");\r
+\r
+               /* decoding */\r
+               m_reducefactor = 0;\r
+               m_qualitylayers = 0;\r
+               m_components = 0;\r
+#ifdef USE_JPWL\r
+               m_enablejpwl = true;\r
+               m_expcomps = JPWL_EXPECTED_COMPONENTS;\r
+               m_maxtiles = JPWL_MAXIMUM_TILES;\r
+#endif // USE_JPWL\r
+\r
+               /* encoding */\r
+               m_subsampling = wxT("1,1");\r
+               m_origin = wxT("0,0");\r
+               m_rates = wxT("20,10,5");\r
+               m_quality = wxT("30,35,40");\r
+               m_enablequality = false;\r
+               m_multicomp = false;\r
+               m_irreversible = false;\r
+               m_resolutions = 6;\r
+               m_progression = 0;\r
+               m_cbsize = wxT("32,32");\r
+               m_prsize = wxT("[128,128],[128,128]");\r
+               m_tsize = wxT("");\r
+               m_torigin = wxT("0,0");\r
+               /*m_progression\r
+               m_resilience*/\r
+               m_enablesop = false;\r
+               m_enableeph = false;\r
+               m_enablereset = false;\r
+               m_enablesegmark = false;\r
+               m_enablevsc = false;\r
+               m_enablerestart = false;\r
+               m_enableerterm = false;\r
+               m_enablebypass = false;\r
+               /*m_roicompo\r
+               m_roiup\r
+               m_indexfname*/\r
+               m_enableidx = false;\r
+               m_index = wxT("index.txt");\r
+               m_enablepoc = false;\r
+               m_poc = wxT("T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL");\r
+               m_enablecomm = true;\r
+\r
+#if defined __WXMSW__\r
+               m_comment = wxT("Created by OPJViewer Win32 - OpenJPEG  version ");\r
+#elif defined __WXGTK__\r
+               m_comment = wxT("Created by OPJViewer Lin32 - OpenJPEG version ");\r
+#else\r
+               m_comment = wxT("Created by OPJViewer - OpenJPEG version ");\r
+#endif\r
+\r
+#ifdef USE_JPWL\r
+               m_comment += wxString::Format(wxT("%s with JPWL"), (char *) opj_version());\r
+#else\r
+               m_comment += wxString::Format(wxT("%s"), (char *) opj_version());\r
+#endif\r
+\r
+    }\r
+\r
+       // decoding engine parameters\r
+       int m_reducefactor, m_qualitylayers, m_components, m_framenum;\r
+#ifdef USE_JPWL\r
+       bool m_enablejpwl;\r
+       int m_expcomps, m_maxtiles;\r
+#endif // USE_JPWL\r
+\r
+       // encoding engine parameters\r
+       wxString m_subsampling;\r
+       wxString m_origin;\r
+       wxString m_rates;\r
+       wxString m_quality;\r
+       bool m_enablequality;\r
+       bool m_multicomp;\r
+       bool m_irreversible;\r
+       int m_resolutions;\r
+       int m_progression;\r
+       wxString m_cbsize;\r
+       wxString m_prsize;\r
+       wxString m_tsize;\r
+       wxString m_torigin;\r
+       /*m_progression\r
+       m_resilience*/\r
+       bool m_enablesop;\r
+       bool m_enableeph;\r
+       bool m_enablebypass;\r
+       bool m_enableerterm;\r
+       bool m_enablerestart;\r
+       bool m_enablereset;\r
+       bool m_enablesegmark;\r
+       bool m_enablevsc;\r
+       /*m_roicompo\r
+       m_roiup\r
+       m_indexfname*/\r
+       bool m_enableidx;\r
+       wxString m_index;\r
+       bool m_enablecomm;\r
+       wxString m_comment;\r
+       bool m_enablepoc;\r
+       wxString m_poc;\r
+\r
+#if wxUSE_STREAMS\r
+    virtual bool LoadFile(wxImage *image, wxInputStream& stream, bool verbose=true, int index=-1);\r
+    virtual bool SaveFile(wxImage *image, wxOutputStream& stream, bool verbose=true);\r
+protected:\r
+    virtual bool DoCanRead(wxInputStream& stream);\r
+#endif\r
+\r
+private:\r
+       OPJ_PROG_ORDER give_progression(char progression[4]);\r
+    DECLARE_DYNAMIC_CLASS(wxJPEG2000Handler)\r
+};\r
+\r
+#endif // wxUSE_LIBOPENJPEG\r
+\r
+#endif // _WX_IMAGJPEG2000_H_\r
+\r
diff --git a/applications/OPJViewer/source/imagmxf.cpp b/applications/OPJViewer/source/imagmxf.cpp
new file mode 100644 (file)
index 0000000..99d0b93
--- /dev/null
@@ -0,0 +1,502 @@
+/*\r
+ * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        imagmxf.cpp\r
+// Purpose:     wxImage MXF (Material eXchange Format) JPEG 2000 file format handler\r
+// Author:      Giuseppe Baruffa - based on imagjpeg.cpp, Vaclav Slavik\r
+// RCS-ID:      $Id: imagmxf.cpp,v 0.00 2007/11/19 17:00:00 MW Exp $\r
+// Copyright:   (c) Giuseppe Baruffa\r
+// Licence:     wxWindows licence\r
+/////////////////////////////////////////////////////////////////////////////\r
+\r
+#ifdef USE_MXF\r
+\r
+#include "mxflib/mxflib.h"\r
+using namespace mxflib;\r
+\r
+namespace\r
+{\r
+       //! Structure holding information about the essence in each body stream\r
+       struct EssenceInfo\r
+       {\r
+               UMIDPtr PackageID;\r
+               PackagePtr Package;\r
+               MDObjectPtr Descriptor;\r
+       };\r
+       //! Map of EssenceInfo structures indexed by BodySID\r
+       typedef std::map<UInt32, EssenceInfo> EssenceInfoMap;\r
+\r
+       //! The map of essence info for this file\r
+       EssenceInfoMap EssenceLookup;\r
+};\r
+\r
+//! Build an EssenceInfoMap for the essence in a given file\r
+/*! \return True if al OK, else false\r
+ */\r
+bool BuildEssenceInfo(MXFFilePtr &File, EssenceInfoMap &EssenceLookup);\r
+\r
+// For compilers that support precompilation, includes "wx.h".\r
+#include "wx/wxprec.h"\r
+\r
+#ifdef __BORLANDC__\r
+    #pragma hdrstop\r
+#endif\r
+\r
+#if wxUSE_IMAGE && wxUSE_LIBOPENJPEG\r
+\r
+#include "imagmxf.h"\r
+\r
+#ifndef WX_PRECOMP\r
+    #include "wx/log.h"\r
+    #include "wx/app.h"\r
+    #include "wx/intl.h"\r
+    #include "wx/bitmap.h"\r
+    #include "wx/module.h"\r
+#endif\r
+\r
+\r
+#include "libopenjpeg/openjpeg.h"\r
+\r
+\r
+#include "wx/filefn.h"\r
+#include "wx/wfstream.h"\r
+\r
+// ----------------------------------------------------------------------------\r
+// types\r
+// ----------------------------------------------------------------------------\r
+\r
+\r
+//-----------------------------------------------------------------------------\r
+// wxMXFHandler\r
+//-----------------------------------------------------------------------------\r
+\r
+IMPLEMENT_DYNAMIC_CLASS(wxMXFHandler,wxImageHandler)\r
+\r
+#if wxUSE_STREAMS\r
+\r
+#include <stdarg.h>\r
+#define MAX_MESSAGE_LEN 200\r
+\r
+//------------- MXF Manager\r
+\r
+// Debug and error messages\r
+\r
+//! Display a warning message\r
+void mxflib::warning(const char *Fmt, ...)\r
+{\r
+       char msg[MAX_MESSAGE_LEN];\r
+       va_list args;\r
+\r
+       va_start(args, Fmt);\r
+       _vsnprintf(msg, MAX_MESSAGE_LEN, Fmt, args);\r
+       va_end(args);\r
+\r
+       int message_len = strlen(msg) - 1;\r
+       if (msg[message_len] != '\n')\r
+               message_len = MAX_MESSAGE_LEN;\r
+#ifndef __WXGTK__ \r
+               wxMutexGuiEnter();\r
+#endif /* __WXGTK__ */\r
+       wxLogMessage(wxT("[WARNING_MXF] %.*s"), message_len, msg);\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiLeave();\r
+#endif /* __WXGTK__ */\r
+}\r
+\r
+//! Display an error message\r
+void mxflib::error(const char *Fmt, ...)\r
+{\r
+       char msg[MAX_MESSAGE_LEN];\r
+       va_list args;\r
+\r
+       va_start(args, Fmt);\r
+       _vsnprintf(msg, MAX_MESSAGE_LEN, Fmt, args);\r
+       va_end(args);\r
+\r
+       int message_len = strlen(msg) - 1;\r
+       if (msg[message_len] != '\n')\r
+               message_len = MAX_MESSAGE_LEN;\r
+#ifndef __WXGTK__ \r
+               wxMutexGuiEnter();\r
+#endif /* __WXGTK__ */\r
+       wxLogMessage(wxT("[ERROR_MXF] %.*s"), message_len, msg);\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiLeave();\r
+#endif /* __WXGTK__ */\r
+}\r
+\r
+//! Display an error message\r
+void mxflib::debug(const char *Fmt, ...)\r
+{\r
+       char msg[MAX_MESSAGE_LEN];\r
+       va_list args;\r
+\r
+       va_start(args, Fmt);\r
+       _vsnprintf(msg, MAX_MESSAGE_LEN, Fmt, args);\r
+       va_end(args);\r
+\r
+       int message_len = strlen(msg) - 1;\r
+       if (msg[message_len] != '\n')\r
+               message_len = MAX_MESSAGE_LEN;\r
+#ifndef __WXGTK__ \r
+               wxMutexGuiEnter();\r
+#endif /* __WXGTK__ */\r
+       wxLogMessage(wxT("[DEBUG_MXF] %.*s"), message_len, msg);\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiLeave();\r
+#endif /* __WXGTK__ */\r
+}\r
+\r
+\r
+\r
+//------------- JPEG 2000 Data Source Manager\r
+\r
+#define J2K_CFMT 0\r
+#define JP2_CFMT 1\r
+#define JPT_CFMT 2\r
+#define MJ2_CFMT 3\r
+#define PXM_DFMT 0\r
+#define PGX_DFMT 1\r
+#define BMP_DFMT 2\r
+#define YUV_DFMT 3\r
+\r
+/* sample error callback expecting a FILE* client object */\r
+void mxf_error_callback(const char *msg, void *client_data) {\r
+       int message_len = strlen(msg) - 1;\r
+       if (msg[message_len] != '\n')\r
+               message_len = MAX_MESSAGE_LEN;\r
+#ifndef __WXGTK__ \r
+               wxMutexGuiEnter();\r
+#endif /* __WXGTK__ */\r
+       wxLogMessage(wxT("[ERROR] %.*s"), message_len, msg);\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiLeave();\r
+#endif /* __WXGTK__ */\r
+}\r
+\r
+/* sample warning callback expecting a FILE* client object */\r
+void mxf_warning_callback(const char *msg, void *client_data) {\r
+       int message_len = strlen(msg) - 1;\r
+       if (msg[message_len] != '\n')\r
+               message_len = MAX_MESSAGE_LEN;\r
+#ifndef __WXGTK__ \r
+               wxMutexGuiEnter();\r
+#endif /* __WXGTK__ */\r
+       wxLogMessage(wxT("[WARNING] %.*s"), message_len, msg);\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiLeave();\r
+#endif /* __WXGTK__ */\r
+}\r
+\r
+/* sample debug callback expecting no client object */\r
+void mxf_info_callback(const char *msg, void *client_data) {\r
+       int message_len = strlen(msg) - 1;\r
+       if (msg[message_len] != '\n')\r
+               message_len = MAX_MESSAGE_LEN;\r
+#ifndef __WXGTK__ \r
+               wxMutexGuiEnter();\r
+#endif /* __WXGTK__ */\r
+       wxLogMessage(wxT("[INFO] %.*s"), message_len, msg);\r
+#ifndef __WXGTK__ \r
+    wxMutexGuiLeave();\r
+#endif /* __WXGTK__ */\r
+}\r
+\r
+\r
+/////////////////////////////////////////////////\r
+/////////////////////////////////////////////////\r
+\r
+// load the mxf file format\r
+bool wxMXFHandler::LoadFile(wxImage *image, wxInputStream& stream, bool verbose, int index)\r
+{\r
+       opj_dparameters_t parameters;   /* decompression parameters */\r
+       opj_event_mgr_t event_mgr;              /* event manager */\r
+       opj_image_t *opjimage = NULL;\r
+       unsigned char *src = NULL;\r
+    unsigned char *ptr;\r
+       int file_length, j2k_point, j2k_len;\r
+       opj_codestream_info_t cstr_info;  /* Codestream information structure */\r
+       \r
+       // simply display the version of the library\r
+       wxLogMessage(wxT("Version of MXF: %s   "), wxString::FromAscii(LibraryVersion().c_str()));\r
+       //wxLogMessage(wxT("MXF file name: %s"), m_filename.GetFullPath());\r
+\r
+       // open MXF file\r
+       MXFFilePtr TestFile = new MXFFile;\r
+       if (! TestFile->Open(m_filename.GetFullPath().c_str(), true))\r
+       {\r
+               wxLogError(wxT("Could not find %s"), m_filename.GetFullPath().c_str());\r
+               return false;\r
+       } else\r
+               wxLogMessage(wxT("Found %s"), m_filename.GetFullPath().c_str());\r
+\r
+       // Get the size\r
+       TestFile->SeekEnd();\r
+       wxLogMessage(wxT("Size is %d bytes"), TestFile->Tell());\r
+       TestFile->Seek(0);\r
+\r
+       // essence information\r
+       //BuildEssenceInfo(TestFile, EssenceLookup);\r
+\r
+       // close MXF file\r
+       TestFile->Close();\r
+\r
+       return false;\r
+       \r
+       // destroy the image\r
+    image->Destroy();\r
+\r
+       /* handle to a decompressor */\r
+       opj_dinfo_t* dinfo = NULL;      \r
+       opj_cio_t *cio = NULL;\r
+\r
+       /* configure the event callbacks (not required) */\r
+       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));\r
+       event_mgr.error_handler = mxf_error_callback;\r
+       event_mgr.warning_handler = mxf_warning_callback;\r
+       event_mgr.info_handler = mxf_info_callback;\r
+\r
+       /* set decoding parameters to default values */\r
+       opj_set_default_decoder_parameters(&parameters);\r
+\r
+       /* prepare parameters */\r
+       strncpy(parameters.infile, "", sizeof(parameters.infile)-1);\r
+       strncpy(parameters.outfile, "", sizeof(parameters.outfile)-1);\r
+       parameters.decod_format = J2K_CFMT;\r
+       parameters.cod_format = BMP_DFMT;\r
+       if (m_reducefactor)\r
+               parameters.cp_reduce = m_reducefactor;\r
+       if (m_qualitylayers)\r
+               parameters.cp_layer = m_qualitylayers;\r
+       /*if (n_components)\r
+               parameters. = n_components;*/\r
+\r
+       /* JPWL only */\r
+#ifdef USE_JPWL\r
+       parameters.jpwl_exp_comps = m_expcomps;\r
+       parameters.jpwl_max_tiles = m_maxtiles;\r
+       parameters.jpwl_correct = m_enablejpwl;\r
+#endif /* USE_JPWL */\r
+\r
+       /* get a decoder handle */\r
+       dinfo = opj_create_decompress(CODEC_J2K);\r
+\r
+       /* find length of the stream */\r
+       stream.SeekI(0, wxFromEnd);\r
+       file_length = (int) stream.TellI();\r
+\r
+       /* search for the m_framenum codestream position and length  */\r
+       //jp2c_point = searchjp2c(stream, file_length, m_framenum);\r
+       //jp2c_len = searchjp2c(stream, file_length, m_framenum);\r
+       j2k_point = 0;\r
+       j2k_len = 10;\r
+\r
+       // malloc memory source\r
+    src = (unsigned char *) malloc(j2k_len);\r
+\r
+       // copy the jp2c\r
+       stream.SeekI(j2k_point, wxFromStart);\r
+       stream.Read(src, j2k_len);\r
+\r
+       /* catch events using our callbacks and give a local context */\r
+       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);\r
+\r
+       /* setup the decoder decoding parameters using user parameters */\r
+       opj_setup_decoder(dinfo, &parameters);\r
+\r
+       /* open a byte stream */\r
+       cio = opj_cio_open((opj_common_ptr)dinfo, src, j2k_len);\r
+\r
+       /* decode the stream and fill the image structure */\r
+       opjimage = opj_decode_with_info(dinfo, cio, &cstr_info);\r
+       if (!opjimage) {\r
+               wxMutexGuiEnter();\r
+               wxLogError(wxT("MXF: failed to decode image!"));\r
+               wxMutexGuiLeave();\r
+               opj_destroy_decompress(dinfo);\r
+               opj_cio_close(cio);\r
+               free(src);\r
+               return false;\r
+       }\r
+\r
+       /* close the byte stream */\r
+       opj_cio_close(cio);\r
+\r
+       /* common rendering method */\r
+#include "imagjpeg2000.cpp"\r
+\r
+    wxMutexGuiEnter();\r
+    wxLogMessage(wxT("MXF: image loaded."));\r
+    wxMutexGuiLeave();\r
+\r
+       /* close openjpeg structs */\r
+       opj_destroy_decompress(dinfo);\r
+       opj_image_destroy(opjimage);\r
+       free(src);\r
+\r
+       if (!image->Ok())\r
+               return false;\r
+       else\r
+               return true;\r
+\r
+}\r
+\r
+// save the mxf file format\r
+bool wxMXFHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )\r
+{\r
+    wxLogError(wxT("MXF: Couldn't save movie -> not implemented."));\r
+    return false;\r
+}\r
+\r
+#ifdef __VISUALC__\r
+    #pragma warning(default:4611)\r
+#endif /* VC++ */\r
+\r
+// recognize the MXF JPEG 2000 starting box\r
+bool wxMXFHandler::DoCanRead( wxInputStream& stream )\r
+{\r
+    unsigned char hdr[4];\r
+\r
+    if ( !stream.Read(hdr, WXSIZEOF(hdr)) )\r
+        return false;\r
+\r
+    return (hdr[0] == 0x06 &&\r
+                       hdr[1] == 0x0E &&\r
+                       hdr[2] == 0x2B &&\r
+                       hdr[3] == 0x34);\r
+}\r
+\r
+//! Build an EssenceInfoMap for the essence in a given file\r
+/*! \return True if al OK, else false\r
+ */\r
+bool BuildEssenceInfo(MXFFilePtr &File, EssenceInfoMap &EssenceLookup)\r
+{\r
+       // Empty any old data\r
+       EssenceLookup.clear();\r
+\r
+       // Get the master metadata set (or the header if we must)\r
+       PartitionPtr MasterPartition = File->ReadMasterPartition();\r
+       if(!MasterPartition)\r
+       {\r
+               File->Seek(0);\r
+               MasterPartition = File->ReadPartition();\r
+               warning("File %s does not contain a cloased copy of header metadata - using the open copy in the file header\n", File->Name.c_str());\r
+       }\r
+\r
+       if(!MasterPartition) \r
+       {\r
+               error("Could not read header metadata from file %s\n", File->Name.c_str());\r
+               return false;\r
+       }\r
+\r
+       // Read and parse the metadata\r
+       MasterPartition->ReadMetadata();\r
+       MetadataPtr HMeta = MasterPartition->ParseMetadata();\r
+       \r
+       if(!HMeta) \r
+       {\r
+               error("Could not read header metadata from file %s\n", File->Name.c_str());\r
+               return false;\r
+       }\r
+\r
+       /* Scan the Essence container data sets to get PackageID to BodySID mapping */\r
+       MDObjectPtr ECDSet = HMeta[ContentStorage_UL];\r
+       if(ECDSet) ECDSet = ECDSet->GetLink();\r
+       if(ECDSet) ECDSet = ECDSet[EssenceContainerDataBatch_UL];\r
+       if(!ECDSet)\r
+       {\r
+               error("Header metadata in file %s does not contain an EssenceContainerData set\n", File->Name.c_str());\r
+               return false;\r
+       }\r
+\r
+       MDObject::iterator it = ECDSet->begin();\r
+       while(it != ECDSet->end())\r
+       {\r
+               MDObjectPtr ThisECDSet = (*it).second->GetLink();\r
+               MDObjectPtr PackageID;\r
+               if(ThisECDSet) PackageID = ThisECDSet->Child(LinkedPackageUID_UL);\r
+               if(PackageID)\r
+               {\r
+                       EssenceInfo NewEI;\r
+                       NewEI.PackageID = new UMID(PackageID->PutData()->Data);\r
+\r
+                       // Inset the basic essence info - but not if this is external essence (BodySID == 0)\r
+                       UInt32 BodySID = ThisECDSet->GetUInt(BodySID_UL);\r
+                       if(BodySID) EssenceLookup[BodySID] = NewEI;\r
+               }\r
+               it++;\r
+       }\r
+\r
+       /* Now find the other items for the essence lookup map */\r
+       if(EssenceLookup.size())\r
+       {\r
+               PackageList::iterator it = HMeta->Packages.begin();\r
+               while(it != HMeta->Packages.end())\r
+               {\r
+                       // Only Source Packages are of interest\r
+                       if((*it)->IsA(SourcePackage_UL))\r
+                       {\r
+                               MDObjectPtr Descriptor = (*it)->Child(Descriptor_UL);\r
+                               if(Descriptor) Descriptor = Descriptor->GetLink();\r
+\r
+                               if(Descriptor)\r
+                               {\r
+                                       MDObjectPtr PackageID = (*it)->Child(PackageUID_UL);\r
+                                       if(PackageID)\r
+                                       {\r
+                                               UMIDPtr TheID = new UMID(PackageID->PutData()->Data);\r
+                                               \r
+                                               /* Now do a lookup in the essence lookup map (it will need to be done the long way here */\r
+                                               EssenceInfoMap::iterator EL_it = EssenceLookup.begin();\r
+                                               while(EL_it != EssenceLookup.end())\r
+                                               {\r
+                                                       if((*((*EL_it).second.PackageID)) == (*TheID))\r
+                                                       {\r
+                                                               // If found, set the missing items and stop searching\r
+                                                               (*EL_it).second.Package = (*it);\r
+                                                               (*EL_it).second.Descriptor = Descriptor;\r
+                                                               break;\r
+                                                       }\r
+                                                       EL_it++;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+\r
+                       it++;\r
+               }\r
+       }\r
+\r
+       return true;\r
+}\r
+\r
+\r
+#endif   // wxUSE_STREAMS\r
+\r
+#endif   // wxUSE_LIBOPENJPEG\r
+\r
+#endif // USE_MXF\r
+\r
diff --git a/applications/OPJViewer/source/imagmxf.h b/applications/OPJViewer/source/imagmxf.h
new file mode 100644 (file)
index 0000000..c87a4cb
--- /dev/null
@@ -0,0 +1,99 @@
+/*\r
+ * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+/////////////////////////////////////////////////////////////////////////////\r
+// Name:        imagmxf.h\r
+// Purpose:     wxImage MXF (Material eXchange Format) JPEG 2000 file format handler\r
+// Author:      G. Baruffa - based on imagjpeg.h, Vaclav Slavik\r
+// RCS-ID:      $Id: imagmj2.h,v 0.0 2007/11/19 17:00:00 VZ Exp $\r
+// Copyright:   (c) Giuseppe Baruffa\r
+// Licence:     wxWindows licence\r
+/////////////////////////////////////////////////////////////////////////////\r
+\r
+#ifndef _WX_IMAGMXF_H_\r
+#define _WX_IMAGMXF_H_\r
+\r
+#ifdef USE_MXF\r
+\r
+#include "wx/defs.h"\r
+#include "wx/filename.h"\r
+\r
+//-----------------------------------------------------------------------------\r
+// wxMXFHandler\r
+//-----------------------------------------------------------------------------\r
+\r
+#if wxUSE_LIBOPENJPEG\r
+\r
+#include "wx/image.h"\r
+#include "libopenjpeg/openjpeg.h"\r
+\r
+#define wxBITMAP_TYPE_MXF      51\r
+\r
+class WXDLLEXPORT wxMXFHandler: public wxImageHandler\r
+{\r
+public:\r
+    inline wxMXFHandler()\r
+    {\r
+        m_name = wxT("MXF JPEG 2000 file format");\r
+        m_extension = wxT("mxf");\r
+        m_type = wxBITMAP_TYPE_MXF;\r
+        m_mime = wxT("image/mxf");\r
+\r
+               m_reducefactor = 0;\r
+               m_qualitylayers = 0;\r
+               m_components = 0;\r
+               m_filename = wxT("");\r
+#ifdef USE_JPWL\r
+               m_enablejpwl = true;\r
+               m_expcomps = JPWL_EXPECTED_COMPONENTS;\r
+               m_maxtiles = JPWL_MAXIMUM_TILES;\r
+#endif // USE_JPWL\r
+    }\r
+\r
+               // decoding engine parameters\r
+               int m_reducefactor, m_qualitylayers, m_components, m_framenum;\r
+               wxFileName m_filename;\r
+#ifdef USE_JPWL\r
+               bool m_enablejpwl;\r
+               int m_expcomps, m_maxtiles;\r
+#endif // USE_JPWL\r
+\r
+#if wxUSE_STREAMS\r
+    virtual bool LoadFile( wxImage *image, wxInputStream& stream, bool verbose=true, int index=-1 );\r
+    virtual bool SaveFile( wxImage *image, wxOutputStream& stream, bool verbose=true );\r
+protected:\r
+    virtual bool DoCanRead( wxInputStream& stream );\r
+#endif\r
+\r
+private:\r
+    DECLARE_DYNAMIC_CLASS(wxMXFHandler)\r
+};\r
+\r
+#endif // wxUSE_LIBOPENJPEG\r
+\r
+#endif // USE_MXF\r
+\r
+#endif // _WX_IMAGMXF_H_\r
+\r
diff --git a/applications/OPJViewer/source/license.txt b/applications/OPJViewer/source/license.txt
new file mode 100644 (file)
index 0000000..81d6b34
--- /dev/null
@@ -0,0 +1,14 @@
+Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
+Copyright (c) 2002-2007, Professor Benoit Macq\r
+Copyright (c) 2001-2003, David Janssens\r
+Copyright (c) 2002-2003, Yannick Verschueren\r
+Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe\r
+Copyright (c) 2005, Herve Drolon, FreeImage Team\r
+Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
+All rights reserved.\r
+\r
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditionsare met:\r
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\r
+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\r
+\r
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/applications/OPJViewer/source/opj_logo.xpm b/applications/OPJViewer/source/opj_logo.xpm
new file mode 100644 (file)
index 0000000..c64d0a7
--- /dev/null
@@ -0,0 +1,285 @@
+/* XPM */
+static char *opj_logo[] = {
+/* columns rows colors chars-per-pixel */
+"90 61 218 2",
+"   c #BE3D12",
+".  c #BF461D",
+"X  c #AD5435",
+"o  c #B64925",
+"O  c #B54E2B",
+"+  c #BC4620",
+"@  c #BB4B25",
+"#  c #BC4E29",
+"$  c #B5502F",
+"%  c #BD512C",
+"&  c #B45334",
+"*  c #B35638",
+"=  c #B45B3D",
+"-  c #BB5533",
+";  c #BE5937",
+":  c #BC5C3D",
+">  c #9C766A",
+",  c #AD5D42",
+"<  c #B55F41",
+"1  c #BA5E40",
+"2  c #A7634D",
+"3  c #A76C57",
+"4  c #AA6750",
+"5  c #AC6B56",
+"6  c #AA6E5A",
+"7  c #A4705E",
+"8  c #B46045",
+"9  c #B1644B",
+"0  c #BD6244",
+"q  c #B96448",
+"w  c #BC694D",
+"e  c #B36B53",
+"r  c #B26E58",
+"t  c #BB6C52",
+"y  c #B2725D",
+"u  c #BD7056",
+"i  c #BB745C",
+"p  c #A67566",
+"a  c #A57B6D",
+"s  c #AE7562",
+"d  c #AB7867",
+"f  c #AA7C6C",
+"g  c #A07E73",
+"h  c #AA7F71",
+"j  c #B37661",
+"k  c #B47863",
+"l  c #B27D6B",
+"z  c #BB7863",
+"x  c #BA7E69",
+"c  c #C73605",
+"v  c #C63A0B",
+"b  c #CB3300",
+"n  c #CA3807",
+"m  c #C93A0A",
+"M  c #C43E11",
+"N  c #C93E10",
+"B  c #C44115",
+"V  c #C3441A",
+"C  c #C4481E",
+"Z  c #CA4113",
+"A  c #C94519",
+"S  c #CB481C",
+"D  c #C24A23",
+"F  c #C24F28",
+"G  c #CD4D23",
+"H  c #C4522D",
+"J  c #CB532B",
+"K  c #C25632",
+"L  c #C35936",
+"P  c #C25C3B",
+"I  c #C85630",
+"U  c #CB5933",
+"Y  c #CB5E3A",
+"T  c #D05026",
+"R  c #CC613D",
+"E  c #C26343",
+"W  c #C46748",
+"Q  c #C1694C",
+"!  c #CD6744",
+"~  c #CA6C4D",
+"^  c #C37155",
+"/  c #C4755B",
+"(  c #CB7356",
+")  c #C8765B",
+"_  c #D06D4C",
+"`  c #D07253",
+"'  c #D47B5E",
+"]  c #C37B63",
+"[  c #C27E68",
+"{  c #C97F68",
+"}  c #A68175",
+"|  c #A48479",
+" . c #AD8172",
+".. c #AD8578",
+"X. c #AB897D",
+"o. c #B1806F",
+"O. c #BA816F",
+"+. c #B38373",
+"@. c #B58778",
+"#. c #B3897B",
+"$. c #BA8472",
+"%. c #BB8C7C",
+"&. c #C2816B",
+"*. c #CD846C",
+"=. c #C38470",
+"-. c #C38976",
+";. c #C38D7B",
+":. c #CC8973",
+">. c #CF8F7A",
+",. c #CB907D",
+"<. c #D1937F",
+"1. c #948E8C",
+"2. c #9D8C86",
+"3. c #9D8F89",
+"4. c #96908E",
+"5. c #9C918D",
+"6. c #949392",
+"7. c #9B9492",
+"8. c #9D9997",
+"9. c #9D9C9C",
+"0. c #A38B83",
+"q. c #AA8D83",
+"w. c #A4918B",
+"e. c #AC9087",
+"r. c #AB938C",
+"t. c #A49590",
+"y. c #A29996",
+"u. c #A19D9C",
+"i. c #AA9790",
+"p. c #AC9994",
+"a. c #AC9E99",
+"s. c #B18D81",
+"d. c #B59084",
+"f. c #B49389",
+"g. c #BA9184",
+"h. c #B89589",
+"j. c #BA988D",
+"k. c #B29B93",
+"l. c #BC9C92",
+"z. c #ACA19D",
+"x. c #B1A19D",
+"c. c #BCA39B",
+"v. c #A3A3A3",
+"b. c #ABA5A3",
+"n. c #AEA9A7",
+"m. c #ABABAA",
+"M. c #B3A5A1",
+"N. c #B3A9A6",
+"B. c #B3ADAA",
+"V. c #B9A6A0",
+"C. c #B9AAA5",
+"Z. c #BAADA9",
+"A. c #B4B0AF",
+"S. c #BAB0AD",
+"D. c #B4B3B3",
+"F. c #BAB5B3",
+"G. c #BDB8B6",
+"H. c #BBBBBB",
+"J. c #C39384",
+"K. c #C0978A",
+"L. c #C2998B",
+"P. c #CA9483",
+"I. c #CD9A8A",
+"U. c #C19D92",
+"Y. c #D69B89",
+"T. c #DB9680",
+"R. c #C2A095",
+"E. c #C4A69C",
+"W. c #CCA193",
+"Q. c #C8A599",
+"!. c #CBA99D",
+"~. c #C6AEA6",
+"^. c #CCACA2",
+"/. c #CBB2AB",
+"(. c #C3B8B5",
+"). c #C2BDBC",
+"_. c #C9B9B3",
+"`. c #D3ADA0",
+"'. c #D3B4A9",
+"]. c #DCB2A4",
+"[. c #DEB6A8",
+"{. c #D1BFB9",
+"}. c #D9BEB5",
+"|. c #C5C0BE",
+" X c #CDC0BC",
+".X c #D2C1BB",
+"XX c #DDC3BB",
+"oX c #E0C5BC",
+"OX c #E0C8BF",
+"+X c #C2C2C2",
+"@X c #CBC4C2",
+"#X c #CDC8C6",
+"$X c #CCCBCB",
+"%X c #D2C6C2",
+"&X c #D1CECD",
+"*X c #DDC8C1",
+"=X c #DECFCA",
+"-X c #D9D1CE",
+";X c #D3D3D3",
+":X c #D9D5D4",
+">X c #DED9D7",
+",X c #DBDBDB",
+"<X c #E1CAC3",
+"1X c #E2CFC8",
+"2X c #E1D3CE",
+"3X c #E2D5D0",
+"4X c #E5D8D3",
+"5X c #E4DDDB",
+"6X c #E8DBD6",
+"7X c #EADEDA",
+"8X c #E6E0DE",
+"9X c #EBE0DC",
+"0X c #E4E4E4",
+"qX c #E8E2E0",
+"wX c #EBEBEB",
+"eX c #F0EAE8",
+"rX c #F3F3F3",
+"tX c #FEFEFE",
+/* pixels */
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXrXrXtXrXrXrXrXrXrXrXtXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXrXtXrXrXrXwXwXrXwXrXrXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXrXrXrXwXwX0X0XqX0X0X0X0XwXwXwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXrXtXrXwXwX2X[.[.].].].].].1XwXrXwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXrXrXrXwX0X0XL.J b b b b b b b J '.0X0XwXwXrXrXrXrXrXrXrXrXrXrXtXrXrXrXtXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXtXtXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXrXrXwX0XXXt m b m B V N b b v >.;X0XwXwXwXwXrXwXwXrXrXrXrXtXrXtXrXrXrXwXrXrXrXrXrXrXrXrXrXrXrXwXrXrXwXrXrXrXtXtXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXrXrXrX0X,X'.S b b P l.z.M.k.w n b b g.;X,X,X,X0X0X0X0X0XwXwXwXwXwXwXwXwXwX0X0X0XwX0X0XwXwXwXwX0X0X0X0X0X0XwXwXwXwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXrXrXrXwX0X:XT.m b A ] G.D.D.m.$.m b b $.$X&X.X}.XX>XOX}.oXXX<X0X0XwXwXwX0X2XXXoXXXoXOX5X0XwX0X1XoXXX5X*X}.}.oX<XqXrXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXrXrXwX0X,XL.b b D M.H.D.D.D.D.m.L b b W H.Z.# b Y / m b b b Z P.:X:X:X$X:.Z b b b b n :.;X;X;XR b A &.Z b b b b *.wXwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXrXwX0X:X$.b b E B.H.H.D.D.D.D.P b b E H.V.. b U L v v n b b ( #X;X$X~.Y b m N m b b ! {.&X#XI b C R v v n b b ! 0XwXrXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXrXwX0X:X!.A b Z F.H.H.H.H.H.D.m.L b b e b.+.b b V k i.r.t n b b s.H.x v b L q.b.p.D b b t F.$.n b M l a.M.y b b A :X0XwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXrXwX0X:XL.m b D H.).H.+XH.H.H.D.H b b 6 v.j b b - a.A.m.@.m b b h D.< b b w z.b.b.P b b q B.z b b @ B.D.m...v b G :X,XwXwXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXwX0X,X&X/ b b , D.H.+X+X+X+XH.f.B b b 5.8.M b M w.v.v.v.r.D b b h l v b b M     V v b b q u.X b n @.v.m.v.j b b Q &X,X0XwXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXwX0X,X$X^ b b , H.H.+X+XH.H.H.s.N b n 7.7.v b B 8.v.v.v.w.M b b g r b b b n n n b b b b e y.O b n X.m.v.n.e b b u &X,X0XrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXrX0X,X$X/ b b + F.H.H.H.+XH.d.b b M | 8.> c b @ 9.v.9.u., b b - 3.& b b 7 1.1.4.4.4.6.7.9.w.m b + t.v.m.p.D b b K.;X,X0XwXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXwX0X,X$X-.b b b i D.H.G.H.J.N b b = 9.9.5 c b B 7.9.v.y.b b m f 4.O b b 3 6.6.6.g 9 4 h u.h b b - b.m.m.s.b b N ~.;X,X0XwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXwX0X,X;XE.G b b I z ] ] ] W n b H l 9.8.9 b b m e 6 r e b b # 0.y.< b b O 6 p 6 < # ; q.v.t b b 0 n.A.A.+.b b H _.;X,XwXwXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXwXwX,X;X#Xf.b b b b b b b b b - a.v.v.w.@ b b v b b b b b @ b.m.v.w.M b b b b b b v ..m.n.A b n g.H.H.H.4 b b [ &X,X0XwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXwXwX0X:X$XZ.Q H v n b m B H E x n.m.m.q.B b v < . v N + E z m.m.m.b.e - M m v M - t k.D.m.; # - V.H.+XH.s # # K.:X,X0XwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXrXwXwX,X,X$X+XG.Z.Z.B.C.S.F.H.H.H.D.D.j b b q v.b.a.n.B.H.H.+X+X+XH.H.D.Z.C.Z.Z.F.H.H.+X+XH.).H.$X&X&X;X$X#X#X:X,X0XwXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXrXrXwX0X,X;X#X+X+X+XH.H.+X+X+XH.H.H.D.e b n i n.m.D.H.H.+X#X$X$X+X+X+X+XH.H.H.H.+X+X+X$X&X&X&X$X;X;X;X:X;X:X,X,X0XwXwXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXrXrXwXwX,X,X;X;X$X$X$X;X;X&X;X$X#X+XF b v s.H.H.+X$X&X;X;X,X,X,X;X:X;X;X;X;X;X;X:X,X,X,X0X,X0X,X0X0X0X0X0X0X0XwXwXrXtXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXrXtXrXwXwX0X,X:X;X;X;X;X;X:X;X;X;X$X+XC b B k.+X+X$X$X;X,X,X0X0X0X0X0X;X,X,X,X,X,X,X,X,X0X0X0X0X0X0XwX0X0X0XwXwXrXrXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXrXrXrXrXwXwXwX0X0X0X0X0X0X0X,X,X:X^.^.!.$X$X;X,X,X0XwXwXwXwXwXwXwXwX0X0X0X0XwXwXwXwXwXwXrXrXwXrXrXrXrXrXrXrXrXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXrXrXrXrXwXwXwXwX0XwXwXwX0X0X,X:X;X$X&X&X;X,X,X0XwXwXwXrXrXrXrXrXwXwXwXwXwXwXwXrXrXrXwXrXrXrXrXrXrXrXrXrXrXtXrXtXtXrXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXrXrXrXrXrXrXrXrXrXwXwXwXwX0X,X0X0X0XwXwXrXrXrXrXrXrXrXrXrXrXrXrXrXrXwXrXrXrXrXrXtXrXrXrXtXrXrXrXrXrXrXrXrXrXtXtXtXrXrXtXtXtXtXrXrXtXrXrXtXrXtXrXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXrXtXtXrXtXrXrXrXrXrXrXwXwXwX0XwX0XwXwXwXrXrXrXtXtXrXrXrXrXrXrXrXrXwXrXwXrXwXwXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXrXtXrXrXtXtXrXrXrXrXrXrXrXrXrXrXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXwXrXrXrXrXrXrXtXrXtXrXrXrXrXrXwXwXwXwXwX0X0XwX0XwXwXwXwXwXwXwXrXwXwXwX0X0X0X0XwX0XwXwXrXrXrXwXrXwXwXwX0XwX0XwXwXwXrXrXrXrXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXrXrXrXrXrXtXtXrXrXtXrXrXeX7X7X9XwXwXwX5X3X3X3X2X2X2X5X0XwXwXwXwXwX8X3X3X2X2X2X2X2X3X6X6X7XwXwXwXwXwXwX7X1XXXOXOX1X8XwXwXrXrXrXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXtXtXrXrXrXwXT.T T :.,X,X-X` G G G G G G U _ J.-X,X,X,X[ G G G G G G G G G G _ >XwX0X,X&XI.R N b b b m ! `.5XwXrXrXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXtXtXrXtXrXrXrXwX0X' b b ] >X,X%XJ b b b b b b b b Q {.:X;X:Xq b b b b b b b b b b Y >X0X,X-X'.^ n b b b b b m *.1XwXwXrXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrX0X0X%XL b b L.@X+X-.b b M L L L D b b b M V.+X(.N b b D H H H H H U U W.;X&X^.H b b n W -.-.W n b b J &XwXrXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXwXwX0X XF b b U.+X+X[ b b D z z j P v b b N U.H.S.m b m E Q t ^ ) / ) ) /.$X$X;.m b n A %.H.H.J.N b b N .XwXwXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXwXwX,X:X!.m b L N.D.m.* b b y v.v.v.v.p.n b M f.m.w b b D u.v.m.m.D.G.H.H.+X).g.b b B j.F.D.D.D.D.l.; F I /.0XwXrXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXwX,X:XU.n b E B.A.n.$ b b s v.9.v.v.r.n n M r.b.1 b b D u.v.m.m.D.D.H.H.).H.k b b # M.G.D.D.D.D.Z.t w u _.0XwXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXwXwX,X;X$XJ b m h b.v.i.m b M a 5.5.2.p M b c < 8.2.+ b b M o o o o # % j G.H.g.m b A M.D.D.D.B.M.M.M.M.Z.(.:X0XwXrXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXrXrXwX,X,X&X(.n b M 0.v.v.s b b b b b n b b c b M u.v.g M b b b b b b b b b i G.D.0 b b 8 D.D.H.G.P n b b n b U :X,XwXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXrXwX0X,X;X$XV.n b M w.v.9.< b b b b b b b b c H r 9.v.a n b   * < < w w Q Q g.D.B.: b b r D.D.D.m.C b b b b b ) ;X0XwXrXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXrX6XP.=.K.;X#X+Xx n b D v.u.7.. b b M D . D & 2 q.b.b.v.v.< b b X 6.9.9.b.m.D.D.D.D.n.# b b f D.D.D.b.= 1 * N b n !.;X,XwXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXrXrXwX<X~ P x $X+XH.z b b - v.v.3.M b b < r r r k 0.a.m.m.m.v.# b b , 6.9.v.m.D.D.D.H.D.z.O b b s D.D.D.N.f l 9 v b M ~.;X,XwXrXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXrXwX0XY.n b e H.H.V.F b b p b.v.h v b v v.m.A.D.H.+X+X+XH.D.p.b b m p 9.v.m.D.D.H.H.H.D.N.- b b - m.A.D.A.m.a.B b b - (.:X0XwXrXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXwXwX0XY.n b ; Z.C.$.A b v 0.m.m.l n b M m.D.D.H.+X#X+X+XH.H.r.b b m < d l l l $.;.J.V.H.B.w b b C @.s.a.k.#.j n b b : ).:X,XwXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXwXwX0X'.N b b A B n b n z m.D.B.0 b b 9 H.H.+X$X;X:X;X$X$X+Xl b b b b b b b b b b b s.H.H.B.H b b b n Z Z b b V n b ] $X:X0XwXrXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXwX0X,X.XR b b b b b A P d.D.D.C.H b b j H.$X$X;X:X,X,X;X;X+X/ b b b b b b b b b b b a.H.H.D.u G b b b b b B H : v m ;.$X,XwXwXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXwXwX,X:X Xg.j 5 y s.C.H.H.+X+X|.E.Q.Q. X;X;X,X0XwXwX0X0X,X;X/.U.j.h.g.f.h.j.U.U.U.!.$X$X+X+XH.Z.g.y 4 6 l x.D.A.l.~.#X,X0XwXrXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXwX0X:X$XG.k.e.f.B.H.H.+X$X$X$X#X$X$X;X;X,X0XwXwXwXwX0X0X;X$X+XH.D.D.D.F.H.+X+X#X&X$X;X$X$X+X+XA.r.X.e.a.H.H.H.+X+X;X,X0XwXrXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXwX,X,X$X&X$X$X$X$X;X;X,X,X,X,X,X,X0XwXwXwXrXtXrXrXwXwX0X,X;X$X$X+X$X$X$X;X;X:X,X,X,X,X,X;X$X&X#X#X$X$X$X$X$X;X,X,X0XwXrXrXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXwXwX0X,X:X;X;X$X;X;X:X,X,X0X0X,X0X0X0XwXwXwXrXrXtXrXrXwXwX0X;X;X$X&X$X$X&X:X,X,X,X,X0X,X,X:X;X;X$X$X$X$X$X;X:X,X,X0XwXwXrXrXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXrXwXwXwX0X0X0X0X0X0XwXwXwXwXwXwXwXwXrXwXrXtXtXrXtXtXrXrXrXwX0X0X0X0X,X,X0X0X0X0XwXwXwXwXwXwX0X0X0X,X,X,X,X0X0XwXwXwXrXtXrXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXrXrXrXwXwX0X0X0X0X0XwXwXwXrXwXrXrXrXrXrXtXrXtXtXtXtXrXrXrXwXwXwX0X0X0X0X0X0X0XwXwXwXwXwXwXwXwXwX0X0X0X0XwXwXwXwXwXrXrXrXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXrXrXrXrXrXrXrXrXrXrXtXtXrXtXtXrXtXtXtXtXtXtXtXrXtXrXtXrXrXrXrXwXwXrXrXrXrXrXrXrXtXrXrXrXrXrXrXrXwXrXrXrXrXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXrXtXrXrXrXrXrXrXtXtXrXtXrXtXrXrXtXtXtXtXtXtXtXtXtXtXtXrXrXrXrXrXrXrXrXrXrXrXtXtXrXtXrXrXtXrXrXrXrXrXrXrXrXtXrXrXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX",
+"tXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtXtX"
+};
diff --git a/applications/OPJViewer/source/readmeafter.txt b/applications/OPJViewer/source/readmeafter.txt
new file mode 100644 (file)
index 0000000..d5e8fb9
--- /dev/null
@@ -0,0 +1,34 @@
+This viewer is conceived to open and display information and image content of J2K, JP2,\r
+and MJ2 files.\r
+The viewer application interface is divided into three main panels:\r
+- a browsing pane;\r
+- a viewing pane;\r
+- a log/peek pane.\r
+\r
+The browsing pane will present the markers or boxes hierarchy, with position (byte number where marker/box starts and stops) and length information (i.e., inner length as signalled by marker/box and total length, with marker/box sign included), in the following form:\r
+\r
+filename\r
+|\r
+|_ #000: Marker/Box short name (Hex code)\r
+|  |\r
+|  |_ *** Marker/Box long name ***\r
+|  |_ startbyte > stopbyte, inner_length + marker/box sign length (total length)\r
+|  |_ Additional info, depending on the marker/box type\r
+|  |_ ...\r
+|\r
+|_ #001: Marker/Box short name (Hex code)\r
+|  |\r
+|  |_ ...\r
+|\r
+...\r
+\r
+\r
+The viewing pane will display the decoded image contained in the JPEG 2000 file.\r
+It should display correctly images as large as 4000x2000, provided that a couple of GB of RAM are available. Nothing is known about the display of larger sizes: let us know if you manage to get it working.\r
+\r
+\r
+The log/peek pane is shared among two different subpanels:\r
+\r
+- the log panel will report a lot of debugging info coming out from the wx GUI as well as from the openjpeg library\r
+- the peek pane tries to give a peek on the codestream/file portion which is currently selected in the browsing pane. It shows both hex and ascii values corresponding to the marker/box section. \r
+\r
diff --git a/applications/OPJViewer/source/readmebefore.txt b/applications/OPJViewer/source/readmebefore.txt
new file mode 100644 (file)
index 0000000..c5e1ed8
--- /dev/null
@@ -0,0 +1,11 @@
+What is OpenJPEG ?\r
+==================\r
+The OpenJPEG library is an open-source JPEG 2000 codec written in C language. It has been developed in order to promote the use of JPEG 2000, the new still-image compression standard from the Joint Photographic Experts Group (JPEG). In addition to the basic codec, various other features are under development, among them the JP2 and MJ2 (Motion JPEG 2000) file formats, an indexing tool useful for the JPIP protocol, JPWL-tools for error-resilience, a Java-viewer for j2k-images, ... \r
+\r
+Who can use the library ?\r
+=========================\r
+Anybody. As the OpenJPEG library is released under the BSD license, anybody can use or modify the library, even for commercial applications. The only restriction is to retain the copyright in the sources or the binaries documentation.\r
+\r
+Who is developing the library ?\r
+===============================\r
+The library is developed by the Communications and Remote Sensing Lab (TELE), in the Universit� Catholique de Louvain (UCL). The JPWL module is developped and maintained by the Digital Signal Processing Lab (DSPLab) of the University of Perugia, Italy (UNIPG). As our purpose is to make OpenJPEG really useful for those interested in the image compression field, any feedback/advices are obviously welcome ! We will do our best to handle them quickly. 
\ No newline at end of file
diff --git a/applications/OPJViewer/source/wxj2kparser.cpp b/applications/OPJViewer/source/wxj2kparser.cpp
new file mode 100644 (file)
index 0000000..600fd65
--- /dev/null
@@ -0,0 +1,1465 @@
+/*\r
+ * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+#include "OPJViewer.h"\r
+\r
+/* From little endian to big endian, 2 bytes */\r
+#define        BYTE_SWAP2(X)   ((X & 0x00FF) << 8) | ((X & 0xFF00) >> 8)\r
+#define        BYTE_SWAP4(X)   ((X & 0x000000FF) << 24) | ((X & 0x0000FF00) << 8) | ((X & 0x00FF0000) >> 8) | ((X & 0xFF000000) >> 24)\r
+\r
+/* From codestream to int values */\r
+#define STREAM_TO_UINT32(C, P) (((unsigned long int) (C)[(P) + 0] << 24) + \\r
+                                                               ((unsigned long int) (C)[(P) + 1] << 16) + \\r
+                                                               ((unsigned long int) (C)[(P) + 2] << 8) + \\r
+                                                               ((unsigned long int) (C)[(P) + 3] << 0))\r
+\r
+#define STREAM_TO_UINT16(C, P) (((unsigned long int) (C)[(P) + 0] << 8) + \\r
+                                                               ((unsigned long int) (C)[(P) + 1] << 0))\r
+\r
+\r
+/* Markers values */\r
+#define J2KMARK_NUM 24\r
+enum {\r
+       SOC_VAL = 0xFF4F,\r
+       SOT_VAL = 0xFF90,\r
+       SOD_VAL = 0xFF93,\r
+       EOC_VAL = 0xFFD9,\r
+       SIZ_VAL = 0xFF51,\r
+       COD_VAL = 0xFF52,\r
+       COC_VAL = 0xFF53,\r
+       RGN_VAL = 0xFF5E,\r
+       QCD_VAL = 0xFF5C,\r
+       QCC_VAL = 0xFF5D,\r
+       POD_VAL = 0xFF5F,\r
+       TLM_VAL = 0xFF55,\r
+       PLM_VAL = 0xFF57,\r
+       PLT_VAL = 0xFF58,\r
+       PPM_VAL = 0xFF60,\r
+       PPT_VAL = 0xFF61,\r
+       SOP_VAL = 0xFF91,\r
+       EPH_VAL = 0xFF92,\r
+       COM_VAL = 0xFF64\r
+#ifdef USE_JPWL\r
+       , EPB_VAL       = 0xFF66,\r
+       ESD_VAL = 0xFF67,\r
+       EPC_VAL = 0xFF68,\r
+       RED_VAL = 0xFF69\r
+       /*, EPB_VAL = 0xFF96,\r
+       ESD_VAL = 0xFF98,\r
+       EPC_VAL = 0xFF97,\r
+       RED_VAL = 0xFF99*/\r
+#endif // USE_JPWL\r
+#ifdef USE_JPSEC\r
+       , SEC_VAL = 0xFF65\r
+#endif // USE_JPSEC\r
+};\r
+\r
+// All the markers in one vector\r
+unsigned short int marker_val[] = {\r
+       SOC_VAL, SOT_VAL, SOD_VAL, EOC_VAL,\r
+       SIZ_VAL,\r
+       COD_VAL, COC_VAL, RGN_VAL, QCD_VAL, QCC_VAL, POD_VAL,\r
+       TLM_VAL, PLM_VAL, PLT_VAL, PPM_VAL, PPT_VAL,\r
+       SOP_VAL, EPH_VAL,\r
+       COM_VAL\r
+#ifdef USE_JPWL\r
+       , EPB_VAL, ESD_VAL, EPC_VAL, RED_VAL\r
+#endif // USE_JPWL\r
+#ifdef USE_JPSEC\r
+       , SEC_VAL\r
+#endif // USE_JPSEC\r
+};\r
+\r
+// Marker names\r
+char *marker_name[] = {\r
+       "SOC", "SOT", "SOD", "EOC",\r
+       "SIZ",\r
+       "COD", "COC", "RGN", "QCD", "QCC", "POD",\r
+       "TLM", "PLM", "PLT", "PPM", "PPT",\r
+       "SOP", "EPH",\r
+       "COM"\r
+#ifdef USE_JPWL\r
+       , "EPB", "ESD", "EPC", "RED"\r
+#endif // USE_JPWL\r
+#ifdef USE_JPSEC\r
+       , "SEC"\r
+#endif // USE_JPSEC\r
+};\r
+\r
+// Marker descriptions\r
+char *marker_descr[] = {\r
+       "Start of codestream", "Start of tile-part", "Start of data", "End of codestream",\r
+       "Image and tile size",\r
+       "Coding style default", "Coding style component", "Region-of-interest", "Quantization default",\r
+       "Quantization component", "Progression order change, default",\r
+       "Tile-part lengths, main header", "Packet length, main header", "Packets length, tile-part header",\r
+       "Packed packet headers, main header", "Packed packet headers, tile-part header",\r
+       "Start of packet", "End of packet header",\r
+       "Comment and extension"\r
+#ifdef USE_JPWL\r
+       , "Error Protection Block", "Error Sensitivity Descriptor", "Error Protection Capability",\r
+       "Residual Errors Descriptor"\r
+#endif // USE_JPWL\r
+#ifdef USE_JPSEC\r
+       , "Main security marker"\r
+#endif // USE_JPSEC\r
+};\r
+\r
+void OPJParseThread::ParseJ2KFile(wxFile *m_file, wxFileOffset offset, wxFileOffset length, wxTreeItemId parentid)\r
+{\r
+       unsigned short int csiz = 0;\r
+\r
+       // check if the file is opened\r
+       if (m_file->IsOpened())\r
+               WriteText(wxT("File OK"));\r
+       else\r
+               return;\r
+\r
+       // position at the beginning\r
+       m_file->Seek(offset, wxFromStart);\r
+\r
+       // navigate the file\r
+       int m, inside_sod = 0, inside_sop = 0;\r
+       int nmarks = 0, maxmarks = 10000;\r
+       unsigned char onebyte[1];\r
+       unsigned char twobytes[2], firstbyte, secondbyte;\r
+       unsigned char fourbytes[4];\r
+       unsigned short int currmark;\r
+       unsigned short int currlen;\r
+       int lastPsot = 0, lastsotpos = 0;\r
+\r
+       WriteText(wxT("Start search..."));\r
+\r
+// advancing macro\r
+#define OPJ_ADVANCE(A) {offset += A; if (offset < length) m_file->Seek(offset, wxFromStart); else return;}\r
+\r
+       // begin search\r
+       while ((offset < length) && (!m_file->Eof())) {\r
+\r
+               // read one byte\r
+               if (m_file->Read(&firstbyte, 1) != 1)\r
+                       break;\r
+\r
+               // look for 0xFF\r
+               if (firstbyte == 0xFF) {\r
+\r
+                       // it is a possible marker\r
+                       if (m_file->Read(&secondbyte, 1) != 1)\r
+                               break;\r
+                       else\r
+                               currmark = (((unsigned short int) firstbyte) << 8) + (unsigned short int) secondbyte;\r
+\r
+               } else {\r
+\r
+                       // nope, advance by one and search again\r
+                       OPJ_ADVANCE(1);\r
+                       continue;\r
+               }\r
+               \r
+               // search the marker\r
+               for (m = 0; m < J2KMARK_NUM; m++) {\r
+                       if (currmark == marker_val[m])\r
+                               break;\r
+               }\r
+\r
+               // marker not found\r
+               if (m == J2KMARK_NUM) {\r
+                       // nope, advance by one and search again\r
+                       OPJ_ADVANCE(1);\r
+                       continue;\r
+               }\r
+\r
+               // if we are inside SOD, only some markers are allowed\r
+               if (inside_sod) {\r
+\r
+                       // we are inside SOP\r
+                       if (inside_sop) {\r
+\r
+                       }\r
+\r
+                       // randomly marker coincident data\r
+                       if ((currmark != SOT_VAL) &&\r
+                               (currmark != EOC_VAL) &&\r
+                               (currmark != SOP_VAL) &&\r
+                               (currmark != EPH_VAL)) {\r
+                               OPJ_ADVANCE(1);\r
+                               continue;\r
+                       }\r
+\r
+                       // possible SOT?\r
+                       if ((currmark == SOT_VAL)) {\r
+                               // too early SOT\r
+                               if (offset < (lastsotpos + lastPsot)) {\r
+                                       OPJ_ADVANCE(1);\r
+                                       continue;\r
+                               }\r
+                               // we were not in the last tile\r
+                               /*if (lastPsot != 0) {\r
+                                       OPJ_ADVANCE(1);\r
+                                       break;\r
+                               }*/\r
+                       }\r
+               }\r
+\r
+               // beyond this point, the marker MUST BE real\r
+\r
+               // length of current marker segment\r
+               if ((currmark == SOD_VAL) ||\r
+                       (currmark == SOC_VAL) ||\r
+                       (currmark == EOC_VAL) ||\r
+                       (currmark == EPH_VAL))\r
+\r
+                       // zero length markers\r
+                       currlen = 0;\r
+\r
+               else {\r
+\r
+                       // read length field\r
+                       if (m_file->Read(twobytes, 2) != 2)\r
+                               break;\r
+\r
+                       currlen = (((unsigned short int) twobytes[0]) << 8) + (unsigned short int) twobytes[1];\r
+               }\r
+\r
+               // here we pass to AppendItem() normal and selected item images (we\r
+               // suppose that selected image follows the normal one in the enum)\r
+               int image, imageSel;\r
+               image = m_tree->TreeCtrlIcon_Folder;\r
+               imageSel = image + 1;\r
+\r
+               // append the marker\r
+               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                       wxString::Format(wxT("%03d: "), nmarks) +\r
+                       wxString::FromAscii(marker_name[m]) + \r
+                       wxString::Format(wxT(" (0x%04X)"), marker_val[m]),\r
+                       image, imageSel,\r
+                       new OPJMarkerData(wxT("MARK") + wxString::Format(wxT(" (%d)"), marker_val[m]),\r
+                               m_tree->m_fname.GetFullPath(), offset, offset + currlen + 1)\r
+                       );\r
+\r
+               // append some info\r
+               image = m_tree->TreeCtrlIcon_File;\r
+               imageSel = image + 1;\r
+\r
+               // marker name\r
+               wxTreeItemId subcurrid1 = m_tree->AppendItem(currid,\r
+                       wxT("*** ") + wxString::FromAscii(marker_descr[m]) + wxT(" ***"),\r
+                       image, imageSel,\r
+                       new OPJMarkerData(wxT("INFO"))\r
+                       );\r
+               m_tree->SetItemFont(subcurrid1, *wxITALIC_FONT);\r
+\r
+               // position and length\r
+               wxTreeItemId subcurrid2 = m_tree->AppendItem(currid,\r
+                       wxLongLong(offset).ToString() + wxT(" > ") + wxLongLong(offset + currlen + 1).ToString() + \r
+                       wxT(", ") + wxString::Format(wxT("%d + 2 (%d)"), currlen, currlen + 2),\r
+                       image, imageSel,\r
+                       new OPJMarkerData(wxT("INFO"))\r
+                       );\r
+\r
+               // give additional info on markers\r
+               switch (currmark) {\r
+\r
+               /////////\r
+               // SOP //\r
+               /////////\r
+               case SOP_VAL:\r
+                       {\r
+                       // read packet number\r
+                       if (m_file->Read(twobytes, 2) != 2)\r
+                               break;\r
+                       int packnum = STREAM_TO_UINT16(twobytes, 0);\r
+\r
+                       image = m_tree->TreeCtrlIcon_File;\r
+                       imageSel = image + 1;\r
+\r
+                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("Pack. no. %d"), packnum),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+                       inside_sop = 1;\r
+                       };\r
+                       break;\r
+\r
+#ifdef USE_JPWL\r
+               /////////\r
+               // RED //\r
+               /////////\r
+               case RED_VAL:\r
+                       {\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char pred = onebyte[0];\r
+\r
+                       image = m_tree->TreeCtrlIcon_File;\r
+                       imageSel = image + 1;\r
+\r
+                       wxString address[] = {\r
+                               wxT("Packet addressing"),\r
+                               wxT("Byte-range addressing"),\r
+                               wxT("Packet-range addressing"),\r
+                               wxT("Reserved")\r
+                       };\r
+\r
+                       wxTreeItemId subcurrid = m_tree->AppendItem(currid,\r
+                               address[(pred & 0xC0) >> 6],\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       subcurrid = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("%d bytes range"), (((pred & 0x02) >> 1) + 1) * 2),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       subcurrid = m_tree->AppendItem(currid,\r
+                               pred & 0x01 ? wxT("Errors/erasures in codestream") : wxT("Error free codestream"),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       subcurrid = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("Residual corruption level: %d"), (pred & 0x38) >> 3),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       }\r
+                       break;\r
+\r
+               /////////\r
+               // ESD //\r
+               /////////\r
+               case ESD_VAL:\r
+                       {\r
+                       unsigned short int cesd;\r
+                       if (csiz < 257) {\r
+                               if (m_file->Read(onebyte, 1) != 1)\r
+                                       break;\r
+                               cesd = onebyte[0];\r
+                       } else {\r
+                               if (m_file->Read(twobytes, 2) != 2)\r
+                                       break;\r
+                               cesd = STREAM_TO_UINT16(twobytes, 0);\r
+                       }\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char pesd = onebyte[0];\r
+\r
+                       image = m_tree->TreeCtrlIcon_File;\r
+                       imageSel = image + 1;\r
+\r
+                       wxTreeItemId subcurrid = m_tree->AppendItem(currid,\r
+                               pesd & 0x01 ? wxT("Comp. average") : wxString::Format(wxT("Comp. no. %d"), cesd),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       wxString meth[] = {\r
+                               wxT("Relative error sensitivity"),\r
+                               wxT("MSE"),\r
+                               wxT("MSE reduction"),\r
+                               wxT("PSNR"),\r
+                               wxT("PSNR increase"),\r
+                               wxT("MAXERR (absolute peak error)"),\r
+                               wxT("TSE (total squared error)"),\r
+                               wxT("Reserved")\r
+                       };\r
+\r
+                       subcurrid = m_tree->AppendItem(currid,\r
+                               meth[(pesd & 0x38) >> 3],\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       wxString address[] = {\r
+                               wxT("Packet addressing"),\r
+                               wxT("Byte-range addressing"),\r
+                               wxT("Packet-range addressing"),\r
+                               wxT("Reserved")\r
+                       };\r
+\r
+                       subcurrid = m_tree->AppendItem(currid,\r
+                               address[(pesd & 0xC0) >> 6],\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       subcurrid = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("%d bytes/value, %d bytes range"), ((pesd & 0x04) >> 2) + 1, (((pesd & 0x02) >> 1) + 1) * 2),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       }\r
+                       break;\r
+\r
+               /////////\r
+               // EPC //\r
+               /////////\r
+               case EPC_VAL:\r
+                       {\r
+                       if (m_file->Read(twobytes, 2) != 2)\r
+                               break;\r
+                       unsigned short int pcrc = STREAM_TO_UINT16(twobytes, 0);\r
+\r
+                       if (m_file->Read(fourbytes, 4) != 4)\r
+                               break;\r
+                       unsigned long int dl = STREAM_TO_UINT32(fourbytes, 0);\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char pepc = onebyte[0];\r
+\r
+                       image = m_tree->TreeCtrlIcon_File;\r
+                       imageSel = image + 1;\r
+\r
+                       wxTreeItemId subcurrid = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("CRC-16 = 0x%x"), pcrc),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       subcurrid = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("Tot. length = %d"), dl),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       subcurrid = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("%s%s%s%s"),\r
+                                       pepc & 0x10 ? wxT("ESD, ") : wxT(""),\r
+                                       pepc & 0x20 ? wxT("RED, ") : wxT(""),\r
+                                       pepc & 0x40 ? wxT("EPB, ") : wxT(""),\r
+                                       pepc & 0x80 ? wxT("Info") : wxT("")\r
+                                       ),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       }\r
+                       break;\r
+\r
+               /////////\r
+               // EPB //\r
+               /////////\r
+               case EPB_VAL:\r
+                       {\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char depb = onebyte[0];\r
+\r
+                       if (m_file->Read(fourbytes, 4) != 4)\r
+                               break;\r
+                       unsigned long int ldpepb = STREAM_TO_UINT32(fourbytes, 0);\r
+\r
+                       if (m_file->Read(fourbytes, 4) != 4)\r
+                               break;\r
+                       unsigned long int pepb = STREAM_TO_UINT32(fourbytes, 0);\r
+\r
+                       image = m_tree->TreeCtrlIcon_File;\r
+                       imageSel = image + 1;\r
+\r
+                       wxTreeItemId subcurrid = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("No. %d, %slatest, %spacked"),\r
+                                       depb & 0x3F,\r
+                                       depb & 0x40 ? wxT("") : wxT("not "),\r
+                                       depb & 0x80 ? wxT("") : wxT("un")),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       subcurrid = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("%d bytes protected"), ldpepb),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (pepb == 0x00000000)\r
+\r
+                               subcurrid = m_tree->AppendItem(currid,\r
+                                       wxT("Predefined codes"),\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+                       else if ((pepb >= 0x10000000) && (pepb <= 0x1FFFFFFF)) {\r
+\r
+                               wxString text = wxT("CRC code");\r
+                               if (pepb == 0x10000000)\r
+                                       text << wxT(", CCITT (X25) 16 bits");\r
+                               else if (pepb == 0x10000001)\r
+                                       text << wxT(", Ethernet 32 bits");\r
+                               else\r
+                                       text << wxT(", JPWL RA");\r
+                               subcurrid = m_tree->AppendItem(currid,\r
+                                       text,\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+                       } else if ((pepb >= 0x20000000) && (pepb <= 0x2FFFFFFF)) {\r
+\r
+                               wxString text;\r
+                               subcurrid = m_tree->AppendItem(currid,\r
+                                       wxString::Format(wxT("RS code, RS(%d, %d)"),\r
+                                               (pepb & 0x0000FF00) >> 8,\r
+                                               (pepb & 0x000000FF)),\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+                       } else if ((pepb >= 0x30000000) && (pepb <= 0x3FFFFFFE))\r
+\r
+                               subcurrid = m_tree->AppendItem(currid,\r
+                                       wxT("JPWL RA"),\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+                       else if (pepb == 0xFFFFFFFF)\r
+\r
+                               subcurrid = m_tree->AppendItem(currid,\r
+                                       wxT("No method"),\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+                       }\r
+                       break;\r
+#endif // USE_JPWL\r
+\r
+#ifdef USE_JPSEC\r
+               case SEC_VAL:\r
+                       {\r
+\r
+                       }\r
+                       break;\r
+#endif // USE_JPSEC\r
+\r
+               /////////\r
+               // SIZ //\r
+               /////////\r
+               case SIZ_VAL:\r
+                       {\r
+                       int c;\r
+                       \r
+                       if (m_file->Read(twobytes, 2) != 2)\r
+                               break;\r
+                       unsigned short int rsiz = STREAM_TO_UINT16(twobytes, 0);\r
+\r
+                       if (m_file->Read(fourbytes, 4) != 4)\r
+                               break;\r
+                       unsigned long int xsiz = STREAM_TO_UINT32(fourbytes, 0);\r
+\r
+                       if (m_file->Read(fourbytes, 4) != 4)\r
+                               break;\r
+                       unsigned long int ysiz = STREAM_TO_UINT32(fourbytes, 0);\r
+\r
+                       if (m_file->Read(fourbytes, 4) != 4)\r
+                               break;\r
+                       unsigned long int xosiz = STREAM_TO_UINT32(fourbytes, 0);\r
+\r
+                       if (m_file->Read(fourbytes, 4) != 4)\r
+                               break;\r
+                       unsigned long int yosiz = STREAM_TO_UINT32(fourbytes, 0);\r
+\r
+                       if (m_file->Read(fourbytes, 4) != 4)\r
+                               break;\r
+                       unsigned long int xtsiz = STREAM_TO_UINT32(fourbytes, 0);\r
+                       this->m_tree->m_childframe->m_twidth = xtsiz;\r
+\r
+                       if (m_file->Read(fourbytes, 4) != 4)\r
+                               break;\r
+                       unsigned long int ytsiz = STREAM_TO_UINT32(fourbytes, 0);\r
+                       this->m_tree->m_childframe->m_theight = ytsiz;\r
+\r
+                       if (m_file->Read(fourbytes, 4) != 4)\r
+                               break;\r
+                       unsigned long int xtosiz = STREAM_TO_UINT32(fourbytes, 0);\r
+                       this->m_tree->m_childframe->m_tx = xtosiz;\r
+\r
+                       if (m_file->Read(fourbytes, 4) != 4)\r
+                               break;\r
+                       unsigned long int ytosiz = STREAM_TO_UINT32(fourbytes, 0);\r
+                       this->m_tree->m_childframe->m_ty = ytosiz;\r
+\r
+                       if (m_file->Read(twobytes, 2) != 2)\r
+                               break;\r
+                       csiz = STREAM_TO_UINT16(twobytes, 0);\r
+\r
+                       bool equaldepth = true, equalsize = true;\r
+                       unsigned char *ssiz  = new unsigned char(csiz);\r
+                       unsigned char *xrsiz = new unsigned char(csiz);\r
+                       unsigned char *yrsiz = new unsigned char(csiz);\r
+\r
+                       for (c = 0; c < csiz; c++) {\r
+\r
+                               if (m_file->Read(&ssiz[c], 1) != 1)\r
+                                       break;\r
+\r
+                               if (c > 0)\r
+                                       equaldepth = equaldepth && (ssiz[c] == ssiz[c - 1]);\r
+\r
+                               if (m_file->Read(&xrsiz[c], 1) != 1)\r
+                                       break;\r
+\r
+                               if (m_file->Read(&yrsiz[c], 1) != 1)\r
+                                       break;\r
+\r
+                               if (c > 0)\r
+                                       equalsize = equalsize && (xrsiz[c] == xrsiz[c - 1]) && (yrsiz[c] == yrsiz[c - 1]) ;\r
+\r
+                       }\r
+\r
+                       if (equaldepth && equalsize)\r
+                               wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
+                                       wxString::Format(wxT("I: %dx%d (%d, %d), %d c., %d%s bpp"),\r
+                                       xsiz, ysiz,\r
+                                       xosiz, yosiz,\r
+                                       csiz, ((ssiz[0] & 0x7F) + 1),\r
+                                       (ssiz[0] & 0x80) ? wxT("s") : wxT("u")),\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                       else\r
+                               wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
+                                       wxString::Format(wxT("I: %dx%d (%d, %d), %d c."),\r
+                                       xsiz, ysiz,\r
+                                       xosiz, yosiz,\r
+                                       csiz),\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("T: %dx%d (%d, %d)"),\r
+                               xtsiz, ytsiz,\r
+                               xtosiz, ytosiz),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       image = m_tree->TreeCtrlIcon_Folder;\r
+                       imageSel = image + 1;\r
+\r
+                       wxTreeItemId subcurrid4 = m_tree->AppendItem(currid,\r
+                               wxT("Components"),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       image = m_tree->TreeCtrlIcon_File;\r
+                       imageSel = image + 1;\r
+\r
+                       for (c = 0; c < csiz; c++) {\r
+\r
+                               wxTreeItemId subcurrid5 = m_tree->AppendItem(subcurrid4,\r
+                                       wxString::Format(wxT("#%d: %dx%d, %d%s bpp"),\r
+                                       c,\r
+                                       xsiz/xrsiz[c], ysiz/yrsiz[c],\r
+                                       ((ssiz[c] & 0x7F) + 1),\r
+                                       (ssiz[c] & 0x80) ? wxT("s") : wxT("u")),\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+                       }\r
+\r
+                       };\r
+                       break;\r
+\r
+               /////////\r
+               // SOT //\r
+               /////////\r
+               case SOT_VAL:\r
+                       {\r
+                       if (m_file->Read(twobytes, 2) != 2)\r
+                               break;\r
+                       unsigned short int isot = STREAM_TO_UINT16(twobytes, 0);\r
+\r
+                       if (m_file->Read(fourbytes, 4) != 4)\r
+                               break;\r
+                       unsigned long int psot = STREAM_TO_UINT32(fourbytes, 0);\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char tpsot = onebyte[0];\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char tnsot = onebyte[0];\r
+\r
+                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("tile %d, psot = %d, part %d of %d"), isot, psot, tpsot, tnsot),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       lastPsot = psot;\r
+                       lastsotpos = offset;\r
+                       inside_sod = 0;\r
+                       };\r
+                       break;\r
+\r
+               /////////\r
+               // COC //\r
+               /////////\r
+               case COC_VAL:\r
+                       {\r
+                       unsigned short int ccoc;\r
+                       if (csiz < 257) {\r
+                               if (m_file->Read(onebyte, 1) != 1)\r
+                                       break;\r
+                               ccoc = onebyte[0];\r
+                       } else {\r
+                               if (m_file->Read(twobytes, 2) != 2)\r
+                                       break;\r
+                               ccoc = STREAM_TO_UINT16(twobytes, 0);\r
+                       }\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char scoc = onebyte[0];\r
+\r
+                       wxTreeItemId subcurrid = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("Comp. no. %d"), ccoc),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+                       \r
+                       wxString text;\r
+                       if (scoc & 0x01)\r
+                               text << wxT("Partitioned entropy coder");\r
+                       else\r
+                               text << wxT("Unpartitioned entropy coder");\r
+\r
+                       subcurrid = m_tree->AppendItem(currid,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char decomplevs = onebyte[0];\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char cbswidth = onebyte[0];\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char cbsheight = onebyte[0];\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char cbstyle = onebyte[0];\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char transform = onebyte[0];\r
+\r
+                       subcurrid = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("%d levels (%d resolutions)"), decomplevs, decomplevs + 1),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (transform & 0x01)\r
+                               text = wxT("5-3 reversible wavelet");\r
+                       else\r
+                               text = wxT("9-7 irreversible wavelet");\r
+                       subcurrid = m_tree->AppendItem(currid,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       subcurrid = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("Code-blocks: %dx%d"), 1 << ((cbswidth & 0x0F) + 2), 1 << ((cbsheight & 0x0F) + 2)),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       image = m_tree->TreeCtrlIcon_Folder;\r
+                       imageSel = image + 1;\r
+\r
+                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
+                               wxT("Coding styles"),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       image = m_tree->TreeCtrlIcon_File;\r
+                       imageSel = image + 1;\r
+\r
+                       if (cbstyle & 0x01)\r
+                               text = wxT("Selective arithmetic coding bypass");\r
+                       else\r
+                               text = wxT("No selective arithmetic coding bypass");\r
+                       wxTreeItemId subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (cbstyle & 0x02)\r
+                               text = wxT("Reset context probabilities on coding pass boundaries");\r
+                       else\r
+                               text = wxT("No reset of context probabilities on coding pass boundaries");\r
+                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (cbstyle & 0x04)\r
+                               text = wxT("Termination on each coding passs");\r
+                       else\r
+                               text = wxT("No termination on each coding pass");\r
+                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (cbstyle & 0x08)\r
+                               text = wxT("Vertically stripe causal context");\r
+                       else\r
+                               text = wxT("No vertically stripe causal context");\r
+                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (cbstyle & 0x10)\r
+                               text = wxT("Predictable termination");\r
+                       else\r
+                               text = wxT("No predictable termination");\r
+                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (cbstyle & 0x20)\r
+                               text = wxT("Segmentation symbols are used");\r
+                       else\r
+                               text = wxT("No segmentation symbols are used");\r
+                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       }\r
+                       break;\r
+\r
+               /////////\r
+               // COD //\r
+               /////////\r
+               case COD_VAL:\r
+                       {\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char scod = onebyte[0];\r
+\r
+                       wxString text;\r
+\r
+                       if (scod & 0x01)\r
+                               text << wxT("Partitioned entropy coder");\r
+                       else\r
+                               text << wxT("Unpartitioned entropy coder");\r
+\r
+                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       text = wxT("");\r
+                       if (scod & 0x02)\r
+                               text << wxT("Possible SOPs");\r
+                       else\r
+                               text << wxT("No SOPs");\r
+\r
+                       if (scod & 0x04)\r
+                               text << wxT(", possible EPHs");\r
+                       else\r
+                               text << wxT(", no EPHs");\r
+\r
+                       subcurrid3 = m_tree->AppendItem(currid,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char progord = onebyte[0];\r
+\r
+                       if (m_file->Read(twobytes, 2) != 2)\r
+                               break;\r
+                       unsigned short int numlayers = STREAM_TO_UINT16(twobytes, 0);\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char mctransform = onebyte[0];\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char decomplevs = onebyte[0];\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char cbswidth = onebyte[0];\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char cbsheight = onebyte[0];\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char cbstyle = onebyte[0];\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char transform = onebyte[0];\r
+\r
+                       subcurrid3 = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("%d levels (%d resolutions)"), decomplevs, decomplevs + 1),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       text = wxT("");\r
+                       switch (progord) {\r
+                       case (0):\r
+                               text << wxT("LRCP");\r
+                               break;\r
+                       case (1):\r
+                               text << wxT("RLCP");\r
+                               break;\r
+                       case (2):\r
+                               text << wxT("LRCP");\r
+                               break;\r
+                       case (3):\r
+                               text << wxT("RPCL");\r
+                               break;\r
+                       case (4):\r
+                               text << wxT("CPRL");\r
+                               break;\r
+                       default:\r
+                               text << wxT("unknown progression");\r
+                               break;\r
+                       }\r
+                       text << wxString::Format(wxT(", %d layers"), numlayers);\r
+                       if (transform & 0x01)\r
+                               text << wxT(", 5-3 rev.");\r
+                       else\r
+                               text << wxT(", 9-7 irr.");\r
+                       subcurrid3 = m_tree->AppendItem(currid,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       subcurrid3 = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("Code-blocks: %dx%d"), 1 << ((cbswidth & 0x0F) + 2), 1 << ((cbsheight & 0x0F) + 2)),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       switch (mctransform) {\r
+                       case (0):\r
+                               {\r
+                               text = wxT("No MCT");\r
+                               }\r
+                               break;\r
+                       case (1):\r
+                               {\r
+                               text = wxT("Reversible MCT on 0, 1, 2");\r
+                               }\r
+                               break;\r
+                       case (2):\r
+                               {\r
+                               text = wxT("Irreversible MCT on 0, 1, 2");\r
+                               }\r
+                               break;\r
+                       default:\r
+                               {\r
+                               text = wxT("Unknown");\r
+                               }\r
+                               break;\r
+                       };\r
+                       subcurrid3 = m_tree->AppendItem(currid,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+\r
+                       image = m_tree->TreeCtrlIcon_Folder;\r
+                       imageSel = image + 1;\r
+\r
+                       subcurrid3 = m_tree->AppendItem(currid,\r
+                               wxT("Coding styles"),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       image = m_tree->TreeCtrlIcon_File;\r
+                       imageSel = image + 1;\r
+\r
+                       if (cbstyle & 0x01)\r
+                               text = wxT("Selective arithmetic coding bypass");\r
+                       else\r
+                               text = wxT("No selective arithmetic coding bypass");\r
+                       wxTreeItemId subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (cbstyle & 0x02)\r
+                               text = wxT("Reset context probabilities on coding pass boundaries");\r
+                       else\r
+                               text = wxT("No reset of context probabilities on coding pass boundaries");\r
+                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (cbstyle & 0x04)\r
+                               text = wxT("Termination on each coding passs");\r
+                       else\r
+                               text = wxT("No termination on each coding pass");\r
+                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (cbstyle & 0x08)\r
+                               text = wxT("Vertically stripe causal context");\r
+                       else\r
+                               text = wxT("No vertically stripe causal context");\r
+                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (cbstyle & 0x10)\r
+                               text = wxT("Predictable termination");\r
+                       else\r
+                               text = wxT("No predictable termination");\r
+                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (cbstyle & 0x20)\r
+                               text = wxT("Segmentation symbols are used");\r
+                       else\r
+                               text = wxT("No segmentation symbols are used");\r
+                       subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       };\r
+                       break;\r
+\r
+               /////////\r
+               // QCC //\r
+               /////////\r
+               case QCC_VAL:\r
+                       {\r
+                       unsigned short int cqcc;\r
+                       if (csiz < 257) {\r
+                               if (m_file->Read(onebyte, 1) != 1)\r
+                                       break;\r
+                               cqcc = onebyte[0];\r
+                       } else {\r
+                               if (m_file->Read(twobytes, 2) != 2)\r
+                                       break;\r
+                               cqcc = STREAM_TO_UINT16(twobytes, 0);\r
+                       }\r
+\r
+                       wxTreeItemId subcurrid = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("Comp. no. %d"), cqcc),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+                       \r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char sqcc = onebyte[0];\r
+\r
+                       wxString text;\r
+                       switch (sqcc & 0x1F) {\r
+                       case (0):\r
+                               text = wxT("No quantization");\r
+                               break;\r
+                       case (1):\r
+                               text = wxT("Scalar implicit");\r
+                               break;\r
+                       case (2):\r
+                               text = wxT("Scalar explicit");\r
+                               break;\r
+                       default:\r
+                               text = wxT("Unknown");\r
+                               break;\r
+                       }\r
+                       text << wxString::Format(wxT(", %d guard bits"), (sqcc & 0xE0) >> 5);\r
+                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       }\r
+                       break;\r
+\r
+               /////////\r
+               // QCD //\r
+               /////////\r
+               case QCD_VAL:\r
+                       {\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char sqcd = onebyte[0];\r
+\r
+                       wxString text;\r
+                       switch (sqcd & 0x1F) {\r
+                       case (0):\r
+                               text = wxT("No quantization");\r
+                               break;\r
+                       case (1):\r
+                               text = wxT("Scalar implicit");\r
+                               break;\r
+                       case (2):\r
+                               text = wxT("Scalar explicit");\r
+                               break;\r
+                       default:\r
+                               text = wxT("Unknown");\r
+                               break;\r
+                       }\r
+                       text << wxString::Format(wxT(", %d guard bits"), (sqcd & 0xE0) >> 5);\r
+                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       };\r
+                       break;\r
+\r
+               /////////\r
+               // COM //\r
+               /////////\r
+               case COM_VAL:\r
+                       {\r
+                       #define showlen 25\r
+                       char comment[showlen];\r
+                       wxString comments;\r
+\r
+                       if (m_file->Read(twobytes, 2) != 2)\r
+                               break;\r
+                       unsigned short int rcom = STREAM_TO_UINT16(twobytes, 0);\r
+\r
+                       wxString text;\r
+                       if (rcom == 0)\r
+                               text = wxT("Binary values");\r
+                       else if (rcom == 1)\r
+                               text = wxT("ISO 8859-1 (latin-1) values");\r
+                       else if (rcom < 65535)\r
+                               text = wxT("Reserved for registration");\r
+                       else\r
+                               text = wxT("Reserved for extension");\r
+                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
+                               text,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (m_file->Read(comment, showlen) != showlen)\r
+                               break;\r
+                       comments = wxString::FromAscii(comment).Truncate(wxMin(showlen, currlen - 4));\r
+                       if ((currlen - 4) > showlen)\r
+                               comments << wxT("...");\r
+                       subcurrid3 = m_tree->AppendItem(currid,\r
+                               comments,\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+                       };\r
+                       break;\r
+\r
+               /////////\r
+               // TLM //\r
+               /////////\r
+               case TLM_VAL:\r
+                       {\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char ztlm = onebyte[0];\r
+\r
+                       if (m_file->Read(onebyte, 1) != 1)\r
+                               break;\r
+                       unsigned char stlm = onebyte[0];\r
+\r
+                       image = m_tree->TreeCtrlIcon_File;\r
+                       imageSel = image + 1;\r
+\r
+                       wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("TLM #%d"), ztlm),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       subcurrid3 = m_tree->AppendItem(currid,\r
+                               wxString::Format(wxT("%d bits/index, %d bits/length"),\r
+                               8 * ((stlm & 0x30) >> 4), 16 + 16 * ((stlm & 0x40) >> 6)),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       int n, numparts;\r
+\r
+                       numparts = (currlen - 2) / ( ((stlm & 0x30) >> 4) + 2 + 2 * ((stlm & 0x40) >> 6));\r
+\r
+                       image = m_tree->TreeCtrlIcon_Folder;\r
+                       imageSel = image + 1;\r
+\r
+                       subcurrid3 = m_tree->AppendItem(currid,\r
+                               wxT("Tile parts"),\r
+                               image, imageSel,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       image = m_tree->TreeCtrlIcon_File;\r
+                       imageSel = image + 1;\r
+\r
+                       for (n = 0; n < numparts; n++) {\r
+\r
+                               unsigned short int ttlm;\r
+                               unsigned long int ptlm;\r
+\r
+                               switch (((stlm & 0x30) >> 4)) {\r
+\r
+                               case 0:\r
+                                       ttlm = 0;\r
+                                       break;\r
+\r
+                               case 1:\r
+                                       if (m_file->Read(onebyte, 1) != 1)\r
+                                               break;\r
+                                       ttlm = onebyte[0];\r
+                                       break;\r
+\r
+                               case 2:\r
+                                       if (m_file->Read(twobytes, 2) != 2)\r
+                                               break;\r
+                                       ttlm = STREAM_TO_UINT16(twobytes, 0);\r
+                                       break;\r
+\r
+                               }\r
+\r
+                               switch (((stlm & 0x40) >> 6)) {\r
+\r
+                               case 0:\r
+                                       if (m_file->Read(twobytes, 2) != 2)\r
+                                               break;\r
+                                       ptlm = STREAM_TO_UINT16(twobytes, 0);\r
+                                       break;\r
+\r
+                               case 1:\r
+                                       if (m_file->Read(fourbytes, 4) != 4)\r
+                                               break;\r
+                                       ptlm = STREAM_TO_UINT32(fourbytes, 0);\r
+                                       break;\r
+\r
+                               }\r
+\r
+                               wxTreeItemId subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                                       wxString::Format(wxT("Tile %d: %d bytes"), ttlm, ptlm),\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+                       }\r
+\r
+                       }\r
+                       break;\r
+\r
+               /////////\r
+               // POD //\r
+               /////////\r
+               case POD_VAL:\r
+                       {\r
+                       int n, numchanges;\r
+\r
+                       if (csiz < 257)\r
+                               numchanges = (currlen - 2) / 7;\r
+                       else\r
+                               numchanges = (currlen - 2) / 9;\r
+\r
+                       for (n = 0; n < numchanges; n++) {\r
+\r
+                               image = m_tree->TreeCtrlIcon_Folder;\r
+                               imageSel = image + 1;\r
+\r
+                               wxTreeItemId subcurrid3 = m_tree->AppendItem(currid,\r
+                                       wxString::Format(wxT("Change #%d"), n),\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+                               if (m_file->Read(onebyte, 1) != 1)\r
+                                       break;\r
+                               unsigned char rspod = onebyte[0];\r
+\r
+                               unsigned short int cspod;\r
+                               if (csiz < 257) {\r
+                                       if (m_file->Read(onebyte, 1) != 1)\r
+                                               break;\r
+                                       cspod = onebyte[0];\r
+                               } else {\r
+                                       if (m_file->Read(twobytes, 2) != 2)\r
+                                               break;\r
+                                       cspod = STREAM_TO_UINT16(twobytes, 0);\r
+                               }\r
+\r
+                               if (m_file->Read(twobytes, 2) != 2)\r
+                                       break;\r
+                               unsigned short int lyepod = STREAM_TO_UINT16(twobytes, 0);\r
+\r
+                               if (m_file->Read(onebyte, 1) != 1)\r
+                                       break;\r
+                               unsigned char repod = onebyte[0];\r
+\r
+                               unsigned short int cepod;\r
+                               if (csiz < 257) {\r
+                                       if (m_file->Read(onebyte, 1) != 1)\r
+                                               break;\r
+                                       cepod = onebyte[0];\r
+                               } else {\r
+                                       if (m_file->Read(twobytes, 2) != 2)\r
+                                               break;\r
+                                       cepod = STREAM_TO_UINT16(twobytes, 0);\r
+                               }\r
+\r
+                               if (m_file->Read(onebyte, 1) != 1)\r
+                                       break;\r
+                               unsigned char ppod = onebyte[0];\r
+\r
+                               image = m_tree->TreeCtrlIcon_File;\r
+                               imageSel = image + 1;\r
+\r
+                               wxTreeItemId subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                                       wxString::Format(wxT("%d <= Resolution < %d"), rspod, repod),\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+                               subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                                       wxString::Format(wxT("%d <= Component < %d"), cspod, cepod),\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+                               subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                                       wxString::Format(wxT("0 <= Layer < %d"), lyepod),\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+                               wxString text = wxT("");\r
+                               switch (ppod) {\r
+                               case (0):\r
+                                       text << wxT("LRCP");\r
+                                       break;\r
+                               case (1):\r
+                                       text << wxT("RLCP");\r
+                                       break;\r
+                               case (2):\r
+                                       text << wxT("LRCP");\r
+                                       break;\r
+                               case (3):\r
+                                       text << wxT("RPCL");\r
+                                       break;\r
+                               case (4):\r
+                                       text << wxT("CPRL");\r
+                                       break;\r
+                               default:\r
+                                       text << wxT("unknown progression");\r
+                                       break;\r
+                               }\r
+                               subcurrid4 = m_tree->AppendItem(subcurrid3,\r
+                                       text,\r
+                                       image, imageSel,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                       }\r
+\r
+                       }\r
+                       break;\r
+\r
+               /////////\r
+               // SOD //\r
+               /////////\r
+               case SOD_VAL:\r
+                       {\r
+                       inside_sod = 1;\r
+                       };\r
+                       break;\r
+\r
+               default:\r
+                       break;\r
+                       \r
+               }\r
+                                                               \r
+               // increment number of markers\r
+               if (nmarks++ >= maxmarks) {\r
+                       WriteText(wxT("Maximum amount of markers exceeded"));\r
+                       break;\r
+               }\r
+\r
+               // advance position\r
+               OPJ_ADVANCE(currlen + 2);\r
+       }       \r
+\r
+       WriteText(wxT("Search finished"));\r
+}\r
diff --git a/applications/OPJViewer/source/wxjp2parser.cpp b/applications/OPJViewer/source/wxjp2parser.cpp
new file mode 100644 (file)
index 0000000..6e89390
--- /dev/null
@@ -0,0 +1,1116 @@
+/*\r
+ * Copyright (c) 2007, Digital Signal Processing Laboratory, Universit� degli studi di Perugia (UPG), Italy\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+#include "OPJViewer.h"\r
+\r
+/* defines */\r
+#define SHORT_DESCR_LEN        32\r
+#define LONG_DESCR_LEN         256\r
+\r
+/* enumeration for file formats */\r
+#define J2FILENUM              4\r
+typedef enum {\r
+\r
+        JP2_FILE,\r
+        J2K_FILE,\r
+               MJ2_FILE,\r
+               UNK_FILE\r
+\r
+} j2filetype;\r
+\r
+/* enumeration for the box types */\r
+#define j22boxNUM                23\r
+typedef enum {\r
+\r
+                       FILE_BOX,\r
+                       JP_BOX,\r
+                       FTYP_BOX,\r
+                       JP2H_BOX,\r
+                       IHDR_BOX,\r
+                       COLR_BOX,\r
+                       JP2C_BOX,\r
+                       JP2I_BOX,\r
+                       XML_BOX,\r
+                       UUID_BOX,\r
+                       UINF_BOX,\r
+                       MOOV_BOX,\r
+                       MVHD_BOX,\r
+                       TRAK_BOX,\r
+                       TKHD_BOX,\r
+                       MDIA_BOX,\r
+                       MDHD_BOX,\r
+                       HDLR_BOX,\r
+                       MINF_BOX,\r
+                       VMHD_BOX,\r
+                       STBL_BOX,\r
+                       STSD_BOX,\r
+                       STSZ_BOX,\r
+                       MJP2_BOX,\r
+                       MDAT_BOX,\r
+                       ANY_BOX,\r
+                       UNK_BOX\r
+\r
+} j22boxtype;\r
+\r
+/* the box structure itself */\r
+struct boxdef {\r
+\r
+        char                  value[5];                 /* hexadecimal value/string*/\r
+               char                  name[SHORT_DESCR_LEN];    /* short description       */\r
+               char                  descr[LONG_DESCR_LEN];    /* long  description       */\r
+               int                   sbox;                     /* is it a superbox?       */\r
+               int                   req[J2FILENUM];           /* mandatory box           */\r
+               j22boxtype             ins;                      /* contained in box...     */\r
+\r
+};\r
+\r
+\r
+/* jp2 family box signatures */\r
+#define FILE_SIGN           ""\r
+#define JP_SIGN             "jP\040\040"\r
+#define FTYP_SIGN           "ftyp"\r
+#define JP2H_SIGN           "jp2h"\r
+#define IHDR_SIGN           "ihdr"\r
+#define COLR_SIGN           "colr"\r
+#define JP2C_SIGN           "jp2c"\r
+#define JP2I_SIGN           "jp2i"\r
+#define XML_SIGN            "xml\040"\r
+#define UUID_SIGN           "uuid"\r
+#define UINF_SIGN           "uinf"\r
+#define MOOV_SIGN           "moov"\r
+#define MVHD_SIGN           "mvhd"\r
+#define TRAK_SIGN           "trak"\r
+#define TKHD_SIGN           "tkhd"\r
+#define MDIA_SIGN           "mdia"\r
+#define MDHD_SIGN           "mdhd"\r
+#define HDLR_SIGN           "hdlr"\r
+#define MINF_SIGN           "minf"\r
+#define VMHD_SIGN           "vmhd"\r
+#define STBL_SIGN           "stbl"\r
+#define STSD_SIGN           "stsd"\r
+#define STSZ_SIGN           "stsz"\r
+#define MJP2_SIGN           "mjp2"\r
+#define MDAT_SIGN           "mdat"\r
+#define ANY_SIGN                       ""\r
+#define UNK_SIGN            ""\r
+\r
+/* the possible boxes */\r
+struct boxdef j22box[] =\r
+{\r
+/* sign */     {FILE_SIGN,\r
+/* short */    "placeholder for nothing",\r
+/* long */     "Nothing to say",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {JP_SIGN,\r
+/* short */    "JPEG 2000 Signature box",\r
+/* long */     "This box uniquely identifies the file as being part of the JPEG 2000 family of files",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {FTYP_SIGN,\r
+/* short */    "File Type box",\r
+/* long */     "This box specifies file type, version and compatibility information, including specifying if this file "\r
+                       "is a conforming JP2 file or if it can be read by a conforming JP2 reader",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {JP2H_SIGN,\r
+/* short */    "JP2 Header box",\r
+/* long */     "This box contains a series of boxes that contain header-type information about the file",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {IHDR_SIGN,\r
+/* short */    "Image Header box",\r
+/* long */     "This box specifies the size of the image and other related fields",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      JP2H_BOX},\r
+\r
+/* sign */     {COLR_SIGN,\r
+/* short */    "Colour Specification box",\r
+/* long */     "This box specifies the colourspace of the image",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      JP2H_BOX},\r
+\r
+/* sign */     {JP2C_SIGN,\r
+/* short */    "Contiguous Codestream box",\r
+/* long */     "This box contains the codestream as defined by Annex A",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {JP2I_SIGN,\r
+/* short */    "Intellectual Property box",\r
+/* long */     "This box contains intellectual property information about the image",\r
+/* sbox */     0,\r
+/* req */      {0, 0, 0},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {XML_SIGN,\r
+/* short */    "XML box",\r
+/* long */     "This box provides a tool by which vendors can add XML formatted information to a JP2 file",\r
+/* sbox */     0,\r
+/* req */      {0, 0, 0},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {UUID_SIGN,\r
+/* short */    "UUID box",\r
+/* long */     "This box provides a tool by which vendors can add additional information to a file "\r
+                       "without risking conflict with other vendors",\r
+/* sbox */     0,\r
+/* req */      {0, 0, 0},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {UINF_SIGN,\r
+/* short */    "UUID Info box",\r
+/* long */     "This box provides a tool by which a vendor may provide access to additional information associated with a UUID",\r
+/* sbox */     0,\r
+/* req */      {0, 0, 0},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {MOOV_SIGN,\r
+/* short */    "Movie box",\r
+/* long */     "This box contains the media data. In video tracks, this box would contain JPEG2000 video frames",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {MVHD_SIGN,\r
+/* short */    "Movie Header box",\r
+/* long */     "This box defines overall information which is media-independent, and relevant to the entire presentation "\r
+                       "considered as a whole",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MOOV_BOX},\r
+\r
+/* sign */     {TRAK_SIGN,\r
+/* short */    "Track box",\r
+/* long */     "This is a container box for a single track of a presentation. A presentation may consist of one or more tracks",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MOOV_BOX},\r
+\r
+/* sign */     {TKHD_SIGN,\r
+/* short */    "Track Header box",\r
+/* long */     "This box specifies the characteristics of a single track. Exactly one Track Header Box is contained in a track",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      TRAK_BOX},\r
+\r
+/* sign */     {MDIA_SIGN,\r
+/* short */    "Media box",\r
+/* long */     "The media declaration container contains all the objects which declare information about the media data "\r
+                       "within a track",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      TRAK_BOX},\r
+\r
+/* sign */     {MDHD_SIGN,\r
+/* short */    "Media Header box",\r
+/* long */     "The media header declares overall information which is media-independent, and relevant to characteristics "\r
+                       "of the media in a track",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MDIA_BOX},\r
+\r
+/* sign */     {HDLR_SIGN,\r
+/* short */    "Handler Reference box",\r
+/* long */     "This box within a Media Box declares the process by which the media-data in the track may be presented, "\r
+                       "and thus, the nature of the media in a track",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MDIA_BOX},\r
+\r
+/* sign */     {MINF_SIGN,\r
+/* short */    "Media Information box",\r
+/* long */     "This box contains all the objects which declare characteristic information of the media in the track",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MDIA_BOX},\r
+\r
+/* sign */     {VMHD_SIGN,\r
+/* short */    "Video Media Header box",\r
+/* long */     "The video media header contains general presentation information, independent of the coding, for video media",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MINF_BOX},\r
+\r
+/* sign */     {STBL_SIGN,\r
+/* short */    "Sample Table box",\r
+/* long */     "The sample table contains all the time and data indexing of the media samples in a track",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MINF_BOX},\r
+\r
+/* sign */     {STSD_SIGN,\r
+/* short */    "STSD Sample Description box",\r
+/* long */     "The sample description table gives detailed information about the coding type used, and any initialization "\r
+                       "information needed for that coding",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MINF_BOX},\r
+\r
+/* sign */     {STSZ_SIGN,\r
+/* short */    "Sample Size box",\r
+/* long */     "This box contains the sample count and a table giving the size of each sample",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      STBL_BOX},\r
+\r
+/* sign */     {MJP2_SIGN,\r
+/* short */    "MJP2 Sample Description box",\r
+/* long */     "The MJP2 sample description table gives detailed information about the coding type used, and any initialization "\r
+                       "information needed for that coding",\r
+/* sbox */     0,\r
+/* req */      {1, 1, 1},\r
+/* ins */      MINF_BOX},\r
+\r
+/* sign */     {MDAT_SIGN,\r
+/* short */    "Media Data box",\r
+/* long */     "The meta-data for a presentation is stored in the single Movie Box which occurs at the top-level of a file",\r
+/* sbox */     1,\r
+/* req */      {1, 1, 1},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {ANY_SIGN,\r
+/* short */    "Any box",\r
+/* long */     "All the existing boxes",\r
+/* sbox */     0,\r
+/* req */      {0, 0, 0},\r
+/* ins */      FILE_BOX},\r
+\r
+/* sign */     {UNK_SIGN,\r
+/* short */    "Unknown Type box",\r
+/* long */     "The signature is not recognised to be that of an existing box",\r
+/* sbox */     0,\r
+/* req */      {0, 0, 0},\r
+/* ins */      ANY_BOX}\r
+\r
+};\r
+\r
+\r
+/* macro functions */\r
+/* From little endian to big endian, 2 and 4 bytes */\r
+#define        BYTE_SWAP2(X)   ((X & 0x00FF) << 8) | ((X & 0xFF00) >> 8)\r
+#define        BYTE_SWAP4(X)   ((X & 0x000000FF) << 24) | ((X & 0x0000FF00) << 8) | ((X & 0x00FF0000) >> 8) | ((X & 0xFF000000) >> 24)\r
+\r
+#ifdef __WXGTK__\r
+#define        BYTE_SWAP8(X)   ((X & 0x00000000000000FFULL) << 56) | ((X & 0x000000000000FF00ULL) << 40) | \\r
+                        ((X & 0x0000000000FF0000ULL) << 24) | ((X & 0x00000000FF000000ULL) << 8) | \\r
+                                               ((X & 0x000000FF00000000ULL) >> 8)  | ((X & 0x0000FF0000000000ULL) >> 24) | \\r
+                                               ((X & 0x00FF000000000000ULL) >> 40) | ((X & 0xFF00000000000000ULL) >> 56)\r
+#else\r
+#define        BYTE_SWAP8(X)   ((X & 0x00000000000000FF) << 56) | ((X & 0x000000000000FF00) << 40) | \\r
+                        ((X & 0x0000000000FF0000) << 24) | ((X & 0x00000000FF000000) << 8) | \\r
+                                               ((X & 0x000000FF00000000) >> 8)  | ((X & 0x0000FF0000000000) >> 24) | \\r
+                                               ((X & 0x00FF000000000000) >> 40) | ((X & 0xFF00000000000000) >> 56)\r
+#endif\r
+\r
+/* From codestream to int values */\r
+#define STREAM_TO_UINT32(C, P) (((unsigned long int) (C)[(P) + 0] << 24) + \\r
+                                                               ((unsigned long int) (C)[(P) + 1] << 16) + \\r
+                                                               ((unsigned long int) (C)[(P) + 2] << 8) + \\r
+                                                               ((unsigned long int) (C)[(P) + 3] << 0))\r
+\r
+#define STREAM_TO_UINT16(C, P) (((unsigned long int) (C)[(P) + 0] << 8) + \\r
+                                                               ((unsigned long int) (C)[(P) + 1] << 0))\r
+\r
+#define OPJREAD_LONG(F,L,N) { \\r
+                                                       if (F->Read(fourbytes, 4) < 4) { \\r
+                                                               wxLogMessage(wxT("Problem reading " N " from the file (file ended?)")); \\r
+                                                               return -1; \\r
+                                                       }; \\r
+                                                       L = STREAM_TO_UINT32(fourbytes, 0); \\r
+                                                       }\r
+\r
+/* handling functions */\r
+#define ITEM_PER_ROW   10\r
+\r
+//#define indprint     if (0) printf("%.*s", 2 * level + 9, indent), printf\r
+char    indent[] =  "                                                                   "\r
+                                       "                                                                   "\r
+                                       "                                                                   "\r
+                                       "                                                                   ";\r
+\r
+void indprint(wxString printout, int level)\r
+{\r
+       wxLogMessage(/*wxString::Format(wxT("%.*s"), 2 * level + 9, indent) + */printout);\r
+}\r
+\r
+/* Box handler function */\r
+int OPJParseThread::box_handler_function(int boxtype, wxFile *fileid, wxFileOffset filepoint, wxFileOffset filelimit,\r
+                                                wxTreeItemId parentid, int level, char *scansign, unsigned long int *scanpoint)\r
+{\r
+       switch ((j22boxtype) boxtype) {\r
+\r
+\r
+       /* JPEG 2000 Signature box */\r
+       case (JP_BOX): {\r
+\r
+                       unsigned long int checkdata = 0;\r
+                       fileid->Read(&checkdata, sizeof(unsigned long int));\r
+                       checkdata = BYTE_SWAP4(checkdata);\r
+\r
+                       // add info\r
+                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Check data: %X -> %s"), checkdata, (checkdata == 0x0D0A870A) ? wxT("OK") : wxT("KO")),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+               };\r
+               break;\r
+\r
+\r
+       /* JPEG 2000 codestream box */\r
+       case (JP2C_BOX): {\r
+\r
+                       // add info\r
+                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                               wxString(wxT("Codestream")),\r
+                               m_tree->TreeCtrlIcon_Folder, m_tree->TreeCtrlIcon_Folder + 1,\r
+                               new OPJMarkerData(wxT("INFO-CSTREAM"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
+                               );\r
+\r
+                       m_tree->SetItemHasChildren(currid);\r
+\r
+                       // parse the file\r
+                       //ParseJ2KFile(fileid, filepoint, filelimit, currid);\r
+\r
+               };\r
+               break;\r
+\r
+\r
+\r
+\r
+\r
+       /* File Type box */\r
+       case (FTYP_BOX): {\r
+\r
+                       char BR[4], CL[4];\r
+                       unsigned long int MinV, numCL, i;\r
+                       fileid->Read(BR, sizeof(char) * 4);\r
+                       fileid->Read(&MinV, sizeof(unsigned long int));\r
+                       MinV = BYTE_SWAP4(MinV);\r
+                       numCL = (filelimit - fileid->Tell()) / 4;                               \r
+\r
+                       // add info\r
+                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                               wxT("Brand/Minor version: ") +\r
+                               wxString::FromAscii(BR).Truncate(4) +\r
+                               wxString::Format(wxT("/%d"), MinV),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Compatibility list")),\r
+                               m_tree->TreeCtrlIcon_Folder, m_tree->TreeCtrlIcon_Folder + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       for (i = 0; i < numCL; i++) {\r
+                               fileid->Read(CL, sizeof(char) * 4);\r
+                               m_tree->AppendItem(currid,\r
+                                       wxString::FromAscii(CL).Truncate(4),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                       };\r
+                       \r
+               };\r
+               break;\r
+\r
+\r
+\r
+       /* JP2 Header box */\r
+       case (IHDR_BOX): {\r
+\r
+                       unsigned long int height, width;\r
+                       unsigned short int nc;\r
+                       unsigned char bpc, C, UnkC, IPR;\r
+                       fileid->Read(&height, sizeof(unsigned long int));\r
+                       height = BYTE_SWAP4(height);\r
+                       fileid->Read(&width, sizeof(unsigned long int));\r
+                       width = BYTE_SWAP4(width);\r
+                       fileid->Read(&nc, sizeof(unsigned short int));\r
+                       nc = BYTE_SWAP2(nc);\r
+                       fileid->Read(&bpc, sizeof(unsigned char));\r
+                       fileid->Read(&C, sizeof(unsigned char));\r
+                       fileid->Read(&UnkC, sizeof(unsigned char));\r
+                       fileid->Read(&IPR, sizeof(unsigned char));\r
+                       \r
+                       // add info\r
+                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Dimensions: %d x %d x %d @ %d bpc"), width, height, nc, bpc + 1),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Compression type: %d"), C),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Colourspace unknown: %d"), UnkC),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Intellectual Property Rights: %d"), IPR),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+                       \r
+               };\r
+               break;\r
+\r
+\r
+\r
+       /* Colour Specification box */\r
+       case (COLR_BOX): {\r
+\r
+                       unsigned char METH, PREC, APPROX;\r
+                       char methdescr[80], enumcsdescr[80];\r
+                       unsigned long int EnumCS;\r
+                       fileid->Read(&METH, sizeof(unsigned char));\r
+                       switch (METH) {\r
+                       case 1:\r
+                               strcpy(methdescr, "Enumerated Colourspace");\r
+                               break;\r
+                       case 2:\r
+                               strcpy(methdescr, "Restricted ICC profile");\r
+                               break;\r
+                       default:\r
+                               strcpy(methdescr, "Unknown");\r
+                               break;\r
+                       };\r
+                       fileid->Read(&PREC, sizeof(unsigned char));\r
+                       fileid->Read(&APPROX, sizeof(unsigned char));\r
+                       if (METH != 2) {\r
+                               fileid->Read(&EnumCS, sizeof(unsigned long int));\r
+                               EnumCS = BYTE_SWAP4(EnumCS);\r
+                               switch (EnumCS) {\r
+                               case 16:\r
+                                       strcpy(enumcsdescr, "sRGB");\r
+                                       break;\r
+                               case 17:\r
+                                       strcpy(enumcsdescr, "greyscale");\r
+                                       break;\r
+                               case 18:\r
+                                       strcpy(enumcsdescr, "sYCC");\r
+                                       break;\r
+                               default:\r
+                                       strcpy(enumcsdescr, "Unknown");\r
+                                       break;\r
+                               };\r
+                       };\r
+\r
+                       // add info\r
+                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Specification method: %d ("), METH) +\r
+                               wxString::FromAscii(methdescr) +\r
+                               wxT(")"),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Precedence: %d"), PREC),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Colourspace approximation: %d"), APPROX),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+\r
+                       if (METH != 2)\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Enumerated colourspace: %d ("), EnumCS) +\r
+                                       wxString::FromAscii(enumcsdescr) +\r
+                                       wxT(")"),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+                       if (METH != 1)\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("ICC profile: there is one")),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+\r
+\r
+               };\r
+               break;\r
+\r
+\r
+\r
+\r
+               \r
+\r
+       /* Movie Header Box */\r
+       case (MVHD_BOX): {\r
+\r
+                       unsigned long int version, rate, matrix[9], next_track_ID;\r
+                       unsigned short int volume;\r
+                       fileid->Read(&version, sizeof(unsigned long int));\r
+                       version = BYTE_SWAP4(version);\r
+                       if (version == 0) {\r
+                               unsigned long int creation_time, modification_time, timescale, duration;\r
+                               fileid->Read(&creation_time, sizeof(unsigned long int));\r
+                               creation_time = BYTE_SWAP4(creation_time);\r
+                               fileid->Read(&modification_time, sizeof(unsigned long int));\r
+                               modification_time = BYTE_SWAP4(modification_time);\r
+                               fileid->Read(&timescale, sizeof(unsigned long int));\r
+                               timescale = BYTE_SWAP4(timescale);\r
+                               fileid->Read(&duration, sizeof(unsigned long int));\r
+                               duration = BYTE_SWAP4(duration);\r
+                               const long unix_time = creation_time - 2082844800L;\r
+                               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Creation time: %u (%.24s)"), creation_time, ctime(&unix_time)),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                               const long unix_time1 = modification_time - 2082844800L;\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Modification time: %u (%.24s)"), modification_time, ctime(&unix_time1)),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Timescale: %u (%.6fs)"), timescale, 1.0 / (float) timescale),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Duration: %u (%.3fs)"), duration, (float) duration / (float) timescale),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                       } else {\r
+                               int8byte creation_time, modification_time, duration;\r
+                               unsigned long int timescale;\r
+                               fileid->Read(&creation_time, sizeof(int8byte));\r
+                               creation_time = BYTE_SWAP8(creation_time);\r
+                               fileid->Read(&modification_time, sizeof(int8byte));\r
+                               modification_time = BYTE_SWAP8(modification_time);\r
+                               fileid->Read(&timescale, sizeof(unsigned long int));\r
+                               timescale = BYTE_SWAP4(timescale);\r
+                               fileid->Read(&duration, sizeof(int8byte));\r
+                               duration = BYTE_SWAP8(duration);\r
+                               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Creation time: %u"), creation_time),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Modification time: %u"), modification_time),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Timescale: %u"), timescale),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Duration: %u"), duration),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                       };\r
+                       fileid->Read(&rate, sizeof(unsigned long int));\r
+                       rate = BYTE_SWAP4(rate);\r
+                       fileid->Read(&volume, sizeof(unsigned short int));\r
+                       volume = BYTE_SWAP2(volume);\r
+                       fileid->Seek(6, wxFromCurrent);\r
+                       fileid->Read(&matrix, sizeof(unsigned char) * 9);\r
+                       fileid->Seek(4, wxFromCurrent);\r
+                       fileid->Read(&next_track_ID, sizeof(unsigned long int));\r
+                       next_track_ID = BYTE_SWAP4(next_track_ID);\r
+                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Rate: %d (%d.%d)"), rate, rate >> 16, rate & 0x0000FFFF),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+                       currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Volume: %d (%d.%d)"), volume, volume >> 8, volume & 0x00FF),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+                       currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Next track ID: %d"), next_track_ID),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+               };\r
+               break;\r
+\r
+\r
+                       /* Sample Description box */\r
+       case (STSD_BOX): {\r
+\r
+                       unsigned long int version, entry_count;\r
+                       fileid->Read(&version, sizeof(unsigned long int));\r
+                       version = BYTE_SWAP4(version);\r
+                       fileid->Read(&entry_count, sizeof(unsigned long int));\r
+                       entry_count = BYTE_SWAP4(entry_count);\r
+                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Entry count: %d"), entry_count),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
+                               );\r
+                       jpeg2000parse(fileid, filepoint + 8, filelimit, parentid, level + 1, scansign, scanpoint);\r
+               };\r
+               break;\r
+\r
+\r
+                       /* Sample Size box */\r
+       case (STSZ_BOX): {\r
+\r
+                       unsigned long int version, sample_size, sample_count, entry_size;\r
+                       \r
+                       fileid->Read(&version, sizeof(unsigned long int));\r
+                       version = BYTE_SWAP4(version);\r
+                       \r
+                       fileid->Read(&sample_size, sizeof(unsigned long int));\r
+                       sample_size = BYTE_SWAP4(sample_size);\r
+\r
+                       if (sample_size == 0) {\r
+                               fileid->Read(&sample_count, sizeof(unsigned long int));\r
+                               sample_count = BYTE_SWAP4(sample_count);\r
+\r
+                               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Sample count: %d"), sample_count),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
+                                       );\r
+\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxT("Entries size (bytes)"),\r
+                                       m_tree->TreeCtrlIcon_Folder, m_tree->TreeCtrlIcon_Folder + 1,\r
+                                       new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
+                                       );\r
+\r
+                               wxString text;\r
+                               for (unsigned int s = 0; s < sample_count; s++) {\r
+                                       fileid->Read(&entry_size, sizeof(unsigned long int));\r
+                                       entry_size = BYTE_SWAP4(entry_size);\r
+                                       \r
+                                       text << wxString::Format(wxT("%d, "), entry_size);\r
+\r
+                                       if (((s % 10) == (ITEM_PER_ROW - 1)) || (s == (sample_count - 1))) {\r
+                                               m_tree->AppendItem(currid,\r
+                                                       text,\r
+                                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                                       new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
+                                                       );\r
+                                               text = wxT("");\r
+                                       }\r
+\r
+                               }\r
+                               \r
+                       }\r
+\r
+               };\r
+               break;\r
+\r
+\r
+                       /* Video Media Header box */\r
+       case (VMHD_BOX): {\r
+\r
+                       unsigned long int version;\r
+                       unsigned short int graphicsmode, opcolor[3];\r
+                       char graphicsdescr[100];\r
+\r
+                       fileid->Read(&version, sizeof(unsigned long int));\r
+                       version = BYTE_SWAP4(version);\r
+\r
+                       fileid->Read(&graphicsmode, sizeof(unsigned short int));\r
+                       graphicsmode = BYTE_SWAP2(graphicsmode);\r
+                       switch (graphicsmode) {\r
+                       case (0x00):\r
+                                       strcpy(graphicsdescr, "copy");\r
+                                       break;\r
+                       case (0x24):\r
+                                       strcpy(graphicsdescr, "transparent");\r
+                                       break;\r
+                       case (0x0100):\r
+                                       strcpy(graphicsdescr, "alpha");\r
+                                       break;\r
+                       case (0x0101):\r
+                                       strcpy(graphicsdescr, "whitealpha");\r
+                                       break;\r
+                       case (0x0102):\r
+                                       strcpy(graphicsdescr, "blackalpha");\r
+                                       break;\r
+                       default:\r
+                                       strcpy(graphicsdescr, "unknown");\r
+                                       break;\r
+                       };\r
+\r
+                       fileid->Read(opcolor, 3 * sizeof(unsigned short int));\r
+                       opcolor[0] = BYTE_SWAP2(opcolor[0]);\r
+                       opcolor[1] = BYTE_SWAP2(opcolor[1]);\r
+                       opcolor[2] = BYTE_SWAP2(opcolor[2]);\r
+\r
+                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Composition mode: %d (")) + \r
+                               wxString::FromAscii(graphicsdescr) +\r
+                               wxT(")"),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
+                               );\r
+\r
+                       currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("OP color: %d %d %d"), opcolor[0], opcolor[1], opcolor[2]),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
+                               );\r
+               };\r
+               break;\r
+\r
+\r
+\r
+                       /* MJP2 Sample Description box */\r
+       case (MJP2_BOX): {\r
+\r
+                       unsigned short int height, width, depth;\r
+                       unsigned long int horizresolution, vertresolution;\r
+                       char compressor_name[32];\r
+                       fileid->Seek(24, wxFromCurrent);\r
+                       fileid->Read(&width, sizeof(unsigned short int));\r
+                       width = BYTE_SWAP2(width);\r
+                       fileid->Read(&height, sizeof(unsigned short int));\r
+                       height = BYTE_SWAP2(height);\r
+                       fileid->Read(&horizresolution, sizeof(unsigned long int));\r
+                       horizresolution = BYTE_SWAP4(horizresolution);\r
+                       fileid->Read(&vertresolution, sizeof(unsigned long int));\r
+                       vertresolution = BYTE_SWAP4(vertresolution);\r
+                       fileid->Seek(6, wxFromCurrent);\r
+                       fileid->Read(compressor_name, sizeof(char) * 32);\r
+                       fileid->Read(&depth, sizeof(unsigned short int));\r
+                       depth = BYTE_SWAP2(depth);\r
+                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Dimensions: %d x %d @ %d bpp"), width, height, depth),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"), m_tree->m_fname.GetFullPath(), filepoint, filelimit)\r
+                               );\r
+                       currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Resolution: %d.%d x %d.%d"), horizresolution >> 16, horizresolution & 0x0000FFFF,\r
+                               vertresolution >> 16, vertresolution & 0x0000FFFF),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+                       currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Compressor: %.32s"), compressor_name),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+                       jpeg2000parse(fileid, filepoint + 78, filelimit, parentid, level + 1, scansign, scanpoint);\r
+\r
+               };\r
+               break;\r
+\r
+               /* Media Header box */\r
+       case (MDHD_BOX): {\r
+                       unsigned long int version;\r
+                       unsigned short int language;\r
+                       fileid->Read(&version, sizeof(unsigned long int));\r
+                       version = BYTE_SWAP4(version);\r
+                       if (version == 0) {\r
+                               unsigned long int creation_time, modification_time, timescale, duration;\r
+                               fileid->Read(&creation_time, sizeof(unsigned long int));\r
+                               creation_time = BYTE_SWAP4(creation_time);\r
+                               fileid->Read(&modification_time, sizeof(unsigned long int));\r
+                               modification_time = BYTE_SWAP4(modification_time);\r
+                               fileid->Read(&timescale, sizeof(unsigned long int));\r
+                               timescale = BYTE_SWAP4(timescale);\r
+                               fileid->Read(&duration, sizeof(unsigned long int));\r
+                               duration = BYTE_SWAP4(duration);\r
+                               const long unix_time = creation_time - 2082844800L;\r
+                               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Creation time: %u (%.24s)"), creation_time, ctime(&unix_time)),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                               const long unix_time1 = modification_time - 2082844800L;\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Modification time: %u (%.24s)"), modification_time, ctime(&unix_time1)),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Timescale: %u (%.6fs)"), timescale, 1.0 / (float) timescale),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Duration: %u (%.3fs)"), duration, (float) duration / (float) timescale),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                       } else {\r
+                               int8byte creation_time, modification_time, duration;\r
+                               unsigned long int timescale;\r
+                               fileid->Read(&creation_time, sizeof(int8byte));\r
+                               creation_time = BYTE_SWAP8(creation_time);\r
+                               fileid->Read(&modification_time, sizeof(int8byte));\r
+                               modification_time = BYTE_SWAP8(modification_time);\r
+                               fileid->Read(&timescale, sizeof(unsigned long int));\r
+                               timescale = BYTE_SWAP4(timescale);\r
+                               fileid->Read(&duration, sizeof(int8byte));\r
+                               duration = BYTE_SWAP8(duration);\r
+                               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Creation time: %u"), creation_time),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Modification time: %u"), modification_time),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Timescale: %u"), timescale),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                               currid = m_tree->AppendItem(parentid,\r
+                                       wxString::Format(wxT("Duration: %u"), duration),\r
+                                       m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                                       new OPJMarkerData(wxT("INFO"))\r
+                                       );\r
+                       }\r
+                       fileid->Read(&language, sizeof(unsigned short int));\r
+\r
+                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Language: %d (%c%c%c)"), language & 0xEFFF,\r
+                               0x60 + (char) ((language >> 10) & 0x001F), 0x60 + (char) ((language >> 5) & 0x001F), 0x60 + (char) ((language >> 0) & 0x001F)),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+               };\r
+               break;\r
+               \r
+               /* Media Handler box */\r
+       case (HDLR_BOX): {\r
+                       unsigned long int version, predefined, temp[3];\r
+                       char handler[4], name[256];\r
+                       int namelen = wxMin(256, (filelimit - filepoint - 24));\r
+                       fileid->Read(&version, sizeof(unsigned long int));\r
+                       version = BYTE_SWAP4(version);\r
+                       fileid->Read(&predefined, sizeof(unsigned long int));\r
+                       fileid->Read(handler, 4 * sizeof(char));\r
+                       fileid->Read(&temp, 3 * sizeof(unsigned long int));\r
+                       fileid->Read(name, namelen * sizeof(char));\r
+\r
+                       wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Handler: %.4s"), handler),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+                                        \r
+                       currid = m_tree->AppendItem(parentid,\r
+                               wxString::Format(wxT("Name: %.255s"), name),\r
+                               m_tree->TreeCtrlIcon_File, m_tree->TreeCtrlIcon_File + 1,\r
+                               new OPJMarkerData(wxT("INFO"))\r
+                               );\r
+                                                                        \r
+               }\r
+               break;\r
+\r
+       /* not yet implemented */\r
+       default:\r
+               break;\r
+\r
+       };\r
+\r
+       return (0);\r
+}\r
+\r
+\r
+void OPJParseThread::ParseJP2File(wxFile *fileid, wxFileOffset filepoint, wxFileOffset filelimit, wxTreeItemId parentid)\r
+{\r
+       unsigned long int scanpoint;\r
+\r
+       jpeg2000parse(fileid, filepoint, filelimit, parentid, 0, NULL, &scanpoint);\r
+}\r
+\r
+/* the parsing function itself */\r
+/*\r
+  fileid    = fid of the file to scan (you should open it by yourself)\r
+  filepoint = first byte where to start to scan from (usually 0)\r
+  filelimit = first byte where to stop to scan from (usually the file size)\r
+  level     = set this to 0\r
+  scansign  = signature to scan for (NULL avoids search, returns "    " if successful)\r
+  scanpoint = point where the scan signature lies\r
+*/\r
+int OPJParseThread::jpeg2000parse(wxFile *fileid, wxFileOffset filepoint, wxFileOffset filelimit,\r
+                                                                 wxTreeItemId parentid, int level, char *scansign, unsigned long int *scanpoint)\r
+{\r
+       unsigned long int       LBox = 0x00000000;\r
+       //int                     LBox_read;\r
+       char                    TBox[5] = "\0\0\0\0";\r
+       //int                     TBox_read;\r
+       int8byte                                XLBox = 0x0000000000000000;\r
+       //int                     XLBox_read;\r
+       unsigned long int       box_length = 0;\r
+       int                     last_box = 0, box_num = 0;\r
+       int                     box_type = ANY_BOX;\r
+       unsigned char           /*onebyte[1], twobytes[2],*/ fourbytes[4];\r
+\r
+       /* cycle all over the file */\r
+       box_num = 0;\r
+       last_box = 0;\r
+       while (!last_box) {\r
+\r
+               /* do not exceed file limit */\r
+               if (filepoint >= filelimit)\r
+                       return (0);\r
+\r
+               /* seek on file */\r
+               if (fileid->Seek(filepoint, wxFromStart) == wxInvalidOffset)\r
+                       return (-1);\r
+\r
+               /* read the mandatory LBox, 4 bytes */\r
+               if (fileid->Read(fourbytes, 4) < 4) {\r
+                       WriteText(wxT("Problem reading LBox from the file (file ended?)"));\r
+                       return -1;\r
+               };\r
+               LBox = STREAM_TO_UINT32(fourbytes, 0);\r
+\r
+               /* read the mandatory TBox, 4 bytes */\r
+               if (fileid->Read(TBox, 4) < 4) {\r
+                       WriteText(wxT("Problem reading TBox from the file (file ended?)"));\r
+                       return -1;\r
+               };\r
+\r
+               /* look if scansign is got */\r
+               if ((scansign != NULL) && (memcmp(TBox, scansign, 4) == 0)) {\r
+                       memcpy(scansign, "    ", 4);\r
+                       *scanpoint = filepoint;\r
+\r
+                       /* hack/exploit */\r
+                       // stop as soon as you find the codebox\r
+                       return (0);\r
+\r
+               };\r
+\r
+               /* determine the box type */\r
+               for (box_type = JP_BOX; box_type < UNK_BOX; box_type++)\r
+                       if (memcmp(TBox, j22box[box_type].value, 4) == 0)\r
+                               break;  \r
+\r
+               /* read the optional XLBox, 8 bytes */\r
+               if (LBox == 1) {\r
+\r
+                       if (fileid->Read(&XLBox, 8) < 8) {\r
+                               WriteText(wxT("Problem reading XLBox from the file (file ended?)"));\r
+                               return -1;\r
+                       };\r
+                       box_length = (unsigned long int) BYTE_SWAP8(XLBox);\r
+\r
+               } else if (LBox == 0x00000000) {\r
+\r
+                       /* last box in file */\r
+                       last_box = 1; \r
+                       box_length = filelimit - filepoint;\r
+\r
+               } else\r
+\r
+                       box_length = LBox;\r
+\r
+               /* show box info */\r
+\r
+               // append the marker\r
+               int image, imageSel;\r
+               image = m_tree->TreeCtrlIcon_Folder;\r
+               imageSel = image + 1;\r
+               wxTreeItemId currid = m_tree->AppendItem(parentid,\r
+                       wxString::Format(wxT("%03d: "), box_num) +\r
+                       wxString::FromAscii(TBox) +\r
+                       wxString::Format(wxT(" (0x%04X)"),\r
+                               ((unsigned long int) TBox[3]) + ((unsigned long int) TBox[2] << 8) +\r
+                               ((unsigned long int) TBox[1] << 16) + ((unsigned long int) TBox[0] << 24)\r
+                       ),\r
+                       image, imageSel,\r
+                       new OPJMarkerData(wxT("BOX"), m_tree->m_fname.GetFullPath(), filepoint, filepoint + box_length)\r
+                       );\r
+\r
+               // append some info\r
+               image = m_tree->TreeCtrlIcon_File;\r
+               imageSel = image + 1;\r
+\r
+               // box name\r
+               wxTreeItemId subcurrid1 = m_tree->AppendItem(currid,\r
+                       wxT("*** ") + wxString::FromAscii(j22box[box_type].name) + wxT(" ***"),\r
+                       image, imageSel,\r
+                       new OPJMarkerData(wxT("INFO"))\r
+                       );\r
+               m_tree->SetItemFont(subcurrid1, *wxITALIC_FONT);\r
+\r
+               // position and length\r
+               wxTreeItemId subcurrid2 = m_tree->AppendItem(currid,\r
+                       wxLongLong(filepoint).ToString() + wxT(" > ") + wxLongLong(filepoint + box_length - 1).ToString() + \r
+                       wxT(", ") + wxString::Format(wxT("%d + 8 (%d)"), box_length, box_length + 8),\r
+                       image, imageSel,\r
+                       new OPJMarkerData(wxT("INFO"))\r
+                       );\r
+\r
+               /* go deep in the box */\r
+               box_handler_function((int) box_type, fileid, (LBox == 1) ? (filepoint + 16) : (filepoint + 8), filepoint + box_length,\r
+                       currid, level, scansign, scanpoint);\r
+\r
+               /* if it's a superbox go inside it */\r
+               if (j22box[box_type].sbox)\r
+                       jpeg2000parse(fileid, (LBox == 1) ? (filepoint + 16) : (filepoint + 8), filepoint + box_length,\r
+                               currid, level + 1, scansign, scanpoint);\r
+\r
+               /* increment box number and filepoint*/\r
+               box_num++;\r
+               filepoint += box_length;\r
+\r
+       };\r
+\r
+       /* all good */\r
+       return (0);\r
+}\r
+\r
diff --git a/applications/codec/CMakeLists.txt b/applications/codec/CMakeLists.txt
new file mode 100644 (file)
index 0000000..791d13b
--- /dev/null
@@ -0,0 +1,97 @@
+  # Build the demo app, small examples
+
+# First thing define the common source:
+SET(common_SRCS
+  convert.c
+  index.c
+  ${OPENJPEG_SOURCE_DIR}/common/color.c
+)
+
+# If not getopt was found then add it to the lib:
+IF(DONT_HAVE_GETOPT)
+  SET(common_SRCS
+    ${common_SRCS}
+    ${OPENJPEG_SOURCE_DIR}/common/getopt.c
+  )
+ENDIF(DONT_HAVE_GETOPT)
+
+# Headers file are located here:
+INCLUDE_DIRECTORIES(
+  ${OPENJPEG_SOURCE_DIR}/libopenjpeg
+  ${LCMS_INCLUDE_DIRNAME}
+  ${OPENJPEG_SOURCE_DIR}/common
+  ${Z_INCLUDE_DIRNAME}
+  ${PNG_INCLUDE_DIRNAME}
+  ${TIFF_INCLUDE_DIRNAME}
+  )
+
+IF(WIN32)
+  IF(BUILD_SHARED_LIBS)
+    ADD_DEFINITIONS(-DOPJ_EXPORTS)
+  ELSE(BUILD_SHARED_LIBS)
+    ADD_DEFINITIONS(-DOPJ_STATIC)
+  ENDIF(BUILD_SHARED_LIBS)
+ENDIF(WIN32)
+
+# Loop over all executables:
+FOREACH(exe j2k_to_image image_to_j2k j2k_dump)
+  ADD_EXECUTABLE(${exe} ${exe}.c ${common_SRCS})
+  TARGET_LINK_LIBRARIES(${exe} ${OPENJPEG_LIBRARY_NAME} 
+       ${LCMS_LIBNAME} ${Z_LIBNAME} ${PNG_LIBNAME} ${TIFF_LIBNAME})
+
+  ADD_TEST(${exe} ${EXECUTABLE_OUTPUT_PATH}/${exe})
+  # calling those exe without option will make them fail always:
+  SET_TESTS_PROPERTIES(${exe} PROPERTIES WILL_FAIL TRUE)
+  # On unix you need to link to the math library:
+  IF(UNIX)
+    TARGET_LINK_LIBRARIES(${exe} m)
+  ENDIF(UNIX)
+  # Install exe
+  INSTALL(TARGETS ${exe}
+    EXPORT OpenJPEGTargets
+    DESTINATION ${OPENJPEG_INSTALL_BIN_DIR} COMPONENT Applications
+  )
+ENDFOREACH(exe)
+
+# Install man pages
+INSTALL(
+  FILES       ../doc/man/man1/image_to_j2k.1
+              ../doc/man/man1/j2k_dump.1
+              ../doc/man/man1/j2k_to_image.1
+  DESTINATION ${OPENJPEG_INSTALL_MAN_DIR}/man1)
+#
+
+if(BUILD_TESTING)
+# Do testing here, once we know the examples are being built:
+FILE(GLOB_RECURSE OPENJPEG_DATA_IMAGES_GLOB
+  "${JPEG2000_CONFORMANCE_DATA_ROOT}/*.j2k"
+  "${JPEG2000_CONFORMANCE_DATA_ROOT}/*.j2c"
+  "${JPEG2000_CONFORMANCE_DATA_ROOT}/*.jp2"
+  )
+
+foreach(filename ${OPENJPEG_DATA_IMAGES_GLOB})
+  get_filename_component(filename_temp ${filename} NAME)
+  get_filename_component(filename_ext ${filename} EXT)
+  execute_process(COMMAND ${EXECUTABLE_OUTPUT_PATH}/j2k_dump -i ${filename}
+    OUTPUT_VARIABLE dump_success
+    OUTPUT_FILE ${CMAKE_CURRENT_BINARY_DIR}/${filename_temp}.dump
+    ERROR_QUIET
+  )
+  if(dump_success)
+  file(READ ${CMAKE_CURRENT_BINARY_DIR}/${filename_temp}.dump numcomp_file)
+  string(REGEX REPLACE ".*numcomps=([0-9]+).*" "\\1"
+    numcomps "${numcomp_file}")
+  #message( "found:${output_variable} for ${filename_temp}" )
+  endif()
+  ADD_TEST(dump-${filename_temp} ${EXECUTABLE_OUTPUT_PATH}/j2k_dump -i ${filename})
+  foreach(codec_type ppm pgx bmp tif raw tga png)
+    ADD_TEST(j2i-${filename_temp}-${codec_type} ${EXECUTABLE_OUTPUT_PATH}/j2k_to_image -i ${filename} -o ${filename_temp}.${codec_type})
+  endforeach(codec_type)
+  foreach(codec_type ppm bmp tif tga png)
+    ADD_TEST(i2j-${filename_temp}-${codec_type} ${EXECUTABLE_OUTPUT_PATH}/image_to_j2k -i ${filename_temp}.${codec_type} -o ${filename_temp}.${codec_type}${filename_ext})
+    #if(UNIX)
+    #  ADD_TEST(cmp-${filename_temp}-${codec_type} cmp ${filename} ${filename_temp}.${codec_type}${filename_ext})
+    #endif(UNIX)
+  endforeach(codec_type)
+endforeach(filename)
+endif(BUILD_TESTING)
diff --git a/applications/codec/Makefile.am b/applications/codec/Makefile.am
new file mode 100644 (file)
index 0000000..14e5160
--- /dev/null
@@ -0,0 +1,72 @@
+MAINTAINERCLEANFILES = Makefile.in
+
+bin_PROGRAMS = j2k_to_image image_to_j2k j2k_dump
+
+j2k_to_image_CPPFLAGS = \
+-I. \
+-I$(top_srcdir)/codec \
+-I$(top_builddir)/codec \
+-I$(top_srcdir)/common \
+-I$(top_builddir)/common \
+-I$(top_srcdir)/libopenjpeg \
+-I$(top_builddir)/libopenjpeg \
+@PNG_CFLAGS@ \
+@TIFF_CFLAGS@ \
+@LCMS1_CFLAGS@ \
+@LCMS2_CFLAGS@
+j2k_to_image_CFLAGS = 
+j2k_to_image_LDADD = $(top_builddir)/libopenjpeg/libopenjpeg.la @LCMS1_LIBS@ @LCMS2_LIBS@ @TIFF_LIBS@ @PNG_LIBS@ -lm
+j2k_to_image_SOURCES = \
+../common/color.c \
+../common/getopt.c \
+convert.c \
+index.c \
+j2k_to_image.c \
+../common/color.h
+
+image_to_j2k_CPPFLAGS = \
+-I. \
+-I$(top_srcdir)/codec \
+-I$(top_builddir)/codec \
+-I$(top_srcdir)/common \
+-I$(top_builddir)/common \
+-I$(top_srcdir)/libopenjpeg \
+-I$(top_builddir)/libopenjpeg \
+@PNG_CFLAGS@ \
+@TIFF_CFLAGS@
+image_to_j2k_CFLAGS = 
+image_to_j2k_LDADD = $(top_builddir)/libopenjpeg/libopenjpeg.la @TIFF_LIBS@ @PNG_LIBS@ -lm
+image_to_j2k_SOURCES = \
+../common/getopt.c \
+convert.c \
+index.c \
+image_to_j2k.c \
+convert.h \
+../common/format_defs.h \
+index.h
+
+j2k_dump_CPPFLAGS = \
+-I. \
+-I$(top_srcdir)/codec \
+-I$(top_builddir)/codec \
+-I$(top_srcdir)/common \
+-I$(top_builddir)/common \
+-I$(top_srcdir)/libopenjpeg \
+-I$(top_builddir)/libopenjpeg
+j2k_dump_CFLAGS = 
+j2k_dump_LDADD = $(top_builddir)/libopenjpeg/libopenjpeg.la -lm
+j2k_dump_SOURCES = \
+../common/getopt.c \
+index.c \
+j2k_dump.c \
+../common/getopt.h \
+index.h
+
+EXTRA_DIST = \
+CMakeLists.txt \
+windirent.h
+
+install-data-hook:
+       @echo -e " (B)\t$(bindir)/j2k_to_image$(EXEEXT)" >> $(top_builddir)/report.txt
+       @echo -e " (B)\t$(bindir)/image_to_j2k$(EXEEXT)" >> $(top_builddir)/report.txt
+       @echo -e " (B)\t$(bindir)/j2k_dump$(EXEEXT)" >> $(top_builddir)/report.txt
diff --git a/applications/codec/Makefile.nix b/applications/codec/Makefile.nix
new file mode 100644 (file)
index 0000000..183e905
--- /dev/null
@@ -0,0 +1,68 @@
+#codec Makefile
+include ../config.nix
+
+CFLAGS = -Wall
+
+INSTALL_BIN = $(prefix)/bin
+
+INCLUDE = -I.. -I. -I../libopenjpeg -I../common
+USERLIBS = -lm
+
+ifeq ($(WITH_TIFF),yes)
+INCLUDE += $(TIFF_INCLUDE)
+USERLIBS += $(TIFF_LIB)
+endif
+
+ifeq ($(WITH_PNG),yes)
+INCLUDE += $(PNG_INCLUDE)
+USERLIBS += $(PNG_LIB)
+endif
+
+ifeq ($(WITH_LCMS2),yes)
+INCLUDE += $(LCMS2_INCLUDE)
+USERLIBS += $(LCMS2_LIB)
+endif
+
+ifeq ($(WITH_LCMS1),yes)
+INCLUDE += $(LCMS1_INCLUDE)
+USERLIBS += $(LCMS1_LIB)
+endif
+
+CFLAGS += $(INCLUDE) -lstdc++ # -g -p -pg
+
+all: j2k_to_image image_to_j2k j2k_dump
+       install -d ../bin
+       install j2k_to_image image_to_j2k j2k_dump ../bin
+
+ifeq ($(ENABLE_SHARED),yes)
+ELIB = ../libopenjpeg.so.$(MAJOR).$(MINOR).$(BUILD)
+else
+ELIB = ../libopenjpeg.a
+endif
+
+j2k_to_image: j2k_to_image.c $(ELIB)
+       $(CC)  $(CFLAGS) ../common/getopt.c index.c convert.c \
+       ../common/color.c j2k_to_image.c \
+       -o j2k_to_image  $(ELIB) $(USERLIBS)
+
+image_to_j2k: image_to_j2k.c  $(ELIB)
+       $(CC) $(CFLAGS) ../common/getopt.c index.c convert.c image_to_j2k.c \
+       -o image_to_j2k  $(ELIB) $(USERLIBS)
+
+j2k_dump: j2k_dump.c  $(ELIB)
+       $(CC) $(CFLAGS) ../common/getopt.c index.c j2k_dump.c \
+       -o j2k_dump $(ELIB) $(USERLIBS)
+
+clean:
+       rm -f j2k_to_image image_to_j2k j2k_dump
+
+install: all
+       install -d $(DESTDIR)$(INSTALL_BIN)
+       install -m 755 -o root -g root j2k_to_image $(DESTDIR)$(INSTALL_BIN)
+       install -m 755 -o root -g root image_to_j2k $(DESTDIR)$(INSTALL_BIN)
+       install -m 755 -o root -g root j2k_dump $(DESTDIR)$(INSTALL_BIN)
+
+uninstall:
+       rm -f $(DESTDIR)$(INSTALL_BIN)/j2k_to_image
+       rm -f $(DESTDIR)$(INSTALL_BIN)/image_to_j2k
+       rm -f $(DESTDIR)$(INSTALL_BIN)/j2k_dump
diff --git a/applications/codec/README b/applications/codec/README
new file mode 100644 (file)
index 0000000..8004998
--- /dev/null
@@ -0,0 +1,8 @@
+Simple codec compilation
+------------------------
+Once you've built the library, you might want to test it with a basic codec. To do this, go to the codec directory and either use the provided Makefile or use one of the following commands to build an encoder and decoder respectively:
+
+gcc index.c convert.c image_to_j2k.c -o image_to_j2k -lopenjpeg -I ../libopenjpeg/ -lm -ltiff
+gcc index.c convert.c j2k_to_image.c -o j2k_to_image -lopenjpeg -I ../libopenjpeg/ -lm -ltiff
+
+You should add '-L..' to those lines if you did not use the 'install' target when building the library.
\ No newline at end of file
diff --git a/applications/codec/convert.c b/applications/codec/convert.c
new file mode 100644 (file)
index 0000000..98d5435
--- /dev/null
@@ -0,0 +1,3193 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * Copyright (c) 2006-2007, Parvatha Elangovan
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "opj_config.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+
+#ifdef HAVE_LIBTIFF
+#include <tiffio.h>
+#endif /* HAVE_LIBTIFF */
+
+#ifdef HAVE_LIBPNG
+#include <zlib.h>
+#include <png.h>
+#endif /* HAVE_LIBPNG */
+
+#include "../libopenjpeg/openjpeg.h"
+#include "convert.h"
+
+/*
+ * Get logarithm of an integer and round downwards.
+ *
+ * log2(a)
+ */
+static int int_floorlog2(int a) {
+       int l;
+       for (l = 0; a > 1; l++) {
+               a >>= 1;
+       }
+       return l;
+}
+
+/* -->> -->> -->> -->>
+
+  TGA IMAGE FORMAT
+
+ <<-- <<-- <<-- <<-- */
+
+// TGA header definition.
+#pragma pack(push,1) // Pack structure byte aligned
+typedef struct tga_header
+{                           
+    unsigned char   id_length;              /* Image id field length    */
+    unsigned char   colour_map_type;        /* Colour map type          */
+    unsigned char   image_type;             /* Image type               */
+    /*
+    ** Colour map specification
+    */
+    unsigned short  colour_map_index;       /* First entry index        */
+    unsigned short  colour_map_length;      /* Colour map length        */
+    unsigned char   colour_map_entry_size;  /* Colour map entry size    */
+    /*
+    ** Image specification
+    */
+    unsigned short  x_origin;               /* x origin of image        */
+    unsigned short  y_origin;               /* u origin of image        */
+    unsigned short  image_width;            /* Image width              */
+    unsigned short  image_height;           /* Image height             */
+    unsigned char   pixel_depth;            /* Pixel depth              */
+    unsigned char   image_desc;             /* Image descriptor         */
+} tga_header;
+#pragma pack(pop) // Return to normal structure packing alignment.
+
+int tga_readheader(FILE *fp, unsigned int *bits_per_pixel, 
+       unsigned int *width, unsigned int *height, int *flip_image)
+{
+       int palette_size;
+       tga_header tga ;
+
+       if (!bits_per_pixel || !width || !height || !flip_image)
+               return 0;
+       
+       // Read TGA header
+       fread((unsigned char*)&tga, sizeof(tga_header), 1, fp);
+
+       *bits_per_pixel = tga.pixel_depth;
+       
+       *width  = tga.image_width;
+       *height = tga.image_height ;
+
+       // Ignore tga identifier, if present ...
+       if (tga.id_length)
+       {
+               unsigned char *id = (unsigned char *) malloc(tga.id_length);
+               fread(id, tga.id_length, 1, fp);
+               free(id);  
+       }
+
+       // Test for compressed formats ... not yet supported ...
+       // Note :-  9 - RLE encoded palettized.
+       //                 10 - RLE encoded RGB.
+       if (tga.image_type > 8)
+       {
+               fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
+               return 0 ;
+       }
+
+       *flip_image = !(tga.image_desc & 32);
+
+       // Palettized formats are not yet supported, skip over the palette, if present ... 
+       palette_size = tga.colour_map_length * (tga.colour_map_entry_size/8);
+       
+       if (palette_size>0)
+       {
+               fprintf(stderr, "File contains a palette - not yet supported.");
+               fseek(fp, palette_size, SEEK_CUR);
+       }
+       return 1;
+}
+
+int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height, 
+       bool flip_image)
+{
+       tga_header tga;
+
+       if (!bits_per_pixel || !width || !height)
+               return 0;
+
+       memset(&tga, 0, sizeof(tga_header));
+
+       tga.pixel_depth = bits_per_pixel;
+       tga.image_width  = width;
+       tga.image_height = height;
+       tga.image_type = 2; // Uncompressed.
+       tga.image_desc = 8; // 8 bits per component.
+
+       if (flip_image)
+               tga.image_desc |= 32;
+
+       // Write TGA header
+       fwrite((unsigned char*)&tga, sizeof(tga_header), 1, fp);
+
+       return 1;
+}
+
+opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
+       FILE *f;
+       opj_image_t *image;
+       unsigned int image_width, image_height, pixel_bit_depth;
+       unsigned int x, y;
+       int flip_image=0;
+       opj_image_cmptparm_t cmptparm[4];       /* maximum 4 components */
+       int numcomps;
+       OPJ_COLOR_SPACE color_space;
+       bool mono ;
+       bool save_alpha;
+       int subsampling_dx, subsampling_dy;
+       int i;  
+
+       f = fopen(filename, "rb");
+       if (!f) {
+               fprintf(stderr, "Failed to open %s for reading !!\n", filename);
+               return 0;
+       }
+
+       if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image))
+               return NULL;
+
+       // We currently only support 24 & 32 bit tga's ...
+       if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32)))
+               return NULL;
+
+       /* initialize image components */   
+       memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
+
+       mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16);  // Mono with & without alpha.
+       save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); // Mono with alpha, or RGB with alpha
+
+       if (mono) {
+               color_space = CLRSPC_GRAY;
+               numcomps = save_alpha ? 2 : 1;
+       }       
+       else {
+               numcomps = save_alpha ? 4 : 3;
+               color_space = CLRSPC_SRGB;
+       }
+
+       subsampling_dx = parameters->subsampling_dx;
+       subsampling_dy = parameters->subsampling_dy;
+
+       for (i = 0; i < numcomps; i++) {
+               cmptparm[i].prec = 8;
+               cmptparm[i].bpp = 8;
+               cmptparm[i].sgnd = 0;
+               cmptparm[i].dx = subsampling_dx;
+               cmptparm[i].dy = subsampling_dy;
+               cmptparm[i].w = image_width;
+               cmptparm[i].h = image_height;
+       }
+
+       /* create the image */
+       image = opj_image_create(numcomps, &cmptparm[0], color_space);
+
+       if (!image)
+               return NULL;
+
+       /* set image offset and reference grid */
+       image->x0 = parameters->image_offset_x0;
+       image->y0 = parameters->image_offset_y0;
+       image->x1 =     !image->x0 ? (image_width - 1) * subsampling_dx + 1 : image->x0 + (image_width - 1) * subsampling_dx + 1;
+       image->y1 =     !image->y0 ? (image_height - 1) * subsampling_dy + 1 : image->y0 + (image_height - 1) * subsampling_dy + 1;
+
+       /* set image data */
+       for (y=0; y < image_height; y++) 
+       {
+               int index;
+
+               if (flip_image)
+                       index = (image_height-y-1)*image_width;
+               else
+                       index = y*image_width;
+
+               if (numcomps==3)
+               {
+                       for (x=0;x<image_width;x++) 
+                       {
+                               unsigned char r,g,b;
+                               fread(&b, 1, 1, f);
+                               fread(&g, 1, 1, f);
+                               fread(&r, 1, 1, f);
+
+                               image->comps[0].data[index]=r;
+                               image->comps[1].data[index]=g;
+                               image->comps[2].data[index]=b;
+                               index++;
+                       }
+               }
+               else if (numcomps==4)
+               {
+                       for (x=0;x<image_width;x++) 
+                       {
+                               unsigned char r,g,b,a;
+                               fread(&b, 1, 1, f);
+                               fread(&g, 1, 1, f);
+                               fread(&r, 1, 1, f);
+                               fread(&a, 1, 1, f);
+
+                               image->comps[0].data[index]=r;
+                               image->comps[1].data[index]=g;
+                               image->comps[2].data[index]=b;
+                               image->comps[3].data[index]=a;
+                               index++;
+                       }
+               }
+               else {
+                       fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
+               }
+       }       
+       return image;
+}
+
+int imagetotga(opj_image_t * image, const char *outfile) {
+       int width, height, bpp, x, y;
+       bool write_alpha;
+       int i;
+       unsigned int alpha_channel;
+       float r,g,b,a;
+       unsigned char value;
+       float scale;
+       FILE *fdest;
+
+       fdest = fopen(outfile, "wb");
+       if (!fdest) {
+               fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
+               return 1;
+       }
+
+       for (i = 0; i < image->numcomps-1; i++) {
+               if ((image->comps[0].dx != image->comps[i+1].dx) 
+                       ||(image->comps[0].dy != image->comps[i+1].dy) 
+                       ||(image->comps[0].prec != image->comps[i+1].prec))     {
+      fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
+      return 1;
+   }
+       }
+
+       width = image->comps[0].w;
+       height = image->comps[0].h; 
+
+       // Mono with alpha, or RGB with alpha.
+       write_alpha = (image->numcomps==2) || (image->numcomps==4);   
+
+       // Write TGA header 
+       bpp = write_alpha ? 32 : 24;
+       if (!tga_writeheader(fdest, bpp, width , height, true))
+               return 1;
+
+       alpha_channel = image->numcomps-1; 
+
+       scale = 255.0f / (float)((1<<image->comps[0].prec)-1);
+
+       for (y=0; y < height; y++) {
+               unsigned int index=y*width;
+
+               for (x=0; x < width; x++, index++)      {
+                       r = (float)(image->comps[0].data[index]);
+
+                       if (image->numcomps>2) {
+                               g = (float)(image->comps[1].data[index]);
+                               b = (float)(image->comps[2].data[index]);
+                       }
+                       else  {// Greyscale ...
+                               g = r;
+                               b = r;
+                       }
+
+                       // TGA format writes BGR ...
+                       value = (unsigned char)(b*scale);
+                       fwrite(&value,1,1,fdest);
+
+                       value = (unsigned char)(g*scale);
+                       fwrite(&value,1,1,fdest);
+
+                       value = (unsigned char)(r*scale);
+                       fwrite(&value,1,1,fdest);
+
+                       if (write_alpha) {
+                               a = (float)(image->comps[alpha_channel].data[index]);
+                               value = (unsigned char)(a*scale);
+                               fwrite(&value,1,1,fdest);
+                       }
+               }
+       }
+
+       return 0;
+}
+
+/* -->> -->> -->> -->>
+
+  BMP IMAGE FORMAT
+
+ <<-- <<-- <<-- <<-- */
+
+/* WORD defines a two byte word */
+typedef unsigned short int WORD;
+
+/* DWORD defines a four byte word */
+typedef unsigned long int DWORD;
+
+typedef struct {
+  WORD bfType;                 /* 'BM' for Bitmap (19776) */
+  DWORD bfSize;                        /* Size of the file        */
+  WORD bfReserved1;            /* Reserved : 0            */
+  WORD bfReserved2;            /* Reserved : 0            */
+  DWORD bfOffBits;             /* Offset                  */
+} BITMAPFILEHEADER_t;
+
+typedef struct {
+  DWORD biSize;                        /* Size of the structure in bytes */
+  DWORD biWidth;               /* Width of the image in pixels */
+  DWORD biHeight;              /* Heigth of the image in pixels */
+  WORD biPlanes;               /* 1 */
+  WORD biBitCount;             /* Number of color bits by pixels */
+  DWORD biCompression;         /* Type of encoding 0: none 1: RLE8 2: RLE4 */
+  DWORD biSizeImage;           /* Size of the image in bytes */
+  DWORD biXpelsPerMeter;       /* Horizontal (X) resolution in pixels/meter */
+  DWORD biYpelsPerMeter;       /* Vertical (Y) resolution in pixels/meter */
+  DWORD biClrUsed;             /* Number of color used in the image (0: ALL) */
+  DWORD biClrImportant;                /* Number of important color (0: ALL) */
+} BITMAPINFOHEADER_t;
+
+opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters) {
+       int subsampling_dx = parameters->subsampling_dx;
+       int subsampling_dy = parameters->subsampling_dy;
+
+       int i, numcomps, w, h;
+       OPJ_COLOR_SPACE color_space;
+       opj_image_cmptparm_t cmptparm[3];       /* maximum of 3 components */
+       opj_image_t * image = NULL;
+
+       FILE *IN;
+       BITMAPFILEHEADER_t File_h;
+       BITMAPINFOHEADER_t Info_h;
+       unsigned char *RGB;
+       unsigned char *table_R, *table_G, *table_B;
+       unsigned int j, PAD = 0;
+
+       int x, y, index;
+       int gray_scale = 1, not_end_file = 1; 
+
+       unsigned int line = 0, col = 0;
+       unsigned char v, v2;
+       DWORD W, H;
+  
+       IN = fopen(filename, "rb");
+       if (!IN) {
+               fprintf(stderr, "Failed to open %s for reading !!\n", filename);
+               return 0;
+       }
+       
+       File_h.bfType = getc(IN);
+       File_h.bfType = (getc(IN) << 8) + File_h.bfType;
+       
+       if (File_h.bfType != 19778) {
+               fprintf(stderr,"Error, not a BMP file!\n");
+               return 0;
+       } else {
+               /* FILE HEADER */
+               /* ------------- */
+               File_h.bfSize = getc(IN);
+               File_h.bfSize = (getc(IN) << 8) + File_h.bfSize;
+               File_h.bfSize = (getc(IN) << 16) + File_h.bfSize;
+               File_h.bfSize = (getc(IN) << 24) + File_h.bfSize;
+
+               File_h.bfReserved1 = getc(IN);
+               File_h.bfReserved1 = (getc(IN) << 8) + File_h.bfReserved1;
+
+               File_h.bfReserved2 = getc(IN);
+               File_h.bfReserved2 = (getc(IN) << 8) + File_h.bfReserved2;
+
+               File_h.bfOffBits = getc(IN);
+               File_h.bfOffBits = (getc(IN) << 8) + File_h.bfOffBits;
+               File_h.bfOffBits = (getc(IN) << 16) + File_h.bfOffBits;
+               File_h.bfOffBits = (getc(IN) << 24) + File_h.bfOffBits;
+
+               /* INFO HEADER */
+               /* ------------- */
+
+               Info_h.biSize = getc(IN);
+               Info_h.biSize = (getc(IN) << 8) + Info_h.biSize;
+               Info_h.biSize = (getc(IN) << 16) + Info_h.biSize;
+               Info_h.biSize = (getc(IN) << 24) + Info_h.biSize;
+
+               Info_h.biWidth = getc(IN);
+               Info_h.biWidth = (getc(IN) << 8) + Info_h.biWidth;
+               Info_h.biWidth = (getc(IN) << 16) + Info_h.biWidth;
+               Info_h.biWidth = (getc(IN) << 24) + Info_h.biWidth;
+               w = Info_h.biWidth;
+
+               Info_h.biHeight = getc(IN);
+               Info_h.biHeight = (getc(IN) << 8) + Info_h.biHeight;
+               Info_h.biHeight = (getc(IN) << 16) + Info_h.biHeight;
+               Info_h.biHeight = (getc(IN) << 24) + Info_h.biHeight;
+               h = Info_h.biHeight;
+
+               Info_h.biPlanes = getc(IN);
+               Info_h.biPlanes = (getc(IN) << 8) + Info_h.biPlanes;
+
+               Info_h.biBitCount = getc(IN);
+               Info_h.biBitCount = (getc(IN) << 8) + Info_h.biBitCount;
+
+               Info_h.biCompression = getc(IN);
+               Info_h.biCompression = (getc(IN) << 8) + Info_h.biCompression;
+               Info_h.biCompression = (getc(IN) << 16) + Info_h.biCompression;
+               Info_h.biCompression = (getc(IN) << 24) + Info_h.biCompression;
+
+               Info_h.biSizeImage = getc(IN);
+               Info_h.biSizeImage = (getc(IN) << 8) + Info_h.biSizeImage;
+               Info_h.biSizeImage = (getc(IN) << 16) + Info_h.biSizeImage;
+               Info_h.biSizeImage = (getc(IN) << 24) + Info_h.biSizeImage;
+
+               Info_h.biXpelsPerMeter = getc(IN);
+               Info_h.biXpelsPerMeter = (getc(IN) << 8) + Info_h.biXpelsPerMeter;
+               Info_h.biXpelsPerMeter = (getc(IN) << 16) + Info_h.biXpelsPerMeter;
+               Info_h.biXpelsPerMeter = (getc(IN) << 24) + Info_h.biXpelsPerMeter;
+
+               Info_h.biYpelsPerMeter = getc(IN);
+               Info_h.biYpelsPerMeter = (getc(IN) << 8) + Info_h.biYpelsPerMeter;
+               Info_h.biYpelsPerMeter = (getc(IN) << 16) + Info_h.biYpelsPerMeter;
+               Info_h.biYpelsPerMeter = (getc(IN) << 24) + Info_h.biYpelsPerMeter;
+
+               Info_h.biClrUsed = getc(IN);
+               Info_h.biClrUsed = (getc(IN) << 8) + Info_h.biClrUsed;
+               Info_h.biClrUsed = (getc(IN) << 16) + Info_h.biClrUsed;
+               Info_h.biClrUsed = (getc(IN) << 24) + Info_h.biClrUsed;
+
+               Info_h.biClrImportant = getc(IN);
+               Info_h.biClrImportant = (getc(IN) << 8) + Info_h.biClrImportant;
+               Info_h.biClrImportant = (getc(IN) << 16) + Info_h.biClrImportant;
+               Info_h.biClrImportant = (getc(IN) << 24) + Info_h.biClrImportant;
+
+               /* Read the data and store them in the OUT file */
+    
+               if (Info_h.biBitCount == 24) {
+                       numcomps = 3;
+                       color_space = CLRSPC_SRGB;
+                       /* initialize image components */
+                       memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
+                       for(i = 0; i < numcomps; i++) {
+                               cmptparm[i].prec = 8;
+                               cmptparm[i].bpp = 8;
+                               cmptparm[i].sgnd = 0;
+                               cmptparm[i].dx = subsampling_dx;
+                               cmptparm[i].dy = subsampling_dy;
+                               cmptparm[i].w = w;
+                               cmptparm[i].h = h;
+                       }
+                       /* create the image */
+                       image = opj_image_create(numcomps, &cmptparm[0], color_space);
+                       if(!image) {
+                               fclose(IN);
+                               return NULL;
+                       }
+
+                       /* set image offset and reference grid */
+                       image->x0 = parameters->image_offset_x0;
+                       image->y0 = parameters->image_offset_y0;
+                       image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
+                       image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
+
+                       /* set image data */
+
+                       /* Place the cursor at the beginning of the image information */
+                       fseek(IN, 0, SEEK_SET);
+                       fseek(IN, File_h.bfOffBits, SEEK_SET);
+                       
+                       W = Info_h.biWidth;
+                       H = Info_h.biHeight;
+
+                       /* PAD = 4 - (3 * W) % 4; */
+                       /* PAD = (PAD == 4) ? 0 : PAD; */
+                       PAD = (3 * W) % 4 ? 4 - (3 * W) % 4 : 0;
+                       
+                       RGB = (unsigned char *) malloc((3 * W + PAD) * H * sizeof(unsigned char));
+                       
+                       fread(RGB, sizeof(unsigned char), (3 * W + PAD) * H, IN);
+                       
+                       index = 0;
+
+                       for(y = 0; y < (int)H; y++) {
+                               unsigned char *scanline = RGB + (3 * W + PAD) * (H - 1 - y);
+                               for(x = 0; x < (int)W; x++) {
+                                       unsigned char *pixel = &scanline[3 * x];
+                                       image->comps[0].data[index] = pixel[2]; /* R */
+                                       image->comps[1].data[index] = pixel[1]; /* G */
+                                       image->comps[2].data[index] = pixel[0]; /* B */
+                                       index++;
+                               }
+                       }
+
+                       free(RGB);
+
+               } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 0) {
+                       table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
+                       table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
+                       table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
+                       
+                       for (j = 0; j < Info_h.biClrUsed; j++) {
+                               table_B[j] = getc(IN);
+                               table_G[j] = getc(IN);
+                               table_R[j] = getc(IN);
+                               getc(IN);
+                               if (table_R[j] != table_G[j] && table_R[j] != table_B[j] && table_G[j] != table_B[j])
+                                       gray_scale = 0;
+                       }
+                       
+                       /* Place the cursor at the beginning of the image information */
+                       fseek(IN, 0, SEEK_SET);
+                       fseek(IN, File_h.bfOffBits, SEEK_SET);
+                       
+                       W = Info_h.biWidth;
+                       H = Info_h.biHeight;
+                       if (Info_h.biWidth % 2)
+                               W++;
+                       
+                       numcomps = gray_scale ? 1 : 3;
+                       color_space = gray_scale ? CLRSPC_GRAY : CLRSPC_SRGB;
+                       /* initialize image components */
+                       memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
+                       for(i = 0; i < numcomps; i++) {
+                               cmptparm[i].prec = 8;
+                               cmptparm[i].bpp = 8;
+                               cmptparm[i].sgnd = 0;
+                               cmptparm[i].dx = subsampling_dx;
+                               cmptparm[i].dy = subsampling_dy;
+                               cmptparm[i].w = w;
+                               cmptparm[i].h = h;
+                       }
+                       /* create the image */
+                       image = opj_image_create(numcomps, &cmptparm[0], color_space);
+                       if(!image) {
+                               fclose(IN);
+                               return NULL;
+                       }
+
+                       /* set image offset and reference grid */
+                       image->x0 = parameters->image_offset_x0;
+                       image->y0 = parameters->image_offset_y0;
+                       image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
+                       image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
+
+                       /* set image data */
+
+                       RGB = (unsigned char *) malloc(W * H * sizeof(unsigned char));
+                       
+                       fread(RGB, sizeof(unsigned char), W * H, IN);
+                       if (gray_scale) {
+                               index = 0;
+                               for (j = 0; j < W * H; j++) {
+                                       if ((j % W < W - 1 && Info_h.biWidth % 2) || !(Info_h.biWidth % 2)) {
+                                               image->comps[0].data[index] = table_R[RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)]];
+                                               index++;
+                                       }
+                               }
+
+                       } else {                
+                               index = 0;
+                               for (j = 0; j < W * H; j++) {
+                                       if ((j % W < W - 1 && Info_h.biWidth % 2) || !(Info_h.biWidth % 2)) {
+                                               unsigned char pixel_index = RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)];
+                                               image->comps[0].data[index] = table_R[pixel_index];
+                                               image->comps[1].data[index] = table_G[pixel_index];
+                                               image->comps[2].data[index] = table_B[pixel_index];
+                                               index++;
+                                       }
+                               }
+                       }
+                       free(RGB);
+      free(table_R);
+      free(table_G);
+      free(table_B);
+               } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 1) {                               
+                       table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
+                       table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
+                       table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
+                       
+                       for (j = 0; j < Info_h.biClrUsed; j++) {
+                               table_B[j] = getc(IN);
+                               table_G[j] = getc(IN);
+                               table_R[j] = getc(IN);
+                               getc(IN);
+                               if (table_R[j] != table_G[j] && table_R[j] != table_B[j] && table_G[j] != table_B[j])
+                                       gray_scale = 0;
+                       }
+
+                       numcomps = gray_scale ? 1 : 3;
+                       color_space = gray_scale ? CLRSPC_GRAY : CLRSPC_SRGB;
+                       /* initialize image components */
+                       memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
+                       for(i = 0; i < numcomps; i++) {
+                               cmptparm[i].prec = 8;
+                               cmptparm[i].bpp = 8;
+                               cmptparm[i].sgnd = 0;
+                               cmptparm[i].dx = subsampling_dx;
+                               cmptparm[i].dy = subsampling_dy;
+                               cmptparm[i].w = w;
+                               cmptparm[i].h = h;
+                       }
+                       /* create the image */
+                       image = opj_image_create(numcomps, &cmptparm[0], color_space);
+                       if(!image) {
+                               fclose(IN);
+                               return NULL;
+                       }
+
+                       /* set image offset and reference grid */
+                       image->x0 = parameters->image_offset_x0;
+                       image->y0 = parameters->image_offset_y0;
+                       image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
+                       image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
+
+                       /* set image data */
+                       
+                       /* Place the cursor at the beginning of the image information */
+                       fseek(IN, 0, SEEK_SET);
+                       fseek(IN, File_h.bfOffBits, SEEK_SET);
+                       
+                       RGB = (unsigned char *) malloc(Info_h.biWidth * Info_h.biHeight * sizeof(unsigned char));
+            
+                       while (not_end_file) {
+                               v = getc(IN);
+                               if (v) {
+                                       v2 = getc(IN);
+                                       for (i = 0; i < (int) v; i++) {
+                                               RGB[line * Info_h.biWidth + col] = v2;
+                                               col++;
+                                       }
+                               } else {
+                                       v = getc(IN);
+                                       switch (v) {
+                                               case 0:
+                                                       col = 0;
+                                                       line++;
+                                                       break;
+                                               case 1:
+                                                       line++;
+                                                       not_end_file = 0;
+                                                       break;
+                                               case 2:
+                                                       fprintf(stderr,"No Delta supported\n");
+                                                       opj_image_destroy(image);
+                                                       fclose(IN);
+                                                       return NULL;
+                                               default:
+                                                       for (i = 0; i < v; i++) {
+                                                               v2 = getc(IN);
+                                                               RGB[line * Info_h.biWidth + col] = v2;
+                                                               col++;
+                                                       }
+                                                       if (v % 2)
+                                                               v2 = getc(IN);
+                                                       break;
+                                       }
+                               }
+                       }
+                       if (gray_scale) {
+                               index = 0;
+                               for (line = 0; line < Info_h.biHeight; line++) {
+                                       for (col = 0; col < Info_h.biWidth; col++) {
+                                               image->comps[0].data[index] = table_R[(int)RGB[(Info_h.biHeight - line - 1) * Info_h.biWidth + col]];
+                                               index++;
+                                       }
+                               }
+                       } else {
+                               index = 0;
+                               for (line = 0; line < Info_h.biHeight; line++) {
+                                       for (col = 0; col < Info_h.biWidth; col++) {
+                                               unsigned char pixel_index = (int)RGB[(Info_h.biHeight - line - 1) * Info_h.biWidth + col];
+                                               image->comps[0].data[index] = table_R[pixel_index];
+                                               image->comps[1].data[index] = table_G[pixel_index];
+                                               image->comps[2].data[index] = table_B[pixel_index];
+                                               index++;
+                                       }
+                               }
+                       }
+                       free(RGB);
+      free(table_R);
+      free(table_G);
+      free(table_B);
+       } else {
+               fprintf(stderr, 
+                       "Other system than 24 bits/pixels or 8 bits (no RLE coding) is not yet implemented [%d]\n", Info_h.biBitCount);
+       }
+       fclose(IN);
+ }
+ return image;
+}
+
+int imagetobmp(opj_image_t * image, const char *outfile) {
+       int w, h;
+       int i, pad;
+       FILE *fdest = NULL;
+       int adjustR, adjustG, adjustB;
+
+       if (image->numcomps == 3 && image->comps[0].dx == image->comps[1].dx
+               && image->comps[1].dx == image->comps[2].dx
+               && image->comps[0].dy == image->comps[1].dy
+               && image->comps[1].dy == image->comps[2].dy
+               && image->comps[0].prec == image->comps[1].prec
+               && image->comps[1].prec == image->comps[2].prec) {
+               
+               /* -->> -->> -->> -->>    
+               24 bits color       
+               <<-- <<-- <<-- <<-- */
+           
+               fdest = fopen(outfile, "wb");
+               if (!fdest) {
+                       fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
+                       return 1;
+               }
+           
+               w = image->comps[0].w;      
+               h = image->comps[0].h;
+           
+               fprintf(fdest, "BM");
+           
+               /* FILE HEADER */
+               /* ------------- */
+               fprintf(fdest, "%c%c%c%c",
+                       (unsigned char) (h * w * 3 + 3 * h * (w % 2) + 54) & 0xff,
+                       (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 8) & 0xff,
+                       (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 16) & 0xff,
+                       (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,((54) >> 16) & 0xff, ((54) >> 24) & 0xff);
+           
+               /* INFO HEADER   */
+               /* ------------- */
+               fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
+                       (unsigned char) ((w) >> 8) & 0xff,
+                       (unsigned char) ((w) >> 16) & 0xff,
+                       (unsigned char) ((w) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
+                       (unsigned char) ((h) >> 8) & 0xff,
+                       (unsigned char) ((h) >> 16) & 0xff,
+                       (unsigned char) ((h) >> 24) & 0xff);
+               fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
+               fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (unsigned char) (3 * h * w + 3 * h * (w % 2)) & 0xff,
+                       (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 8) & 0xff,
+                       (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 16) & 0xff,
+                       (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
+           
+               if (image->comps[0].prec > 8) {
+                       adjustR = image->comps[0].prec - 8;
+                       printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
+               }
+               else 
+                       adjustR = 0;
+               if (image->comps[1].prec > 8) {
+                       adjustG = image->comps[1].prec - 8;
+                       printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
+               }
+               else 
+                       adjustG = 0;
+               if (image->comps[2].prec > 8) {
+                       adjustB = image->comps[2].prec - 8;
+                       printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec);
+               }
+               else 
+                       adjustB = 0;
+
+               for (i = 0; i < w * h; i++) {
+                       unsigned char rc, gc, bc;
+                       int r, g, b;
+                                                       
+                       r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
+                       r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
+                       r = ((r >> adjustR)+((r >> (adjustR-1))%2));
+                       if(r > 255) r = 255; else if(r < 0) r = 0;
+                       rc = (unsigned char)r;
+
+                       g = image->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
+                       g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
+                       g = ((g >> adjustG)+((g >> (adjustG-1))%2));
+                       if(g > 255) g = 255; else if(g < 0) g = 0;
+                       gc = (unsigned char)g;
+
+                       b = image->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
+                       b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
+                       b = ((b >> adjustB)+((b >> (adjustB-1))%2));
+                       if(b > 255) b = 255; else if(b < 0) b = 0;
+                       bc = (unsigned char)b;
+
+                       fprintf(fdest, "%c%c%c", bc, gc, rc);
+                       
+                       if ((i + 1) % w == 0) {
+                               for (pad = (3 * w) % 4 ? 4 - (3 * w) % 4 : 0; pad > 0; pad--)   /* ADD */
+                                       fprintf(fdest, "%c", 0);
+                       }
+               }
+               fclose(fdest);
+       } else {                        /* Gray-scale */
+
+               /* -->> -->> -->> -->>
+               8 bits non code (Gray scale)
+               <<-- <<-- <<-- <<-- */
+
+               fdest = fopen(outfile, "wb");
+               w = image->comps[0].w;      
+               h = image->comps[0].h;
+           
+               fprintf(fdest, "BM");
+           
+               /* FILE HEADER */
+               /* ------------- */
+               fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + 54 + 1024 + h * (w % 2)) & 0xff,
+                       (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 8) & 0xff,
+                       (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 16) & 0xff,
+                       (unsigned char) ((h * w + 54 + 1024 + w * (w % 2)) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff, 
+                       ((54 + 1024) >> 16) & 0xff,
+                       ((54 + 1024) >> 24) & 0xff);
+           
+               /* INFO HEADER */
+               /* ------------- */
+               fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
+                       (unsigned char) ((w) >> 8) & 0xff,
+                       (unsigned char) ((w) >> 16) & 0xff,
+                       (unsigned char) ((w) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
+                       (unsigned char) ((h) >> 8) & 0xff,
+                       (unsigned char) ((h) >> 16) & 0xff,
+                       (unsigned char) ((h) >> 24) & 0xff);
+               fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
+               fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + h * (w % 2)) & 0xff,
+                       (unsigned char) ((h * w + h * (w % 2)) >> 8) &  0xff,
+                       (unsigned char) ((h * w + h * (w % 2)) >> 16) & 0xff,
+                       (unsigned char) ((h * w + h * (w % 2)) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
+               fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
+
+               if (image->comps[0].prec > 8) {
+                       adjustR = image->comps[0].prec - 8;
+                       printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
+               }else 
+                       adjustR = 0;
+
+               for (i = 0; i < 256; i++) {
+                       fprintf(fdest, "%c%c%c%c", i, i, i, 0);
+               }
+
+               for (i = 0; i < w * h; i++) {
+                       unsigned char rc;
+                       int r;
+                       
+                       r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
+                       r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
+                       r = ((r >> adjustR)+((r >> (adjustR-1))%2));
+                       if(r > 255) r = 255; else if(r < 0) r = 0;
+
+                       fprintf(fdest, "%c", (unsigned char)r);
+
+                       if ((i + 1) % w == 0) {
+                               for (pad = w % 4 ? 4 - w % 4 : 0; pad > 0; pad--)       /* ADD */
+                                       fprintf(fdest, "%c", 0);
+                       }
+               }
+               fclose(fdest);
+       }
+
+       return 0;
+}
+
+/* -->> -->> -->> -->>
+
+PGX IMAGE FORMAT
+
+<<-- <<-- <<-- <<-- */
+
+
+unsigned char readuchar(FILE * f)
+{
+  unsigned char c1;
+  fread(&c1, 1, 1, f);
+  return c1;
+}
+
+unsigned short readushort(FILE * f, int bigendian)
+{
+  unsigned char c1, c2;
+  fread(&c1, 1, 1, f);
+  fread(&c2, 1, 1, f);
+  if (bigendian)
+    return (c1 << 8) + c2;
+  else
+    return (c2 << 8) + c1;
+}
+
+unsigned int readuint(FILE * f, int bigendian)
+{
+  unsigned char c1, c2, c3, c4;
+  fread(&c1, 1, 1, f);
+  fread(&c2, 1, 1, f);
+  fread(&c3, 1, 1, f);
+  fread(&c4, 1, 1, f);
+  if (bigendian)
+    return (c1 << 24) + (c2 << 16) + (c3 << 8) + c4;
+  else
+    return (c4 << 24) + (c3 << 16) + (c2 << 8) + c1;
+}
+
+opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
+       FILE *f = NULL;
+       int w, h, prec;
+       int i, numcomps, max;
+       OPJ_COLOR_SPACE color_space;
+       opj_image_cmptparm_t cmptparm;  /* maximum of 1 component  */
+       opj_image_t * image = NULL;
+
+       char endian1,endian2,sign;
+       char signtmp[32];
+
+       char temp[32];
+       int bigendian;
+       opj_image_comp_t *comp = NULL;
+
+       numcomps = 1;
+       color_space = CLRSPC_GRAY;
+
+       memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
+
+       max = 0;
+
+       f = fopen(filename, "rb");
+       if (!f) {
+         fprintf(stderr, "Failed to open %s for reading !\n", filename);
+         return NULL;
+       }
+
+       fseek(f, 0, SEEK_SET);
+       fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h);
+       
+       i=0;
+       sign='+';               
+       while (signtmp[i]!='\0') {
+               if (signtmp[i]=='-') sign='-';
+               i++;
+       }
+       
+       fgetc(f);
+       if (endian1=='M' && endian2=='L') {
+               bigendian = 1;
+       } else if (endian2=='M' && endian1=='L') {
+               bigendian = 0;
+       } else {
+               fprintf(stderr, "Bad pgx header, please check input file\n");
+               return NULL;
+       }
+
+       /* initialize image component */
+
+       cmptparm.x0 = parameters->image_offset_x0;
+       cmptparm.y0 = parameters->image_offset_y0;
+       cmptparm.w = !cmptparm.x0 ? (w - 1) * parameters->subsampling_dx + 1 : cmptparm.x0 + (w - 1) * parameters->subsampling_dx + 1;
+       cmptparm.h = !cmptparm.y0 ? (h - 1) * parameters->subsampling_dy + 1 : cmptparm.y0 + (h - 1) * parameters->subsampling_dy + 1;
+       
+       if (sign == '-') {
+               cmptparm.sgnd = 1;
+       } else {
+               cmptparm.sgnd = 0;
+       }
+       cmptparm.prec = prec;
+       cmptparm.bpp = prec;
+       cmptparm.dx = parameters->subsampling_dx;
+       cmptparm.dy = parameters->subsampling_dy;
+       
+       /* create the image */
+       image = opj_image_create(numcomps, &cmptparm, color_space);
+       if(!image) {
+               fclose(f);
+               return NULL;
+       }
+       /* set image offset and reference grid */
+       image->x0 = cmptparm.x0;
+       image->y0 = cmptparm.x0;
+       image->x1 = cmptparm.w;
+       image->y1 = cmptparm.h;
+
+       /* set image data */
+
+       comp = &image->comps[0];
+
+       for (i = 0; i < w * h; i++) {
+               int v;
+               if (comp->prec <= 8) {
+                       if (!comp->sgnd) {
+                               v = readuchar(f);
+                       } else {
+                               v = (char) readuchar(f);
+                       }
+               } else if (comp->prec <= 16) {
+                       if (!comp->sgnd) {
+                               v = readushort(f, bigendian);
+                       } else {
+                               v = (short) readushort(f, bigendian);
+                       }
+               } else {
+                       if (!comp->sgnd) {
+                               v = readuint(f, bigendian);
+                       } else {
+                               v = (int) readuint(f, bigendian);
+                       }
+               }
+               if (v > max)
+                       max = v;
+               comp->data[i] = v;
+       }
+       fclose(f);
+       comp->bpp = int_floorlog2(max) + 1;
+
+       return image;
+}
+
+int imagetopgx(opj_image_t * image, const char *outfile) {
+       int w, h;
+       int i, j, compno;
+       FILE *fdest = NULL;
+
+       for (compno = 0; compno < image->numcomps; compno++) {
+               opj_image_comp_t *comp = &image->comps[compno];
+               char bname[256]; /* buffer for name */
+    char *name = bname; /* pointer */
+    int nbytes = 0;
+    const size_t olen = strlen(outfile);
+    const size_t dotpos = olen - 4;
+    const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
+    if( outfile[dotpos] != '.' ) {
+      /* `pgx` was recognized but there is no dot at expected position */
+      fprintf(stderr, "ERROR -> Impossible happen." );
+      return 1;
+      }
+    if( total > 256 ) {
+      name = (char*)malloc(total+1);
+      }
+    strncpy(name, outfile, dotpos);
+               if (image->numcomps > 1) {
+                       sprintf(name+dotpos, "-%d.pgx", compno);
+               } else {
+                       strcpy(name+dotpos, ".pgx");
+               }
+               fdest = fopen(name, "wb");
+               if (!fdest) {
+                       fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
+                       return 1;
+               }
+    /* dont need name anymore */
+    if( total > 256 ) {
+      free(name);
+      }
+
+               w = image->comps[compno].w;
+               h = image->comps[compno].h;
+           
+               fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec, w, h);
+               if (comp->prec <= 8) {
+                       nbytes = 1;
+               } else if (comp->prec <= 16) {
+                       nbytes = 2;
+               } else {
+                       nbytes = 4;
+               }
+               for (i = 0; i < w * h; i++) {
+                       int v = image->comps[compno].data[i];
+                       for (j = nbytes - 1; j >= 0; j--) {
+                               char byte = (char) (v >> (j * 8));
+                               fwrite(&byte, 1, 1, fdest);
+                       }
+               }
+               fclose(fdest);
+       }
+
+       return 0;
+}
+
+/* -->> -->> -->> -->>
+
+PNM IMAGE FORMAT
+
+<<-- <<-- <<-- <<-- */
+
+struct pnm_header
+{
+    int width, height, maxval, depth, format;
+    char rgb, rgba, gray, graya, bw;
+    char ok;
+};
+
+static char *skip_white(char *s)
+{
+    while(*s)
+   {
+    if(*s == '\n' || *s == '\r') return NULL;
+    if(isspace(*s)) { ++s; continue; }
+    return s;
+   }
+    return NULL;
+}
+
+static char *skip_int(char *start, int *out_n)
+{
+    char *s;
+    char c;
+
+    *out_n = 0; s = start;
+
+    s = skip_white(start);
+    if(s == NULL) return NULL;
+    start = s;
+
+    while(*s)
+   {
+    if( !isdigit(*s)) break;
+    ++s;
+   }
+    c = *s; *s = 0; *out_n = atoi(start); *s = c;
+    return s;
+}
+
+static char *skip_idf(char *start, char out_idf[256])
+{
+    char *s;
+    char c;
+
+    s = skip_white(start);
+    if(s == NULL) return NULL;
+    start = s;
+
+    while(*s)
+   {
+    if(isalpha(*s) || *s == '_') { ++s; continue; }
+    break;
+   }
+    c = *s; *s = 0; strncpy(out_idf, start, 255); *s = c;
+    return s;
+}
+
+static void read_pnm_header(FILE *reader, struct pnm_header *ph)
+{
+    char *s;
+    int format, have_wh, end, ttype;
+    char idf[256], type[256];
+    char line[256];
+
+    fgets(line, 250, reader);
+
+    if(line[0] != 'P')
+   {
+    fprintf(stderr,"read_pnm_header:PNM:magic P missing\n"); return;
+   }
+    format = atoi(line + 1);
+    if(format < 1 || format > 7)
+   {
+    fprintf(stderr,"read_pnm_header:magic format %d invalid\n", format);
+    return;
+   }
+    ph->format = format;
+    ttype = end = have_wh = 0;
+
+    while(fgets(line, 250, reader))
+   {
+    if(*line == '#') continue;
+
+    s = line;
+
+    if(format == 7)
+  {
+    s = skip_idf(s, idf);
+
+    if(s == NULL || *s == 0) return;
+
+    if(strcmp(idf, "ENDHDR") == 0)
+ {
+    end = 1; break;
+ }
+    if(strcmp(idf, "WIDTH") == 0)
+ {
+    s = skip_int(s, &ph->width);
+    if(s == NULL || *s == 0) return;
+
+    continue;
+ }
+    if(strcmp(idf, "HEIGHT") == 0)
+ {
+    s = skip_int(s, &ph->height);
+    if(s == NULL || *s == 0) return;
+
+    continue;
+ }
+    if(strcmp(idf, "DEPTH") == 0)
+ {
+    s = skip_int(s, &ph->depth);
+    if(s == NULL || *s == 0) return;
+
+    continue;
+ }
+    if(strcmp(idf, "MAXVAL") == 0)
+ {
+    s = skip_int(s, &ph->maxval);
+    if(s == NULL || *s == 0) return;
+
+    continue;
+ }
+    if(strcmp(idf, "TUPLTYPE") == 0)
+ {
+    s = skip_idf(s, type);
+    if(s == NULL || *s == 0) return;
+
+        if(strcmp(type, "BLACKANDWHITE") == 0)
+       {
+        ph->bw = 1; ttype = 1; continue;
+       }
+        if(strcmp(type, "GRAYSCALE") == 0)
+       {
+        ph->gray = 1; ttype = 1; continue;
+       }
+        if(strcmp(type, "GRAYSCALE_ALPHA") == 0)
+       {
+        ph->graya = 1; ttype = 1; continue;
+       }
+        if(strcmp(type, "RGB") == 0)
+       {
+        ph->rgb = 1; ttype = 1; continue;
+       }
+        if(strcmp(type, "RGB_ALPHA") == 0)
+       {
+        ph->rgba = 1; ttype = 1; continue;
+       }
+    fprintf(stderr,"read_pnm_header:unknown P7 TUPLTYPE %s\n",type);
+    return;
+ }
+    fprintf(stderr,"read_pnm_header:unknown P7 idf %s\n",idf);
+    return;
+  } /* if(format == 7) */
+
+    if( !have_wh)
+  {
+    s = skip_int(s, &ph->width);
+
+    s = skip_int(s, &ph->height);
+
+    have_wh = 1;
+
+    if(format == 1 || format == 4) break;
+
+    continue;
+  }
+    if(format == 2 || format == 3 || format == 5 || format == 6)
+  {
+/* P2, P3, P5, P6: */
+    s = skip_int(s, &ph->maxval);
+
+    if(ph->maxval > 65535) return;
+  }
+    break;
+   }/* while(fgets( ) */
+    if(format == 2 || format == 3 || format > 4)
+   {
+    if(ph->maxval < 1 || ph->maxval > 65535) return;
+   }
+    if(ph->width < 1 || ph->height < 1) return;
+
+    if(format == 7)
+   {
+    if(!end)
+  {
+    fprintf(stderr,"read_pnm_header:P7 without ENDHDR\n"); return;
+  }
+    if(ph->depth < 1 || ph->depth > 4) return;
+
+    if(ph->width && ph->height && ph->depth & ph->maxval && ttype)
+     ph->ok = 1;
+   }
+    else
+   {
+    if(format != 1 && format != 4)
+  {
+    if(ph->width && ph->height && ph->maxval) ph->ok = 1;
+  }
+    else
+  {
+    if(ph->width && ph->height) ph->ok = 1;
+    ph->maxval = 255;
+  }
+   }
+}
+
+static int has_prec(int val)
+{
+    if(val < 2) return 1;
+    if(val < 4) return 2;
+    if(val < 8) return 3;
+    if(val < 16) return 4;
+    if(val < 32) return 5;
+    if(val < 64) return 6;
+    if(val < 128) return 7;
+    if(val < 256) return 8;
+    if(val < 512) return 9;
+    if(val < 1024) return 10;
+    if(val < 2048) return 11;
+    if(val < 4096) return 12;
+    if(val < 8192) return 13;
+    if(val < 16384) return 14;
+    if(val < 32768) return 15;
+    return 16;
+}
+
+opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
+       int subsampling_dx = parameters->subsampling_dx;
+       int subsampling_dy = parameters->subsampling_dy;
+
+       FILE *fp = NULL;
+       int i, compno, numcomps, w, h, prec, format;
+       OPJ_COLOR_SPACE color_space;
+       opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
+       opj_image_t * image = NULL;
+       struct pnm_header header_info;
+       
+       if((fp = fopen(filename, "rb")) == NULL)
+   {
+       fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n",filename);
+       return NULL;
+   }
+       memset(&header_info, 0, sizeof(struct pnm_header));
+
+       read_pnm_header(fp, &header_info);
+
+       if(!header_info.ok) { fclose(fp); return NULL; }
+
+       format = header_info.format;
+
+    switch(format)
+   {
+    case 1: /* ascii bitmap */
+    case 4: /* raw bitmap */
+        numcomps = 1;
+        break;
+
+    case 2: /* ascii greymap */
+    case 5: /* raw greymap */
+        numcomps = 1;
+        break;
+
+    case 3: /* ascii pixmap */
+    case 6: /* raw pixmap */
+        numcomps = 3;
+        break;
+
+    case 7: /* arbitrary map */
+        numcomps = header_info.depth;
+               break;
+
+    default: fclose(fp); return NULL;
+   }
+    if(numcomps < 3)
+     color_space = CLRSPC_GRAY;/* GRAY, GRAYA */
+    else
+     color_space = CLRSPC_SRGB;/* RGB, RGBA */
+
+    prec = has_prec(header_info.maxval);
+
+       if(prec < 8) prec = 8;
+
+    w = header_info.width;
+    h = header_info.height;
+    subsampling_dx = parameters->subsampling_dx;
+    subsampling_dy = parameters->subsampling_dy;
+
+    memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
+
+    for(i = 0; i < numcomps; i++)
+   {
+    cmptparm[i].prec = prec;
+    cmptparm[i].bpp = prec;
+    cmptparm[i].sgnd = 0;
+    cmptparm[i].dx = subsampling_dx;
+    cmptparm[i].dy = subsampling_dy;
+    cmptparm[i].w = w;
+    cmptparm[i].h = h;
+   }
+    image = opj_image_create(numcomps, &cmptparm[0], color_space);
+
+    if(!image) { fclose(fp); return NULL; }
+
+/* set image offset and reference grid */
+       image->x0 = parameters->image_offset_x0;
+       image->y0 = parameters->image_offset_y0;
+       image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
+       image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
+
+    if((format == 2) || (format == 3)) /* ascii pixmap */
+   {
+    unsigned int index;
+
+    for (i = 0; i < w * h; i++)
+  {
+    for(compno = 0; compno < numcomps; compno++)
+ {
+       index = 0;
+    fscanf(fp, "%u", &index);
+
+    image->comps[compno].data[i] = (index * 255)/header_info.maxval;
+ }
+  }
+   }
+    else
+    if((format == 5)
+    || (format == 6)
+    ||((format == 7)
+        && (   header_info.gray || header_info.graya
+            || header_info.rgb || header_info.rgba)))/* binary pixmap */
+   {
+    unsigned char c0, c1, one;
+
+    one = (prec < 9); 
+
+    for (i = 0; i < w * h; i++)
+  {
+    for(compno = 0; compno < numcomps; compno++)
+ {
+        fread(&c0, 1, 1, fp);
+        if(one)
+       {
+        image->comps[compno].data[i] = c0;
+       }
+        else
+       {
+        fread(&c1, 1, 1, fp);
+/* netpbm: */
+               image->comps[compno].data[i] = ((c0<<8) | c1);
+       }
+ }
+  }
+   }
+    else
+    if(format == 1) /* ascii bitmap */
+   {
+    for (i = 0; i < w * h; i++)
+  {
+    unsigned int index;
+
+    fscanf(fp, "%u", &index);
+
+    image->comps[0].data[i] = (index?0:255);
+  }
+   }
+    else
+    if(format == 4)
+   {
+    int x, y, bit;
+    unsigned char uc;
+
+    i = 0;
+    for(y = 0; y < h; ++y)
+  {
+    bit = -1; uc = 0;
+
+    for(x = 0; x < w; ++x)
+ {
+        if(bit == -1)
+       {
+        bit = 7;
+        uc = (unsigned char)getc(fp);
+       }
+    image->comps[0].data[i] = (((uc>>bit) & 1)?0:255);
+    --bit; ++i;
+ }
+  }
+   }
+       else
+       if((format == 7 && header_info.bw)) //MONO
+   {
+       unsigned char uc;
+
+       for(i = 0; i < w * h; ++i)
+  {
+       fread(&uc, 1, 1, fp);
+       image->comps[0].data[i] = (uc & 1)?0:255;
+  }
+   }
+    fclose(fp);
+
+    return image;
+}/* pnmtoimage() */
+
+int imagetopnm(opj_image_t * image, const char *outfile) 
+{
+       int *red, *green, *blue, *alpha;
+       int wr, hr, max;
+       int i, compno, ncomp;
+       int adjustR, adjustG, adjustB, adjustA;
+       int fails, two, want_gray, has_alpha, triple;
+       int prec, v;
+       FILE *fdest = NULL;
+       const char *tmp = outfile;
+       char *destname;
+
+    if((prec = image->comps[0].prec) > 16)
+   {
+       fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
+       "\n\t: refused.\n",__FILE__,__LINE__,prec);
+       return 1;
+   }
+    two = has_alpha = 0; fails = 1;
+       ncomp = image->numcomps;
+
+       while (*tmp) ++tmp; tmp -= 2; 
+       want_gray = (*tmp == 'g' || *tmp == 'G'); 
+       ncomp = image->numcomps;
+
+       if(want_gray) ncomp = 1;
+
+       if (ncomp == 2 /* GRAYA */
+       || (ncomp > 2 /* RGB, RGBA */
+               && image->comps[0].dx == image->comps[1].dx
+               && image->comps[1].dx == image->comps[2].dx
+               && image->comps[0].dy == image->comps[1].dy
+               && image->comps[1].dy == image->comps[2].dy
+               && image->comps[0].prec == image->comps[1].prec
+               && image->comps[1].prec == image->comps[2].prec
+          ))
+   {
+       fdest = fopen(outfile, "wb");
+
+       if (!fdest) 
+  {
+       fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
+       return fails;
+  }
+       two = (prec > 8);
+       triple = (ncomp > 2);
+       wr = image->comps[0].w; hr = image->comps[0].h;
+       max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);
+
+    red = image->comps[0].data;
+
+       if(triple)
+  {
+    green = image->comps[1].data;
+    blue = image->comps[2].data;
+  }
+       else green = blue = NULL;
+       
+       if(has_alpha)
+  {
+       const char *tt = (triple?"RGB_ALPHA":"GRAYSCALE_ALPHA");
+
+       fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %d\n"
+               "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
+               wr, hr, ncomp, max, tt);
+       alpha = image->comps[ncomp - 1].data;
+       adjustA = (image->comps[ncomp - 1].sgnd ?
+        1 << (image->comps[ncomp - 1].prec - 1) : 0);
+  }
+       else
+  {
+       fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n", 
+               opj_version(), wr, hr, max);
+       alpha = NULL; adjustA = 0;
+  }
+    adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
+
+       if(triple)
+  {
+    adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
+    adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
+  }
+       else adjustG = adjustB = 0;
+
+    for(i = 0; i < wr * hr; ++i)
+  {
+       if(two)
+ {
+       v = *red + adjustR; ++red;
+/* netpbm: */
+       fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
+
+               if(triple)
+          {
+               v = *green + adjustG; ++green;
+/* netpbm: */
+               fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
+
+               v =  *blue + adjustB; ++blue;
+/* netpbm: */
+               fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
+
+          }/* if(triple) */
+
+        if(has_alpha)
+       {
+        v = *alpha + adjustA; ++alpha;
+/* netpbm: */
+               fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
+       }
+        continue;
+
+ }     /* if(two) */
+
+/* prec <= 8: */
+
+       fprintf(fdest, "%c", (unsigned char)*red++);
+       if(triple)
+        fprintf(fdest, "%c%c",(unsigned char)*green++, (unsigned char)*blue++);
+
+       if(has_alpha)
+        fprintf(fdest, "%c", (unsigned char)*alpha++);
+
+  }    /* for(i */
+
+       fclose(fdest); return 0;
+   }
+
+/* YUV or MONO: */
+
+       if (image->numcomps > ncomp) 
+   {
+       fprintf(stderr,"WARNING -> [PGM file] Only the first component\n");
+       fprintf(stderr,"           is written to the file\n");
+   }
+       destname = (char*)malloc(strlen(outfile) + 8);
+
+       for (compno = 0; compno < ncomp; compno++) 
+   {
+       if (ncomp > 1) 
+        sprintf(destname, "%d.%s", compno, outfile);
+       else
+        sprintf(destname, "%s", outfile);
+
+       fdest = fopen(destname, "wb");
+       if (!fdest) 
+  {
+       fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
+       free(destname);
+       return 1;
+  }
+       wr = image->comps[compno].w; hr = image->comps[compno].h;
+       prec = image->comps[compno].prec;
+       max = (1<<prec) - 1;
+
+       fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n", 
+               opj_version(), wr, hr, max);
+
+       red = image->comps[compno].data;
+       adjustR = 
+       (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
+
+    if(prec > 8)
+  {
+       for (i = 0; i < wr * hr; i++) 
+ {
+       v = *red + adjustR; ++red;
+/* netpbm: */
+       fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
+
+        if(has_alpha)
+      {
+        v = *alpha++;
+/* netpbm: */
+               fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
+      }
+ }/* for(i */
+  }
+       else /* prec <= 8 */
+  {
+       for(i = 0; i < wr * hr; ++i)
+ {
+        fprintf(fdest, "%c", (unsigned char)(*red + adjustR)); ++red;
+ }
+  }
+       fclose(fdest);
+   } /* for (compno */
+       free(destname);
+
+       return 0;
+}/* imagetopnm() */
+
+#ifdef HAVE_LIBTIFF
+/* -->> -->> -->> -->>
+
+       TIFF IMAGE FORMAT
+
+ <<-- <<-- <<-- <<-- */
+
+typedef struct tiff_infoheader{
+       DWORD tiWidth;  // Width of Image in pixel
+       DWORD tiHeight; // Height of Image in pixel
+       DWORD tiPhoto;  // Photometric
+       WORD  tiBps;    // Bits per sample
+       WORD  tiSf;             // Sample Format
+       WORD  tiSpp;    // Sample per pixel 1-bilevel,gray scale , 2- RGB
+       WORD  tiPC;     // Planar config (1-Interleaved, 2-Planarcomp)
+}tiff_infoheader_t;
+
+int imagetotif(opj_image_t * image, const char *outfile) 
+{
+       int width, height, imgsize;
+       int bps,index,adjust, sgnd;
+       int ushift, dshift, has_alpha, force16;
+       unsigned int last_i=0;
+       TIFF *tif;
+       tdata_t buf;
+       tstrip_t strip;
+       tsize_t strip_size;
+
+       ushift = dshift = force16 = has_alpha = 0;
+       bps = image->comps[0].prec;
+
+       if(bps > 8 && bps < 16)
+   {
+       ushift = 16 - bps; dshift = bps - ushift;
+       bps = 16; force16 = 1;
+   }
+
+       if(bps != 8 && bps != 16)
+   {
+       fprintf(stderr,"imagetotif: Bits=%d, Only 8 and 16 bits implemented\n",
+        bps);
+       fprintf(stderr,"\tAborting\n");
+       return 1;
+   }
+       tif = TIFFOpen(outfile, "wb");
+
+       if (!tif) 
+   {
+       fprintf(stderr, "imagetotif:failed to open %s for writing\n", outfile);
+       return 1;
+   }
+       sgnd = image->comps[0].sgnd;
+       adjust = sgnd ? 1 << (image->comps[0].prec - 1) : 0;
+
+       if(image->numcomps >= 3 
+       && image->comps[0].dx == image->comps[1].dx
+       && image->comps[1].dx == image->comps[2].dx
+       && image->comps[0].dy == image->comps[1].dy
+       && image->comps[1].dy == image->comps[2].dy
+       && image->comps[0].prec == image->comps[1].prec
+       && image->comps[1].prec == image->comps[2].prec) 
+   {
+       has_alpha = (image->numcomps == 4);
+
+       width   = image->comps[0].w;
+       height  = image->comps[0].h;
+       imgsize = width * height ;
+       TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
+       TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
+       TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3 + has_alpha);
+       TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
+       TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
+       TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
+       TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
+       TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
+       strip_size = TIFFStripSize(tif);
+       buf = _TIFFmalloc(strip_size);
+       index=0;
+
+       for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
+  {
+       unsigned char *dat8;
+       tsize_t i, ssize;
+       ssize = TIFFStripSize(tif);
+       dat8 = (unsigned char*)buf;
+       int step, restx;
+
+       if(bps == 8)
+ {
+       step = 3 + has_alpha;
+       restx = step - 1;
+
+               for(i=0; i < ssize - restx; i += step) 
+          {    
+               int r, g, b, a = 0;
+
+               if(index < imgsize)
+         {
+               r = image->comps[0].data[index];
+               g = image->comps[1].data[index];
+               b = image->comps[2].data[index];
+               if(has_alpha) a = image->comps[3].data[index];
+
+               if(sgnd)
+        {
+               r += adjust;
+               g += adjust;
+               b += adjust;
+               if(has_alpha) a += adjust;
+        }
+               dat8[i+0] = r ;
+               dat8[i+1] = g ;
+               dat8[i+2] = b ;
+               if(has_alpha) dat8[i+3] = a;
+
+               index++;
+               last_i = i + step;
+         }
+               else
+                break;
+          }//for(i = 0;)
+
+               if(last_i < ssize)
+          {
+               for(i = last_i; i < ssize; i += step) 
+         { 
+               int r, g, b, a = 0;
+
+               if(index < imgsize)
+        {
+               r = image->comps[0].data[index];
+               g = image->comps[1].data[index];
+               b = image->comps[2].data[index];
+               if(has_alpha) a = image->comps[3].data[index];
+
+               if(sgnd)
+       {
+               r += adjust;
+               g += adjust;
+               b += adjust;
+               if(has_alpha) a += adjust;
+       }
+               dat8[i+0] = r ;
+               if(i+1 < ssize) dat8[i+1] = g ;  else break;
+               if(i+2 < ssize) dat8[i+2] = b ;  else break;
+               if(has_alpha)
+       {
+               if(i+3 < ssize) dat8[i+3] = a ;  else break;
+       }
+               index++;
+        }
+               else
+                break;
+         }//for(i)
+          }//if(last_i < ssize)
+
+ }     //if(bps == 8)
+       else 
+       if(bps == 16)
+ {
+       step = 6 + has_alpha + has_alpha;
+       restx = step - 1;
+
+               for(i = 0; i < ssize - restx ; i += step) 
+          {  
+               int r, g, b, a = 0;
+
+               if(index < imgsize)
+         {
+               r = image->comps[0].data[index];
+               g = image->comps[1].data[index];
+               b = image->comps[2].data[index];
+               if(has_alpha) a = image->comps[3].data[index];
+
+               if(sgnd)
+        {
+               r += adjust;
+               g += adjust;
+               b += adjust;
+               if(has_alpha) a += adjust;
+        }
+               if(force16) 
+        { 
+               r = (r<<ushift) + (r>>dshift); 
+               g = (g<<ushift) + (g>>dshift); 
+               b = (b<<ushift) + (b>>dshift); 
+               if(has_alpha) a = (a<<ushift) + (a>>dshift);
+        }
+               dat8[i+0] =  r;//LSB
+               dat8[i+1] = (r >> 8);//MSB
+               dat8[i+2] =  g;
+               dat8[i+3] = (g >> 8);
+               dat8[i+4] =  b;
+               dat8[i+5] = (b >> 8);
+               if(has_alpha) 
+        { 
+               dat8[i+6] =  a; 
+               dat8[i+7] = (a >> 8); 
+        }
+               index++;
+               last_i = i + step;
+         }
+               else
+                break;
+          }//for(i = 0;)
+
+               if(last_i < ssize)
+          {
+               for(i = last_i ; i < ssize ; i += step) 
+         {    
+               int r, g, b, a = 0;
+
+               if(index < imgsize)
+        {
+               r = image->comps[0].data[index];
+               g = image->comps[1].data[index];
+               b = image->comps[2].data[index];
+               if(has_alpha) a = image->comps[3].data[index];
+
+               if(sgnd)
+       {
+               r += adjust;
+               g += adjust;
+               b += adjust;
+               if(has_alpha) a += adjust;
+       }
+           if(force16)
+       {
+           r = (r<<ushift) + (r>>dshift);
+           g = (g<<ushift) + (g>>dshift);
+           b = (b<<ushift) + (b>>dshift);
+           if(has_alpha) a = (a<<ushift) + (a>>dshift);
+       }
+               dat8[i+0] =  r;//LSB
+               if(i+1 < ssize) dat8[i+1] = (r >> 8);else break;//MSB
+               if(i+2 < ssize) dat8[i+2] =  g;      else break;
+               if(i+3 < ssize) dat8[i+3] = (g >> 8);else break;
+               if(i+4 < ssize) dat8[i+4] =  b;      else break;
+               if(i+5 < ssize) dat8[i+5] = (b >> 8);else break;
+
+               if(has_alpha)
+       {
+               if(i+6 < ssize) dat8[i+6] = a; else break;
+               if(i+7 < ssize) dat8[i+7] = (a >> 8); else break;
+       }
+               index++;
+        }
+               else
+                break;
+         }//for(i)
+          }//if(last_i < ssize)
+
+ }//if(bps == 16)
+       (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
+  }//for(strip = 0; )
+
+       _TIFFfree((void*)buf);
+       TIFFClose(tif);
+
+       return 0;
+   }//RGB(A)
+
+       if(image->numcomps == 1 /* GRAY */
+       || (   image->numcomps == 2 /* GRAY_ALPHA */
+               && image->comps[0].dx == image->comps[1].dx
+               && image->comps[0].dy == image->comps[1].dy
+               && image->comps[0].prec == image->comps[1].prec))
+   {
+       int step;
+
+       has_alpha = (image->numcomps == 2);
+
+       width   = image->comps[0].w;
+       height  = image->comps[0].h;
+       imgsize = width * height;
+
+/* Set tags */
+       TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
+       TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
+       TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1 + has_alpha);
+       TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
+       TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
+       TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
+       TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
+       TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
+
+/* Get a buffer for the data */
+       strip_size = TIFFStripSize(tif);
+       buf = _TIFFmalloc(strip_size);
+       index = 0;
+
+       for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
+  {
+       unsigned char *dat8;
+       tsize_t i, ssize = TIFFStripSize(tif);
+       dat8 = (unsigned char*)buf;
+
+       if(bps == 8)
+ {
+       step = 1 + has_alpha;
+
+               for(i=0; i < ssize; i += step) 
+          { 
+               if(index < imgsize)
+         {
+               int r, a = 0;
+
+               r = image->comps[0].data[index];
+               if(has_alpha) a = image->comps[1].data[index];
+
+               if(sgnd)
+        {
+               r += adjust;
+               if(has_alpha) a += adjust;
+        }
+               dat8[i+0] = r;
+               if(has_alpha) dat8[i+1] = a;
+               index++;
+        }
+               else
+                break;
+         }//for(i )
+ }//if(bps == 8
+       else 
+       if(bps == 16)
+ {
+       step = 2 + has_alpha + has_alpha;
+
+               for(i=0; i < ssize; i += step) 
+          {
+               if(index < imgsize)
+         {
+               int r, a = 0;
+
+               r = image->comps[0].data[index];
+               if(has_alpha) a = image->comps[1].data[index];
+
+               if(sgnd)
+        {
+               r += adjust;
+               if(has_alpha) a += adjust;
+        }
+               if(force16)
+        {
+               r = (r<<ushift) + (r>>dshift);
+               if(has_alpha) a = (a<<ushift) + (a>>dshift);
+        }
+               dat8[i+0] = r;//LSB
+               dat8[i+1] = r >> 8;//MSB
+               if(has_alpha)
+        {
+               dat8[i+2] = a;
+               dat8[i+3] = a >> 8;
+        }
+               index++;
+         }//if(index < imgsize)
+               else
+                break;
+          }//for(i )
+ }
+       (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
+  }//for(strip
+
+       _TIFFfree(buf);
+       TIFFClose(tif);
+
+       return 0;
+   }
+
+       TIFFClose(tif);
+
+       fprintf(stderr,"imagetotif: Bad color format.\n"
+        "\tOnly RGB(A) and GRAY(A) has been implemented\n");
+       fprintf(stderr,"\tFOUND: numcomps(%d)\n\tAborting\n",
+        image->numcomps);
+
+       return 1;
+}/* imagetotif() */
+
+/*
+ * libtiff/tif_getimage.c : 1,2,4,8,16 bitspersample accepted
+ * CINEMA                 : 12 bit precision
+*/
+opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
+{
+       int subsampling_dx = parameters->subsampling_dx;
+       int subsampling_dy = parameters->subsampling_dy;
+       TIFF *tif;
+       tiff_infoheader_t Info;
+       tdata_t buf;
+       tstrip_t strip;
+       tsize_t strip_size;
+       int j, numcomps, w, h,index;
+       OPJ_COLOR_SPACE color_space;
+       opj_image_cmptparm_t cmptparm[4]; /* RGBA */
+       opj_image_t *image = NULL;
+       int imgsize = 0;
+       int has_alpha = 0;
+
+       tif = TIFFOpen(filename, "r");
+
+       if(!tif) 
+   {
+       fprintf(stderr, "tiftoimage:Failed to open %s for reading\n", filename);
+       return 0;
+   }
+       TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &Info.tiWidth);
+       TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &Info.tiHeight);
+       TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &Info.tiBps);
+       TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &Info.tiSf);
+       TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &Info.tiSpp);
+       Info.tiPhoto = 0;
+       TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &Info.tiPhoto);
+       TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &Info.tiPC);
+       w= Info.tiWidth;
+       h= Info.tiHeight;
+
+   {
+       int b, p;
+
+       if((b = Info.tiBps) != 8 && b != 16 && b != 12) b = 0;
+       if((p = Info.tiPhoto) != 1 && p != 2) p = 0;
+
+    if( !b || !p)
+  {
+       if( !b)
+     fprintf(stderr,"imagetotif: Bits=%d, Only 8 and 16 bits"
+      " implemented\n",Info.tiBps);
+       else
+       if( !p)
+     fprintf(stderr,"tiftoimage: Bad color format %d.\n\tOnly RGB(A)"
+      " and GRAY(A) has been implemented\n",(int) Info.tiPhoto);
+
+    fprintf(stderr,"\tAborting\n");
+       TIFFClose(tif);
+
+    return NULL;
+  }
+   }
+
+   {/* From: tiff-4.0.x/libtiff/tif_getimage.c : */
+       uint16* sampleinfo;
+       uint16 extrasamples;
+
+       TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
+        &extrasamples, &sampleinfo);
+
+       if(extrasamples >= 1)
+  {
+       switch(sampleinfo[0]) 
+ {
+       case EXTRASAMPLE_UNSPECIFIED: 
+/* Workaround for some images without correct info about alpha channel
+*/
+               if(Info.tiSpp > 3)
+                has_alpha = 1;
+               break;
+
+       case EXTRASAMPLE_ASSOCALPHA: /* data pre-multiplied */
+       case EXTRASAMPLE_UNASSALPHA: /* data not pre-multiplied */
+               has_alpha = 1;
+               break;
+ }
+  }
+   }
+/* initialize image components
+*/ 
+       memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
+
+       if(Info.tiPhoto == PHOTOMETRIC_RGB) /* RGB(A) */
+   {
+       numcomps = 3 + has_alpha;
+       color_space = CLRSPC_SRGB;
+
+       for(j = 0; j < numcomps; j++) 
+  {
+       if(parameters->cp_cinema) 
+ {
+       cmptparm[j].prec = 12;
+       cmptparm[j].bpp = 12;
+ }
+       else
+ {
+       cmptparm[j].prec = Info.tiBps;
+       cmptparm[j].bpp = Info.tiBps;
+ }
+       cmptparm[j].dx = subsampling_dx;
+       cmptparm[j].dy = subsampling_dy;
+       cmptparm[j].w = w;
+       cmptparm[j].h = h;
+  }
+
+       image = opj_image_create(numcomps, &cmptparm[0], color_space);
+
+       if(!image) 
+  {
+       TIFFClose(tif);
+       return NULL;
+  }
+/* set image offset and reference grid 
+*/
+       image->x0 = parameters->image_offset_x0;
+       image->y0 = parameters->image_offset_y0;
+       image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 :
+               image->x0 + (w - 1) * subsampling_dx + 1;
+       image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 :
+               image->y0 + (h - 1) * subsampling_dy + 1;
+
+       buf = _TIFFmalloc(TIFFStripSize(tif));
+
+       strip_size=TIFFStripSize(tif);
+       index = 0;
+       imgsize = image->comps[0].w * image->comps[0].h ;
+/* Read the Image components
+*/
+       for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
+  {
+       unsigned char *dat8;
+       int step;
+       tsize_t i, ssize;
+       ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
+       dat8 = (unsigned char*)buf;
+
+       if(Info.tiBps == 16)
+ {
+       step = 6 + has_alpha + has_alpha;
+
+               for(i = 0; i < ssize; i += step) 
+          {
+               if(index < imgsize)
+         {
+               image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0]; // R 
+               image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2]; // G 
+               image->comps[2].data[index] = ( dat8[i+5] << 8 ) | dat8[i+4]; // B 
+               if(has_alpha)
+                image->comps[3].data[index] = ( dat8[i+7] << 8 ) | dat8[i+6];
+
+               if(parameters->cp_cinema)
+        {
+/* Rounding 16 to 12 bits
+*/
+               image->comps[0].data[index] = 
+                       (image->comps[0].data[index] + 0x08) >> 4 ;
+               image->comps[1].data[index] = 
+                       (image->comps[1].data[index] + 0x08) >> 4 ;
+               image->comps[2].data[index] = 
+                       (image->comps[2].data[index] + 0x08) >> 4 ;
+               if(has_alpha)
+                image->comps[3].data[index] =
+                       (image->comps[3].data[index] + 0x08) >> 4 ;
+        }
+               index++;
+         }
+               else
+                break;
+          }//for(i = 0)
+ }//if(Info.tiBps == 16)
+       else 
+       if(Info.tiBps == 8)
+ {
+       step = 3 + has_alpha;
+
+               for(i = 0; i < ssize; i += step) 
+          {
+               if(index < imgsize)
+         {
+               image->comps[0].data[index] = dat8[i+0];// R 
+               image->comps[1].data[index] = dat8[i+1];// G 
+               image->comps[2].data[index] = dat8[i+2];// B 
+               if(has_alpha)
+                image->comps[3].data[index] = dat8[i+3];
+
+               if(parameters->cp_cinema)
+        {
+/* Rounding 8 to 12 bits
+*/
+               image->comps[0].data[index] = image->comps[0].data[index] << 4 ;
+               image->comps[1].data[index] = image->comps[1].data[index] << 4 ;
+               image->comps[2].data[index] = image->comps[2].data[index] << 4 ;
+               if(has_alpha)
+                image->comps[3].data[index] = image->comps[3].data[index] << 4 ;
+        }
+               index++;
+         }//if(index
+               else
+                break;
+          }//for(i )
+ }//if( Info.tiBps == 8)
+       else
+       if(Info.tiBps == 12)/* CINEMA file */
+ {
+       step = 9;
+
+               for(i = 0; i < ssize; i += step) 
+          {
+               if((index < imgsize)&(index+1 < imgsize))
+         {
+               image->comps[0].data[index]   = ( dat8[i+0]<<4 )        |(dat8[i+1]>>4);
+               image->comps[1].data[index]   = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
+
+               image->comps[2].data[index]   = ( dat8[i+3]<<4)         |(dat8[i+4]>>4);
+               image->comps[0].data[index+1] = ((dat8[i+4]& 0x0f)<< 8) | dat8[i+5];
+
+               image->comps[1].data[index+1] = ( dat8[i+6] <<4)        |(dat8[i+7]>>4);
+               image->comps[2].data[index+1] = ((dat8[i+7]& 0x0f)<< 8) | dat8[i+8];
+
+               index += 2;
+         }
+               else
+                break;
+          }//for(i )
+ }
+  }//for(strip = 0; )
+
+       _TIFFfree(buf);
+       TIFFClose(tif);
+
+       return image;
+   }//RGB(A)
+
+       if(Info.tiPhoto == PHOTOMETRIC_MINISBLACK) /* GRAY(A) */
+   {
+       numcomps = 1 + has_alpha;
+       color_space = CLRSPC_GRAY;
+
+       for(j = 0; j < numcomps; ++j)
+  {
+       cmptparm[j].prec = Info.tiBps;
+       cmptparm[j].bpp = Info.tiBps;
+       cmptparm[j].dx = subsampling_dx;
+       cmptparm[j].dy = subsampling_dy;
+       cmptparm[j].w = w;
+       cmptparm[j].h = h;
+  }
+       image = opj_image_create(numcomps, &cmptparm[0], color_space);
+
+       if(!image) 
+  {
+       TIFFClose(tif);
+       return NULL;
+  }
+/* set image offset and reference grid 
+*/
+       image->x0 = parameters->image_offset_x0;
+       image->y0 = parameters->image_offset_y0;
+       image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 :
+               image->x0 + (w - 1) * subsampling_dx + 1;
+       image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 :
+               image->y0 + (h - 1) * subsampling_dy + 1;
+
+       buf = _TIFFmalloc(TIFFStripSize(tif));
+
+       strip_size = TIFFStripSize(tif);
+       index = 0;
+       imgsize = image->comps[0].w * image->comps[0].h ;
+/* Read the Image components
+*/
+       for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
+  {
+       unsigned char *dat8;
+       tsize_t i, ssize;
+       int step;
+
+       ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
+       dat8 = (unsigned char*)buf;
+
+               if(Info.tiBps == 16)
+          {
+               step = 2 + has_alpha + has_alpha;
+
+               for(i = 0; i < ssize; i += step) 
+         {
+               if(index < imgsize)
+        {
+               image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0];
+               if(has_alpha)
+                image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2];
+               index++;
+        }
+               else
+                break;
+         }//for(i )
+          }
+               else 
+               if(Info.tiBps == 8)
+          {
+               step = 1 + has_alpha;
+
+               for(i = 0; i < ssize; i += step) 
+         {
+               if(index < imgsize)
+        {
+               image->comps[0].data[index] = dat8[i+0];
+               if(has_alpha)
+                image->comps[1].data[index] = dat8[i+1];
+               index++;
+        }
+               else
+                break;
+         }//for(i )
+          }
+  }//for(strip = 0;
+
+       _TIFFfree(buf);
+       TIFFClose(tif);
+
+   }//GRAY(A)
+
+       return image;
+
+}/* tiftoimage() */
+
+#endif /* HAVE_LIBTIFF */
+
+/* -->> -->> -->> -->>
+
+       RAW IMAGE FORMAT
+
+ <<-- <<-- <<-- <<-- */
+
+opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
+       int subsampling_dx = parameters->subsampling_dx;
+       int subsampling_dy = parameters->subsampling_dy;
+
+       FILE *f = NULL;
+       int i, compno, numcomps, w, h;
+       OPJ_COLOR_SPACE color_space;
+       opj_image_cmptparm_t *cmptparm; 
+       opj_image_t * image = NULL;
+       unsigned short ch;
+       
+       if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
+       {
+               fprintf(stderr,"\nError: invalid raw image parameters\n");
+               fprintf(stderr,"Please use the Format option -F:\n");
+               fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
+               fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
+               fprintf(stderr,"Aborting\n");
+               return NULL;
+       }
+
+       f = fopen(filename, "rb");
+       if (!f) {
+               fprintf(stderr, "Failed to open %s for reading !!\n", filename);
+               fprintf(stderr,"Aborting\n");
+               return NULL;
+       }
+       numcomps = raw_cp->rawComp;
+       color_space = CLRSPC_SRGB;
+       w = raw_cp->rawWidth;
+       h = raw_cp->rawHeight;
+       cmptparm = (opj_image_cmptparm_t*) malloc(numcomps * sizeof(opj_image_cmptparm_t));
+       
+       /* initialize image components */       
+       memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
+       for(i = 0; i < numcomps; i++) {         
+               cmptparm[i].prec = raw_cp->rawBitDepth;
+               cmptparm[i].bpp = raw_cp->rawBitDepth;
+               cmptparm[i].sgnd = raw_cp->rawSigned;
+               cmptparm[i].dx = subsampling_dx;
+               cmptparm[i].dy = subsampling_dy;
+               cmptparm[i].w = w;
+               cmptparm[i].h = h;
+       }
+       /* create the image */
+       image = opj_image_create(numcomps, &cmptparm[0], color_space);
+       if(!image) {
+               fclose(f);
+               return NULL;
+       }
+       /* set image offset and reference grid */
+       image->x0 = parameters->image_offset_x0;
+       image->y0 = parameters->image_offset_y0;
+       image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
+       image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
+
+       if(raw_cp->rawBitDepth <= 8)
+       {
+               unsigned char value = 0;
+               for(compno = 0; compno < numcomps; compno++) {
+                       for (i = 0; i < w * h; i++) {
+                               if (!fread(&value, 1, 1, f)) {
+                                       fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
+                                       return NULL;
+                               }
+                               image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
+                       }
+               }
+       }
+       else if(raw_cp->rawBitDepth <= 16)
+       {
+               unsigned short value;
+               for(compno = 0; compno < numcomps; compno++) {
+                       for (i = 0; i < w * h; i++) {
+                               unsigned char temp;
+                               if (!fread(&temp, 1, 1, f)) {
+                                       fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
+                                       return NULL;
+                               }
+                               value = temp << 8;
+                               if (!fread(&temp, 1, 1, f)) {
+                                       fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
+                                       return NULL;
+                               }
+                               value += temp;
+                               image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
+                       }
+               }
+       }
+       else {
+               fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
+               return NULL;
+       }
+
+       if (fread(&ch, 1, 1, f)) {
+               fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
+       }
+       fclose(f);
+
+       return image;
+}
+
+int imagetoraw(opj_image_t * image, const char *outfile)
+{
+       FILE *rawFile = NULL;
+       int compno;
+       int w, h;
+       int line, row;
+       int *ptr;
+
+       if((image->numcomps * image->x1 * image->y1) == 0)
+       {
+               fprintf(stderr,"\nError: invalid raw image parameters\n");
+               return 1;
+       }
+
+       rawFile = fopen(outfile, "wb");
+       if (!rawFile) {
+               fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
+               return 1;
+       }
+
+       fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
+
+       for(compno = 0; compno < image->numcomps; compno++)
+       {
+               fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
+                       image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
+
+               w = image->comps[compno].w;
+               h = image->comps[compno].h;
+
+               if(image->comps[compno].prec <= 8)
+               {
+                       if(image->comps[compno].sgnd == 1)
+                       {
+                               signed char curr;
+                               int mask = (1 << image->comps[compno].prec) - 1;
+                               ptr = image->comps[compno].data;
+                               for (line = 0; line < h; line++) {
+                                       for(row = 0; row < w; row++)    {                               
+                                               curr = (signed char) (*ptr & mask);
+                                               fwrite(&curr, sizeof(signed char), 1, rawFile);
+                                               ptr++;
+                                       }
+                               }
+                       }
+                       else if(image->comps[compno].sgnd == 0)
+                       {
+                               unsigned char curr;
+                               int mask = (1 << image->comps[compno].prec) - 1;
+                               ptr = image->comps[compno].data;
+                               for (line = 0; line < h; line++) {
+                                       for(row = 0; row < w; row++)    {       
+                                               curr = (unsigned char) (*ptr & mask);
+                                               fwrite(&curr, sizeof(unsigned char), 1, rawFile);
+                                               ptr++;
+                                       }
+                               }
+                       }
+               }
+               else if(image->comps[compno].prec <= 16)
+               {
+                       if(image->comps[compno].sgnd == 1)
+                       {
+                               signed short int curr;
+                               int mask = (1 << image->comps[compno].prec) - 1;
+                               ptr = image->comps[compno].data;
+                               for (line = 0; line < h; line++) {
+                                       for(row = 0; row < w; row++)    {                                       
+                                               unsigned char temp;
+                                               curr = (signed short int) (*ptr & mask);
+                                               temp = (unsigned char) (curr >> 8);
+                                               fwrite(&temp, 1, 1, rawFile);
+                                               temp = (unsigned char) curr;
+                                               fwrite(&temp, 1, 1, rawFile);
+                                               ptr++;
+                                       }
+                               }
+                       }
+                       else if(image->comps[compno].sgnd == 0)
+                       {
+                               unsigned short int curr;
+                               int mask = (1 << image->comps[compno].prec) - 1;
+                               ptr = image->comps[compno].data;
+                               for (line = 0; line < h; line++) {
+                                       for(row = 0; row < w; row++)    {                               
+                                               unsigned char temp;
+                                               curr = (unsigned short int) (*ptr & mask);
+                                               temp = (unsigned char) (curr >> 8);
+                                               fwrite(&temp, 1, 1, rawFile);
+                                               temp = (unsigned char) curr;
+                                               fwrite(&temp, 1, 1, rawFile);
+                                               ptr++;
+                                       }
+                               }
+                       }
+               }
+               else if (image->comps[compno].prec <= 32)
+               {
+                       fprintf(stderr,"More than 16 bits per component no handled yet\n");
+                       return 1;
+               }
+               else
+               {
+                       fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
+                       return 1;
+               }
+       }
+       fclose(rawFile);
+       return 0;
+}
+
+#ifdef HAVE_LIBPNG
+
+#define PNG_MAGIC "\x89PNG\x0d\x0a\x1a\x0a"
+#define MAGIC_SIZE 8
+/* PNG allows bits per sample: 1, 2, 4, 8, 16 */
+
+opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
+{
+       png_structp  png;
+       png_infop    info;
+       double gamma, display_exponent;
+       int bit_depth, interlace_type,compression_type, filter_type;
+       int unit;
+       png_uint_32 resx, resy;
+       unsigned int i, j;
+       png_uint_32  width, height;
+       int color_type, has_alpha, is16;
+       unsigned char *s;
+       FILE *reader;
+       unsigned char **rows;
+/* j2k: */
+       opj_image_t *image;
+       opj_image_cmptparm_t cmptparm[4];
+       int sub_dx, sub_dy;
+       unsigned int nr_comp;
+       int *r, *g, *b, *a;
+       unsigned char sigbuf[8];
+
+       if((reader = fopen(read_idf, "rb")) == NULL)
+   {
+       fprintf(stderr,"pngtoimage: can not open %s\n",read_idf);
+       return NULL;
+   }
+       image = NULL; png = NULL; rows = NULL;
+
+       if(fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE
+       || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0)
+   {
+       fprintf(stderr,"pngtoimage: %s is no valid PNG file\n",read_idf);
+       goto fin;
+   }
+/* libpng-VERSION/example.c: 
+ * PC : screen_gamma = 2.2;
+ * Mac: screen_gamma = 1.7 or 1.0;
+*/
+       display_exponent = 2.2;
+
+       if((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,
+                                   NULL, NULL, NULL)) == NULL)
+         goto fin;
+       if((info = png_create_info_struct(png)) == NULL)
+         goto fin;
+
+       if(setjmp(png_jmpbuf(png)))
+         goto fin;
+
+       png_init_io(png, reader);
+       png_set_sig_bytes(png, MAGIC_SIZE);
+
+       png_read_info(png, info);
+
+       if(png_get_IHDR(png, info, &width, &height,
+               &bit_depth, &color_type, &interlace_type, 
+               &compression_type, &filter_type) == 0)
+        goto fin;
+
+/* png_set_expand():
+ * expand paletted images to RGB, expand grayscale images of
+ * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
+ * to alpha channels.
+*/
+       if(color_type == PNG_COLOR_TYPE_PALETTE)
+         png_set_expand(png);
+       else
+       if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
+         png_set_expand(png);
+
+       if(png_get_valid(png, info, PNG_INFO_tRNS))
+         png_set_expand(png);
+
+       is16 = (bit_depth == 16);
+
+/* GRAY => RGB; GRAY_ALPHA => RGBA
+*/
+       if(color_type == PNG_COLOR_TYPE_GRAY
+       || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
+   {
+       png_set_gray_to_rgb(png);
+       color_type = 
+        (color_type == PNG_COLOR_TYPE_GRAY? PNG_COLOR_TYPE_RGB:
+               PNG_COLOR_TYPE_RGB_ALPHA);
+   }
+       if( !png_get_gAMA(png, info, &gamma))
+         gamma = 0.45455;
+
+       png_set_gamma(png, display_exponent, gamma);
+
+       png_read_update_info(png, info);
+
+       png_get_pHYs(png, info, &resx, &resy, &unit);
+
+       color_type = png_get_color_type(png, info);
+
+       has_alpha = (color_type == PNG_COLOR_TYPE_RGB_ALPHA);
+
+       nr_comp = 3 + has_alpha;
+
+       bit_depth = png_get_bit_depth(png, info);
+
+       rows = (unsigned char**)calloc(height+1, sizeof(unsigned char*));
+       for(i = 0; i < height; ++i)
+        rows[i] = (unsigned char*)malloc(png_get_rowbytes(png,info));
+
+       png_read_image(png, rows);
+
+       memset(&cmptparm, 0, 4 * sizeof(opj_image_cmptparm_t));
+
+       sub_dx = params->subsampling_dx; sub_dy = params->subsampling_dy;
+
+       for(i = 0; i < nr_comp; ++i)
+   {
+       cmptparm[i].prec = bit_depth;
+/* bits_per_pixel: 8 or 16 */
+       cmptparm[i].bpp = bit_depth;
+       cmptparm[i].sgnd = 0;
+       cmptparm[i].dx = sub_dx;
+       cmptparm[i].dy = sub_dy;
+       cmptparm[i].w = width;
+       cmptparm[i].h = height;
+   }
+
+       image = opj_image_create(nr_comp, &cmptparm[0], CLRSPC_SRGB);
+
+       if(image == NULL) goto fin;
+
+    image->x0 = params->image_offset_x0;
+    image->y0 = params->image_offset_y0;
+    image->x1 = image->x0 + (width  - 1) * sub_dx + 1 + image->x0;
+    image->y1 = image->y0 + (height - 1) * sub_dy + 1 + image->y0;
+
+       r = image->comps[0].data;
+       g = image->comps[1].data;
+       b = image->comps[2].data;
+       a = image->comps[3].data;
+
+       for(i = 0; i < height; ++i)
+   {
+       s = rows[i];
+
+       for(j = 0; j < width; ++j)
+  {
+       if(is16)
+ {
+       *r++ = s[0]<<8|s[1]; s += 2;
+
+       *g++ = s[0]<<8|s[1]; s += 2;
+       
+       *b++ = s[0]<<8|s[1]; s += 2;
+       
+       if(has_alpha) { *a++ = s[0]<<8|s[1]; s += 2; }
+
+       continue;
+ }
+       *r++ = *s++; *g++ = *s++; *b++ = *s++;
+
+       if(has_alpha) *a++ = *s++;
+  }
+   }
+fin:
+       if(rows)
+   {
+       for(i = 0; i < height; ++i)
+        free(rows[i]);
+       free(rows);
+   }
+       if(png)
+         png_destroy_read_struct(&png, &info, NULL);
+
+       fclose(reader);
+
+       return image;
+
+}/* pngtoimage() */
+
+int imagetopng(opj_image_t * image, const char *write_idf)
+{
+       FILE *writer;
+       png_structp png;
+       png_infop info;
+       int *red, *green, *blue, *alpha;
+       unsigned char *row_buf, *d;
+       int has_alpha, width, height, nr_comp, color_type;
+       int adjustR, adjustG, adjustB, x, y, fails, is16, force16;
+  int opj_prec, prec, ushift, dshift;
+       unsigned short mask = 0xffff;
+       png_color_8 sig_bit;
+
+       is16 = force16 = ushift = dshift = 0; fails = 1;
+       prec = opj_prec = image->comps[0].prec;
+
+       if(prec > 8 && prec < 16)
+   {
+        prec = 16; force16 = 1;
+   }
+       if(prec != 1 && prec != 2 && prec != 4 && prec != 8 && prec != 16)
+   {
+       fprintf(stderr,"imagetopng: can not create %s"
+        "\n\twrong bit_depth %d\n", write_idf, prec);
+       return fails;
+   }
+       writer = fopen(write_idf, "wb");
+
+       if(writer == NULL) return fails;
+
+       info = NULL; has_alpha = 0;
+
+/* Create and initialize the png_struct with the desired error handler
+ * functions.  If you want to use the default stderr and longjump method,
+ * you can supply NULL for the last three parameters.  We also check that
+ * the library version is compatible with the one used at compile time,
+ * in case we are using dynamically linked libraries.  REQUIRED.
+*/
+       png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
+               NULL, NULL, NULL);
+/*png_voidp user_error_ptr, user_error_fn, user_warning_fn); */
+
+       if(png == NULL) goto fin;
+
+/* Allocate/initialize the image information data.  REQUIRED 
+*/
+       info = png_create_info_struct(png);
+
+       if(info == NULL) goto fin;
+
+/* Set error handling.  REQUIRED if you are not supplying your own
+ * error handling functions in the png_create_write_struct() call.
+*/
+       if(setjmp(png_jmpbuf(png))) goto fin;
+
+/* I/O initialization functions is REQUIRED 
+*/
+       png_init_io(png, writer);
+
+/* Set the image information here.  Width and height are up to 2^31,
+ * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
+ * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
+ * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
+ * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
+ * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
+ * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. 
+ * REQUIRED
+*/
+       png_set_compression_level(png, Z_BEST_COMPRESSION);
+
+       if(prec == 16) mask = 0xffff;
+       else
+       if(prec == 8) mask = 0x00ff;
+       else
+       if(prec == 4) mask = 0x000f;
+       else
+       if(prec == 2) mask = 0x0003;
+       else
+       if(prec == 1) mask = 0x0001;
+
+       nr_comp = image->numcomps;
+
+       if(nr_comp >= 3
+    && image->comps[0].dx == image->comps[1].dx
+    && image->comps[1].dx == image->comps[2].dx
+    && image->comps[0].dy == image->comps[1].dy
+    && image->comps[1].dy == image->comps[2].dy
+    && image->comps[0].prec == image->comps[1].prec
+    && image->comps[1].prec == image->comps[2].prec)
+   {
+       int v;
+
+    has_alpha = (nr_comp > 3); 
+
+       is16 = (prec == 16);
+       
+    width = image->comps[0].w;
+    height = image->comps[0].h;
+
+       red = image->comps[0].data;
+       green = image->comps[1].data;
+       blue = image->comps[2].data;
+
+    sig_bit.red = sig_bit.green = sig_bit.blue = prec;
+
+       if(has_alpha) 
+  {
+       sig_bit.alpha = prec;
+       alpha = image->comps[3].data; 
+       color_type = PNG_COLOR_TYPE_RGB_ALPHA;
+  }
+       else 
+  {
+       sig_bit.alpha = 0; alpha = NULL;
+       color_type = PNG_COLOR_TYPE_RGB;
+  }
+       png_set_sBIT(png, info, &sig_bit);
+
+       png_set_IHDR(png, info, width, height, prec, 
+        color_type,
+        PNG_INTERLACE_NONE,
+        PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
+
+/*=============================*/
+       png_write_info(png, info);
+/*=============================*/
+       if(opj_prec < 8)
+  {
+       png_set_packing(png);
+  }
+       if(force16)
+  {
+       ushift = 16 - opj_prec; dshift = opj_prec - ushift;     
+  }
+    adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
+    adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
+    adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
+
+       row_buf = (unsigned char*)malloc(width * nr_comp * 2);
+
+       for(y = 0; y < height; ++y)
+  {
+       d = row_buf;
+
+       for(x = 0; x < width; ++x)
+ {
+               if(is16)
+          {
+               v = *red + adjustR; ++red;
+               
+               if(force16) { v = (v<<ushift) + (v>>dshift); }
+
+               *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
+
+               v = *green + adjustG; ++green;
+               
+               if(force16) { v = (v<<ushift) + (v>>dshift); }
+
+               *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
+
+               v =  *blue + adjustB; ++blue;
+               
+               if(force16) { v = (v<<ushift) + (v>>dshift); }
+
+               *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
+
+               if(has_alpha)
+         {
+               v = *alpha++;
+               
+               if(force16) { v = (v<<ushift) + (v>>dshift); }
+
+               *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
+         }
+               continue;
+          }
+               *d++ = (unsigned char)((*red + adjustR) & mask); ++red;
+               *d++ = (unsigned char)((*green + adjustG) & mask); ++green;
+               *d++ = (unsigned char)((*blue + adjustB) & mask); ++blue;
+
+               if(has_alpha)
+          {
+               *d++ = (unsigned char)(*alpha & mask); ++alpha;
+          }
+ }     /* for(x) */
+
+       png_write_row(png, row_buf);
+
+  }    /* for(y) */
+       free(row_buf);
+
+   }/* nr_comp >= 3 */
+       else
+       if(nr_comp == 1 /* GRAY */
+       || (   nr_comp == 2 /* GRAY_ALPHA */
+               && image->comps[0].dx == image->comps[1].dx
+               && image->comps[0].dy == image->comps[1].dy
+               && image->comps[0].prec == image->comps[1].prec))
+   {
+       int v;
+
+       red = image->comps[0].data;
+
+    if(force16)
+  {
+    ushift = 16 - opj_prec; dshift = opj_prec - ushift;
+  }
+    sig_bit.gray = prec;
+    sig_bit.red = sig_bit.green = sig_bit.blue = sig_bit.alpha = 0;
+       alpha = NULL;
+       color_type = PNG_COLOR_TYPE_GRAY;
+
+    if(nr_comp == 2) 
+  { 
+       has_alpha = 1; sig_bit.alpha = prec;
+       alpha = image->comps[1].data;
+       color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
+  }
+    width = image->comps[0].w;
+    height = image->comps[0].h;
+
+       png_set_IHDR(png, info, width, height, sig_bit.gray,
+     color_type,
+     PNG_INTERLACE_NONE,
+     PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
+
+       png_set_sBIT(png, info, &sig_bit);
+/*=============================*/
+       png_write_info(png, info);
+/*=============================*/
+       adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
+
+       if(opj_prec < 8)
+  {
+       png_set_packing(png);
+  }
+
+       if(prec > 8)
+  {
+       row_buf = (unsigned char*)
+        malloc(width * nr_comp * sizeof(unsigned short));
+
+       for(y = 0; y < height; ++y)
+ {
+       d = row_buf;
+
+               for(x = 0; x < width; ++x)
+          {
+               v = *red + adjustR; ++red;
+
+               if(force16) { v = (v<<ushift) + (v>>dshift); }
+
+               *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
+
+               if(has_alpha)
+         {
+               v = *alpha++;
+
+               if(force16) { v = (v<<ushift) + (v>>dshift); }
+
+               *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
+         }
+          }/* for(x) */
+       png_write_row(png, row_buf);
+
+ }     /* for(y) */
+       free(row_buf);
+  }
+       else /* prec <= 8 */
+  {
+       row_buf = (unsigned char*)calloc(width, nr_comp * 2);
+
+       for(y = 0; y < height; ++y)
+ {
+       d = row_buf;
+
+               for(x = 0; x < width; ++x)
+          {
+               *d++ = (unsigned char)((*red + adjustR) & mask); ++red;
+
+               if(has_alpha)
+         {
+               *d++ = (unsigned char)(*alpha & mask); ++alpha;
+         }
+          }/* for(x) */
+
+       png_write_row(png, row_buf);
+
+ }     /* for(y) */
+       free(row_buf);
+  }
+   }
+       else
+   {
+       fprintf(stderr,"imagetopng: can not create %s\n",write_idf);
+       goto fin;
+   }
+       png_write_end(png, info);
+
+       fails = 0;
+
+fin:
+
+       if(png)
+   {
+    png_destroy_write_struct(&png, &info);
+   }
+       fclose(writer);
+
+       if(fails) remove(write_idf);
+
+       return fails;
+}/* imagetopng() */
+#endif /* HAVE_LIBPNG */
diff --git a/applications/codec/convert.h b/applications/codec/convert.h
new file mode 100644 (file)
index 0000000..1dc58d7
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef __J2K_CONVERT_H
+#define __J2K_CONVERT_H
+
+/**@name RAW image encoding parameters */
+/*@{*/
+typedef struct raw_cparameters {
+       /** width of the raw image */
+       int rawWidth;
+       /** height of the raw image */
+       int rawHeight;
+       /** components of the raw image */
+       int rawComp;
+       /** bit depth of the raw image */
+       int rawBitDepth;
+       /** signed/unsigned raw image */
+       bool rawSigned;
+       /*@}*/
+} raw_cparameters_t;
+
+/* TGA conversion */
+opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters);
+int imagetotga(opj_image_t * image, const char *outfile);
+
+/* BMP conversion */
+opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters);
+int imagetobmp(opj_image_t *image, const char *outfile);
+
+/* TIFF conversion*/
+opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters);
+int imagetotif(opj_image_t *image, const char *outfile);
+/**
+Load a single image component encoded in PGX file format
+@param filename Name of the PGX file to load
+@param parameters *List ?*
+@return Returns a greyscale image if successful, returns NULL otherwise
+*/
+opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters);
+int imagetopgx(opj_image_t *image, const char *outfile);
+
+opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters);
+int imagetopnm(opj_image_t *image, const char *outfile);
+
+/* RAW conversion */
+int imagetoraw(opj_image_t * image, const char *outfile);
+opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp);
+
+/* PNG conversion*/
+extern int imagetopng(opj_image_t *image, const char *write_idf);
+extern opj_image_t* pngtoimage(const char *filename, opj_cparameters_t *parameters);
+
+#endif /* __J2K_CONVERT_H */
+
diff --git a/applications/codec/image_to_j2k.c b/applications/codec/image_to_j2k.c
new file mode 100644 (file)
index 0000000..66d2bf4
--- /dev/null
@@ -0,0 +1,1789 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * Copyright (c) 2006-2007, Parvatha Elangovan
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <math.h>
+
+#ifdef _WIN32
+#include "windirent.h"
+#else
+#include <dirent.h>
+#endif /* _WIN32 */
+
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <strings.h>
+#define _stricmp strcasecmp
+#define _strnicmp strncasecmp
+#endif /* _WIN32 */
+
+#include "opj_config.h"
+#include "openjpeg.h"
+#include "getopt.h"
+#include "convert.h"
+#include "index.h"
+
+#include "format_defs.h"
+
+#define CINEMA_24_CS 1302083   /*Codestream length for 24fps*/
+#define CINEMA_48_CS 651041            /*Codestream length for 48fps*/
+#define COMP_24_CS 1041666             /*Maximum size per color component for 2K & 4K @ 24fps*/
+#define COMP_48_CS 520833              /*Maximum size per color component for 2K @ 48fps*/
+
+typedef struct dircnt{
+       /** Buffer for holding images read from Directory*/
+       char *filename_buf;
+       /** Pointer to the buffer*/
+       char **filename;
+}dircnt_t;
+
+typedef struct img_folder{
+       /** The directory path of the folder containing input images*/
+       char *imgdirpath;
+       /** Output format*/
+       char *out_format;
+       /** Enable option*/
+       char set_imgdir;
+       /** Enable Cod Format for output*/
+       char set_out_format;
+       /** User specified rate stored in case of cinema option*/
+       float *rates;
+}img_fol_t;
+
+void encode_help_display() {
+       fprintf(stdout,"HELP for image_to_j2k\n----\n\n");
+       fprintf(stdout,"- the -h option displays this help information on screen\n\n");
+
+/* UniPG>> */
+       fprintf(stdout,"List of parameters for the JPEG 2000 "
+#ifdef USE_JPWL
+               "+ JPWL "
+#endif /* USE_JPWL */
+               "encoder:\n");
+/* <<UniPG */
+       fprintf(stdout,"\n");
+       fprintf(stdout,"REMARKS:\n");
+       fprintf(stdout,"---------\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"The markers written to the main_header are : SOC SIZ COD QCD COM.\n");
+       fprintf(stdout,"COD and QCD never appear in the tile_header.\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"By default:\n");
+       fprintf(stdout,"------------\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout," * Lossless\n");
+       fprintf(stdout," * 1 tile\n");
+       fprintf(stdout," * Size of precinct : 2^15 x 2^15 (means 1 precinct)\n");
+       fprintf(stdout," * Size of code-block : 64 x 64\n");
+       fprintf(stdout," * Number of resolutions: 6\n");
+       fprintf(stdout," * No SOP marker in the codestream\n");
+       fprintf(stdout," * No EPH marker in the codestream\n");
+       fprintf(stdout," * No sub-sampling in x or y direction\n");
+       fprintf(stdout," * No mode switch activated\n");
+       fprintf(stdout," * Progression order: LRCP\n");
+       fprintf(stdout," * No index file\n");
+       fprintf(stdout," * No ROI upshifted\n");
+       fprintf(stdout," * No offset of the origin of the image\n");
+       fprintf(stdout," * No offset of the origin of the tiles\n");
+       fprintf(stdout," * Reversible DWT 5-3\n");
+/* UniPG>> */
+#ifdef USE_JPWL
+       fprintf(stdout," * No JPWL protection\n");
+#endif /* USE_JPWL */
+/* <<UniPG */
+       fprintf(stdout,"\n");
+       fprintf(stdout,"Parameters:\n");
+       fprintf(stdout,"------------\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"Required Parameters (except with -h):\n");
+       fprintf(stdout,"One of the two options -ImgDir or -i must be used\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-ImgDir      : Image file Directory path (example ../Images) \n");
+       fprintf(stdout,"    When using this option -OutFor must be used\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-OutFor \n");
+       fprintf(stdout,"    REQUIRED only if -ImgDir is used\n");
+       fprintf(stdout,"          Need to specify only format without filename <BMP>  \n");
+       fprintf(stdout,"    Currently accepts PBM, PGM, PPM, PNM, PAM, PGX, PNG, BMP, TIF, RAW and TGA formats\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-i           : source file  (-i source.pnm also *pbm, *.pgm, *.ppm, *.pam, *.pgx, *png, *.bmp, *.tif, *.raw, *.tga) \n");
+       fprintf(stdout,"    When using this option -o must be used\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-o           : destination file (-o dest.j2k or .jp2) \n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"Optional Parameters:\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-h           : display the help information \n ");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-cinema2K    : Digital Cinema 2K profile compliant codestream for 2K resolution.(-cinema2k 24 or 48) \n");
+  fprintf(stdout,"       Need to specify the frames per second for a 2K resolution. Only 24 or 48 fps is allowed\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-cinema4K    : Digital Cinema 4K profile compliant codestream for 4K resolution \n");
+       fprintf(stdout,"          Frames per second not required. Default value is 24fps\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-r           : different compression ratios for successive layers (-r 20,10,5)\n ");
+       fprintf(stdout,"                 - The rate specified for each quality level is the desired \n");
+       fprintf(stdout,"                   compression factor.\n");
+       fprintf(stdout,"                   Example: -r 20,10,1 means quality 1: compress 20x, \n");
+       fprintf(stdout,"                     quality 2: compress 10x and quality 3: compress lossless\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"               (options -r and -q cannot be used together)\n ");
+       fprintf(stdout,"\n");
+
+       fprintf(stdout,"-q           : different psnr for successive layers (-q 30,40,50) \n ");
+
+       fprintf(stdout,"               (options -r and -q cannot be used together)\n ");
+
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-n           : number of resolutions (-n 3) \n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-b           : size of code block (-b 32,32) \n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-c           : size of precinct (-c 128,128) \n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-t           : size of tile (-t 512,512) \n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-p           : progression order (-p LRCP) [LRCP, RLCP, RPCL, PCRL, CPRL] \n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-s           : subsampling factor (-s 2,2) [-s X,Y] \n");
+       fprintf(stdout,"             Remark: subsampling bigger than 2 can produce error\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-POC         : Progression order change (-POC T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL) \n");
+       fprintf(stdout,"      Example: T1=0,0,1,5,3,CPRL \n");
+       fprintf(stdout,"                         : Ttilenumber=Resolution num start,Component num start,Layer num end,Resolution num end,Component num end,Progression order\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-SOP         : write SOP marker before each packet \n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-EPH         : write EPH marker after each header packet \n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-M           : mode switch (-M 3) [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
+       fprintf(stdout,"                 8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)] \n");
+       fprintf(stdout,"                 Indicate multiple modes by adding their values. \n");
+       fprintf(stdout,"                 ex: RESTART(4) + RESET(2) + SEGMARK(32) = -M 38\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-x           : create an index file *.Idx (-x index_name.Idx) \n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-ROI         : c=%%d,U=%%d : quantization indices upshifted \n");
+       fprintf(stdout,"               for component c=%%d [%%d = 0,1,2]\n");
+       fprintf(stdout,"               with a value of U=%%d [0 <= %%d <= 37] (i.e. -ROI c=0,U=25) \n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-d           : offset of the origin of the image (-d 150,300) \n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-T           : offset of the origin of the tiles (-T 100,75) \n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-I           : use the irreversible DWT 9-7 (-I) \n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"-F           : characteristics of the raw input image\n");
+       fprintf(stdout,"               -F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
+       fprintf(stdout,"               Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
+       fprintf(stdout,"\n");
+/* UniPG>> */
+#ifdef USE_JPWL
+       fprintf(stdout,"-W           : adoption of JPWL (Part 11) capabilities (-W params)\n");
+       fprintf(stdout,"               The parameters can be written and repeated in any order:\n");
+       fprintf(stdout,"               [h<tilepart><=type>,s<tilepart><=method>,a=<addr>,...\n");
+       fprintf(stdout,"                ...,z=<size>,g=<range>,p<tilepart:pack><=type>]\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"                 h selects the header error protection (EPB): 'type' can be\n");
+       fprintf(stdout,"                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
+       fprintf(stdout,"                   if 'tilepart' is absent, it is for main and tile headers\n");
+       fprintf(stdout,"                   if 'tilepart' is present, it applies from that tile\n");
+       fprintf(stdout,"                     onwards, up to the next h<> spec, or to the last tilepart\n");
+       fprintf(stdout,"                     in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);
+       fprintf(stdout,"\n");
+       fprintf(stdout,"                 p selects the packet error protection (EEP/UEP with EPBs)\n");
+       fprintf(stdout,"                  to be applied to raw data: 'type' can be\n");
+       fprintf(stdout,"                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
+       fprintf(stdout,"                   if 'tilepart:pack' is absent, it is from tile 0, packet 0\n");
+       fprintf(stdout,"                   if 'tilepart:pack' is present, it applies from that tile\n");
+       fprintf(stdout,"                     and that packet onwards, up to the next packet spec\n");
+       fprintf(stdout,"                     or to the last packet in the last tilepart in the stream\n");
+       fprintf(stdout,"                     (max. %d specs)\n", JPWL_MAX_NO_PACKSPECS);
+       fprintf(stdout,"\n");
+       fprintf(stdout,"                 s enables sensitivity data insertion (ESD): 'method' can be\n");
+       fprintf(stdout,"                   [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR\n");
+       fprintf(stdout,"                    4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED]\n");
+       fprintf(stdout,"                   if 'tilepart' is absent, it is for main header only\n");
+       fprintf(stdout,"                   if 'tilepart' is present, it applies from that tile\n");
+       fprintf(stdout,"                     onwards, up to the next s<> spec, or to the last tilepart\n");
+       fprintf(stdout,"                     in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);
+       fprintf(stdout,"\n");
+       fprintf(stdout,"                 g determines the addressing mode: <range> can be\n");
+       fprintf(stdout,"                   [0=PACKET 1=BYTE RANGE 2=PACKET RANGE]\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"                 a determines the size of data addressing: <addr> can be\n");
+       fprintf(stdout,"                   2/4 bytes (small/large codestreams). If not set, auto-mode\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"                 z determines the size of sensitivity values: <size> can be\n");
+       fprintf(stdout,"                   1/2 bytes, for the transformed pseudo-floating point value\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"                 ex.:\n");
+       fprintf(stdout,"                   h,h0=64,h3=16,h5=32,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,\n");
+       fprintf(stdout,"                     s0=6,s3=-1,a=0,g=1,z=1\n");
+       fprintf(stdout,"                 means\n");
+       fprintf(stdout,"                   predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2,\n");
+       fprintf(stdout,"                   CRC-16 in TPH 3 and TPH 4, CRC-32 in remaining TPHs,\n");
+       fprintf(stdout,"                   UEP rs(78,32) for packets 0 to 23 of tile 0,\n");
+       fprintf(stdout,"                   UEP rs(56,32) for packs. 24 to the last of tilepart 0,\n");
+       fprintf(stdout,"                   UEP rs default for packets of tilepart 1,\n");
+       fprintf(stdout,"                   no UEP for packets 0 to 19 of tilepart 3,\n");
+       fprintf(stdout,"                   UEP CRC-32 for packs. 20 of tilepart 3 to last tilepart,\n");
+       fprintf(stdout,"                   relative sensitivity ESD for MH,\n");
+       fprintf(stdout,"                   TSE ESD from TPH 0 to TPH 2, byte range with automatic\n");
+       fprintf(stdout,"                   size of addresses and 1 byte for each sensitivity value\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"                 ex.:\n");
+       fprintf(stdout,"                       h,s,p\n");
+       fprintf(stdout,"                 means\n");
+       fprintf(stdout,"                   default protection to headers (MH and TPHs) as well as\n");
+       fprintf(stdout,"                   data packets, one ESD in MH\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"                 N.B.: use the following recommendations when specifying\n");
+       fprintf(stdout,"                       the JPWL parameters list\n");
+       fprintf(stdout,"                   - when you use UEP, always pair the 'p' option with 'h'\n");
+       fprintf(stdout,"                 \n");
+#endif /* USE_JPWL */
+/* <<UniPG */
+       fprintf(stdout,"IMPORTANT:\n");
+       fprintf(stdout,"-----------\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"The index file has the structure below:\n");
+       fprintf(stdout,"---------------------------------------\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"Image_height Image_width\n");
+       fprintf(stdout,"progression order\n");
+       fprintf(stdout,"Tiles_size_X Tiles_size_Y\n");
+       fprintf(stdout,"Tiles_nb_X Tiles_nb_Y\n");
+       fprintf(stdout,"Components_nb\n");
+       fprintf(stdout,"Layers_nb\n");
+       fprintf(stdout,"decomposition_levels\n");
+       fprintf(stdout,"[Precincts_size_X_res_Nr Precincts_size_Y_res_Nr]...\n");
+       fprintf(stdout,"   [Precincts_size_X_res_0 Precincts_size_Y_res_0]\n");
+       fprintf(stdout,"Main_header_start_position\n");
+       fprintf(stdout,"Main_header_end_position\n");
+       fprintf(stdout,"Codestream_size\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"INFO ON TILES\n");
+       fprintf(stdout,"tileno start_pos end_hd end_tile nbparts disto nbpix disto/nbpix\n");
+       fprintf(stdout,"Tile_0 start_pos end_Theader end_pos NumParts TotalDisto NumPix MaxMSE\n");
+       fprintf(stdout,"Tile_1   ''           ''        ''        ''       ''    ''      ''\n");
+       fprintf(stdout,"...\n");
+       fprintf(stdout,"Tile_Nt   ''           ''        ''        ''       ''    ''     ''\n");
+       fprintf(stdout,"...\n");
+       fprintf(stdout,"TILE 0 DETAILS\n");
+       fprintf(stdout,"part_nb tileno num_packs start_pos end_tph_pos end_pos\n");
+       fprintf(stdout,"...\n");
+       fprintf(stdout,"Progression_string\n");
+       fprintf(stdout,"pack_nb tileno layno resno compno precno start_pos end_ph_pos end_pos disto\n");
+       fprintf(stdout,"Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");
+       fprintf(stdout,"...\n");
+       fprintf(stdout,"Tpacket_Np ''   ''    ''   ''    ''       ''       ''     ''\n");
+
+       fprintf(stdout,"MaxDisto\n");
+
+       fprintf(stdout,"TotalDisto\n\n");
+}
+
+OPJ_PROG_ORDER give_progression(char progression[4]) {
+       if(strncmp(progression, "LRCP", 4) == 0) {
+               return LRCP;
+       }
+       if(strncmp(progression, "RLCP", 4) == 0) {
+               return RLCP;
+       }
+       if(strncmp(progression, "RPCL", 4) == 0) {
+               return RPCL;
+       }
+       if(strncmp(progression, "PCRL", 4) == 0) {
+               return PCRL;
+       }
+       if(strncmp(progression, "CPRL", 4) == 0) {
+               return CPRL;
+       }
+
+       return PROG_UNKNOWN;
+}
+
+int get_num_images(char *imgdirpath){
+       DIR *dir;
+       struct dirent* content;
+       int num_images = 0;
+
+       /*Reading the input images from given input directory*/
+
+       dir= opendir(imgdirpath);
+       if(!dir){
+               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
+               return 0;
+       }
+
+       num_images=0;
+       while((content=readdir(dir))!=NULL){
+               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
+                       continue;
+               num_images++;
+       }
+       return num_images;
+}
+
+int load_images(dircnt_t *dirptr, char *imgdirpath){
+       DIR *dir;
+       struct dirent* content;
+       int i = 0;
+
+       /*Reading the input images from given input directory*/
+
+       dir= opendir(imgdirpath);
+       if(!dir){
+               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
+               return 1;
+       }else   {
+               fprintf(stderr,"Folder opened successfully\n");
+       }
+
+       while((content=readdir(dir))!=NULL){
+               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
+                       continue;
+
+               strcpy(dirptr->filename[i],content->d_name);
+               i++;
+       }
+       return 0;
+}
+
+int get_file_format(char *filename) {
+       unsigned int i;
+       static const char *extension[] = {
+    "pgx", "pnm", "pgm", "ppm", "pbm", "pam", "bmp", "tif", "raw", "tga", "png", "j2k", "jp2", "j2c", "jpc"
+    };
+       static const int format[] = {
+    PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, TGA_DFMT, PNG_DFMT, J2K_CFMT, JP2_CFMT, J2K_CFMT, J2K_CFMT
+    };
+       char * ext = strrchr(filename, '.');
+       if (ext == NULL)
+               return -1;
+       ext++;
+       for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
+               if(_strnicmp(ext, extension[i], 3) == 0) {
+                       return format[i];
+               }
+       }
+       return -1;
+}
+
+char * get_file_name(char *name){
+       char *fname;
+       fname= (char*)malloc(OPJ_PATH_LEN*sizeof(char));
+       fname= strtok(name,".");
+       return fname;
+}
+
+char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_cparameters_t *parameters){
+       char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
+  char *temp_p, temp1[OPJ_PATH_LEN]="";
+
+       strcpy(image_filename,dirptr->filename[imageno]);
+       fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
+       parameters->decod_format = get_file_format(image_filename);
+       if (parameters->decod_format == -1)
+               return 1;
+       sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
+       strncpy(parameters->infile, infilename, sizeof(infilename));
+
+       //Set output file
+       strcpy(temp_ofname,get_file_name(image_filename));
+       while((temp_p = strtok(NULL,".")) != NULL){
+               strcat(temp_ofname,temp1);
+               sprintf(temp1,".%s",temp_p);
+       }
+       if(img_fol->set_out_format==1){
+               sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
+               strncpy(parameters->outfile, outfilename, sizeof(outfilename));
+       }
+ return 0;
+}
+
+static int initialise_4K_poc(opj_poc_t *POC, int numres){
+       POC[0].tile  = 1;
+       POC[0].resno0  = 0;
+       POC[0].compno0 = 0;
+       POC[0].layno1  = 1;
+       POC[0].resno1  = numres-1;
+       POC[0].compno1 = 3;
+       POC[0].prg1 = CPRL;
+       POC[1].tile  = 1;
+       POC[1].resno0  = numres-1;
+       POC[1].compno0 = 0;
+       POC[1].layno1  = 1;
+       POC[1].resno1  = numres;
+       POC[1].compno1 = 3;
+       POC[1].prg1 = CPRL;
+       return 2;
+}
+
+void cinema_parameters(opj_cparameters_t *parameters){
+       parameters->tile_size_on = false;
+       parameters->cp_tdx=1;
+       parameters->cp_tdy=1;
+
+       /*Tile part*/
+       parameters->tp_flag = 'C';
+       parameters->tp_on = 1;
+
+       /*Tile and Image shall be at (0,0)*/
+       parameters->cp_tx0 = 0;
+       parameters->cp_ty0 = 0;
+       parameters->image_offset_x0 = 0;
+       parameters->image_offset_y0 = 0;
+
+       /*Codeblock size= 32*32*/
+       parameters->cblockw_init = 32;
+       parameters->cblockh_init = 32;
+       parameters->csty |= 0x01;
+
+       /*The progression order shall be CPRL*/
+       parameters->prog_order = CPRL;
+
+       /* No ROI */
+       parameters->roi_compno = -1;
+
+       parameters->subsampling_dx = 1;         parameters->subsampling_dy = 1;
+
+       /* 9-7 transform */
+       parameters->irreversible = 1;
+
+}
+
+void cinema_setup_encoder(opj_cparameters_t *parameters,opj_image_t *image, img_fol_t *img_fol){
+       int i;
+       float temp_rate;
+
+       switch (parameters->cp_cinema){
+       case CINEMA2K_24:
+       case CINEMA2K_48:
+               if(parameters->numresolution > 6){
+                       parameters->numresolution = 6;
+               }
+               if (!((image->comps[0].w == 2048) | (image->comps[0].h == 1080))){
+                       fprintf(stdout,"Image coordinates %d x %d is not 2K compliant.\nJPEG Digital Cinema Profile-3 "
+                               "(2K profile) compliance requires that at least one of coordinates match 2048 x 1080\n",
+                               image->comps[0].w,image->comps[0].h);
+                       parameters->cp_rsiz = STD_RSIZ;
+               }
+       break;
+
+       case CINEMA4K_24:
+               if(parameters->numresolution < 1){
+                               parameters->numresolution = 1;
+                       }else if(parameters->numresolution > 7){
+                               parameters->numresolution = 7;
+                       }
+               if (!((image->comps[0].w == 4096) | (image->comps[0].h == 2160))){
+                       fprintf(stdout,"Image coordinates %d x %d is not 4K compliant.\nJPEG Digital Cinema Profile-4"
+                               "(4K profile) compliance requires that at least one of coordinates match 4096 x 2160\n",
+                               image->comps[0].w,image->comps[0].h);
+                       parameters->cp_rsiz = STD_RSIZ;
+               }
+               parameters->numpocs = initialise_4K_poc(parameters->POC,parameters->numresolution);
+               break;
+       default :
+               break;
+       }
+
+       switch (parameters->cp_cinema){
+               case CINEMA2K_24:
+               case CINEMA4K_24:
+                       for(i=0 ; i<parameters->tcp_numlayers ; i++){
+                               temp_rate = 0 ;
+                               if (img_fol->rates[i]== 0){
+                                       parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
+                                       (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);
+                               }else{
+                                       temp_rate =((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
+                                               (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy);
+                                       if (temp_rate > CINEMA_24_CS ){
+                                               parameters->tcp_rates[i]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
+                                               (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);
+                                       }else{
+                                               parameters->tcp_rates[i]= img_fol->rates[i];
+                                       }
+                               }
+                       }
+                       parameters->max_comp_size = COMP_24_CS;
+                       break;
+
+               case CINEMA2K_48:
+                       for(i=0 ; i<parameters->tcp_numlayers ; i++){
+                               temp_rate = 0 ;
+                               if (img_fol->rates[i]== 0){
+                                       parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
+                                       (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);
+                               }else{
+                                       temp_rate =((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
+                                               (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy);
+                                       if (temp_rate > CINEMA_48_CS ){
+                                               parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
+                                               (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);
+                                       }else{
+                                               parameters->tcp_rates[i]= img_fol->rates[i];
+                                       }
+                               }
+                       }
+                       parameters->max_comp_size = COMP_48_CS;
+                       break;
+               default:
+                       break;
+       }
+       parameters->cp_disto_alloc = 1;
+}
+
+/* ------------------------------------------------------------------------------------ */
+
+int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *parameters,
+                                                                                                       img_fol_t *img_fol, raw_cparameters_t *raw_cp, char *indexfilename) {
+       int i, j,totlen;
+       option_t long_option[]={
+               {"cinema2K",REQ_ARG, NULL ,'w'},
+               {"cinema4K",NO_ARG, NULL ,'y'},
+               {"ImgDir",REQ_ARG, NULL ,'z'},
+               {"TP",REQ_ARG, NULL ,'v'},
+               {"SOP",NO_ARG, NULL ,'S'},
+               {"EPH",NO_ARG, NULL ,'E'},
+               {"OutFor",REQ_ARG, NULL ,'O'},
+               {"POC",REQ_ARG, NULL ,'P'},
+               {"ROI",REQ_ARG, NULL ,'R'},
+       };
+
+       /* parse the command line */
+       const char optlist[] = "i:o:r:q:n:b:c:t:p:s:SEM:x:R:d:T:If:P:C:F:"
+#ifdef USE_JPWL
+               "W:"
+#endif /* USE_JPWL */
+               "h";
+
+       totlen=sizeof(long_option);
+       img_fol->set_out_format=0;
+       raw_cp->rawWidth = 0;
+
+       while (1) {
+    int c = getopt_long(argc, argv, optlist,long_option,totlen);
+               if (c == -1)
+                       break;
+               switch (c) {
+                       case 'i':                       /* input file */
+                       {
+                               char *infile = optarg;
+                               parameters->decod_format = get_file_format(infile);
+                               switch(parameters->decod_format) {
+                                       case PGX_DFMT:
+                                       case PXM_DFMT:
+                                       case BMP_DFMT:
+                                       case TIF_DFMT:
+                                       case RAW_DFMT:
+                                       case TGA_DFMT:
+                                       case PNG_DFMT:
+                                               break;
+                                       default:
+                                               fprintf(stderr,
+                                                       "!! Unrecognized format for infile : %s "
+              "[accept only *.pnm, *.pgm, *.ppm, *.pgx, *png, *.bmp, *.tif, *.raw or *.tga] !!\n\n",
+                                                       infile);
+                                               return 1;
+                               }
+                               strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+
+                       case 'o':                       /* output file */
+                       {
+                               char *outfile = optarg;
+                               parameters->cod_format = get_file_format(outfile);
+                               switch(parameters->cod_format) {
+                                       case J2K_CFMT:
+                                       case JP2_CFMT:
+                                               break;
+                                       default:
+                                               fprintf(stderr, "Unknown output format image %s [only *.j2k, *.j2c or *.jp2]!! \n", outfile);
+                                               return 1;
+                               }
+                               strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+                       case 'O':                       /* output format */
+                               {
+                                       char outformat[50];
+                                       char *of = optarg;
+                                       sprintf(outformat,".%s",of);
+                                       img_fol->set_out_format = 1;
+                                       parameters->cod_format = get_file_format(outformat);
+                                       switch(parameters->cod_format) {
+                                               case J2K_CFMT:
+                                               case JP2_CFMT:
+                                                       img_fol->out_format = optarg;
+                                                       break;
+                                               default:
+                                                       fprintf(stderr, "Unknown output format image [only j2k, j2c, jp2]!! \n");
+                                                       return 1;
+                                       }
+                               }
+                               break;
+
+
+                               /* ----------------------------------------------------- */
+
+
+                       case 'r':                       /* rates rates/distorsion */
+                       {
+                               char *s = optarg;
+                               parameters->tcp_numlayers = 0;
+                               while (sscanf(s, "%f", &parameters->tcp_rates[parameters->tcp_numlayers]) == 1) {
+                                       parameters->tcp_numlayers++;
+                                       while (*s && *s != ',') {
+                                               s++;
+                                       }
+                                       if (!*s)
+                                               break;
+                                       s++;
+                               }
+                               parameters->cp_disto_alloc = 1;
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+
+
+                       case 'F':                       /* Raw image format parameters */
+                       {
+                               char signo;
+                               char *s = optarg;
+                               if (sscanf(s, "%d,%d,%d,%d,%c", &raw_cp->rawWidth, &raw_cp->rawHeight, &raw_cp->rawComp, &raw_cp->rawBitDepth, &signo) == 5) {
+                                       if (signo == 's') {
+                                               raw_cp->rawSigned = true;
+                                               fprintf(stdout,"\nRaw file parameters: %d,%d,%d,%d Signed\n", raw_cp->rawWidth, raw_cp->rawHeight, raw_cp->rawComp, raw_cp->rawBitDepth);
+                                       }
+                                       else if (signo == 'u') {
+                                               raw_cp->rawSigned = false;
+                                               fprintf(stdout,"\nRaw file parameters: %d,%d,%d,%d Unsigned\n", raw_cp->rawWidth, raw_cp->rawHeight, raw_cp->rawComp, raw_cp->rawBitDepth);
+                                       }
+                                       else {
+                                               fprintf(stderr,"\nError: invalid raw image parameters: Unknown sign of raw file\n");
+                                               fprintf(stderr,"Please use the Format option -F:\n");
+                                               fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
+                                               fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
+                                               fprintf(stderr,"Aborting\n");
+                                       }
+                               }
+                               else {
+                                       fprintf(stderr,"\nError: invalid raw image parameters\n");
+                                       fprintf(stderr,"Please use the Format option -F:\n");
+                                       fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
+                                               fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
+                                       fprintf(stderr,"Aborting\n");
+                                       return 1;
+                               }
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+
+                       case 'q':                       /* add fixed_quality */
+                       {
+                               char *s = optarg;
+                               while (sscanf(s, "%f", &parameters->tcp_distoratio[parameters->tcp_numlayers]) == 1) {
+                                       parameters->tcp_numlayers++;
+                                       while (*s && *s != ',') {
+                                               s++;
+                                       }
+                                       if (!*s)
+                                               break;
+                                       s++;
+                               }
+                               parameters->cp_fixed_quality = 1;
+                       }
+                       break;
+
+                               /* dda */
+                               /* ----------------------------------------------------- */
+
+                       case 'f':                       /* mod fixed_quality (before : -q) */
+                       {
+                               int *row = NULL, *col = NULL;
+                               int numlayers = 0, numresolution = 0, matrix_width = 0;
+
+                               char *s = optarg;
+                               sscanf(s, "%d", &numlayers);
+                               s++;
+                               if (numlayers > 9)
+                                       s++;
+
+                               parameters->tcp_numlayers = numlayers;
+                               numresolution = parameters->numresolution;
+                               matrix_width = numresolution * 3;
+                               parameters->cp_matrice = (int *) malloc(numlayers * matrix_width * sizeof(int));
+                               s = s + 2;
+
+                               for (i = 0; i < numlayers; i++) {
+                                       row = &parameters->cp_matrice[i * matrix_width];
+                                       col = row;
+                                       parameters->tcp_rates[i] = 1;
+                                       sscanf(s, "%d,", &col[0]);
+                                       s += 2;
+                                       if (col[0] > 9)
+                                               s++;
+                                       col[1] = 0;
+                                       col[2] = 0;
+                                       for (j = 1; j < numresolution; j++) {
+                                               col += 3;
+                                               sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);
+                                               s += 6;
+                                               if (col[0] > 9)
+                                                       s++;
+                                               if (col[1] > 9)
+                                                       s++;
+                                               if (col[2] > 9)
+                                                       s++;
+                                       }
+                                       if (i < numlayers - 1)
+                                               s++;
+                               }
+                               parameters->cp_fixed_alloc = 1;
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+
+                       case 't':                       /* tiles */
+                       {
+                               sscanf(optarg, "%d,%d", &parameters->cp_tdx, &parameters->cp_tdy);
+                               parameters->tile_size_on = true;
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+
+                       case 'n':                       /* resolution */
+                       {
+                               sscanf(optarg, "%d", &parameters->numresolution);
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+                       case 'c':                       /* precinct dimension */
+                       {
+                               char sep;
+                               int res_spec = 0;
+
+                               char *s = optarg;
+                               do {
+                                       sep = 0;
+                                       sscanf(s, "[%d,%d]%c", &parameters->prcw_init[res_spec],
+                                 &parameters->prch_init[res_spec], &sep);
+                                       parameters->csty |= 0x01;
+                                       res_spec++;
+                                       s = strpbrk(s, "]") + 2;
+                               }
+                               while (sep == ',');
+                               parameters->res_spec = res_spec;
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+
+                       case 'b':                       /* code-block dimension */
+                       {
+                               int cblockw_init = 0, cblockh_init = 0;
+                               sscanf(optarg, "%d,%d", &cblockw_init, &cblockh_init);
+                               if (cblockw_init * cblockh_init > 4096 || cblockw_init > 1024
+                                       || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {
+                                       fprintf(stderr,
+                                               "!! Size of code_block error (option -b) !!\n\nRestriction :\n"
+            "    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");
+                                       return 1;
+                               }
+                               parameters->cblockw_init = cblockw_init;
+                               parameters->cblockh_init = cblockh_init;
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+
+                       case 'x':                       /* creation of index file */
+                       {
+                               char *index = optarg;
+                               strncpy(indexfilename, index, OPJ_PATH_LEN);
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+
+                       case 'p':                       /* progression order */
+                       {
+                               char progression[4];
+
+                               strncpy(progression, optarg, 4);
+                               parameters->prog_order = give_progression(progression);
+                               if (parameters->prog_order == -1) {
+                                       fprintf(stderr, "Unrecognized progression order "
+            "[LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
+                                       return 1;
+                               }
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+
+                       case 's':                       /* subsampling factor */
+                       {
+                               if (sscanf(optarg, "%d,%d", &parameters->subsampling_dx,
+                                    &parameters->subsampling_dy) != 2) {
+                                       fprintf(stderr, "'-s' sub-sampling argument error !  [-s dx,dy]\n");
+                                       return 1;
+                               }
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+
+                       case 'd':                       /* coordonnate of the reference grid */
+                       {
+                               if (sscanf(optarg, "%d,%d", &parameters->image_offset_x0,
+                                    &parameters->image_offset_y0) != 2) {
+                                       fprintf(stderr, "-d 'coordonnate of the reference grid' argument "
+            "error !! [-d x0,y0]\n");
+                                       return 1;
+                               }
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+
+                       case 'h':                       /* display an help description */
+                               encode_help_display();
+                               return 1;
+
+                               /* ----------------------------------------------------- */
+
+                       case 'P':                       /* POC */
+                       {
+                               int numpocs = 0;                /* number of progression order change (POC) default 0 */
+                               opj_poc_t *POC = NULL;  /* POC : used in case of Progression order change */
+
+                               char *s = optarg;
+                               POC = parameters->POC;
+
+                               while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%4s", &POC[numpocs].tile,
+                                       &POC[numpocs].resno0, &POC[numpocs].compno0,
+                                       &POC[numpocs].layno1, &POC[numpocs].resno1,
+                                       &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
+                                       POC[numpocs].prg1 = give_progression(POC[numpocs].progorder);
+                                       numpocs++;
+                                       while (*s && *s != '/') {
+                                               s++;
+                                       }
+                                       if (!*s) {
+                                               break;
+                                       }
+                                       s++;
+                               }
+                               parameters->numpocs = numpocs;
+                       }
+                       break;
+
+                               /* ------------------------------------------------------ */
+
+                       case 'S':                       /* SOP marker */
+                       {
+                               parameters->csty |= 0x02;
+                       }
+                       break;
+
+                               /* ------------------------------------------------------ */
+
+                       case 'E':                       /* EPH marker */
+                       {
+                               parameters->csty |= 0x04;
+                       }
+                       break;
+
+                               /* ------------------------------------------------------ */
+
+                       case 'M':                       /* Mode switch pas tous au point !! */
+                       {
+                               int value = 0;
+                               if (sscanf(optarg, "%d", &value) == 1) {
+                                       for (i = 0; i <= 5; i++) {
+                                               int cache = value & (1 << i);
+                                               if (cache)
+                                                       parameters->mode |= (1 << i);
+                                       }
+                               }
+                       }
+                       break;
+
+                               /* ------------------------------------------------------ */
+
+                       case 'R':                       /* ROI */
+                       {
+                               if (sscanf(optarg, "c=%d,U=%d", &parameters->roi_compno,
+                                           &parameters->roi_shift) != 2) {
+                                       fprintf(stderr, "ROI error !! [-ROI c='compno',U='shift']\n");
+                                       return 1;
+                               }
+                       }
+                       break;
+
+                               /* ------------------------------------------------------ */
+
+                       case 'T':                       /* Tile offset */
+                       {
+                               if (sscanf(optarg, "%d,%d", &parameters->cp_tx0, &parameters->cp_ty0) != 2) {
+                                       fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");
+                                       return 1;
+                               }
+                       }
+                       break;
+
+                               /* ------------------------------------------------------ */
+
+                       case 'C':                       /* add a comment */
+                       {
+                               parameters->cp_comment = (char*)malloc(strlen(optarg) + 1);
+                               if(parameters->cp_comment) {
+                                       strcpy(parameters->cp_comment, optarg);
+                               }
+                       }
+                       break;
+
+
+                               /* ------------------------------------------------------ */
+
+                       case 'I':                       /* reversible or not */
+                       {
+                               parameters->irreversible = 1;
+                       }
+                       break;
+
+                       /* ------------------------------------------------------ */
+
+                       case 'v':                       /* Tile part generation*/
+                       {
+                               parameters->tp_flag = optarg[0];
+                               parameters->tp_on = 1;
+                       }
+                       break;
+
+                               /* ------------------------------------------------------ */
+
+                       case 'z':                       /* Image Directory path */
+                       {
+                               img_fol->imgdirpath = (char*)malloc(strlen(optarg) + 1);
+                               strcpy(img_fol->imgdirpath,optarg);
+                               img_fol->set_imgdir=1;
+                       }
+                       break;
+
+                               /* ------------------------------------------------------ */
+
+                       case 'w':                       /* Digital Cinema 2K profile compliance*/
+                       {
+                               int fps=0;
+                               sscanf(optarg,"%d",&fps);
+                               if(fps == 24){
+                                       parameters->cp_cinema = CINEMA2K_24;
+                               }else if(fps == 48 ){
+                                       parameters->cp_cinema = CINEMA2K_48;
+                               }else {
+                                       fprintf(stderr,"Incorrect value!! must be 24 or 48\n");
+                                       return 1;
+                               }
+                               fprintf(stdout,"CINEMA 2K compliant codestream\n");
+                               parameters->cp_rsiz = CINEMA2K;
+
+                       }
+                       break;
+
+                               /* ------------------------------------------------------ */
+
+                       case 'y':                       /* Digital Cinema 4K profile compliance*/
+                       {
+                               parameters->cp_cinema = CINEMA4K_24;
+                               fprintf(stdout,"CINEMA 4K compliant codestream\n");
+                               parameters->cp_rsiz = CINEMA4K;
+                       }
+                       break;
+
+                               /* ------------------------------------------------------ */
+
+/* UniPG>> */
+#ifdef USE_JPWL
+                               /* ------------------------------------------------------ */
+
+                       case 'W':                       /* JPWL capabilities switched on */
+                       {
+                               char *token = NULL;
+                               int hprot, pprot, sens, addr, size, range;
+
+                               /* we need to enable indexing */
+                               if (!indexfilename || !*indexfilename) {
+                                       strncpy(indexfilename, JPWL_PRIVATEINDEX_NAME, OPJ_PATH_LEN);
+                               }
+
+                               /* search for different protection methods */
+
+                               /* break the option in comma points and parse the result */
+                               token = strtok(optarg, ",");
+                               while(token != NULL) {
+
+                                       /* search header error protection method */
+                                       if (*token == 'h') {
+
+                                               static int tile = 0, tilespec = 0, lasttileno = 0;
+
+                                               hprot = 1; /* predefined method */
+
+                                               if(sscanf(token, "h=%d", &hprot) == 1) {
+                                                       /* Main header, specified */
+                                                       if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
+                                                               ((hprot >= 37) && (hprot <= 128)))) {
+                                                               fprintf(stderr, "ERROR -> invalid main header protection method h = %d\n", hprot);
+                                                               return 1;
+                                                       }
+                                                       parameters->jpwl_hprot_MH = hprot;
+
+                                               } else if(sscanf(token, "h%d=%d", &tile, &hprot) == 2) {
+                                                       /* Tile part header, specified */
+                                                       if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
+                                                               ((hprot >= 37) && (hprot <= 128)))) {
+                                                               fprintf(stderr, "ERROR -> invalid tile part header protection method h = %d\n", hprot);
+                                                               return 1;
+                                                       }
+                                                       if (tile < 0) {
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method t = %d\n", tile);
+                                                               return 1;
+                                                       }
+                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {
+                                                               parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
+                                                               parameters->jpwl_hprot_TPH[tilespec++] = hprot;
+                                                       }
+
+                                               } else if(sscanf(token, "h%d", &tile) == 1) {
+                                                       /* Tile part header, unspecified */
+                                                       if (tile < 0) {
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method t = %d\n", tile);
+                                                               return 1;
+                                                       }
+                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {
+                                                               parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
+                                                               parameters->jpwl_hprot_TPH[tilespec++] = hprot;
+                                                       }
+
+
+                                               } else if (!strcmp(token, "h")) {
+                                                       /* Main header, unspecified */
+                                                       parameters->jpwl_hprot_MH = hprot;
+
+                                               } else {
+                                                       fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
+                                                       return 1;
+                                               };
+
+                                       }
+
+                                       /* search packet error protection method */
+                                       if (*token == 'p') {
+
+                                               static int pack = 0, tile = 0, packspec = 0;
+
+                                               pprot = 1; /* predefined method */
+
+                                               if (sscanf(token, "p=%d", &pprot) == 1) {
+                                                       /* Method for all tiles and all packets */
+                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
+                                                               ((pprot >= 37) && (pprot <= 128)))) {
+                                                               fprintf(stderr, "ERROR -> invalid default packet protection method p = %d\n", pprot);
+                                                               return 1;
+                                                       }
+                                                       parameters->jpwl_pprot_tileno[0] = 0;
+                                                       parameters->jpwl_pprot_packno[0] = 0;
+                                                       parameters->jpwl_pprot[0] = pprot;
+
+                                               } else if (sscanf(token, "p%d=%d", &tile, &pprot) == 2) {
+                                                       /* method specified from that tile on */
+                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
+                                                               ((pprot >= 37) && (pprot <= 128)))) {
+                                                               fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
+                                                               return 1;
+                                                       }
+                                                       if (tile < 0) {
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);
+                                                               return 1;
+                                                       }
+                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {
+                                                               parameters->jpwl_pprot_tileno[packspec] = tile;
+                                                               parameters->jpwl_pprot_packno[packspec] = 0;
+                                                               parameters->jpwl_pprot[packspec++] = pprot;
+                                                       }
+
+                                               } else if (sscanf(token, "p%d:%d=%d", &tile, &pack, &pprot) == 3) {
+                                                       /* method fully specified from that tile and that packet on */
+                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
+                                                               ((pprot >= 37) && (pprot <= 128)))) {
+                                                               fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
+                                                               return 1;
+                                                       }
+                                                       if (tile < 0) {
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);
+                                                               return 1;
+                                                       }
+                                                       if (pack < 0) {
+                                                               fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n", pack);
+                                                               return 1;
+                                                       }
+                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {
+                                                               parameters->jpwl_pprot_tileno[packspec] = tile;
+                                                               parameters->jpwl_pprot_packno[packspec] = pack;
+                                                               parameters->jpwl_pprot[packspec++] = pprot;
+                                                       }
+
+                                               } else if (sscanf(token, "p%d:%d", &tile, &pack) == 2) {
+                                                       /* default method from that tile and that packet on */
+                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
+                                                               ((pprot >= 37) && (pprot <= 128)))) {
+                                                               fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
+                                                               return 1;
+                                                       }
+                                                       if (tile < 0) {
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);
+                                                               return 1;
+                                                       }
+                                                       if (pack < 0) {
+                                                               fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n", pack);
+                                                               return 1;
+                                                       }
+                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {
+                                                               parameters->jpwl_pprot_tileno[packspec] = tile;
+                                                               parameters->jpwl_pprot_packno[packspec] = pack;
+                                                               parameters->jpwl_pprot[packspec++] = pprot;
+                                                       }
+
+                                               } else if (sscanf(token, "p%d", &tile) == 1) {
+                                                       /* default from a tile on */
+                                                       if (tile < 0) {
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);
+                                                               return 1;
+                                                       }
+                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {
+                                                               parameters->jpwl_pprot_tileno[packspec] = tile;
+                                                               parameters->jpwl_pprot_packno[packspec] = 0;
+                                                               parameters->jpwl_pprot[packspec++] = pprot;
+                                                       }
+
+
+                                               } else if (!strcmp(token, "p")) {
+                                                       /* all default */
+                                                       parameters->jpwl_pprot_tileno[0] = 0;
+                                                       parameters->jpwl_pprot_packno[0] = 0;
+                                                       parameters->jpwl_pprot[0] = pprot;
+
+                                               } else {
+                                                       fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
+                                                       return 1;
+                                               };
+
+                                       }
+
+                                       /* search sensitivity method */
+                                       if (*token == 's') {
+
+                                               static int tile = 0, tilespec = 0, lasttileno = 0;
+
+                                               sens = 0; /* predefined: relative error */
+
+                                               if(sscanf(token, "s=%d", &sens) == 1) {
+                                                       /* Main header, specified */
+                                                       if ((sens < -1) || (sens > 7)) {
+                                                               fprintf(stderr, "ERROR -> invalid main header sensitivity method s = %d\n", sens);
+                                                               return 1;
+                                                       }
+                                                       parameters->jpwl_sens_MH = sens;
+
+                                               } else if(sscanf(token, "s%d=%d", &tile, &sens) == 2) {
+                                                       /* Tile part header, specified */
+                                                       if ((sens < -1) || (sens > 7)) {
+                                                               fprintf(stderr, "ERROR -> invalid tile part header sensitivity method s = %d\n", sens);
+                                                               return 1;
+                                                       }
+                                                       if (tile < 0) {
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);
+                                                               return 1;
+                                                       }
+                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {
+                                                               parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
+                                                               parameters->jpwl_sens_TPH[tilespec++] = sens;
+                                                       }
+
+                                               } else if(sscanf(token, "s%d", &tile) == 1) {
+                                                       /* Tile part header, unspecified */
+                                                       if (tile < 0) {
+                                                               fprintf(stderr, "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);
+                                                               return 1;
+                                                       }
+                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {
+                                                               parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
+                                                               parameters->jpwl_sens_TPH[tilespec++] = hprot;
+                                                       }
+
+                                               } else if (!strcmp(token, "s")) {
+                                                       /* Main header, unspecified */
+                                                       parameters->jpwl_sens_MH = sens;
+
+                                               } else {
+                                                       fprintf(stderr, "ERROR -> invalid sensitivity method selection = %s\n", token);
+                                                       return 1;
+                                               };
+
+                                               parameters->jpwl_sens_size = 2; /* 2 bytes for default size */
+                                       }
+
+                                       /* search addressing size */
+                                       if (*token == 'a') {
+
+
+                                               addr = 0; /* predefined: auto */
+
+                                               if(sscanf(token, "a=%d", &addr) == 1) {
+                                                       /* Specified */
+                                                       if ((addr != 0) && (addr != 2) && (addr != 4)) {
+                                                               fprintf(stderr, "ERROR -> invalid addressing size a = %d\n", addr);
+                                                               return 1;
+                                                       }
+                                                       parameters->jpwl_sens_addr = addr;
+
+                                               } else if (!strcmp(token, "a")) {
+                                                       /* default */
+                                                       parameters->jpwl_sens_addr = addr; /* auto for default size */
+
+                                               } else {
+                                                       fprintf(stderr, "ERROR -> invalid addressing selection = %s\n", token);
+                                                       return 1;
+                                               };
+
+                                       }
+
+                                       /* search sensitivity size */
+                                       if (*token == 'z') {
+
+
+                                               size = 1; /* predefined: 1 byte */
+
+                                               if(sscanf(token, "z=%d", &size) == 1) {
+                                                       /* Specified */
+                                                       if ((size != 0) && (size != 1) && (size != 2)) {
+                                                               fprintf(stderr, "ERROR -> invalid sensitivity size z = %d\n", size);
+                                                               return 1;
+                                                       }
+                                                       parameters->jpwl_sens_size = size;
+
+                                               } else if (!strcmp(token, "a")) {
+                                                       /* default */
+                                                       parameters->jpwl_sens_size = size; /* 1 for default size */
+
+                                               } else {
+                                                       fprintf(stderr, "ERROR -> invalid size selection = %s\n", token);
+                                                       return 1;
+                                               };
+
+                                       }
+
+                                       /* search range method */
+                                       if (*token == 'g') {
+
+
+                                               range = 0; /* predefined: 0 (packet) */
+
+                                               if(sscanf(token, "g=%d", &range) == 1) {
+                                                       /* Specified */
+                                                       if ((range < 0) || (range > 3)) {
+                                                               fprintf(stderr, "ERROR -> invalid sensitivity range method g = %d\n", range);
+                                                               return 1;
+                                                       }
+                                                       parameters->jpwl_sens_range = range;
+
+                                               } else if (!strcmp(token, "g")) {
+                                                       /* default */
+                                                       parameters->jpwl_sens_range = range;
+
+                                               } else {
+                                                       fprintf(stderr, "ERROR -> invalid range selection = %s\n", token);
+                                                       return 1;
+                                               };
+
+                                       }
+
+                                       /* next token or bust */
+                                       token = strtok(NULL, ",");
+                               };
+
+
+                               /* some info */
+                               fprintf(stdout, "Info: JPWL capabilities enabled\n");
+                               parameters->jpwl_epc_on = true;
+
+                       }
+                       break;
+#endif /* USE_JPWL */
+/* <<UniPG */
+
+                               /* ------------------------------------------------------ */
+
+                       default:
+                               fprintf(stderr, "ERROR -> Command line not valid\n");
+                               return 1;
+               }
+       }
+
+       /* check for possible errors */
+       if (parameters->cp_cinema){
+               if(parameters->tcp_numlayers > 1){
+                       parameters->cp_rsiz = STD_RSIZ;
+       fprintf(stdout,"Warning: DC profiles do not allow more than one quality layer. The codestream created will not be compliant with the DC profile\n");
+               }
+       }
+       if(img_fol->set_imgdir == 1){
+               if(!(parameters->infile[0] == 0)){
+                       fprintf(stderr, "Error: options -ImgDir and -i cannot be used together !!\n");
+                       return 1;
+               }
+               if(img_fol->set_out_format == 0){
+                       fprintf(stderr, "Error: When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
+                       fprintf(stderr, "Only one format allowed! Valid formats are j2k and jp2!!\n");
+                       return 1;
+               }
+               if(!((parameters->outfile[0] == 0))){
+                       fprintf(stderr, "Error: options -ImgDir and -o cannot be used together !!\n");
+                       fprintf(stderr, "Specify OutputFormat using -OutFor<FORMAT> !!\n");
+                       return 1;
+               }
+       }else{
+               if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
+                       fprintf(stderr, "Example: %s -i image.ppm  -o image.j2k\n",argv[0]);
+                       fprintf(stderr, "    Try: %s -h\n",argv[0]);
+                       return 1;
+               }
+       }
+
+       if (parameters->decod_format == RAW_DFMT && raw_cp->rawWidth == 0) {
+                       fprintf(stderr,"\nError: invalid raw image parameters\n");
+                       fprintf(stderr,"Please use the Format option -F:\n");
+                       fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
+                                               fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
+                       fprintf(stderr,"Aborting\n");
+                       return 1;
+       }
+
+       if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc || parameters->cp_fixed_quality)
+               && (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_alloc ^ parameters->cp_fixed_quality))) {
+               fprintf(stderr, "Error: options -r -q and -f cannot be used together !!\n");
+               return 1;
+       }                               /* mod fixed_quality */
+
+       /* if no rate entered, lossless by default */
+       if (parameters->tcp_numlayers == 0) {
+               parameters->tcp_rates[0] = 0;   /* MOD antonin : losslessbug */
+               parameters->tcp_numlayers++;
+               parameters->cp_disto_alloc = 1;
+       }
+
+       if((parameters->cp_tx0 > parameters->image_offset_x0) || (parameters->cp_ty0 > parameters->image_offset_y0)) {
+               fprintf(stderr,
+                       "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
+                       parameters->cp_tx0, parameters->image_offset_x0, parameters->cp_ty0, parameters->image_offset_y0);
+               return 1;
+       }
+
+       for (i = 0; i < parameters->numpocs; i++) {
+               if (parameters->POC[i].prg == -1) {
+                       fprintf(stderr,
+                               "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
+                               i + 1);
+               }
+       }
+
+       return 0;
+}
+
+/* -------------------------------------------------------------------------- */
+
+/**
+sample error callback expecting a FILE* client object
+*/
+void error_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[ERROR] %s", msg);
+}
+/**
+sample warning callback expecting a FILE* client object
+*/
+void warning_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[WARNING] %s", msg);
+}
+/**
+sample debug callback expecting a FILE* client object
+*/
+void info_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[INFO] %s", msg);
+}
+
+/* -------------------------------------------------------------------------- */
+
+int main(int argc, char **argv) {
+       bool bSuccess;
+       opj_cparameters_t parameters;   /* compression parameters */
+       img_fol_t img_fol;
+       opj_event_mgr_t event_mgr;              /* event manager */
+       opj_image_t *image = NULL;
+       int i,num_images;
+       int imageno;
+       dircnt_t *dirptr;
+       raw_cparameters_t raw_cp;
+       opj_codestream_info_t cstr_info;                /* Codestream information structure */
+       char indexfilename[OPJ_PATH_LEN];       /* index file name */
+
+       /*
+       configure the event callbacks (not required)
+       setting of each callback is optionnal
+       */
+       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
+       event_mgr.error_handler = error_callback;
+       event_mgr.warning_handler = warning_callback;
+       event_mgr.info_handler = info_callback;
+
+       /* set encoding parameters to default values */
+       opj_set_default_encoder_parameters(&parameters);
+
+       /* Initialize indexfilename and img_fol */
+       *indexfilename = 0;
+       memset(&img_fol,0,sizeof(img_fol_t));
+
+       /* parse input and get user encoding parameters */
+       if(parse_cmdline_encoder(argc, argv, &parameters,&img_fol, &raw_cp, indexfilename) == 1) {
+               return 1;
+       }
+
+       if (parameters.cp_cinema){
+               img_fol.rates = (float*)malloc(parameters.tcp_numlayers * sizeof(float));
+               for(i=0; i< parameters.tcp_numlayers; i++){
+                       img_fol.rates[i] = parameters.tcp_rates[i];
+               }
+               cinema_parameters(&parameters);
+       }
+
+       /* Create comment for codestream */
+       if(parameters.cp_comment == NULL) {
+    const char comment[] = "Created by OpenJPEG version ";
+               const size_t clen = strlen(comment);
+    const char *version = opj_version();
+/* UniPG>> */
+#ifdef USE_JPWL
+               parameters.cp_comment = (char*)malloc(clen+strlen(version)+11);
+               sprintf(parameters.cp_comment,"%s%s with JPWL", comment, version);
+#else
+               parameters.cp_comment = (char*)malloc(clen+strlen(version)+1);
+               sprintf(parameters.cp_comment,"%s%s", comment, version);
+#endif
+/* <<UniPG */
+       }
+
+       /* Read directory if necessary */
+       if(img_fol.set_imgdir==1){
+               num_images=get_num_images(img_fol.imgdirpath);
+               dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
+               if(dirptr){
+                       dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));     // Stores at max 10 image file names
+                       dirptr->filename = (char**) malloc(num_images*sizeof(char*));
+                       if(!dirptr->filename_buf){
+                               return 0;
+                       }
+                       for(i=0;i<num_images;i++){
+                               dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN;
+                       }
+               }
+               if(load_images(dirptr,img_fol.imgdirpath)==1){
+                       return 0;
+               }
+               if (num_images==0){
+                       fprintf(stdout,"Folder is empty\n");
+                       return 0;
+               }
+       }else{
+               num_images=1;
+       }
+       /*Encoding image one by one*/
+       for(imageno=0;imageno<num_images;imageno++)     {
+               image = NULL;
+               fprintf(stderr,"\n");
+
+               if(img_fol.set_imgdir==1){
+                       if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
+                               fprintf(stderr,"skipping file...\n");
+                               continue;
+                       }
+               }
+               switch(parameters.decod_format) {
+                       case PGX_DFMT:
+                               break;
+                       case PXM_DFMT:
+                               break;
+                       case BMP_DFMT:
+                               break;
+                       case TIF_DFMT:
+                               break;
+                       case RAW_DFMT:
+                               break;
+                       case TGA_DFMT:
+                               break;
+                       case PNG_DFMT:
+                               break;
+                       default:
+                               fprintf(stderr,"skipping file...\n");
+                               continue;
+               }
+
+                       /* decode the source image */
+                       /* ----------------------- */
+
+                       switch (parameters.decod_format) {
+                               case PGX_DFMT:
+                                       image = pgxtoimage(parameters.infile, &parameters);
+                                       if (!image) {
+                                               fprintf(stderr, "Unable to load pgx file\n");
+                                               return 1;
+                                       }
+                                       break;
+
+                               case PXM_DFMT:
+                                       image = pnmtoimage(parameters.infile, &parameters);
+                                       if (!image) {
+                                               fprintf(stderr, "Unable to load pnm file\n");
+                                               return 1;
+                                       }
+                                       break;
+
+                               case BMP_DFMT:
+                                       image = bmptoimage(parameters.infile, &parameters);
+                                       if (!image) {
+                                               fprintf(stderr, "Unable to load bmp file\n");
+                                               return 1;
+                                       }
+                                       break;
+#ifdef HAVE_LIBTIFF
+                               case TIF_DFMT:
+                                       image = tiftoimage(parameters.infile, &parameters);
+                                       if (!image) {
+                                               fprintf(stderr, "Unable to load tiff file\n");
+                                               return 1;
+                                       }
+                               break;
+#endif /* HAVE_LIBTIFF */
+                               case RAW_DFMT:
+                                       image = rawtoimage(parameters.infile, &parameters, &raw_cp);
+                                       if (!image) {
+                                               fprintf(stderr, "Unable to load raw file\n");
+                                               return 1;
+                                       }
+                               break;
+
+                               case TGA_DFMT:
+                                       image = tgatoimage(parameters.infile, &parameters);
+                                       if (!image) {
+                                               fprintf(stderr, "Unable to load tga file\n");
+                                               return 1;
+                                       }
+                               break;
+#ifdef HAVE_LIBPNG
+                               case PNG_DFMT:
+                                       image = pngtoimage(parameters.infile, &parameters);
+                                       if (!image) {
+                                               fprintf(stderr, "Unable to load png file\n");
+                                               return 1;
+                                       }
+                                       break;
+#endif /* HAVE_LIBPNG */
+               }
+/* Can happen if input file is TIFF or PNG 
+ * and HAVE_LIBTIF or HAVE_LIBPNG is undefined
+*/
+                       if( !image)
+                  {
+                       fprintf(stderr, "Unable to load file: got no image\n");
+                       return 1;
+                  }
+                       /* Decide if MCT should be used */
+                       parameters.tcp_mct = image->numcomps == 3 ? 1 : 0;
+
+                       if(parameters.cp_cinema){
+                               cinema_setup_encoder(&parameters,image,&img_fol);
+                       }
+
+                       /* encode the destination image */
+                       /* ---------------------------- */
+
+                       if (parameters.cod_format == J2K_CFMT) {        /* J2K format output */
+                               int codestream_length;
+                               opj_cio_t *cio = NULL;
+                               FILE *f = NULL;
+
+                               /* get a J2K compressor handle */
+                               opj_cinfo_t* cinfo = opj_create_compress(CODEC_J2K);
+
+                               /* catch events using our callbacks and give a local context */
+                               opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
+
+                               /* setup the encoder parameters using the current image and user parameters */
+                               opj_setup_encoder(cinfo, &parameters, image);
+
+                               /* open a byte stream for writing */
+                               /* allocate memory for all tiles */
+                               cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
+
+                               /* encode the image */
+                               if (*indexfilename)                                     // If need to extract codestream information
+                                       bSuccess = opj_encode_with_info(cinfo, cio, image, &cstr_info);
+                               else
+                                       bSuccess = opj_encode(cinfo, cio, image, NULL);
+                               if (!bSuccess) {
+                                       opj_cio_close(cio);
+                                       fprintf(stderr, "failed to encode image\n");
+                                       return 1;
+                               }
+                               codestream_length = cio_tell(cio);
+
+                               /* write the buffer to disk */
+                               f = fopen(parameters.outfile, "wb");
+                               if (!f) {
+                                       fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
+                                       return 1;
+                               }
+                               fwrite(cio->buffer, 1, codestream_length, f);
+                               fclose(f);
+
+                               fprintf(stderr,"Generated outfile %s\n",parameters.outfile);
+                               /* close and free the byte stream */
+                               opj_cio_close(cio);
+
+                               /* Write the index to disk */
+                               if (*indexfilename) {
+                                       bSuccess = write_index_file(&cstr_info, indexfilename);
+                                       if (bSuccess) {
+                                               fprintf(stderr, "Failed to output index file into [%s]\n", indexfilename);
+                                       }
+                               }
+
+                               /* free remaining compression structures */
+                               opj_destroy_compress(cinfo);
+                               if (*indexfilename)
+                                       opj_destroy_cstr_info(&cstr_info);
+                       } else {                        /* JP2 format output */
+                               int codestream_length;
+                               opj_cio_t *cio = NULL;
+                               FILE *f = NULL;
+
+                               /* get a JP2 compressor handle */
+                               opj_cinfo_t* cinfo = opj_create_compress(CODEC_JP2);
+
+                               /* catch events using our callbacks and give a local context */
+                               opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
+
+                               /* setup the encoder parameters using the current image and using user parameters */
+                               opj_setup_encoder(cinfo, &parameters, image);
+
+                               /* open a byte stream for writing */
+                               /* allocate memory for all tiles */
+                               cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
+
+                               /* encode the image */
+                               if (*indexfilename)                                     // If need to extract codestream information
+                                       bSuccess = opj_encode_with_info(cinfo, cio, image, &cstr_info);
+                               else
+                                       bSuccess = opj_encode(cinfo, cio, image, NULL);
+                               if (!bSuccess) {
+                                       opj_cio_close(cio);
+                                       fprintf(stderr, "failed to encode image\n");
+                                       return 1;
+                               }
+                               codestream_length = cio_tell(cio);
+
+                               /* write the buffer to disk */
+                               f = fopen(parameters.outfile, "wb");
+                               if (!f) {
+                                       fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
+                                       return 1;
+                               }
+                               fwrite(cio->buffer, 1, codestream_length, f);
+                               fclose(f);
+                               fprintf(stderr,"Generated outfile %s\n",parameters.outfile);
+                               /* close and free the byte stream */
+                               opj_cio_close(cio);
+
+                               /* Write the index to disk */
+                               if (*indexfilename) {
+                                       bSuccess = write_index_file(&cstr_info, indexfilename);
+                                       if (bSuccess) {
+                                               fprintf(stderr, "Failed to output index file\n");
+                                       }
+                               }
+
+                               /* free remaining compression structures */
+                               opj_destroy_compress(cinfo);
+                               if (*indexfilename)
+                                       opj_destroy_cstr_info(&cstr_info);
+                       }
+
+                       /* free image data */
+                       opj_image_destroy(image);
+       }
+
+       /* free user parameters structure */
+  if(parameters.cp_comment) free(parameters.cp_comment);
+       if(parameters.cp_matrice) free(parameters.cp_matrice);
+
+       return 0;
+}
diff --git a/applications/codec/index.c b/applications/codec/index.c
new file mode 100644 (file)
index 0000000..873b340
--- /dev/null
@@ -0,0 +1,391 @@
+/*\r
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
+ * Copyright (c) 2002-2007, Professor Benoit Macq\r
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux \r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+\r
+#include <stdio.h>\r
+#include <math.h>\r
+#include <string.h>\r
+#include "openjpeg.h"\r
+#include "index.h"\r
+\r
+/* ------------------------------------------------------------------------------------ */\r
+\r
+/**\r
+Write a structured index to a file\r
+@param cstr_info Codestream information \r
+@param index Index filename\r
+@return Returns 0 if successful, returns 1 otherwise\r
+*/\r
+int write_index_file(opj_codestream_info_t *cstr_info, char *index) {\r
+       int tileno, compno, layno, resno, precno, pack_nb, x, y;\r
+       FILE *stream = NULL;\r
+       double total_disto = 0;\r
+/* UniPG>> */\r
+       int tilepartno;\r
+       char disto_on, numpix_on;\r
+\r
+#ifdef USE_JPWL\r
+       if (!strcmp(index, JPWL_PRIVATEINDEX_NAME))\r
+               return 0;\r
+#endif /* USE_JPWL */\r
+/* <<UniPG */\r
+\r
+       if (!cstr_info)         \r
+               return 1;\r
+\r
+       stream = fopen(index, "w");\r
+       if (!stream) {\r
+               fprintf(stderr, "failed to open index file [%s] for writing\n", index);\r
+               return 1;\r
+       }\r
+       \r
+       if (cstr_info->tile[0].distotile)\r
+               disto_on = 1;\r
+       else \r
+               disto_on = 0;\r
+\r
+       if (cstr_info->tile[0].numpix)\r
+               numpix_on = 1;\r
+       else \r
+               numpix_on = 0;\r
+\r
+       fprintf(stream, "%d %d\n", cstr_info->image_w, cstr_info->image_h);\r
+       fprintf(stream, "%d\n", cstr_info->prog);\r
+       fprintf(stream, "%d %d\n", cstr_info->tile_x, cstr_info->tile_y);\r
+       fprintf(stream, "%d %d\n", cstr_info->tw, cstr_info->th);\r
+       fprintf(stream, "%d\n", cstr_info->numcomps);\r
+       fprintf(stream, "%d\n", cstr_info->numlayers);\r
+       fprintf(stream, "%d\n", cstr_info->numdecompos[0]); /* based on component 0 */\r
+\r
+       for (resno = cstr_info->numdecompos[0]; resno >= 0; resno--) {\r
+               fprintf(stream, "[%d,%d] ", \r
+                       (1 << cstr_info->tile[0].pdx[resno]), (1 << cstr_info->tile[0].pdx[resno]));    /* based on tile 0 and component 0 */\r
+       }\r
+\r
+       fprintf(stream, "\n");\r
+/* UniPG>> */\r
+       fprintf(stream, "%d\n", cstr_info->main_head_start);\r
+/* <<UniPG */\r
+       fprintf(stream, "%d\n", cstr_info->main_head_end);\r
+       fprintf(stream, "%d\n", cstr_info->codestream_size);\r
+       \r
+       fprintf(stream, "\nINFO ON TILES\n");\r
+       fprintf(stream, "tileno start_pos  end_hd  end_tile   nbparts");\r
+       if (disto_on)\r
+               fprintf(stream,"         disto");\r
+       if (numpix_on)\r
+               fprintf(stream,"     nbpix");\r
+       if (disto_on && numpix_on)\r
+               fprintf(stream,"  disto/nbpix");\r
+       fprintf(stream, "\n");\r
+\r
+       for (tileno = 0; tileno < cstr_info->tw * cstr_info->th; tileno++) {\r
+               fprintf(stream, "%4d %9d %9d %9d %9d", \r
+                       cstr_info->tile[tileno].tileno,\r
+                       cstr_info->tile[tileno].start_pos,\r
+                       cstr_info->tile[tileno].end_header,\r
+                       cstr_info->tile[tileno].end_pos,\r
+                       cstr_info->tile[tileno].num_tps);\r
+               if (disto_on)\r
+                       fprintf(stream," %9e", cstr_info->tile[tileno].distotile);\r
+               if (numpix_on)\r
+                       fprintf(stream," %9d", cstr_info->tile[tileno].numpix);\r
+               if (disto_on && numpix_on)\r
+                       fprintf(stream," %9e", cstr_info->tile[tileno].distotile / cstr_info->tile[tileno].numpix);\r
+               fprintf(stream, "\n");\r
+       }\r
+               \r
+       for (tileno = 0; tileno < cstr_info->tw * cstr_info->th; tileno++) {\r
+               int start_pos, end_ph_pos, end_pos;\r
+               double disto = 0;\r
+               int max_numdecompos = 0;\r
+               pack_nb = 0;\r
+\r
+               for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
+                       if (max_numdecompos < cstr_info->numdecompos[compno])\r
+                               max_numdecompos = cstr_info->numdecompos[compno];\r
+               }       \r
+\r
+               fprintf(stream, "\nTILE %d DETAILS\n", tileno); \r
+               fprintf(stream, "part_nb tileno  start_pack num_packs  start_pos end_tph_pos   end_pos\n");\r
+               for (tilepartno = 0; tilepartno < cstr_info->tile[tileno].num_tps; tilepartno++)\r
+                       fprintf(stream, "%4d %9d   %9d %9d  %9d %11d %9d\n",\r
+                               tilepartno, tileno,\r
+                               cstr_info->tile[tileno].tp[tilepartno].tp_start_pack,\r
+                               cstr_info->tile[tileno].tp[tilepartno].tp_numpacks,\r
+                               cstr_info->tile[tileno].tp[tilepartno].tp_start_pos,\r
+                               cstr_info->tile[tileno].tp[tilepartno].tp_end_header,\r
+                               cstr_info->tile[tileno].tp[tilepartno].tp_end_pos\r
+                               );\r
+\r
+               if (cstr_info->prog == LRCP) {  /* LRCP */\r
+                       fprintf(stream, "LRCP\npack_nb tileno layno resno compno precno start_pos end_ph_pos end_pos");\r
+                       if (disto_on)\r
+                               fprintf(stream, " disto");\r
+                       fprintf(stream,"\n");\r
+\r
+                       for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
+                               for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
+                                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
+                                               int prec_max;\r
+                                               if (resno > cstr_info->numdecompos[compno])\r
+                                                       break;\r
+                                               prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
+                                               for (precno = 0; precno < prec_max; precno++) {\r
+                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                       end_ph_pos = cstr_info->tile[tileno].packet[pack_nb].end_ph_pos;\r
+                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                       disto = cstr_info->tile[tileno].packet[pack_nb].disto;\r
+                                                       fprintf(stream, "%4d %6d %7d %5d %6d  %6d    %6d     %6d %7d",\r
+                                                               pack_nb, tileno, layno, resno, compno, precno, start_pos, end_ph_pos, end_pos);\r
+                                                       if (disto_on)\r
+                                                               fprintf(stream, " %8e", disto);\r
+                                                       fprintf(stream, "\n");\r
+                                                       total_disto += disto;\r
+                                                       pack_nb++;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               } /* LRCP */\r
+\r
+               else if (cstr_info->prog == RLCP) {     /* RLCP */                      \r
+                       fprintf(stream, "RLCP\npack_nb tileno resno layno compno precno start_pos end_ph_pos end_pos\n");\r
+                       if (disto_on)\r
+                               fprintf(stream, " disto");\r
+                       fprintf(stream,"\n");\r
+\r
+                       for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
+                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
+                                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
+                                               int prec_max; \r
+                                               if (resno > cstr_info->numdecompos[compno])\r
+                                                       break;\r
+                                               prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
+                                               for (precno = 0; precno < prec_max; precno++) {\r
+                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                       end_ph_pos = cstr_info->tile[tileno].packet[pack_nb].end_ph_pos;\r
+                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                       disto = cstr_info->tile[tileno].packet[pack_nb].disto;\r
+                                                       fprintf(stream, "%4d %6d %5d %7d %6d %6d %9d   %9d %7d",\r
+                                                               pack_nb, tileno, resno, layno, compno, precno, start_pos, end_ph_pos, end_pos);\r
+                                                       if (disto_on)\r
+                                                               fprintf(stream, " %8e", disto);\r
+                                                       fprintf(stream, "\n");\r
+                                                       total_disto += disto;\r
+                                                       pack_nb++;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               } /* RLCP */\r
+\r
+               else if (cstr_info->prog == RPCL) {     /* RPCL */\r
+\r
+                       fprintf(stream, "RPCL\npack_nb tileno resno precno compno layno start_pos end_ph_pos end_pos"); \r
+                       if (disto_on)\r
+                               fprintf(stream, " disto");\r
+                       fprintf(stream,"\n");\r
+\r
+                       for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
+                               int numprec = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
+                               for (precno = 0; precno < numprec; precno++) {                                                          \r
+                                       /* I suppose components have same XRsiz, YRsiz */\r
+                                       int x0 = cstr_info->tile_Ox + tileno - (int)floor((float)tileno/(float)cstr_info->tw ) * cstr_info->tw * cstr_info->tile_x;\r
+                                       int y0 = cstr_info->tile_Ox + (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tile_y;\r
+                                       int x1 = x0 + cstr_info->tile_x;\r
+                                       int y1 = y0 + cstr_info->tile_y;\r
+                                       for (compno = 0; compno < cstr_info->numcomps; compno++) {                                      \r
+                                               int pcnx = cstr_info->tile[tileno].pw[resno];\r
+                                               int pcx = (int) pow( 2, cstr_info->tile[tileno].pdx[resno] + cstr_info->numdecompos[compno] - resno );\r
+                                               int pcy = (int) pow( 2, cstr_info->tile[tileno].pdy[resno] + cstr_info->numdecompos[compno] - resno );\r
+                                               int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
+                                               int precno_y = (int) floor( (float)precno/(float)pcnx );\r
+                                               if (resno > cstr_info->numdecompos[compno])\r
+                                                       break;\r
+                                               for(y = y0; y < y1; y++) {                                                      \r
+                                                       if (precno_y*pcy == y ) {\r
+                                                               for (x = x0; x < x1; x++) {                                                                     \r
+                                                                       if (precno_x*pcx == x ) {\r
+                                                                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
+                                                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                                                       end_ph_pos = cstr_info->tile[tileno].packet[pack_nb].end_ph_pos;\r
+                                                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                                                       disto = cstr_info->tile[tileno].packet[pack_nb].disto;\r
+                                                                                       fprintf(stream, "%4d %6d %5d %6d %6d %7d %9d   %9d %7d",\r
+                                                                                               pack_nb, tileno, resno, precno, compno, layno, start_pos, end_ph_pos, end_pos); \r
+                                                                                       if (disto_on)\r
+                                                                                               fprintf(stream, " %8e", disto);\r
+                                                                                       fprintf(stream, "\n");\r
+                                                                                       total_disto += disto;\r
+                                                                                       pack_nb++; \r
+                                                                               }\r
+                                                                       }\r
+                                                               }/* x = x0..x1 */\r
+                                                       } \r
+                                               }  /* y = y0..y1 */\r
+                                       } /* precno */\r
+                               } /* compno */\r
+                       } /* resno */\r
+               } /* RPCL */\r
+\r
+               else if (cstr_info->prog == PCRL) {     /* PCRL */\r
+                       /* I suppose components have same XRsiz, YRsiz */\r
+                       int x0 = cstr_info->tile_Ox + tileno - (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tw * cstr_info->tile_x;\r
+                       int y0 = cstr_info->tile_Ox + (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tile_y;\r
+                       int x1 = x0 + cstr_info->tile_x;\r
+                       int y1 = y0 + cstr_info->tile_y;\r
+\r
+                       // Count the maximum number of precincts \r
+                       int max_numprec = 0;\r
+                       for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
+                               int numprec = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
+                               if (numprec > max_numprec)\r
+                                       max_numprec = numprec;\r
+                       }\r
+\r
+                       fprintf(stream, "PCRL\npack_nb tileno precno compno resno layno start_pos end_ph_pos end_pos"); \r
+                       if (disto_on)\r
+                               fprintf(stream, " disto");\r
+                       fprintf(stream,"\n");\r
+\r
+                       for (precno = 0; precno < max_numprec; precno++) {\r
+                               for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
+                                       for (resno = 0; resno < cstr_info->numdecompos[compno] + 1; resno++) {\r
+                                               int numprec = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
+                                               int pcnx = cstr_info->tile[tileno].pw[resno];\r
+                                               int pcx = (int) pow( 2, cstr_info->tile[tileno].pdx[resno] + cstr_info->numdecompos[compno] - resno );\r
+                                               int pcy = (int) pow( 2, cstr_info->tile[tileno].pdy[resno] + cstr_info->numdecompos[compno] - resno );\r
+                                               int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
+                                               int precno_y = (int) floor( (float)precno/(float)pcnx );\r
+                                               if (precno >= numprec)\r
+                                                       continue;\r
+                                               for(y = y0; y < y1; y++) {                                                      \r
+                                                       if (precno_y*pcy == y ) {\r
+                                                               for (x = x0; x < x1; x++) {                                                                     \r
+                                                                       if (precno_x*pcx == x ) {\r
+                                                                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
+                                                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                                                       end_ph_pos = cstr_info->tile[tileno].packet[pack_nb].end_ph_pos;\r
+                                                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                                                       disto = cstr_info->tile[tileno].packet[pack_nb].disto;\r
+                                                                                       fprintf(stream, "%4d %6d %6d %6d %5d %7d %9d   %9d %7d",\r
+                                                                                               pack_nb, tileno, precno, compno, resno, layno, start_pos, end_ph_pos, end_pos); \r
+                                                                                       if (disto_on)\r
+                                                                                               fprintf(stream, " %8e", disto);\r
+                                                                                       fprintf(stream, "\n");\r
+                                                                                       total_disto += disto;\r
+                                                                                       pack_nb++; \r
+                                                                               }\r
+                                                                       }\r
+                                                               }/* x = x0..x1 */\r
+                                                       } \r
+                                               }  /* y = y0..y1 */\r
+                                       } /* resno */\r
+                               } /* compno */\r
+                       } /* precno */\r
+               } /* PCRL */\r
+\r
+               else {  /* CPRL */\r
+                       // Count the maximum number of precincts \r
+                       int max_numprec = 0;\r
+                       for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
+                               int numprec = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
+                               if (numprec > max_numprec)\r
+                                       max_numprec = numprec;\r
+                       }\r
+\r
+                       fprintf(stream, "CPRL\npack_nb tileno compno precno resno layno start_pos end_ph_pos end_pos"); \r
+                       if (disto_on)\r
+                               fprintf(stream, " disto");\r
+                       fprintf(stream,"\n");\r
+\r
+                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
+                               /* I suppose components have same XRsiz, YRsiz */\r
+                               int x0 = cstr_info->tile_Ox + tileno - (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tw * cstr_info->tile_x;\r
+                               int y0 = cstr_info->tile_Ox + (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tile_y;\r
+                               int x1 = x0 + cstr_info->tile_x;\r
+                               int y1 = y0 + cstr_info->tile_y;\r
+\r
+                               for (precno = 0; precno < max_numprec; precno++) {\r
+                                       for (resno = 0; resno < cstr_info->numdecompos[compno] + 1; resno++) {\r
+                                               int numprec = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
+                                               int pcnx = cstr_info->tile[tileno].pw[resno];\r
+                                               int pcx = (int) pow( 2, cstr_info->tile[tileno].pdx[resno] + cstr_info->numdecompos[compno] - resno );\r
+                                               int pcy = (int) pow( 2, cstr_info->tile[tileno].pdy[resno] + cstr_info->numdecompos[compno] - resno );\r
+                                               int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
+                                               int precno_y = (int) floor( (float)precno/(float)pcnx );\r
+                                               if (precno >= numprec)\r
+                                                       continue;\r
+\r
+                                               for(y = y0; y < y1; y++) {\r
+                                                       if (precno_y*pcy == y ) {\r
+                                                               for (x = x0; x < x1; x++) {\r
+                                                                       if (precno_x*pcx == x ) {\r
+                                                                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
+                                                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
+                                                                                       end_ph_pos = cstr_info->tile[tileno].packet[pack_nb].end_ph_pos;\r
+                                                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
+                                                                                       disto = cstr_info->tile[tileno].packet[pack_nb].disto;\r
+                                                                                       fprintf(stream, "%4d %6d %6d %6d %5d %7d %9d   %9d %7d",\r
+                                                                                               pack_nb, tileno, compno, precno, resno, layno, start_pos, end_ph_pos, end_pos); \r
+                                                                                       if (disto_on)\r
+                                                                                               fprintf(stream, " %8e", disto);\r
+                                                                                       fprintf(stream, "\n");\r
+                                                                                       total_disto += disto;\r
+                                                                                       pack_nb++; \r
+                                                                               }\r
+                                                                       }\r
+                                                               }/* x = x0..x1 */\r
+                                                       }\r
+                                               } /* y = y0..y1 */\r
+                                       } /* resno */\r
+                               } /* precno */\r
+                       } /* compno */\r
+               } /* CPRL */   \r
+       } /* tileno */\r
+       \r
+       if (disto_on) {\r
+               fprintf(stream, "%8e\n", cstr_info->D_max); /* SE max */        \r
+               fprintf(stream, "%.8e\n", total_disto); /* SE totale */\r
+       }\r
+/* UniPG>> */\r
+       /* print the markers' list */\r
+       if (cstr_info->marknum) {\r
+               fprintf(stream, "\nMARKER LIST\n");\r
+               fprintf(stream, "%d\n", cstr_info->marknum);\r
+               fprintf(stream, "type\tstart_pos    length\n");\r
+               for (x = 0; x < cstr_info->marknum; x++)\r
+                       fprintf(stream, "%X\t%9d %9d\n", cstr_info->marker[x].type, cstr_info->marker[x].pos, cstr_info->marker[x].len);\r
+       }\r
+/* <<UniPG */\r
+       fclose(stream);\r
+\r
+       fprintf(stderr,"Generated index file %s\n", index);\r
+\r
+       return 0;\r
+}\r
diff --git a/applications/codec/index.h b/applications/codec/index.h
new file mode 100644 (file)
index 0000000..29f673a
--- /dev/null
@@ -0,0 +1,49 @@
+/*\r
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
+ * Copyright (c) 2002-2007, Professor Benoit Macq\r
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+\r
+#ifndef __J2K_INDEX_H\r
+#define __J2K_INDEX_H\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+/**\r
+Write a structured index to a file\r
+@param cstr_info Codestream information \r
+@param index Index filename\r
+@return Returns 0 if successful, returns 1 otherwise\r
+*/\r
+int write_index_file(opj_codestream_info_t *cstr_info, char *index);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif /* __J2K_INDEX_H */\r
+\r
diff --git a/applications/codec/j2k_dump.c b/applications/codec/j2k_dump.c
new file mode 100644 (file)
index 0000000..508dd65
--- /dev/null
@@ -0,0 +1,634 @@
+/*
+ * Copyright (c) 20010, Mathieu Malaterre, GDCM
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <math.h>
+
+#ifdef _WIN32
+#include "windirent.h"
+#else
+#include <dirent.h>
+#endif /* _WIN32 */
+
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <strings.h>
+#define _stricmp strcasecmp
+#define _strnicmp strncasecmp
+#endif /* _WIN32 */
+
+#include "opj_config.h"
+#include "openjpeg.h"
+#include "../libopenjpeg/j2k.h"
+#include "../libopenjpeg/jp2.h"
+#include "getopt.h"
+#include "convert.h"
+#include "index.h"
+
+#include "format_defs.h"
+
+typedef struct dircnt{
+       /** Buffer for holding images read from Directory*/
+       char *filename_buf;
+       /** Pointer to the buffer*/
+       char **filename;
+}dircnt_t;
+
+
+typedef struct img_folder{
+       /** The directory path of the folder containing input images*/
+       char *imgdirpath;
+       /** Output format*/
+       const char *out_format;
+       /** Enable option*/
+       char set_imgdir;
+       /** Enable Cod Format for output*/
+       char set_out_format;
+
+}img_fol_t;
+
+void decode_help_display() {
+       fprintf(stdout,"HELP for j2k_dump\n----\n\n");
+       fprintf(stdout,"- the -h option displays this help information on screen\n\n");
+
+/* UniPG>> */
+       fprintf(stdout,"List of parameters for the JPEG 2000 "
+#ifdef USE_JPWL
+               "+ JPWL "
+#endif /* USE_JPWL */
+               "decoder:\n");
+/* <<UniPG */
+       fprintf(stdout,"\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"  -ImgDir \n");
+       fprintf(stdout,"        Image file Directory path \n");
+       fprintf(stdout,"  -i <compressed file>\n");
+       fprintf(stdout,"    REQUIRED only if an Input image directory not specified\n");
+       fprintf(stdout,"    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n");
+       fprintf(stdout,"    is identified based on its suffix.\n");
+       fprintf(stdout,"\n");
+}
+
+/* -------------------------------------------------------------------------- */
+static void j2k_dump_image(FILE *fd, opj_image_t * img);
+static void j2k_dump_cp(FILE *fd, opj_image_t * img, opj_cp_t * cp);
+
+int get_num_images(char *imgdirpath){
+       DIR *dir;
+       struct dirent* content; 
+       int num_images = 0;
+
+       /*Reading the input images from given input directory*/
+
+       dir= opendir(imgdirpath);
+       if(!dir){
+               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
+               return 0;
+       }
+       
+       while((content=readdir(dir))!=NULL){
+               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
+                       continue;
+               num_images++;
+       }
+       return num_images;
+}
+
+int load_images(dircnt_t *dirptr, char *imgdirpath){
+       DIR *dir;
+       struct dirent* content; 
+       int i = 0;
+
+       /*Reading the input images from given input directory*/
+
+       dir= opendir(imgdirpath);
+       if(!dir){
+               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
+               return 1;
+       }else   {
+               fprintf(stderr,"Folder opened successfully\n");
+       }
+       
+       while((content=readdir(dir))!=NULL){
+               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
+                       continue;
+
+               strcpy(dirptr->filename[i],content->d_name);
+               i++;
+       }
+       return 0;       
+}
+
+int get_file_format(char *filename) {
+       unsigned int i;
+       static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc"  };
+       static const int format[] = { PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, TGA_DFMT, PNG_DFMT, J2K_CFMT, JP2_CFMT, JPT_CFMT, J2K_CFMT, J2K_CFMT };
+       char * ext = strrchr(filename, '.');
+       if (ext == NULL)
+               return -1;
+       ext++;
+       if(ext) {
+               for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
+                       if(_strnicmp(ext, extension[i], 3) == 0) {
+                               return format[i];
+                       }
+               }
+       }
+
+       return -1;
+}
+
+char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters){
+       char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
+       char *temp_p, temp1[OPJ_PATH_LEN]="";
+
+       strcpy(image_filename,dirptr->filename[imageno]);
+       fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
+       parameters->decod_format = get_file_format(image_filename);
+       if (parameters->decod_format == -1)
+               return 1;
+       sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
+       strncpy(parameters->infile, infilename, sizeof(infilename));
+
+       //Set output file
+       strcpy(temp_ofname,strtok(image_filename,"."));
+       while((temp_p = strtok(NULL,".")) != NULL){
+               strcat(temp_ofname,temp1);
+               sprintf(temp1,".%s",temp_p);
+       }
+       if(img_fol->set_out_format==1){
+               sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
+               strncpy(parameters->outfile, outfilename, sizeof(outfilename));
+       }
+       return 0;
+}
+
+/* -------------------------------------------------------------------------- */
+int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol, char *indexfilename) {
+       /* parse the command line */
+       int totlen;
+       option_t long_option[]={
+               {"ImgDir",REQ_ARG, NULL ,'y'},
+       };
+
+       const char optlist[] = "i:h";
+       totlen=sizeof(long_option);
+       img_fol->set_out_format = 0;
+       while (1) {
+               int c = getopt_long(argc, argv,optlist,long_option,totlen);
+               if (c == -1)
+                       break;
+               switch (c) {
+                       case 'i':                       /* input file */
+                       {
+                               char *infile = optarg;
+                               parameters->decod_format = get_file_format(infile);
+                               switch(parameters->decod_format) {
+                                       case J2K_CFMT:
+                                       case JP2_CFMT:
+                                       case JPT_CFMT:
+                                               break;
+                                       default:
+                                               fprintf(stderr, 
+                                                       "!! Unrecognized format for infile : %s [accept only *.j2k, *.jp2, *.jpc or *.jpt] !!\n\n", 
+                                                       infile);
+                                               return 1;
+                               }
+                               strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
+                       }
+                       break;
+                               
+                               /* ----------------------------------------------------- */
+
+                       case 'h':                       /* display an help description */
+                               decode_help_display();
+                               return 1;                               
+
+                               /* ------------------------------------------------------ */
+
+                       case 'y':                       /* Image Directory path */
+                               {
+                                       img_fol->imgdirpath = (char*)malloc(strlen(optarg) + 1);
+                                       strcpy(img_fol->imgdirpath,optarg);
+                                       img_fol->set_imgdir=1;
+                               }
+                               break;
+
+                               /* ----------------------------------------------------- */
+                       
+                       default:
+                               fprintf(stderr,"WARNING -> this option is not valid \"-%c %s\"\n",c, optarg);
+                               break;
+               }
+       }
+
+       /* check for possible errors */
+       if(img_fol->set_imgdir==1){
+               if(!(parameters->infile[0]==0)){
+                       fprintf(stderr, "Error: options -ImgDir and -i cannot be used together !!\n");
+                       return 1;
+               }
+               if(img_fol->set_out_format == 0){
+                       fprintf(stderr, "Error: When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
+                       fprintf(stderr, "Only one format allowed! Valid format PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA!!\n");
+                       return 1;
+               }
+               if(!((parameters->outfile[0] == 0))){
+                       fprintf(stderr, "Error: options -ImgDir and -o cannot be used together !!\n");
+                       return 1;
+               }
+       }else{
+               if((parameters->infile[0] == 0) ) {
+                       fprintf(stderr, "Example: %s -i image.j2k\n",argv[0]);
+                       fprintf(stderr, "    Try: %s -h\n",argv[0]);
+                       return 1;
+               }
+       }
+
+       return 0;
+}
+
+/* -------------------------------------------------------------------------- */
+
+/**
+sample error callback expecting a FILE* client object
+*/
+void error_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[ERROR] %s", msg);
+}
+/**
+sample warning callback expecting a FILE* client object
+*/
+void warning_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[WARNING] %s", msg);
+}
+/**
+sample debug callback expecting no client object
+*/
+void info_callback(const char *msg, void *client_data) {
+       (void)client_data;
+       fprintf(stdout, "[INFO] %s", msg);
+}
+
+/* -------------------------------------------------------------------------- */
+
+int main(int argc, char *argv[])
+{
+       opj_dparameters_t parameters;   /* decompression parameters */
+       img_fol_t img_fol;
+       opj_event_mgr_t event_mgr;              /* event manager */
+       opj_image_t *image = NULL;
+       FILE *fsrc = NULL;
+       unsigned char *src = NULL;
+       int file_length;
+       int num_images;
+       int i,imageno;
+       dircnt_t *dirptr = NULL;
+       opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */
+       opj_cio_t *cio = NULL;
+       opj_codestream_info_t cstr_info;  /* Codestream information structure */
+       char indexfilename[OPJ_PATH_LEN];       /* index file name */
+
+       /* configure the event callbacks (not required) */
+       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
+       event_mgr.error_handler = error_callback;
+       event_mgr.warning_handler = warning_callback;
+       event_mgr.info_handler = info_callback;
+
+       /* set decoding parameters to default values */
+       opj_set_default_decoder_parameters(&parameters);
+
+       /* Initialize indexfilename and img_fol */
+       *indexfilename = 0;
+       memset(&img_fol,0,sizeof(img_fol_t));
+
+       /* parse input and get user encoding parameters */
+       if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {
+               return 1;
+       }
+
+       /* Initialize reading of directory */
+       if(img_fol.set_imgdir==1){      
+               num_images=get_num_images(img_fol.imgdirpath);
+
+               dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
+               if(dirptr){
+                       dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));     // Stores at max 10 image file names
+                       dirptr->filename = (char**) malloc(num_images*sizeof(char*));
+
+                       if(!dirptr->filename_buf){
+                               return 1;
+                       }
+                       for(i=0;i<num_images;i++){
+                               dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN;
+                       }
+               }
+               if(load_images(dirptr,img_fol.imgdirpath)==1){
+                       return 1;
+               }
+               if (num_images==0){
+                       fprintf(stdout,"Folder is empty\n");
+                       return 1;
+               }
+       }else{
+               num_images=1;
+       }
+
+       /*Encoding image one by one*/
+       for(imageno = 0; imageno < num_images ; imageno++)
+  {
+               image = NULL;
+               fprintf(stderr,"\n");
+
+               if(img_fol.set_imgdir==1){
+                       if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
+                               fprintf(stderr,"skipping file...\n");
+                               continue;
+                       }
+               }
+
+               /* read the input file and put it in memory */
+               /* ---------------------------------------- */
+               fsrc = fopen(parameters.infile, "rb");
+               if (!fsrc) {
+                       fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);
+                       return 1;
+               }
+               fseek(fsrc, 0, SEEK_END);
+               file_length = ftell(fsrc);
+               fseek(fsrc, 0, SEEK_SET);
+               src = (unsigned char *) malloc(file_length);
+               fread(src, 1, file_length, fsrc);
+               fclose(fsrc);
+
+               /* decode the code-stream */
+               /* ---------------------- */
+
+               switch(parameters.decod_format) {
+               case J2K_CFMT:
+               {
+                       /* JPEG-2000 codestream */
+
+                       /* get a decoder handle */
+                       dinfo = opj_create_decompress(CODEC_J2K);
+
+                       /* catch events using our callbacks and give a local context */
+                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
+
+                       /* setup the decoder decoding parameters using user parameters */
+                       opj_setup_decoder(dinfo, &parameters);
+
+                       /* open a byte stream */
+                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
+
+                       /* decode the stream and fill the image structure */
+                       if (*indexfilename)                             // If need to extract codestream information
+                               image = opj_decode_with_info(dinfo, cio, &cstr_info);
+                       else
+                               image = opj_decode(dinfo, cio);
+                       if(!image) {
+                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
+                               opj_destroy_decompress(dinfo);
+                               opj_cio_close(cio);
+                               return 1;
+                       }
+                       /* dump image */
+      j2k_dump_image(stdout, image);
+
+                       /* dump cp */
+      j2k_dump_cp(stdout, image, ((opj_j2k_t*)dinfo->j2k_handle)->cp);
+
+                       /* close the byte stream */
+                       opj_cio_close(cio);
+
+                       /* Write the index to disk */
+                       if (*indexfilename) {
+                               char bSuccess;
+                               bSuccess = write_index_file(&cstr_info, indexfilename);
+                               if (bSuccess) {
+                                       fprintf(stderr, "Failed to output index file\n");
+                               }
+                       }
+               }
+               break;
+
+               case JP2_CFMT:
+               {
+                       /* JPEG 2000 compressed image data */
+
+                       /* get a decoder handle */
+                       dinfo = opj_create_decompress(CODEC_JP2);
+
+                       /* catch events using our callbacks and give a local context */
+                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
+
+                       /* setup the decoder decoding parameters using the current image and user parameters */
+                       opj_setup_decoder(dinfo, &parameters);
+
+                       /* open a byte stream */
+                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
+
+                       /* decode the stream and fill the image structure */
+                       if (*indexfilename)                             // If need to extract codestream information
+                               image = opj_decode_with_info(dinfo, cio, &cstr_info);
+                       else
+                               image = opj_decode(dinfo, cio);                 
+                       if(!image) {
+                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
+                               opj_destroy_decompress(dinfo);
+                               opj_cio_close(cio);
+                               return 1;
+                       }
+                       /* dump image */
+         if(image->icc_profile_buf)
+        {
+         free(image->icc_profile_buf); image->icc_profile_buf = NULL;
+        }      
+      j2k_dump_image(stdout, image);
+
+                       /* dump cp */
+      j2k_dump_cp(stdout, image, ((opj_jp2_t*)dinfo->jp2_handle)->j2k->cp);
+
+                       /* close the byte stream */
+                       opj_cio_close(cio);
+
+                       /* Write the index to disk */
+                       if (*indexfilename) {
+                               char bSuccess;
+                               bSuccess = write_index_file(&cstr_info, indexfilename);
+                               if (bSuccess) {
+                                       fprintf(stderr, "Failed to output index file\n");
+                               }
+                       }
+               }
+               break;
+
+               case JPT_CFMT:
+               {
+                       /* JPEG 2000, JPIP */
+
+                       /* get a decoder handle */
+                       dinfo = opj_create_decompress(CODEC_JPT);
+
+                       /* catch events using our callbacks and give a local context */
+                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
+
+                       /* setup the decoder decoding parameters using user parameters */
+                       opj_setup_decoder(dinfo, &parameters);
+
+                       /* open a byte stream */
+                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
+
+                       /* decode the stream and fill the image structure */
+                       if (*indexfilename)                             // If need to extract codestream information
+                               image = opj_decode_with_info(dinfo, cio, &cstr_info);
+                       else
+                               image = opj_decode(dinfo, cio);
+                       if(!image) {
+                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
+                               opj_destroy_decompress(dinfo);
+                               opj_cio_close(cio);
+                               return 1;
+                       }
+
+                       /* close the byte stream */
+                       opj_cio_close(cio);
+
+                       /* Write the index to disk */
+                       if (*indexfilename) {
+                               char bSuccess;
+                               bSuccess = write_index_file(&cstr_info, indexfilename);
+                               if (bSuccess) {
+                                       fprintf(stderr, "Failed to output index file\n");
+                               }
+                       }
+               }
+               break;
+
+               default:
+                       fprintf(stderr, "skipping file..\n");
+                       continue;
+       }
+
+               /* free the memory containing the code-stream */
+               free(src);
+               src = NULL;
+
+               /* free remaining structures */
+               if(dinfo) {
+                       opj_destroy_decompress(dinfo);
+               }
+               /* free codestream information structure */
+               if (*indexfilename)     
+                       opj_destroy_cstr_info(&cstr_info);
+               /* free image data structure */
+               opj_image_destroy(image);
+
+       }
+
+  return EXIT_SUCCESS;
+}
+
+
+static void j2k_dump_image(FILE *fd, opj_image_t * img) {
+       int compno;
+       fprintf(fd, "image {\n");
+       fprintf(fd, "  x0=%d, y0=%d, x1=%d, y1=%d\n", img->x0, img->y0, img->x1, img->y1);
+       fprintf(fd, "  numcomps=%d\n", img->numcomps);
+       for (compno = 0; compno < img->numcomps; compno++) {
+               opj_image_comp_t *comp = &img->comps[compno];
+               fprintf(fd, "  comp %d {\n", compno);
+               fprintf(fd, "    dx=%d, dy=%d\n", comp->dx, comp->dy);
+               fprintf(fd, "    prec=%d\n", comp->prec);
+               //fprintf(fd, "    bpp=%d\n", comp->bpp);
+               fprintf(fd, "    sgnd=%d\n", comp->sgnd);
+               fprintf(fd, "  }\n");
+       }
+       fprintf(fd, "}\n");
+}
+
+static void j2k_dump_cp(FILE *fd, opj_image_t * img, opj_cp_t * cp) {
+       int tileno, compno, layno, bandno, resno, numbands;
+       fprintf(fd, "coding parameters {\n");
+       fprintf(fd, "  tx0=%d, ty0=%d\n", cp->tx0, cp->ty0);
+       fprintf(fd, "  tdx=%d, tdy=%d\n", cp->tdx, cp->tdy);
+       fprintf(fd, "  tw=%d, th=%d\n", cp->tw, cp->th);
+       for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
+               opj_tcp_t *tcp = &cp->tcps[tileno];
+               fprintf(fd, "  tile %d {\n", tileno);
+               fprintf(fd, "    csty=%x\n", tcp->csty);
+               fprintf(fd, "    prg=%d\n", tcp->prg);
+               fprintf(fd, "    numlayers=%d\n", tcp->numlayers);
+               fprintf(fd, "    mct=%d\n", tcp->mct);
+               fprintf(fd, "    rates=");
+               for (layno = 0; layno < tcp->numlayers; layno++) {
+                       fprintf(fd, "%.1f ", tcp->rates[layno]);
+               }
+               fprintf(fd, "\n");
+               for (compno = 0; compno < img->numcomps; compno++) {
+                       opj_tccp_t *tccp = &tcp->tccps[compno];
+                       fprintf(fd, "    comp %d {\n", compno);
+                       fprintf(fd, "      csty=%x\n", tccp->csty);
+                       fprintf(fd, "      numresolutions=%d\n", tccp->numresolutions);
+                       fprintf(fd, "      cblkw=%d\n", tccp->cblkw);
+                       fprintf(fd, "      cblkh=%d\n", tccp->cblkh);
+                       fprintf(fd, "      cblksty=%x\n", tccp->cblksty);
+                       fprintf(fd, "      qmfbid=%d\n", tccp->qmfbid);
+                       fprintf(fd, "      qntsty=%d\n", tccp->qntsty);
+                       fprintf(fd, "      numgbits=%d\n", tccp->numgbits);
+                       fprintf(fd, "      roishift=%d\n", tccp->roishift);
+                       fprintf(fd, "      stepsizes=");
+                       numbands = tccp->qntsty == J2K_CCP_QNTSTY_SIQNT ? 1 : tccp->numresolutions * 3 - 2;
+                       for (bandno = 0; bandno < numbands; bandno++) {
+                               fprintf(fd, "(%d,%d) ", tccp->stepsizes[bandno].mant,
+                                       tccp->stepsizes[bandno].expn);
+                       }
+                       fprintf(fd, "\n");
+                       
+                       if (tccp->csty & J2K_CCP_CSTY_PRT) {
+                               fprintf(fd, "      prcw=");
+                               for (resno = 0; resno < tccp->numresolutions; resno++) {
+                                       fprintf(fd, "%d ", tccp->prcw[resno]);
+                               }
+                               fprintf(fd, "\n");
+                               fprintf(fd, "      prch=");
+                               for (resno = 0; resno < tccp->numresolutions; resno++) {
+                                       fprintf(fd, "%d ", tccp->prch[resno]);
+                               }
+                               fprintf(fd, "\n");
+                       }
+                       fprintf(fd, "    }\n");
+               }
+               fprintf(fd, "  }\n");
+       }
+       fprintf(fd, "}\n");
+}
+
diff --git a/applications/codec/j2k_to_image.c b/applications/codec/j2k_to_image.c
new file mode 100644 (file)
index 0000000..ff6141e
--- /dev/null
@@ -0,0 +1,845 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * Copyright (c) 2006-2007, Parvatha Elangovan
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <math.h>
+
+#ifdef _WIN32
+#include "windirent.h"
+#else
+#include <dirent.h>
+#endif /* _WIN32 */
+
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <strings.h>
+#define _stricmp strcasecmp
+#define _strnicmp strncasecmp
+#endif /* _WIN32 */
+
+#include "opj_config.h"
+#include "openjpeg.h"
+#include "getopt.h"
+#include "convert.h"
+#include "index.h"
+
+#ifdef HAVE_LIBLCMS2
+#include <lcms2.h>
+#endif
+#ifdef HAVE_LIBLCMS1
+#include <lcms.h>
+#endif
+#include "color.h"
+
+#include "format_defs.h"
+
+typedef struct dircnt{
+       /** Buffer for holding images read from Directory*/
+       char *filename_buf;
+       /** Pointer to the buffer*/
+       char **filename;
+}dircnt_t;
+
+
+typedef struct img_folder{
+       /** The directory path of the folder containing input images*/
+       char *imgdirpath;
+       /** Output format*/
+       const char *out_format;
+       /** Enable option*/
+       char set_imgdir;
+       /** Enable Cod Format for output*/
+       char set_out_format;
+
+}img_fol_t;
+
+void decode_help_display() {
+       fprintf(stdout,"HELP for j2k_to_image\n----\n\n");
+       fprintf(stdout,"- the -h option displays this help information on screen\n\n");
+
+/* UniPG>> */
+       fprintf(stdout,"List of parameters for the JPEG 2000 "
+#ifdef USE_JPWL
+               "+ JPWL "
+#endif /* USE_JPWL */
+               "decoder:\n");
+/* <<UniPG */
+       fprintf(stdout,"\n");
+       fprintf(stdout,"\n");
+       fprintf(stdout,"  -ImgDir \n");
+       fprintf(stdout,"        Image file Directory path \n");
+       fprintf(stdout,"  -OutFor \n");
+       fprintf(stdout,"    REQUIRED only if -ImgDir is used\n");
+       fprintf(stdout,"          Need to specify only format without filename <BMP>  \n");
+       fprintf(stdout,"    Currently accepts PGM, PPM, PNM, PGX, PNG, BMP, TIF, RAW and TGA formats\n");
+       fprintf(stdout,"  -i <compressed file>\n");
+       fprintf(stdout,"    REQUIRED only if an Input image directory not specified\n");
+       fprintf(stdout,"    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n");
+       fprintf(stdout,"    is identified based on its suffix.\n");
+       fprintf(stdout,"  -o <decompressed file>\n");
+       fprintf(stdout,"    REQUIRED\n");
+       fprintf(stdout,"    Currently accepts PGM, PPM, PNM, PGX, PNG, BMP, TIF, RAW and TGA files\n");
+       fprintf(stdout,"    Binary data is written to the file (not ascii). If a PGX\n");
+       fprintf(stdout,"    filename is given, there will be as many output files as there are\n");
+       fprintf(stdout,"    components: an indice starting from 0 will then be appended to the\n");
+       fprintf(stdout,"    output filename, just before the \"pgx\" extension. If a PGM filename\n");
+       fprintf(stdout,"    is given and there are more than one component, only the first component\n");
+       fprintf(stdout,"    will be written to the file.\n");
+       fprintf(stdout,"  -r <reduce factor>\n");
+       fprintf(stdout,"    Set the number of highest resolution levels to be discarded. The\n");
+       fprintf(stdout,"    image resolution is effectively divided by 2 to the power of the\n");
+       fprintf(stdout,"    number of discarded levels. The reduce factor is limited by the\n");
+       fprintf(stdout,"    smallest total number of decomposition levels among tiles.\n");
+       fprintf(stdout,"  -l <number of quality layers to decode>\n");
+       fprintf(stdout,"    Set the maximum number of quality layers to decode. If there are\n");
+       fprintf(stdout,"    less quality layers than the specified number, all the quality layers\n");
+       fprintf(stdout,"    are decoded.\n");
+       fprintf(stdout,"  -x  \n"); 
+       fprintf(stdout,"    Create an index file *.Idx (-x index_name.Idx) \n");
+       fprintf(stdout,"\n");
+/* UniPG>> */
+#ifdef USE_JPWL
+       fprintf(stdout,"  -W <options>\n");
+       fprintf(stdout,"    Activates the JPWL correction capability, if the codestream complies.\n");
+       fprintf(stdout,"    Options can be a comma separated list of <param=val> tokens:\n");
+       fprintf(stdout,"    c, c=numcomps\n");
+       fprintf(stdout,"       numcomps is the number of expected components in the codestream\n");
+       fprintf(stdout,"       (search of first EPB rely upon this, default is %d)\n", JPWL_EXPECTED_COMPONENTS);
+#endif /* USE_JPWL */
+/* <<UniPG */
+       fprintf(stdout,"\n");
+}
+
+/* -------------------------------------------------------------------------- */
+
+int get_num_images(char *imgdirpath){
+       DIR *dir;
+       struct dirent* content; 
+       int num_images = 0;
+
+       /*Reading the input images from given input directory*/
+
+       dir= opendir(imgdirpath);
+       if(!dir){
+               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
+               return 0;
+       }
+       
+       while((content=readdir(dir))!=NULL){
+               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
+                       continue;
+               num_images++;
+       }
+       return num_images;
+}
+
+int load_images(dircnt_t *dirptr, char *imgdirpath){
+       DIR *dir;
+       struct dirent* content; 
+       int i = 0;
+
+       /*Reading the input images from given input directory*/
+
+       dir= opendir(imgdirpath);
+       if(!dir){
+               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
+               return 1;
+       }else   {
+               fprintf(stderr,"Folder opened successfully\n");
+       }
+       
+       while((content=readdir(dir))!=NULL){
+               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
+                       continue;
+
+               strcpy(dirptr->filename[i],content->d_name);
+               i++;
+       }
+       return 0;       
+}
+
+int get_file_format(char *filename) {
+       unsigned int i;
+       static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc" };
+       static const int format[] = { PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, TGA_DFMT, PNG_DFMT, J2K_CFMT, JP2_CFMT, JPT_CFMT, J2K_CFMT, J2K_CFMT };
+       char * ext = strrchr(filename, '.');
+       if (ext == NULL)
+               return -1;
+       ext++;
+       if(ext) {
+               for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
+                       if(_strnicmp(ext, extension[i], 3) == 0) {
+                               return format[i];
+                       }
+               }
+       }
+
+       return -1;
+}
+
+char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters){
+       char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
+       char *temp_p, temp1[OPJ_PATH_LEN]="";
+
+       strcpy(image_filename,dirptr->filename[imageno]);
+       fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
+       parameters->decod_format = get_file_format(image_filename);
+       if (parameters->decod_format == -1)
+               return 1;
+       sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
+       strncpy(parameters->infile, infilename, sizeof(infilename));
+
+       //Set output file
+       strcpy(temp_ofname,strtok(image_filename,"."));
+       while((temp_p = strtok(NULL,".")) != NULL){
+               strcat(temp_ofname,temp1);
+               sprintf(temp1,".%s",temp_p);
+       }
+       if(img_fol->set_out_format==1){
+               sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
+               strncpy(parameters->outfile, outfilename, sizeof(outfilename));
+       }
+       return 0;
+}
+
+/* -------------------------------------------------------------------------- */
+int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol, char *indexfilename) {
+       /* parse the command line */
+       int totlen;
+       option_t long_option[]={
+               {"ImgDir",REQ_ARG, NULL ,'y'},
+               {"OutFor",REQ_ARG, NULL ,'O'},
+       };
+
+       const char optlist[] = "i:o:r:l:x:"
+
+/* UniPG>> */
+#ifdef USE_JPWL
+                                       "W:"
+#endif /* USE_JPWL */
+/* <<UniPG */
+                       "h"             ;
+       totlen=sizeof(long_option);
+       img_fol->set_out_format = 0;
+       while (1) {
+               int c = getopt_long(argc, argv,optlist,long_option,totlen);
+               if (c == -1)
+                       break;
+               switch (c) {
+                       case 'i':                       /* input file */
+                       {
+                               char *infile = optarg;
+                               parameters->decod_format = get_file_format(infile);
+                               switch(parameters->decod_format) {
+                                       case J2K_CFMT:
+                                       case JP2_CFMT:
+                                       case JPT_CFMT:
+                                               break;
+                                       default:
+                                               fprintf(stderr, 
+                                                       "!! Unrecognized format for infile : %s [accept only *.j2k, *.jp2, *.jpc or *.jpt] !!\n\n", 
+                                                       infile);
+                                               return 1;
+                               }
+                               strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
+                       }
+                       break;
+                               
+                               /* ----------------------------------------------------- */
+
+                       case 'o':                       /* output file */
+                       {
+                               char *outfile = optarg;
+                               parameters->cod_format = get_file_format(outfile);
+                               switch(parameters->cod_format) {
+                                       case PGX_DFMT:
+                                       case PXM_DFMT:
+                                       case BMP_DFMT:
+                                       case TIF_DFMT:
+                                       case RAW_DFMT:
+                                       case TGA_DFMT:
+                                       case PNG_DFMT:
+                                               break;
+                                       default:
+                                               fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outfile);
+                                               return 1;
+                               }
+                               strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);
+                       }
+                       break;
+                       
+                               /* ----------------------------------------------------- */
+
+                       case 'O':                       /* output format */
+                       {
+                               char outformat[50];
+                               char *of = optarg;
+                               sprintf(outformat,".%s",of);
+                               img_fol->set_out_format = 1;
+                               parameters->cod_format = get_file_format(outformat);
+                               switch(parameters->cod_format) {
+                                       case PGX_DFMT:
+                                               img_fol->out_format = "pgx";
+                                               break;
+                                       case PXM_DFMT:
+                                               img_fol->out_format = "ppm";
+                                               break;
+                                       case BMP_DFMT:
+                                               img_fol->out_format = "bmp";
+                                               break;
+                                       case TIF_DFMT:
+                                               img_fol->out_format = "tif";
+                                               break;
+                                       case RAW_DFMT:
+                                               img_fol->out_format = "raw";
+                                               break;
+                                       case TGA_DFMT:
+                                               img_fol->out_format = "raw";
+                                               break;
+                                       case PNG_DFMT:
+                                               img_fol->out_format = "png";
+                                               break;
+                                       default:
+                                               fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outformat);
+                                               return 1;
+                                               break;
+                               }
+                       }
+                       break;
+
+                               /* ----------------------------------------------------- */
+
+
+                       case 'r':               /* reduce option */
+                       {
+                               sscanf(optarg, "%d", &parameters->cp_reduce);
+                       }
+                       break;
+                       
+                               /* ----------------------------------------------------- */
+      
+
+                       case 'l':               /* layering option */
+                       {
+                               sscanf(optarg, "%d", &parameters->cp_layer);
+                       }
+                       break;
+                       
+                               /* ----------------------------------------------------- */
+
+                       case 'h':                       /* display an help description */
+                               decode_help_display();
+                               return 1;                               
+
+                               /* ------------------------------------------------------ */
+
+                       case 'y':                       /* Image Directory path */
+                               {
+                                       img_fol->imgdirpath = (char*)malloc(strlen(optarg) + 1);
+                                       strcpy(img_fol->imgdirpath,optarg);
+                                       img_fol->set_imgdir=1;
+                               }
+                               break;
+                               /* ----------------------------------------------------- */                                                             
+                       case 'x':                       /* Creation of index file */
+                               {
+                                       char *index = optarg;
+                                       strncpy(indexfilename, index, OPJ_PATH_LEN);
+                               }
+                               break;
+                               /* ----------------------------------------------------- */
+                               /* UniPG>> */
+#ifdef USE_JPWL
+                       
+                       case 'W':                       /* activate JPWL correction */
+                       {
+                               char *token = NULL;
+
+                               token = strtok(optarg, ",");
+                               while(token != NULL) {
+
+                                       /* search expected number of components */
+                                       if (*token == 'c') {
+
+                                               static int compno;
+
+                                               compno = JPWL_EXPECTED_COMPONENTS; /* predefined no. of components */
+
+                                               if(sscanf(token, "c=%d", &compno) == 1) {
+                                                       /* Specified */
+                                                       if ((compno < 1) || (compno > 256)) {
+                                                               fprintf(stderr, "ERROR -> invalid number of components c = %d\n", compno);
+                                                               return 1;
+                                                       }
+                                                       parameters->jpwl_exp_comps = compno;
+
+                                               } else if (!strcmp(token, "c")) {
+                                                       /* default */
+                                                       parameters->jpwl_exp_comps = compno; /* auto for default size */
+
+                                               } else {
+                                                       fprintf(stderr, "ERROR -> invalid components specified = %s\n", token);
+                                                       return 1;
+                                               };
+                                       }
+
+                                       /* search maximum number of tiles */
+                                       if (*token == 't') {
+
+                                               static int tileno;
+
+                                               tileno = JPWL_MAXIMUM_TILES; /* maximum no. of tiles */
+
+                                               if(sscanf(token, "t=%d", &tileno) == 1) {
+                                                       /* Specified */
+                                                       if ((tileno < 1) || (tileno > JPWL_MAXIMUM_TILES)) {
+                                                               fprintf(stderr, "ERROR -> invalid number of tiles t = %d\n", tileno);
+                                                               return 1;
+                                                       }
+                                                       parameters->jpwl_max_tiles = tileno;
+
+                                               } else if (!strcmp(token, "t")) {
+                                                       /* default */
+                                                       parameters->jpwl_max_tiles = tileno; /* auto for default size */
+
+                                               } else {
+                                                       fprintf(stderr, "ERROR -> invalid tiles specified = %s\n", token);
+                                                       return 1;
+                                               };
+                                       }
+
+                                       /* next token or bust */
+                                       token = strtok(NULL, ",");
+                               };
+                               parameters->jpwl_correct = true;
+                               fprintf(stdout, "JPWL correction capability activated\n");
+                               fprintf(stdout, "- expecting %d components\n", parameters->jpwl_exp_comps);
+                       }
+                       break;  
+#endif /* USE_JPWL */
+/* <<UniPG */            
+
+                               /* ----------------------------------------------------- */
+                       
+                       default:
+                               fprintf(stderr,"WARNING -> this option is not valid \"-%c %s\"\n",c, optarg);
+                               break;
+               }
+       }
+
+       /* check for possible errors */
+       if(img_fol->set_imgdir==1){
+               if(!(parameters->infile[0]==0)){
+                       fprintf(stderr, "Error: options -ImgDir and -i cannot be used together !!\n");
+                       return 1;
+               }
+               if(img_fol->set_out_format == 0){
+                       fprintf(stderr, "Error: When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
+                       fprintf(stderr, "Only one format allowed! Valid format PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA!!\n");
+                       return 1;
+               }
+               if(!((parameters->outfile[0] == 0))){
+                       fprintf(stderr, "Error: options -ImgDir and -o cannot be used together !!\n");
+                       return 1;
+               }
+       }else{
+               if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
+                       fprintf(stderr, "Example: %s -i image.j2k -o image.pgm\n",argv[0]);
+                       fprintf(stderr, "    Try: %s -h\n",argv[0]);
+                       return 1;
+               }
+       }
+
+       return 0;
+}
+
+/* -------------------------------------------------------------------------- */
+
+/**
+sample error callback expecting a FILE* client object
+*/
+void error_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[ERROR] %s", msg);
+}
+/**
+sample warning callback expecting a FILE* client object
+*/
+void warning_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[WARNING] %s", msg);
+}
+/**
+sample debug callback expecting no client object
+*/
+void info_callback(const char *msg, void *client_data) {
+       (void)client_data;
+       fprintf(stdout, "[INFO] %s", msg);
+}
+
+/* -------------------------------------------------------------------------- */
+
+int main(int argc, char **argv) {
+       opj_dparameters_t parameters;   /* decompression parameters */
+       img_fol_t img_fol;
+       opj_event_mgr_t event_mgr;              /* event manager */
+       opj_image_t *image = NULL;
+       FILE *fsrc = NULL;
+       unsigned char *src = NULL;
+       int file_length;
+       int num_images;
+       int i,imageno;
+       dircnt_t *dirptr;
+       opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */
+       opj_cio_t *cio = NULL;
+       opj_codestream_info_t cstr_info;  /* Codestream information structure */
+       char indexfilename[OPJ_PATH_LEN];       /* index file name */
+
+       /* configure the event callbacks (not required) */
+       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
+       event_mgr.error_handler = error_callback;
+       event_mgr.warning_handler = warning_callback;
+       event_mgr.info_handler = info_callback;
+
+       /* set decoding parameters to default values */
+       opj_set_default_decoder_parameters(&parameters);
+
+       /* Initialize indexfilename and img_fol */
+       *indexfilename = 0;
+       memset(&img_fol,0,sizeof(img_fol_t));
+
+       /* parse input and get user encoding parameters */
+       if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {
+               return 1;
+       }
+
+       /* Initialize reading of directory */
+       if(img_fol.set_imgdir==1){      
+               num_images=get_num_images(img_fol.imgdirpath);
+
+               dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
+               if(dirptr){
+                       dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));     // Stores at max 10 image file names
+                       dirptr->filename = (char**) malloc(num_images*sizeof(char*));
+
+                       if(!dirptr->filename_buf){
+                               return 1;
+                       }
+                       for(i=0;i<num_images;i++){
+                               dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN;
+                       }
+               }
+               if(load_images(dirptr,img_fol.imgdirpath)==1){
+                       return 1;
+               }
+               if (num_images==0){
+                       fprintf(stdout,"Folder is empty\n");
+                       return 1;
+               }
+       }else{
+               num_images=1;
+       }
+
+       /*Encoding image one by one*/
+       for(imageno = 0; imageno < num_images ; imageno++)      {
+               image = NULL;
+               fprintf(stderr,"\n");
+
+               if(img_fol.set_imgdir==1){
+                       if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
+                               fprintf(stderr,"skipping file...\n");
+                               continue;
+                       }
+               }
+
+               /* read the input file and put it in memory */
+               /* ---------------------------------------- */
+               fsrc = fopen(parameters.infile, "rb");
+               if (!fsrc) {
+                       fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);
+                       return 1;
+               }
+               fseek(fsrc, 0, SEEK_END);
+               file_length = ftell(fsrc);
+               fseek(fsrc, 0, SEEK_SET);
+               src = (unsigned char *) malloc(file_length);
+               fread(src, 1, file_length, fsrc);
+               fclose(fsrc);
+
+               /* decode the code-stream */
+               /* ---------------------- */
+
+               switch(parameters.decod_format) {
+               case J2K_CFMT:
+               {
+                       /* JPEG-2000 codestream */
+
+                       /* get a decoder handle */
+                       dinfo = opj_create_decompress(CODEC_J2K);
+
+                       /* catch events using our callbacks and give a local context */
+                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
+
+                       /* setup the decoder decoding parameters using user parameters */
+                       opj_setup_decoder(dinfo, &parameters);
+
+                       /* open a byte stream */
+                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
+
+                       /* decode the stream and fill the image structure */
+                       if (*indexfilename)                             // If need to extract codestream information
+                               image = opj_decode_with_info(dinfo, cio, &cstr_info);
+                       else
+                               image = opj_decode(dinfo, cio);
+                       if(!image) {
+                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
+                               opj_destroy_decompress(dinfo);
+                               opj_cio_close(cio);
+                               return 1;
+                       }
+
+                       /* close the byte stream */
+                       opj_cio_close(cio);
+
+                       /* Write the index to disk */
+                       if (*indexfilename) {
+                               char bSuccess;
+                               bSuccess = write_index_file(&cstr_info, indexfilename);
+                               if (bSuccess) {
+                                       fprintf(stderr, "Failed to output index file\n");
+                               }
+                       }
+               }
+               break;
+
+               case JP2_CFMT:
+               {
+                       /* JPEG 2000 compressed image data */
+
+                       /* get a decoder handle */
+                       dinfo = opj_create_decompress(CODEC_JP2);
+
+                       /* catch events using our callbacks and give a local context */
+                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
+
+                       /* setup the decoder decoding parameters using the current image and user parameters */
+                       opj_setup_decoder(dinfo, &parameters);
+
+                       /* open a byte stream */
+                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
+
+                       /* decode the stream and fill the image structure */
+                       if (*indexfilename)                             // If need to extract codestream information
+                               image = opj_decode_with_info(dinfo, cio, &cstr_info);
+                       else
+                               image = opj_decode(dinfo, cio);                 
+                       if(!image) {
+                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
+                               opj_destroy_decompress(dinfo);
+                               opj_cio_close(cio);
+                               return 1;
+                       }
+
+                       /* close the byte stream */
+                       opj_cio_close(cio);
+
+                       /* Write the index to disk */
+                       if (*indexfilename) {
+                               char bSuccess;
+                               bSuccess = write_index_file(&cstr_info, indexfilename);
+                               if (bSuccess) {
+                                       fprintf(stderr, "Failed to output index file\n");
+                               }
+                       }
+               }
+               break;
+
+               case JPT_CFMT:
+               {
+                       /* JPEG 2000, JPIP */
+
+                       /* get a decoder handle */
+                       dinfo = opj_create_decompress(CODEC_JPT);
+
+                       /* catch events using our callbacks and give a local context */
+                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
+
+                       /* setup the decoder decoding parameters using user parameters */
+                       opj_setup_decoder(dinfo, &parameters);
+
+                       /* open a byte stream */
+                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
+
+                       /* decode the stream and fill the image structure */
+                       if (*indexfilename)                             // If need to extract codestream information
+                               image = opj_decode_with_info(dinfo, cio, &cstr_info);
+                       else
+                               image = opj_decode(dinfo, cio);
+                       if(!image) {
+                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
+                               opj_destroy_decompress(dinfo);
+                               opj_cio_close(cio);
+                               return 1;
+                       }
+
+                       /* close the byte stream */
+                       opj_cio_close(cio);
+
+                       /* Write the index to disk */
+                       if (*indexfilename) {
+                               char bSuccess;
+                               bSuccess = write_index_file(&cstr_info, indexfilename);
+                               if (bSuccess) {
+                                       fprintf(stderr, "Failed to output index file\n");
+                               }
+                       }
+               }
+               break;
+
+               default:
+                       fprintf(stderr, "skipping file..\n");
+                       continue;
+       }
+
+               /* free the memory containing the code-stream */
+               free(src);
+               src = NULL;
+
+       if(image->color_space == CLRSPC_SYCC)
+   {
+       color_sycc_to_rgb(image);
+   }
+
+       if(image->icc_profile_buf)
+   {
+#if defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2)
+       color_apply_icc_profile(image);
+#endif
+
+       free(image->icc_profile_buf);
+       image->icc_profile_buf = NULL; image->icc_profile_len = 0;
+   }
+
+               /* create output image */
+               /* ------------------- */
+               switch (parameters.cod_format) {
+               case PXM_DFMT:                  /* PNM PGM PPM */
+                       if (imagetopnm(image, parameters.outfile)) {
+                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
+                       }
+                       else {
+                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
+                       }
+                       break;
+
+               case PGX_DFMT:                  /* PGX */
+                       if(imagetopgx(image, parameters.outfile)){
+                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
+                       }
+                       else {
+                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
+                       }
+                       break;
+
+               case BMP_DFMT:                  /* BMP */
+                       if(imagetobmp(image, parameters.outfile)){
+                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
+                       }
+                       else {
+                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
+                       }
+                       break;
+#ifdef HAVE_LIBTIFF
+               case TIF_DFMT:                  /* TIFF */
+                       if(imagetotif(image, parameters.outfile)){
+                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
+                       }
+                       else {
+                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
+                       }
+                       break;
+#endif /* HAVE_LIBTIFF */
+               case RAW_DFMT:                  /* RAW */
+                       if(imagetoraw(image, parameters.outfile)){
+                               fprintf(stdout,"Error generating raw file. Outfile %s not generated\n",parameters.outfile);
+                       }
+                       else {
+                               fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile);
+                       }
+                       break;
+
+               case TGA_DFMT:                  /* TGA */
+                       if(imagetotga(image, parameters.outfile)){
+                               fprintf(stdout,"Error generating tga file. Outfile %s not generated\n",parameters.outfile);
+                       }
+                       else {
+                               fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile);
+                       }
+                       break;
+#ifdef HAVE_LIBPNG
+               case PNG_DFMT:                  /* PNG */
+                       if(imagetopng(image, parameters.outfile)){
+                               fprintf(stdout,"Error generating png file. Outfile %s not generated\n",parameters.outfile);
+                       }
+                       else {
+                               fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile);
+                       }
+                       break;
+#endif /* HAVE_LIBPNG */
+/* Can happen if output file is TIFF or PNG
+ * and HAVE_LIBTIF or HAVE_LIBPNG is undefined
+*/
+                       default:
+                               fprintf(stderr,"Outfile %s not generated\n",parameters.outfile);
+               }
+
+               /* free remaining structures */
+               if(dinfo) {
+                       opj_destroy_decompress(dinfo);
+               }
+               /* free codestream information structure */
+               if (*indexfilename)     
+                       opj_destroy_cstr_info(&cstr_info);
+               /* free image data structure */
+               opj_image_destroy(image);
+
+       }
+       return 0;
+}
+//end main
+
+
+
+
diff --git a/applications/codec/windirent.h b/applications/codec/windirent.h
new file mode 100644 (file)
index 0000000..6bcc778
--- /dev/null
@@ -0,0 +1,679 @@
+\r
+/*\r
+ * uce-dirent.h - operating system independent dirent implementation\r
+ * \r
+ * Copyright (C) 1998-2002  Toni Ronkko\r
+ * \r
+ * Permission is hereby granted, free of charge, to any person obtaining\r
+ * a copy of this software and associated documentation files (the\r
+ * ``Software''), to deal in the Software without restriction, including\r
+ * without limitation the rights to use, copy, modify, merge, publish,\r
+ * distribute, sublicense, and/or sell copies of the Software, and to\r
+ * permit persons to whom the Software is furnished to do so, subject to\r
+ * the following conditions:\r
+ * \r
+ * The above copyright notice and this permission notice shall be included\r
+ * in all copies or substantial portions of the Software.\r
+ * \r
+ * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS\r
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r
+ * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR\r
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\r
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r
+ * OTHER DEALINGS IN THE SOFTWARE.\r
+ * \r
+ * \r
+ * May 28 1998, Toni Ronkko <tronkko@messi.uku.fi>\r
+ *\r
+ * $Id: uce-dirent.h,v 1.7 2002/05/13 10:48:35 tr Exp $\r
+ *\r
+ * $Log: uce-dirent.h,v $\r
+ * Revision 1.7  2002/05/13 10:48:35  tr\r
+ * embedded some source code directly to the header so that no source\r
+ * modules need to be included in the MS Visual C project using the\r
+ * interface, removed all the dependencies to other headers of the `uce'\r
+ * library so that the header can be made public\r
+ *\r
+ * Revision 1.6  2002/04/12 16:22:04  tr\r
+ * Unified Compiling Environment (UCE) replaced `std' library\r
+ *\r
+ * Revision 1.5  2001/07/20 16:33:40  tr\r
+ * moved to `std' library and re-named defines accordingly\r
+ *\r
+ * Revision 1.4  2001/07/10 16:47:18  tronkko\r
+ * revised comments\r
+ *\r
+ * Revision 1.3  2001/01/11 13:16:43  tr\r
+ * using ``uce-machine.h'' for finding out defines such as `FREEBSD'\r
+ *\r
+ * Revision 1.2  2000/10/08 16:00:41  tr\r
+ * copy of FreeBSD man page\r
+ *\r
+ * Revision 1.1  2000/07/10 05:53:16  tr\r
+ * Initial revision\r
+ *\r
+ * Revision 1.2  1998/07/19 18:29:14  tr\r
+ * Added error reporting capabilities and some asserts.\r
+ *\r
+ * Revision 1.1  1998/07/04 16:27:51  tr\r
+ * Initial revision\r
+ *\r
+ * \r
+ * MSVC 1.0 scans automatic dependencies incorrectly when your project\r
+ * contains this very header.  The problem is that MSVC cannot handle\r
+ * include directives inside #if..#endif block those are never entered.\r
+ * Since this header ought to compile in many different operating systems,\r
+ * there had to be several conditional blocks that are compiled only in\r
+ * operating systems for what they were designed for.  MSVC 1.0 cannot\r
+ * handle inclusion of sys/dir.h in a part that is compiled only in Apollo\r
+ * operating system.  To fix the problem you need to insert DIR.H into\r
+ * SYSINCL.DAT located in MSVC\BIN directory and restart visual C++.\r
+ * Consult manuals for more informaton about the problem.\r
+ *\r
+ * Since many UNIX systems have dirent.h we assume to have one also.\r
+ * However, if your UNIX system does not have dirent.h you can download one\r
+ * for example at: http://ftp.uni-mannheim.de/ftp/GNU/dirent/dirent.tar.gz.\r
+ * You can also see if you have one of dirent.h, direct.h, dir.h, ndir.h,\r
+ * sys/dir.h and sys/ndir.h somewhere.  Try defining HAVE_DIRENT_H,\r
+ * HAVE_DIRECT_H, HAVE_DIR_H, HAVE_NDIR_H, HAVE_SYS_DIR_H and\r
+ * HAVE_SYS_NDIR_H according to the files found.\r
+ */\r
+#ifndef DIRENT_H\r
+#define DIRENT_H\r
+#define DIRENT_H_INCLUDED\r
+\r
+/* find out platform */\r
+#if defined(MSDOS)                             /* MS-DOS */\r
+#elif defined(__MSDOS__)                       /* Turbo C/Borland */\r
+# define MSDOS\r
+#elif defined(__DOS__)                         /* Watcom */\r
+# define MSDOS\r
+#endif\r
+\r
+#if defined(WIN32)                             /* MS-Windows */\r
+#elif defined(__NT__)                          /* Watcom */\r
+# define WIN32\r
+#elif defined(_WIN32)                          /* Microsoft */\r
+# define WIN32\r
+#elif defined(__WIN32__)                       /* Borland */\r
+# define WIN32\r
+#endif\r
+\r
+/*\r
+ * See what kind of dirent interface we have unless autoconf has already\r
+ * determinated that.\r
+ */\r
+#if !defined(HAVE_DIRENT_H) && !defined(HAVE_DIRECT_H) && !defined(HAVE_SYS_DIR_H) && !defined(HAVE_NDIR_H) && !defined(HAVE_SYS_NDIR_H) && !defined(HAVE_DIR_H)\r
+# if defined(_MSC_VER)                         /* Microsoft C/C++ */\r
+    /* no dirent.h */\r
+# elif defined(__MINGW32__)                    /* MinGW */\r
+    /* no dirent.h */\r
+# elif defined(__BORLANDC__)                   /* Borland C/C++ */\r
+#   define HAVE_DIRENT_H\r
+#   define VOID_CLOSEDIR\r
+# elif defined(__TURBOC__)                     /* Borland Turbo C */\r
+    /* no dirent.h */\r
+# elif defined(__WATCOMC__)                    /* Watcom C/C++ */\r
+#   define HAVE_DIRECT_H\r
+# elif defined(__apollo)                       /* Apollo */\r
+#   define HAVE_SYS_DIR_H\r
+# elif defined(__hpux)                         /* HP-UX */\r
+#   define HAVE_DIRENT_H\r
+# elif (defined(__alpha) || defined(__alpha__)) && !defined(__linux__)  /* Alpha OSF1 */\r
+#   error "not implemented"\r
+# elif defined(__sgi)                          /* Silicon Graphics */\r
+#   define HAVE_DIRENT_H\r
+# elif defined(sun) || defined(_sun)           /* Sun Solaris */\r
+#   define HAVE_DIRENT_H\r
+# elif defined(__FreeBSD__)                    /* FreeBSD */\r
+#   define HAVE_DIRENT_H\r
+# elif defined(__linux__)                      /* Linux */\r
+#   define HAVE_DIRENT_H\r
+# elif defined(__GNUC__)                       /* GNU C/C++ */\r
+#   define HAVE_DIRENT_H\r
+# else\r
+#   error "not implemented"\r
+# endif\r
+#endif\r
+\r
+/* include proper interface headers */\r
+#if defined(HAVE_DIRENT_H)\r
+# include <dirent.h>\r
+# ifdef FREEBSD\r
+#   define NAMLEN(dp) ((int)((dp)->d_namlen))\r
+# else\r
+#   define NAMLEN(dp) ((int)(strlen((dp)->d_name)))\r
+# endif\r
+\r
+#elif defined(HAVE_NDIR_H)\r
+# include <ndir.h>\r
+# define NAMLEN(dp) ((int)((dp)->d_namlen))\r
+\r
+#elif defined(HAVE_SYS_NDIR_H)\r
+# include <sys/ndir.h>\r
+# define NAMLEN(dp) ((int)((dp)->d_namlen))\r
+\r
+#elif defined(HAVE_DIRECT_H)\r
+# include <direct.h>\r
+# define NAMLEN(dp) ((int)((dp)->d_namlen))\r
+\r
+#elif defined(HAVE_DIR_H)\r
+# include <dir.h>\r
+# define NAMLEN(dp) ((int)((dp)->d_namlen))\r
+\r
+#elif defined(HAVE_SYS_DIR_H)\r
+# include <sys/types.h>\r
+# include <sys/dir.h>\r
+# ifndef dirent\r
+#   define dirent direct\r
+# endif\r
+# define NAMLEN(dp) ((int)((dp)->d_namlen))\r
+\r
+#elif defined(MSDOS) || defined(WIN32)\r
+\r
+  /* figure out type of underlaying directory interface to be used */\r
+# if defined(WIN32)\r
+#   define DIRENT_WIN32_INTERFACE\r
+# elif defined(MSDOS)\r
+#   define DIRENT_MSDOS_INTERFACE\r
+# else\r
+#   error "missing native dirent interface"\r
+# endif\r
+\r
+  /*** WIN32 specifics ***/\r
+# if defined(DIRENT_WIN32_INTERFACE)\r
+#   include <windows.h>\r
+#   if !defined(DIRENT_MAXNAMLEN)\r
+#     define DIRENT_MAXNAMLEN (MAX_PATH)\r
+#   endif\r
+\r
+\r
+  /*** MS-DOS specifics ***/\r
+# elif defined(DIRENT_MSDOS_INTERFACE)\r
+#   include <dos.h>\r
+\r
+    /* Borland defines file length macros in dir.h */\r
+#   if defined(__BORLANDC__)\r
+#     include <dir.h>\r
+#     if !defined(DIRENT_MAXNAMLEN)\r
+#       define DIRENT_MAXNAMLEN ((MAXFILE)+(MAXEXT))\r
+#     endif\r
+#     if !defined(_find_t)\r
+#       define _find_t find_t\r
+#     endif\r
+\r
+    /* Turbo C defines ffblk structure in dir.h */\r
+#   elif defined(__TURBOC__)\r
+#     include <dir.h>\r
+#     if !defined(DIRENT_MAXNAMLEN)\r
+#       define DIRENT_MAXNAMLEN ((MAXFILE)+(MAXEXT))\r
+#     endif\r
+#     define DIRENT_USE_FFBLK\r
+\r
+    /* MSVC */\r
+#   elif defined(_MSC_VER)\r
+#     if !defined(DIRENT_MAXNAMLEN)\r
+#       define DIRENT_MAXNAMLEN (12)\r
+#     endif\r
+\r
+    /* Watcom */\r
+#   elif defined(__WATCOMC__)\r
+#     if !defined(DIRENT_MAXNAMLEN)\r
+#       if defined(__OS2__) || defined(__NT__)\r
+#         define DIRENT_MAXNAMLEN (255)\r
+#       else\r
+#         define DIRENT_MAXNAMLEN (12)\r
+#       endif\r
+#     endif\r
+\r
+#   endif\r
+# endif\r
+\r
+  /*** generic MS-DOS and MS-Windows stuff ***/\r
+# if !defined(NAME_MAX) && defined(DIRENT_MAXNAMLEN)\r
+#   define NAME_MAX DIRENT_MAXNAMLEN\r
+# endif\r
+# if NAME_MAX < DIRENT_MAXNAMLEN\r
+#   error "assertion failed: NAME_MAX >= DIRENT_MAXNAMLEN"\r
+# endif\r
+\r
+\r
+  /*\r
+   * Substitute for real dirent structure.  Note that `d_name' field is a\r
+   * true character array although we have it copied in the implementation\r
+   * dependent data.  We could save some memory if we had declared `d_name'\r
+   * as a pointer refering the name within implementation dependent data.\r
+   * We have not done that since some code may rely on sizeof(d_name) to be\r
+   * something other than four.  Besides, directory entries are typically so\r
+   * small that it takes virtually no time to copy them from place to place.\r
+   */\r
+  typedef struct dirent {\r
+    char d_name[NAME_MAX + 1];\r
+\r
+    /*** Operating system specific part ***/\r
+# if defined(DIRENT_WIN32_INTERFACE)       /*WIN32*/\r
+    WIN32_FIND_DATA data;\r
+# elif defined(DIRENT_MSDOS_INTERFACE)     /*MSDOS*/\r
+#   if defined(DIRENT_USE_FFBLK)\r
+    struct ffblk data;\r
+#   else\r
+    struct _find_t data;\r
+#   endif\r
+# endif\r
+  } dirent;\r
+\r
+  /* DIR substitute structure containing directory name.  The name is\r
+   * essential for the operation of ``rewinndir'' function. */\r
+  typedef struct DIR {\r
+    char          *dirname;                    /* directory being scanned */\r
+    dirent        current;                     /* current entry */\r
+    int           dirent_filled;               /* is current un-processed? */\r
+\r
+  /*** Operating system specific part ***/\r
+#  if defined(DIRENT_WIN32_INTERFACE)\r
+    HANDLE        search_handle;\r
+#  elif defined(DIRENT_MSDOS_INTERFACE)\r
+#  endif\r
+  } DIR;\r
+\r
+# ifdef __cplusplus\r
+extern "C" {\r
+# endif\r
+\r
+/* supply prototypes for dirent functions */\r
+static DIR *opendir (const char *dirname);\r
+static struct dirent *readdir (DIR *dirp);\r
+static int closedir (DIR *dirp);\r
+static void rewinddir (DIR *dirp);\r
+\r
+/*\r
+ * Implement dirent interface as static functions so that the user does not\r
+ * need to change his project in any way to use dirent function.  With this\r
+ * it is sufficient to include this very header from source modules using\r
+ * dirent functions and the functions will be pulled in automatically.\r
+ */\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+#include <assert.h>\r
+#include <errno.h>\r
+\r
+/* use ffblk instead of _find_t if requested */\r
+#if defined(DIRENT_USE_FFBLK)\r
+# define _A_ARCH   (FA_ARCH)\r
+# define _A_HIDDEN (FA_HIDDEN)\r
+# define _A_NORMAL (0)\r
+# define _A_RDONLY (FA_RDONLY)\r
+# define _A_SUBDIR (FA_DIREC)\r
+# define _A_SYSTEM (FA_SYSTEM)\r
+# define _A_VOLID  (FA_LABEL)\r
+# define _dos_findnext(dest) findnext(dest)\r
+# define _dos_findfirst(name,flags,dest) findfirst(name,dest,flags)\r
+#endif\r
+\r
+static int _initdir (DIR *p);\r
+static const char *_getdirname (const struct dirent *dp);\r
+static void _setdirname (struct DIR *dirp);\r
+\r
+/*\r
+ * <function name="opendir">\r
+ * <intro>open directory stream for reading\r
+ * <syntax>DIR *opendir (const char *dirname);\r
+ *\r
+ * <desc>Open named directory stream for read and return pointer to the\r
+ * internal working area that is used for retrieving individual directory\r
+ * entries.  The internal working area has no fields of your interest.\r
+ *\r
+ * <ret>Returns a pointer to the internal working area or NULL in case the \r
+ * directory stream could not be opened.  Global `errno' variable will set\r
+ * in case of error as follows:\r
+ *\r
+ * <table>\r
+ * [EACESS  |Permission denied.\r
+ * [EMFILE  |Too many open files used by the process.\r
+ * [ENFILE  |Too many open files in system.\r
+ * [ENOENT  |Directory does not exist.\r
+ * [ENOMEM  |Insufficient memory.\r
+ * [ENOTDIR |dirname does not refer to directory.  This value is not\r
+ *           reliable on MS-DOS and MS-Windows platforms.  Many\r
+ *           implementations return ENOENT even when the name refers to a\r
+ *           file.]\r
+ * </table>\r
+ * </function>\r
+ */\r
+static DIR *opendir(const char *dirname)\r
+{\r
+  DIR *dirp;\r
+  assert (dirname != NULL);\r
+  \r
+  dirp = (DIR*)malloc (sizeof (struct DIR));\r
+  if (dirp != NULL) {\r
+    char *p;\r
+    \r
+    /* allocate room for directory name */\r
+    dirp->dirname = (char*) malloc (strlen (dirname) + 1 + strlen ("\\*.*"));\r
+    if (dirp->dirname == NULL) {\r
+      /* failed to duplicate directory name.  errno set by malloc() */\r
+      free (dirp);\r
+      return NULL;\r
+    }\r
+    /* Copy directory name while appending directory separator and "*.*".\r
+     * Directory separator is not appended if the name already ends with\r
+     * drive or directory separator.  Directory separator is assumed to be\r
+     * '/' or '\' and drive separator is assumed to be ':'. */\r
+    strcpy (dirp->dirname, dirname);\r
+    p = strchr (dirp->dirname, '\0');\r
+    if (dirp->dirname < p  &&\r
+        *(p - 1) != '\\'  &&  *(p - 1) != '/'  &&  *(p - 1) != ':')\r
+    {\r
+      strcpy (p++, "\\");\r
+    }\r
+# ifdef DIRENT_WIN32_INTERFACE\r
+    strcpy (p, "*"); /*scan files with and without extension in win32*/\r
+# else\r
+    strcpy (p, "*.*"); /*scan files with and without extension in DOS*/\r
+# endif\r
+\r
+    /* open stream */\r
+    if (_initdir (dirp) == 0) {\r
+      /* initialization failed */\r
+      free (dirp->dirname);\r
+      free (dirp);\r
+      return NULL;\r
+    }\r
+  }\r
+  return dirp;\r
+}\r
+\r
+\r
+/*\r
+ * <function name="readdir">\r
+ * <intro>read a directory entry\r
+ * <syntax>struct dirent *readdir (DIR *dirp);\r
+ *\r
+ * <desc>Read individual directory entry and return pointer to a structure\r
+ * containing the name of the entry.  Individual directory entries returned\r
+ * include normal files, sub-directories, pseudo-directories "." and ".."\r
+ * and also volume labels, hidden files and system files in MS-DOS and\r
+ * MS-Windows.   You might want to use stat(2) function to determinate which\r
+ * one are you dealing with.  Many dirent implementations already contain\r
+ * equivalent information in dirent structure but you cannot depend on\r
+ * this.\r
+ *\r
+ * The dirent structure contains several system dependent fields that\r
+ * generally have no interest to you.  The only interesting one is char\r
+ * d_name[] that is also portable across different systems.  The d_name\r
+ * field contains the name of the directory entry without leading path.\r
+ * While d_name is portable across different systems the actual storage\r
+ * capacity of d_name varies from system to system and there is no portable\r
+ * way to find out it at compile time as different systems define the\r
+ * capacity of d_name with different macros and some systems do not define\r
+ * capacity at all (besides actual declaration of the field). If you really\r
+ * need to find out storage capacity of d_name then you might want to try\r
+ * NAME_MAX macro. The NAME_MAX is defined in POSIX standard althought\r
+ * there are many MS-DOS and MS-Windows implementations those do not define\r
+ * it.  There are also systems that declare d_name as "char d_name[1]" and\r
+ * then allocate suitable amount of memory at run-time.  Thanks to Alain\r
+ * Decamps (Alain.Decamps@advalvas.be) for pointing it out to me.\r
+ *\r
+ * This all leads to the fact that it is difficult to allocate space\r
+ * for the directory names when the very same program is being compiled on\r
+ * number of operating systems.  Therefore I suggest that you always\r
+ * allocate space for directory names dynamically.\r
+ *\r
+ * <ret>\r
+ * Returns a pointer to a structure containing name of the directory entry\r
+ * in `d_name' field or NULL if there was an error.  In case of an error the\r
+ * global `errno' variable will set as follows:\r
+ *\r
+ * <table>\r
+ * [EBADF  |dir parameter refers to an invalid directory stream.  This value\r
+ *          is not set reliably on all implementations.]\r
+ * </table>\r
+ * </function>\r
+ */\r
+static struct dirent *\r
+readdir (DIR *dirp)\r
+{\r
+  assert(dirp != NULL);\r
+  if (dirp == NULL) {\r
+    errno = EBADF;\r
+    return NULL;\r
+  }\r
+\r
+#if defined(DIRENT_WIN32_INTERFACE)\r
+  if (dirp->search_handle == INVALID_HANDLE_VALUE) {\r
+    /* directory stream was opened/rewound incorrectly or it ended normally */\r
+    errno = EBADF;\r
+    return NULL;\r
+  }\r
+#endif\r
+\r
+  if (dirp->dirent_filled != 0) {\r
+    /*\r
+     * Directory entry has already been retrieved and there is no need to\r
+     * retrieve a new one.  Directory entry will be retrieved in advance\r
+     * when the user calls readdir function for the first time.  This is so\r
+     * because real dirent has separate functions for opening and reading\r
+     * the stream whereas Win32 and DOS dirents open the stream\r
+     * automatically when we retrieve the first file.  Therefore, we have to\r
+     * save the first file when opening the stream and later we have to\r
+     * return the saved entry when the user tries to read the first entry.\r
+     */\r
+    dirp->dirent_filled = 0;\r
+  } else {\r
+    /* fill in entry and return that */\r
+#if defined(DIRENT_WIN32_INTERFACE)\r
+    if (FindNextFile (dirp->search_handle, &dirp->current.data) == FALSE) {\r
+      /* Last file has been processed or an error occured */\r
+      FindClose (dirp->search_handle);\r
+      dirp->search_handle = INVALID_HANDLE_VALUE;\r
+      errno = ENOENT;\r
+      return NULL;\r
+    }\r
+\r
+# elif defined(DIRENT_MSDOS_INTERFACE)\r
+    if (_dos_findnext (&dirp->current.data) != 0) {\r
+      /* _dos_findnext and findnext will set errno to ENOENT when no\r
+       * more entries could be retrieved. */\r
+      return NULL;\r
+    }\r
+# endif\r
+\r
+    _setdirname (dirp);\r
+    assert (dirp->dirent_filled == 0);\r
+  }\r
+  return &dirp->current;\r
+}\r
+\r
+\r
+/*\r
+ * <function name="closedir">\r
+ * <intro>close directory stream.\r
+ * <syntax>int closedir (DIR *dirp);\r
+ *\r
+ * <desc>Close directory stream opened by the `opendir' function.  Close of\r
+ * directory stream invalidates the DIR structure as well as previously read\r
+ * dirent entry.\r
+ *\r
+ * <ret>The function typically returns 0 on success and -1 on failure but\r
+ * the function may be declared to return void on same systems.  At least\r
+ * Borland C/C++ and some UNIX implementations use void as a return type.\r
+ * The dirent wrapper tries to define VOID_CLOSEDIR whenever closedir is\r
+ * known to return nothing.  The very same definition is made by the GNU\r
+ * autoconf if you happen to use it.\r
+ *\r
+ * The global `errno' variable will set to EBADF in case of error.\r
+ * </function>\r
+ */\r
+static int\r
+closedir (DIR *dirp)\r
+{   \r
+  int retcode = 0;\r
+\r
+  /* make sure that dirp points to legal structure */\r
+  assert (dirp != NULL);\r
+  if (dirp == NULL) {\r
+    errno = EBADF;\r
+    return -1;\r
+  }\r
\r
+  /* free directory name and search handles */\r
+  if (dirp->dirname != NULL) free (dirp->dirname);\r
+\r
+#if defined(DIRENT_WIN32_INTERFACE)\r
+  if (dirp->search_handle != INVALID_HANDLE_VALUE) {\r
+    if (FindClose (dirp->search_handle) == FALSE) {\r
+      /* Unknown error */\r
+      retcode = -1;\r
+      errno = EBADF;\r
+    }\r
+  }\r
+#endif                     \r
+\r
+  /* clear dirp structure to make sure that it cannot be used anymore*/\r
+  memset (dirp, 0, sizeof (*dirp));\r
+# if defined(DIRENT_WIN32_INTERFACE)\r
+  dirp->search_handle = INVALID_HANDLE_VALUE;\r
+# endif\r
+\r
+  free (dirp);\r
+  return retcode;\r
+}\r
+\r
+\r
+/*\r
+ * <function name="rewinddir">\r
+ * <intro>rewind directory stream to the beginning\r
+ * <syntax>void rewinddir (DIR *dirp);\r
+ *\r
+ * <desc>Rewind directory stream to the beginning so that the next call of\r
+ * readdir() returns the very first directory entry again.  However, note\r
+ * that next call of readdir() may not return the same directory entry as it\r
+ * did in first time.  The directory stream may have been affected by newly\r
+ * created files.\r
+ *\r
+ * Almost every dirent implementation ensure that rewinddir will update\r
+ * the directory stream to reflect any changes made to the directory entries\r
+ * since the previous ``opendir'' or ``rewinddir'' call.  Keep an eye on\r
+ * this if your program depends on the feature.  I know at least one dirent\r
+ * implementation where you are required to close and re-open the stream to\r
+ * see the changes.\r
+ *\r
+ * <ret>Returns nothing.  If something went wrong while rewinding, you will\r
+ * notice it later when you try to retrieve the first directory entry.\r
+ */\r
+static void\r
+rewinddir (DIR *dirp)\r
+{   \r
+  /* make sure that dirp is legal */\r
+  assert (dirp != NULL);\r
+  if (dirp == NULL) {\r
+    errno = EBADF;\r
+    return;\r
+  }\r
+  assert (dirp->dirname != NULL);\r
+  \r
+  /* close previous stream */\r
+#if defined(DIRENT_WIN32_INTERFACE)\r
+  if (dirp->search_handle != INVALID_HANDLE_VALUE) {\r
+    if (FindClose (dirp->search_handle) == FALSE) {\r
+      /* Unknown error */\r
+      errno = EBADF;\r
+    }\r
+  }\r
+#endif\r
+\r
+  /* re-open previous stream */\r
+  if (_initdir (dirp) == 0) {\r
+    /* initialization failed but we cannot deal with error.  User will notice\r
+     * error later when she tries to retrieve first directory enty. */\r
+    /*EMPTY*/;\r
+  }\r
+}\r
+\r
+\r
+/*\r
+ * Open native directory stream object and retrieve first file.\r
+ * Be sure to close previous stream before opening new one.\r
+ */\r
+static int\r
+_initdir (DIR *dirp)\r
+{ \r
+  assert (dirp != NULL);\r
+  assert (dirp->dirname != NULL);\r
+  dirp->dirent_filled = 0;\r
+\r
+# if defined(DIRENT_WIN32_INTERFACE)\r
+  /* Open stream and retrieve first file */\r
+  dirp->search_handle = FindFirstFile (dirp->dirname, &dirp->current.data);\r
+  if (dirp->search_handle == INVALID_HANDLE_VALUE) {\r
+    /* something went wrong but we don't know what.  GetLastError() could\r
+     * give us more information about the error, but then we should map\r
+     * the error code into errno. */\r
+    errno = ENOENT;\r
+    return 0;\r
+  }\r
+\r
+# elif defined(DIRENT_MSDOS_INTERFACE)\r
+  if (_dos_findfirst (dirp->dirname,\r
+          _A_SUBDIR | _A_RDONLY | _A_ARCH | _A_SYSTEM | _A_HIDDEN,\r
+          &dirp->current.data) != 0)\r
+  {\r
+    /* _dos_findfirst and findfirst will set errno to ENOENT when no \r
+     * more entries could be retrieved. */\r
+    return 0;\r
+  }\r
+# endif\r
+\r
+  /* initialize DIR and it's first entry */\r
+  _setdirname (dirp);\r
+  dirp->dirent_filled = 1;\r
+  return 1;\r
+}\r
+\r
+\r
+/*\r
+ * Return implementation dependent name of the current directory entry.\r
+ */\r
+static const char *\r
+_getdirname (const struct dirent *dp)\r
+{\r
+#if defined(DIRENT_WIN32_INTERFACE)\r
+  return dp->data.cFileName;\r
+  \r
+#elif defined(DIRENT_USE_FFBLK)\r
+  return dp->data.ff_name;\r
+  \r
+#else\r
+  return dp->data.name;\r
+#endif  \r
+}\r
+\r
+\r
+/*\r
+ * Copy name of implementation dependent directory entry to the d_name field.\r
+ */\r
+static void\r
+_setdirname (struct DIR *dirp) {\r
+  /* make sure that d_name is long enough */\r
+  assert (strlen (_getdirname (&dirp->current)) <= NAME_MAX);\r
+  \r
+  strncpy (dirp->current.d_name,\r
+      _getdirname (&dirp->current),\r
+      NAME_MAX);\r
+  dirp->current.d_name[NAME_MAX] = '\0'; /*char d_name[NAME_MAX+1]*/\r
+}\r
+  \r
+# ifdef __cplusplus\r
+}\r
+# endif\r
+# define NAMLEN(dp) ((int)(strlen((dp)->d_name)))\r
+\r
+#else\r
+# error "missing dirent interface"\r
+#endif\r
+\r
+\r
+#endif /*DIRENT_H*/\r
diff --git a/applications/common/color.c b/applications/common/color.c
new file mode 100644 (file)
index 0000000..ac0921a
--- /dev/null
@@ -0,0 +1,463 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <math.h>
+
+#include "opj_config.h"
+#include "openjpeg.h"
+#include "color.h"
+
+#ifdef HAVE_LIBLCMS2
+#include <lcms2.h>
+#endif
+#ifdef HAVE_LIBLCMS1
+#include <lcms.h>
+#endif
+
+/*--------------------------------------------------------
+Matrix f�r sYCC, Amendment 1 to IEC 61966-2-1
+
+Y :   0.299   0.587    0.114   :R
+Cb:  -0.1687 -0.3312   0.5     :G
+Cr:   0.5    -0.4187  -0.0812  :B
+
+Inverse:
+
+R: 1        -3.68213e-05    1.40199      :Y
+G: 1.00003  -0.344125      -0.714128     :Cb - 2^(prec - 1)
+B: 0.999823  1.77204       -8.04142e-06  :Cr - 2^(prec - 1)
+
+-----------------------------------------------------------*/
+static void sycc_to_rgb(int offset, int upb, int y, int cb, int cr,
+       int *out_r, int *out_g, int *out_b)
+{
+       int r, g, b;
+
+       cb -= offset; cr -= offset;
+       r = y + (int)(1.402 * (float)cr);
+       if(r < 0) r = 0; else if(r > upb) r = upb; *out_r = r;
+
+       g = y - (int)(0.344 * (float)cb + 0.714 * (float)cr);
+       if(g < 0) g = 0; else if(g > upb) g = upb; *out_g = g;
+
+       b = y + (int)(1.772 * (float)cb);
+       if(b < 0) b = 0; else if(b > upb) b = upb; *out_b = b;
+}
+
+static void sycc444_to_rgb(opj_image_t *img)
+{
+       int *d0, *d1, *d2, *r, *g, *b;
+       const int *y, *cb, *cr;
+       int maxw, maxh, max, i, offset, upb;
+
+       i = img->comps[0].prec;
+       offset = 1<<(i - 1); upb = (1<<i)-1;
+
+       maxw = img->comps[0].w; maxh = img->comps[0].h;
+       max = maxw * maxh;
+
+       y = img->comps[0].data;
+       cb = img->comps[1].data;
+       cr = img->comps[2].data;
+
+       d0 = r = (int*)malloc(sizeof(int) * max);
+       d1 = g = (int*)malloc(sizeof(int) * max);
+       d2 = b = (int*)malloc(sizeof(int) * max);
+
+       for(i = 0; i < max; ++i)
+   {
+       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);        
+
+       ++y; ++cb; ++cr; ++r; ++g; ++b;
+   }   
+       free(img->comps[0].data); img->comps[0].data = d0;
+       free(img->comps[1].data); img->comps[1].data = d1;
+       free(img->comps[2].data); img->comps[2].data = d2;
+
+}/* sycc444_to_rgb() */
+
+static void sycc422_to_rgb(opj_image_t *img)
+{      
+       int *d0, *d1, *d2, *r, *g, *b;
+       const int *y, *cb, *cr;
+       int maxw, maxh, max, offset, upb;
+       int i, j;
+
+       i = img->comps[0].prec;
+       offset = 1<<(i - 1); upb = (1<<i)-1;
+
+       maxw = img->comps[0].w; maxh = img->comps[0].h;
+       max = maxw * maxh;
+
+       y = img->comps[0].data;
+       cb = img->comps[1].data;
+       cr = img->comps[2].data;
+
+       d0 = r = (int*)malloc(sizeof(int) * max);
+       d1 = g = (int*)malloc(sizeof(int) * max);
+       d2 = b = (int*)malloc(sizeof(int) * max);
+
+       for(i=0; i < maxh; ++i)
+   {
+       for(j=0; j < maxw; j += 2)
+  {
+       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
+
+       ++y; ++r; ++g; ++b;
+
+       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
+
+       ++y; ++r; ++g; ++b; ++cb; ++cr;
+  }
+   }
+       free(img->comps[0].data); img->comps[0].data = d0;
+       free(img->comps[1].data); img->comps[1].data = d1;
+       free(img->comps[2].data); img->comps[2].data = d2;
+
+       img->comps[1].w = maxw; img->comps[1].h = maxh;
+       img->comps[2].w = maxw; img->comps[2].h = maxh;
+       img->comps[1].dx = img->comps[0].dx;
+       img->comps[2].dx = img->comps[0].dx;
+       img->comps[1].dy = img->comps[0].dy;
+       img->comps[2].dy = img->comps[0].dy;
+
+}/* sycc422_to_rgb() */
+
+static void sycc420_to_rgb(opj_image_t *img)
+{
+       int *d0, *d1, *d2, *r, *g, *b, *nr, *ng, *nb;
+       const int *y, *cb, *cr, *ny;
+       int maxw, maxh, max, offset, upb;
+       int i, j;
+
+       i = img->comps[0].prec;
+       offset = 1<<(i - 1); upb = (1<<i)-1;
+
+       maxw = img->comps[0].w; maxh = img->comps[0].h;
+       max = maxw * maxh;
+
+       y = img->comps[0].data;
+       cb = img->comps[1].data;
+       cr = img->comps[2].data;
+
+       d0 = r = (int*)malloc(sizeof(int) * max);
+       d1 = g = (int*)malloc(sizeof(int) * max);
+       d2 = b = (int*)malloc(sizeof(int) * max);
+
+       for(i=0; i < maxh; i += 2)
+   {
+       ny = y + maxw;
+       nr = r + maxw; ng = g + maxw; nb = b + maxw;
+
+       for(j=0; j < maxw;  j += 2)
+  {
+       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
+
+       ++y; ++r; ++g; ++b;
+
+       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
+
+       ++y; ++r; ++g; ++b;
+
+       sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
+
+       ++ny; ++nr; ++ng; ++nb;
+
+       sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
+
+       ++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
+  }
+       y += maxw; r += maxw; g += maxw; b += maxw;
+   }
+       free(img->comps[0].data); img->comps[0].data = d0;
+       free(img->comps[1].data); img->comps[1].data = d1;
+       free(img->comps[2].data); img->comps[2].data = d2;
+
+       img->comps[1].w = maxw; img->comps[1].h = maxh;
+       img->comps[2].w = maxw; img->comps[2].h = maxh;
+       img->comps[1].dx = img->comps[0].dx;
+       img->comps[2].dx = img->comps[0].dx;
+       img->comps[1].dy = img->comps[0].dy;
+       img->comps[2].dy = img->comps[0].dy;
+
+}/* sycc420_to_rgb() */
+
+void color_sycc_to_rgb(opj_image_t *img)
+{
+       if(img->numcomps < 3) 
+   {
+       img->color_space = CLRSPC_GRAY;
+       return;
+   }
+
+       if((img->comps[0].dx == 1)
+       && (img->comps[1].dx == 2)
+       && (img->comps[2].dx == 2)
+       && (img->comps[0].dy == 1)
+       && (img->comps[1].dy == 2)
+       && (img->comps[2].dy == 2))/* horizontal and vertical sub-sample */
+  {
+       sycc420_to_rgb(img);
+  }
+       else
+       if((img->comps[0].dx == 1)
+       && (img->comps[1].dx == 2)
+       && (img->comps[2].dx == 2)
+       && (img->comps[0].dy == 1)
+       && (img->comps[1].dy == 1)
+       && (img->comps[2].dy == 1))/* horizontal sub-sample only */
+  {
+       sycc422_to_rgb(img);
+  }
+       else
+       if((img->comps[0].dx == 1)
+       && (img->comps[1].dx == 1)
+       && (img->comps[2].dx == 1)
+       && (img->comps[0].dy == 1)
+       && (img->comps[1].dy == 1)
+       && (img->comps[2].dy == 1))/* no sub-sample */
+  {
+       sycc444_to_rgb(img);
+  }
+       else
+  {
+       fprintf(stderr,"%s:%d:color_sycc_to_rgb\n\tCAN NOT CONVERT\n",
+        __FILE__,__LINE__);
+       return;
+  }
+       img->color_space = CLRSPC_SRGB;
+
+}/* color_sycc_to_rgb() */
+
+#if defined(HAVE_LIBLCMS2) || defined(HAVE_LIBLCMS1)
+#ifdef HAVE_LIBLCMS1
+/* Bob Friesenhahn proposed:*/
+#define cmsSigXYZData   icSigXYZData
+#define cmsSigLabData   icSigLabData
+#define cmsSigCmykData  icSigCmykData
+#define cmsSigYCbCrData icSigYCbCrData
+#define cmsSigLuvData   icSigLuvData
+#define cmsSigGrayData  icSigGrayData
+#define cmsSigRgbData   icSigRgbData
+#define cmsUInt32Number DWORD
+
+#define cmsColorSpaceSignature icColorSpaceSignature
+#define cmsGetHeaderRenderingIntent cmsTakeRenderingIntent
+
+#endif /* HAVE_LIBLCMS1 */
+
+void color_apply_icc_profile(opj_image_t *image)
+{
+       cmsHPROFILE in_prof, out_prof;
+       cmsHTRANSFORM transform;
+       cmsColorSpaceSignature in_space, out_space;
+       cmsUInt32Number intent, in_type, out_type, nr_samples;
+       int *r, *g, *b;
+       int prec, i, max, max_w, max_h;
+       OPJ_COLOR_SPACE oldspace;
+
+       in_prof = 
+        cmsOpenProfileFromMem(image->icc_profile_buf, image->icc_profile_len);
+       in_space = cmsGetPCS(in_prof);
+       out_space = cmsGetColorSpace(in_prof);
+       intent = cmsGetHeaderRenderingIntent(in_prof);
+
+       
+       max_w = image->comps[0].w; max_h = image->comps[0].h;
+       prec = image->comps[0].prec;
+       oldspace = image->color_space;
+
+       if(out_space == cmsSigRgbData) /* enumCS 16 */
+   {
+       in_type = TYPE_RGB_16;
+       out_type = TYPE_RGB_16;
+       out_prof = cmsCreate_sRGBProfile();
+       image->color_space = CLRSPC_SRGB;
+   }
+       else
+       if(out_space == cmsSigGrayData) /* enumCS 17 */
+   {
+       in_type = TYPE_GRAY_8;
+       out_type = TYPE_RGB_8;
+       out_prof = cmsCreate_sRGBProfile();
+       image->color_space = CLRSPC_SRGB;
+   }
+       else
+       if(out_space == cmsSigYCbCrData) /* enumCS 18 */
+   {
+       in_type = TYPE_YCbCr_16;
+       out_type = TYPE_RGB_16;
+       out_prof = cmsCreate_sRGBProfile();
+       image->color_space = CLRSPC_SRGB;
+   }
+       else
+   {
+#ifdef DEBUG_PROFILE
+fprintf(stderr,"%s:%d: color_apply_icc_profile\n\tICC Profile has unknown "
+"output colorspace(%#x)(%c%c%c%c)\n\tICC Profile ignored.\n",
+__FILE__,__LINE__,out_space,
+(out_space>>24) & 0xff,(out_space>>16) & 0xff,
+(out_space>>8) & 0xff, out_space & 0xff);
+#endif
+       return;
+   }
+
+#ifdef DEBUG_PROFILE
+fprintf(stderr,"%s:%d:color_apply_icc_profile\n\tchannels(%d) prec(%d) w(%d) h(%d)"
+"\n\tprofile: in(%p) out(%p)\n",__FILE__,__LINE__,image->numcomps,prec,
+max_w,max_h, (void*)in_prof,(void*)out_prof);
+
+fprintf(stderr,"\trender_intent (%u)\n\t"
+"color_space: in(%#x)(%c%c%c%c)   out:(%#x)(%c%c%c%c)\n\t"
+"       type: in(%u)              out:(%u)\n",
+intent,
+in_space,
+(in_space>>24) & 0xff,(in_space>>16) & 0xff,
+(in_space>>8) & 0xff, in_space & 0xff,
+
+out_space,
+(out_space>>24) & 0xff,(out_space>>16) & 0xff,
+(out_space>>8) & 0xff, out_space & 0xff,
+
+in_type,out_type
+ );
+#endif /* DEBUG_PROFILE */
+
+       transform = cmsCreateTransform(in_prof, in_type,
+        out_prof, out_type, intent, 0);
+
+#ifdef HAVE_LIBLCMS2
+/* Possible for: LCMS_VERSION >= 2000 :*/
+       cmsCloseProfile(in_prof);
+       cmsCloseProfile(out_prof);
+#endif
+
+       if(transform == NULL)
+   {
+#ifdef DEBUG_PROFILE
+fprintf(stderr,"%s:%d:color_apply_icc_profile\n\tcmsCreateTransform failed. "
+"ICC Profile ignored.\n",__FILE__,__LINE__);
+#endif
+       image->color_space = oldspace;
+#ifdef HAVE_LIBLCMS1
+       cmsCloseProfile(in_prof);
+       cmsCloseProfile(out_prof);
+#endif
+       return;
+   }
+
+       if(image->numcomps > 2)/* RGB, RGBA */
+   {
+       unsigned short *inbuf, *outbuf, *in, *out;
+       max = max_w * max_h; nr_samples = max * 3 * sizeof(unsigned short);
+       in = inbuf = (unsigned short*)malloc(nr_samples);
+       out = outbuf = (unsigned short*)malloc(nr_samples);
+
+       r = image->comps[0].data;
+       g = image->comps[1].data;
+       b = image->comps[2].data;
+
+       for(i = 0; i < max; ++i)
+  {
+       *in++ = (unsigned short)*r++;
+       *in++ = (unsigned short)*g++;
+       *in++ = (unsigned short)*b++;
+  }
+
+       cmsDoTransform(transform, inbuf, outbuf, max);
+
+       r = image->comps[0].data;
+       g = image->comps[1].data;
+       b = image->comps[2].data;
+
+       for(i = 0; i < max; ++i)
+  {
+       *r++ = (int)*out++;
+       *g++ = (int)*out++;
+       *b++ = (int)*out++;
+  }
+       free(inbuf); free(outbuf);
+   }
+       else /* GRAY, GRAYA */
+   {
+       unsigned char *in, *inbuf, *out, *outbuf;
+
+       max = max_w * max_h; nr_samples = max * 3 * sizeof(unsigned char);
+       in = inbuf = (unsigned char*)malloc(nr_samples);
+       out = outbuf = (unsigned char*)malloc(nr_samples);
+
+       image->comps = (opj_image_comp_t*)
+        realloc(image->comps, (image->numcomps+2)*sizeof(opj_image_comp_t));
+
+       if(image->numcomps == 2)
+        image->comps[3] = image->comps[1];
+
+       image->comps[1] = image->comps[0];
+       image->comps[2] = image->comps[0];
+
+       image->comps[1].data = (int*)calloc(max, sizeof(int));
+       image->comps[2].data = (int*)calloc(max, sizeof(int));
+
+       image->numcomps += 2;
+
+       r = image->comps[0].data;
+
+       for(i = 0; i < max; ++i)
+  {
+       *in++ = (unsigned char)*r++;
+  }
+       cmsDoTransform(transform, inbuf, outbuf, max);
+
+       r = image->comps[0].data;
+       g = image->comps[1].data;
+       b = image->comps[2].data;
+
+       for(i = 0; i < max; ++i)
+  {
+       *r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++;
+  }
+       free(inbuf); free(outbuf);
+
+   }/* if(image->numcomps */
+
+       cmsDeleteTransform(transform);
+
+#ifdef HAVE_LIBLCMS1
+       cmsCloseProfile(in_prof);
+       cmsCloseProfile(out_prof);
+#endif
+}/* color_apply_icc_profile() */
+
+#endif /* HAVE_LIBLCMS2 || HAVE_LIBLCMS1 */
+
diff --git a/applications/common/color.h b/applications/common/color.h
new file mode 100644 (file)
index 0000000..26117b0
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _OPJ_COLOR_H_
+#define _OPJ_COLOR_H_
+
+extern void color_sycc_to_rgb(opj_image_t *img);
+extern void color_apply_icc_profile(opj_image_t *image);
+
+#endif /* _OPJ_COLOR_H_ */
diff --git a/applications/common/format_defs.h b/applications/common/format_defs.h
new file mode 100644 (file)
index 0000000..d4be93b
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _OPJ_FORMAT_DEFS_H_
+#define _OPJ_FORMAT_DEFS_H_
+
+#define J2K_CFMT 0
+#define JP2_CFMT 1
+#define JPT_CFMT 2
+
+#define PXM_DFMT 10
+#define PGX_DFMT 11
+#define BMP_DFMT 12
+#define YUV_DFMT 13
+#define TIF_DFMT 14
+#define RAW_DFMT 15
+#define TGA_DFMT 16
+#define PNG_DFMT 17
+
+#endif /* _OPJ_FORMAT_DEFS_H_ */
\ No newline at end of file
diff --git a/applications/common/getopt.c b/applications/common/getopt.c
new file mode 100644 (file)
index 0000000..5e444d3
--- /dev/null
@@ -0,0 +1,261 @@
+/*
+ * Copyright (c) 1987, 1993, 1994
+ *     The Regents of the University of California.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 4. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* last review : october 29th, 2002 */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+static char sccsid[] = "@(#)getopt.c   8.3 (Berkeley) 4/27/95";
+#endif                         /* LIBC_SCCS and not lint */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+int opterr = 1,                        /* if error message should be printed */
+ optind = 1,                   /* index into parent argv vector */
+ optopt,                       /* character checked for validity */
+ optreset;                     /* reset getopt */
+const char *optarg;                    /* argument associated with option */
+
+typedef struct option
+{
+       const char *name;
+       int has_arg;
+       int *flag;
+       int val;
+}option_t;
+
+#define        BADCH   (int)'?'
+#define        BADARG  (int)':'
+#define        EMSG    ""
+
+/* As this class remembers its values from one Java call to the other, reset the values before each use */
+void reset_options_reading() {
+       opterr = 1;
+       optind = 1;
+}
+
+/*
+ * getopt --
+ *     Parse argc/argv argument vector.
+ */
+int getopt(int nargc, char *const *nargv, const char *ostr) {
+#  define __progname nargv[0]
+  static const char *place = EMSG;     /* option letter processing */
+  char *oli;                   /* option letter list index */
+
+  if (optreset || !*place) {   /* update scanning pointer */
+    optreset = 0;
+    if (optind >= nargc || *(place = nargv[optind]) != '-') {
+      place = EMSG;
+      return (-1);
+    }
+    if (place[1] && *++place == '-') { /* found "--" */
+      ++optind;
+      place = EMSG;
+      return (-1);
+    }
+  }                            /* option letter okay? */
+  if ((optopt = (int) *place++) == (int) ':' ||
+      !(oli = strchr(ostr, optopt))) {
+    /*
+     * if the user didn't specify '-' as an option,
+     * assume it means -1.
+     */
+    if (optopt == (int) '-')
+      return (-1);
+    if (!*place)
+      ++optind;
+               if (opterr && *ostr != ':') {
+      fprintf(stderr,
+                    "%s: illegal option -- %c\n", __progname, optopt);
+                       return (BADCH);
+               }
+  }
+  if (*++oli != ':') {         /* don't need argument */
+    optarg = NULL;
+    if (!*place)
+      ++optind;
+  } else {                     /* need an argument */
+    if (*place)                        /* no white space */
+      optarg = place;
+    else if (nargc <= ++optind) {      /* no arg */
+      place = EMSG;
+      if (*ostr == ':')
+       return (BADARG);
+                       if (opterr) {
+                               fprintf(stderr,
+                      "%s: option requires an argument -- %c\n",
+                      __progname, optopt);
+                               return (BADCH);
+                       }
+    } else                     /* white space */
+      optarg = nargv[optind];
+    place = EMSG;
+    ++optind;
+  }
+  return (optopt);             /* dump back option letter */
+}
+
+
+int getopt_long(int argc, char * const argv[], const char *optstring,
+struct option *longopts, int totlen) {
+       static int lastidx,lastofs;
+       char *tmp;
+       int i,len;
+       char param = 1;
+
+again:
+       if (optind >= argc || !argv[optind] || *argv[optind]!='-')
+               return -1;
+
+       if (argv[optind][0]=='-' && argv[optind][1]==0) {
+               if(optind >= (argc - 1)){ /* no more input parameters */
+                       param = 0;
+               }
+               else{ /* more input parameters */
+                       if(argv[optind + 1][0] == '-'){
+                               param = 0; /* Missing parameter after '-' */
+                       }
+                       else{
+                               param = 2;
+                       }
+               }
+       }
+
+       if (param == 0) {
+               ++optind;
+               return (BADCH);
+       }
+
+       if (argv[optind][0]=='-') {     /* long option */
+               char* arg=argv[optind]+1;
+               const struct option* o;
+               o=longopts;
+               len=sizeof(longopts[0]);
+
+               if (param > 1){
+                       arg = argv[optind+1];
+                       optind++;
+               }
+               else
+                       arg = argv[optind]+1;
+
+               if(strlen(arg)>1){
+                       for (i=0;i<totlen;i=i+len,o++) {
+                               if (!strcmp(o->name,arg)) {     /* match */
+                                       if (o->has_arg == 0) {
+                                               if ((argv[optind+1])&&(!(argv[optind+1][0]=='-'))){
+                                                       fprintf(stderr,"%s: option does not require an argument. Ignoring %s\n",arg,argv[optind+1]);
+                                                       ++optind;
+                                               }
+                                       }else{ 
+                                               optarg=argv[optind+1];
+                                               if(optarg){
+                                                       if (optarg[0] == '-'){ /* Has read next input parameter: No arg for current parameter */                                                                
+                                                               if (opterr) {
+                                                                       fprintf(stderr,"%s: option requires an argument\n",arg);
+                                                                       return (BADCH);
+                                                               }
+                                                       }
+                                               }
+                                               if (!optarg && o->has_arg==1) { /* no argument there */
+                                                       if (opterr) {
+                                                               fprintf(stderr,"%s: option requires an argument \n",arg);
+                                                               return (BADCH);
+                                                       }
+                                               }
+                                               ++optind;
+                                       }
+                                       ++optind;
+                                       if (o->flag)
+                                               *(o->flag)=o->val;
+                                       else
+                                               return o->val;
+                                       return 0;
+                               }
+                       }//(end for)String not found in the list
+                       fprintf(stderr,"Invalid option %s\n",arg);
+                       ++optind;
+                       return (BADCH);
+               }else{ /*Single character input parameter*/
+                       if (*optstring==':') return ':';
+                       if (lastidx!=optind) {
+                               lastidx=optind; lastofs=0;
+                       }
+                       optopt=argv[optind][lastofs+1];
+                       if ((tmp=strchr(optstring,optopt))) {/*Found input parameter in list*/
+                               if (*tmp==0) {  /* apparently, we looked for \0, i.e. end of argument */
+                                       ++optind;
+                                       goto again;
+                               }
+                               if (tmp[1]==':') {      /* argument expected */
+                                       if (tmp[2]==':' || argv[optind][lastofs+2]) {   /* "-foo", return "oo" as optarg */
+                                               if (!*(optarg=argv[optind]+lastofs+2)) optarg=0;
+                                               goto found;
+                                       }
+                                       optarg=argv[optind+1];
+                                       if(optarg){
+                                               if (optarg[0] == '-'){ /* Has read next input parameter: No arg for current parameter */
+                                                       if (opterr) {
+                                                               fprintf(stderr,"%s: option requires an argument\n",arg);
+                                                               return (BADCH);
+                                                       }
+                                               }
+                                       }
+                                       if (!optarg) {  /* missing argument */
+                                               if (opterr) {
+                                                       fprintf(stderr,"%s: option requires an argument\n",arg);
+                                                       return (BADCH);
+                                               }
+                                       }
+                                       ++optind;
+                               }else {/*Argument not expected*/
+                                       ++lastofs;
+                                       return optopt;
+                               }
+found:
+                               ++optind;
+                               return optopt;
+                       }       else {  /* not found */
+                               fprintf(stderr,"Invalid option %s\n",arg);
+                               ++optind;
+                               return (BADCH);
+                       }//end of not found
+               
+               }// end of single character
+       }//end '-'
+       fprintf(stderr,"Invalid option\n");
+       ++optind;
+       return (BADCH);;
+}//end function
diff --git a/applications/common/getopt.h b/applications/common/getopt.h
new file mode 100644 (file)
index 0000000..779fe47
--- /dev/null
@@ -0,0 +1,29 @@
+/* last review : october 29th, 2002 */
+
+#ifndef _GETOPT_H_
+#define _GETOPT_H_
+
+typedef struct option
+{
+       const char *name;
+       int has_arg;
+       int *flag;
+       int val;
+}option_t;
+
+#define        NO_ARG  0
+#define REQ_ARG        1
+#define OPT_ARG        2
+
+extern int opterr;
+extern int optind;
+extern int optopt;
+extern int optreset;
+extern char *optarg;
+
+extern int getopt(int nargc, char *const *nargv, const char *ostr);
+extern int getopt_long(int argc, char * const argv[], const char *optstring,
+                       const struct option *longopts, int totlen);
+extern void reset_options_reading();
+
+#endif                         /* _GETOPT_H_ */
diff --git a/applications/indexer_JPIP/CMakeLists.txt b/applications/indexer_JPIP/CMakeLists.txt
new file mode 100644 (file)
index 0000000..c8e378d
--- /dev/null
@@ -0,0 +1,9 @@
+# index_create
+
+ADD_EXECUTABLE(index_create
+bio.c cio.c int.c pi.c t2.c tgt.c tcd.c index_create.c jpip.c jp2.c
+)
+INSTALL(TARGETS index_create
+  EXPORT OpenJPEGTargets
+  DESTINATION ${OPENJPEG_INSTALL_BIN_DIR} COMPONENT Applications
+)
diff --git a/applications/indexer_JPIP/Makefile b/applications/indexer_JPIP/Makefile
new file mode 100644 (file)
index 0000000..40c049e
--- /dev/null
@@ -0,0 +1,23 @@
+CC = gcc
+
+LDFLAGS = -lm
+CFLAGS = -Wall
+
+all: index_create
+
+
+bio.o : bio.c bio.h
+cio.o : cio.c cio.h
+int.o : int.c
+pi.o  : pi.c pi.h int.h
+index_create.o : index_create.c j2k.h cio.h tcd.h int.h
+t2.o  : t2.c t2.h tcd.h bio.h j2k.h pi.h tgt.h int.h cio.h
+tgt.o : tgt.c bio.h tgt.h
+tcd.o : tcd.c tcd.h t2.h int.h
+jpip.o : jpip.c j2k.h cio.h tcd.h int.h
+jp2.o : jp2.c j2k.h cio.h tcd.h int.h
+
+index_create : bio.o cio.o int.o pi.o t2.o tgt.o tcd.o index_create.o jpip.o jp2.o
+
+clean:
+       rm -rf *.o *.*~ *~ core.*
diff --git a/applications/indexer_JPIP/bio.c b/applications/indexer_JPIP/bio.c
new file mode 100644 (file)
index 0000000..2c989e5
--- /dev/null
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "bio.h"
+#include <setjmp.h>
+
+static unsigned char *bio_start, *bio_end, *bio_bp;
+static unsigned int bio_buf;
+static int bio_ct;
+
+extern jmp_buf j2k_error;
+
+/// <summary>
+/// Number of bytes written.
+/// </summary>
+int bio_numbytes() {
+    return bio_bp-bio_start;
+}
+
+/// <summary>
+/// Init decoder.
+/// </summary>
+/// <param name="bp">Input buffer</param>
+/// <param name="len">Input buffer length</param>
+void bio_init_dec(unsigned char *bp, int len) {
+    bio_start=bp;
+    bio_end=bp+len;
+    bio_bp=bp;
+    bio_buf=0;
+    bio_ct=0;
+}
+
+int bio_byteout()
+{
+       bio_buf = (bio_buf << 8) & 0xffff;
+       bio_ct = bio_buf == 0xff00 ? 7 : 8;
+       if (bio_bp >= bio_end)
+               return 1;
+       *bio_bp++ = bio_buf >> 8;
+       return 0;
+}
+
+/// <summary>
+/// Read byte. 
+/// </summary>
+int bio_bytein() {
+    bio_buf=(bio_buf<<8)&0xffff;
+    bio_ct=bio_buf==0xff00?7:8;
+    if (bio_bp>=bio_end) return 1; //longjmp(j2k_error, 1);
+    bio_buf|=*bio_bp++;
+    return 0;
+}
+
+/// <summary>
+/// Read bit.
+/// </summary>
+int bio_getbit() {
+    if (bio_ct==0) {
+        bio_bytein();
+    }
+    bio_ct--;
+    return (bio_buf>>bio_ct)&1;
+}
+
+/// <summary>
+/// Read bits.
+/// </summary>
+/// <param name="n">Number of bits to read</param>
+int bio_read(int n) {
+    int i, v;
+    v=0;
+    for (i=n-1; i>=0; i--) {
+        v+=bio_getbit()<<i;
+    }
+    return v;
+}
+
+/// <summary>
+/// Flush bits.
+/// </summary>
+int bio_flush() {
+    bio_ct=0;
+    bio_byteout();
+    if (bio_ct==7) {
+        bio_ct=0;
+       if ( bio_byteout()) return 1;;
+    }
+    return 0;
+}
+
+/// <summary>
+/// </summary>
+int bio_inalign() {
+    bio_ct=0;
+    if ((bio_buf&0xff)==0xff) {
+       if( bio_bytein()) return 1;
+        bio_ct=0;
+    }
+    return 0;
+}
diff --git a/applications/indexer_JPIP/bio.h b/applications/indexer_JPIP/bio.h
new file mode 100644 (file)
index 0000000..eea6cff
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003-2004, Yannick Verschueren
+ * Copyright (c) 2003-2004, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __BIO_H
+#define __BIO_H
+
+int bio_numbytes();
+void bio_init_dec(unsigned char *bp, int len);
+int bio_read(int n);
+int bio_flush();
+int bio_inalign();
+
+#endif
diff --git a/applications/indexer_JPIP/cio.c b/applications/indexer_JPIP/cio.c
new file mode 100644 (file)
index 0000000..29f160e
--- /dev/null
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "cio.h"
+#include <setjmp.h>
+
+static unsigned char *cio_start, *cio_end, *cio_bp;
+
+extern jmp_buf j2k_error;
+
+/// <summary>
+/// Number of bytes written.
+/// </summary>
+int cio_numbytes() {
+    return cio_bp-cio_start;
+}
+
+/// <summary>
+/// Get position in byte stream.
+/// </summary>
+int cio_tell() {
+    return cio_bp-cio_start;
+}
+
+/// <summary>
+/// Set position in byte stream.
+/// </summary>
+void cio_seek(int pos) {
+    cio_bp=cio_start+pos;
+}
+
+/// <summary>
+/// Number of bytes left before the end of the stream.
+/// </summary>
+int cio_numbytesleft() {
+    return cio_end-cio_bp;
+}
+
+/// <summary>
+/// Get pointer to the current position in the stream.
+/// </summary>
+unsigned char *cio_getbp() {
+    return cio_bp;
+}
+
+/// <summary>
+/// Initialize byte IO.
+/// </summary>
+void cio_init(unsigned char *bp, int len) {
+    cio_start=bp;
+    cio_end=bp+len;
+    cio_bp=bp;
+}
+
+/// <summary>
+/// Write a byte.
+/// </summary>
+void cio_byteout(unsigned char v) {
+  if (cio_bp>=cio_end) longjmp(j2k_error, 1);
+  *cio_bp++=v;
+    
+}
+
+/// <summary>
+/// Read a byte.
+/// </summary>
+unsigned char cio_bytein() {
+    if (cio_bp>=cio_end) longjmp(j2k_error, 1);
+    return *cio_bp++;
+}
+
+/// <summary>
+/// Write a byte.
+/// </summary>
+//void cio_write(unsigned int v, int n) {
+void cio_write(long long v, int n) {
+    int i;
+    for (i=n-1; i>=0; i--) 
+      {
+       cio_byteout((unsigned char)((v>>(i<<3))&0xff));
+      }
+}
+
+/// <summary>
+/// Read some bytes.
+/// </summary>
+/* unsigned int cio_read(int n) { */
+long long cio_read(int n) {
+    int i;
+    /*unsigned int v;*/
+    long long v;
+    v=0;
+    for (i=n-1; i>=0; i--) {
+      v+=cio_bytein()<<(i<<3);
+    }
+    return v;
+}
+
+/// <summary>
+/// Write some bytes.
+/// </summary>
+void cio_skip(int n) {
+    cio_bp+=n;
+}
diff --git a/applications/indexer_JPIP/cio.h b/applications/indexer_JPIP/cio.h
new file mode 100644 (file)
index 0000000..3e29789
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003-2004, Yannick Verschueren
+ * Copyright (c) 2003-2004, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __CIO_H
+#define __CIO_H
+
+int cio_tell();
+void cio_seek(int pos);
+int cio_numbytes();
+int cio_numbytesleft();
+unsigned char *cio_getbp();
+void cio_init(unsigned char *bp, int len);
+/* void cio_write(unsigned int v, int n); */
+void cio_write(long long v, int n);
+/* unsigned int cio_read(int n); */
+long long cio_read(int n);
+void cio_skip(int n);
+
+#endif
diff --git a/applications/indexer_JPIP/fix.c b/applications/indexer_JPIP/fix.c
new file mode 100644 (file)
index 0000000..6bf08c6
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "fix.h"
+
+#ifdef _WIN32
+#include <windows.h>
+
+#define int64 __int64
+#else
+#define int64 long long
+#endif /* _WIN32 */
+
+/// <summary>
+/// Multiply two fixed-precision rational numbers.
+/// </summary>
+int fix_mul(int a, int b) {
+    return (int)((int64)a*(int64)b>>13);
+}
diff --git a/applications/indexer_JPIP/fix.h b/applications/indexer_JPIP/fix.h
new file mode 100644 (file)
index 0000000..4b6e1b5
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __FIX_H
+#define __FIX_H
+
+int fix_mul(int a, int b);
+
+#endif
diff --git a/applications/indexer_JPIP/index_create.c b/applications/indexer_JPIP/index_create.c
new file mode 100644 (file)
index 0000000..518e70f
--- /dev/null
@@ -0,0 +1,1219 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003-2004, Yannick Verschueren
+ * Copyright (c) 2003-2004, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <setjmp.h>
+#include <math.h>
+
+#include "j2k.h"
+#include "cio.h"
+#include "tcd.h"
+#include "int.h"
+#include "jpip.h"
+#include "jp2.h"
+
+#define J2K_MS_SOC 0xff4f
+#define J2K_MS_SOT 0xff90
+#define J2K_MS_SOD 0xff93
+#define J2K_MS_EOC 0xffd9
+#define J2K_MS_SIZ 0xff51
+#define J2K_MS_COD 0xff52
+#define J2K_MS_COC 0xff53
+#define J2K_MS_RGN 0xff5e
+#define J2K_MS_QCD 0xff5c
+#define J2K_MS_QCC 0xff5d
+#define J2K_MS_POC 0xff5f
+#define J2K_MS_TLM 0xff55
+#define J2K_MS_PLM 0xff57
+#define J2K_MS_PLT 0xff58
+#define J2K_MS_PPM 0xff60
+#define J2K_MS_PPT 0xff61
+#define J2K_MS_SOP 0xff91
+#define J2K_MS_EPH 0xff92
+#define J2K_MS_CRG 0xff63
+#define J2K_MS_COM 0xff64
+
+#define J2K_STATE_MHSOC 0x0001
+#define J2K_STATE_MHSIZ 0x0002
+#define J2K_STATE_MH 0x0004
+#define J2K_STATE_TPHSOT 0x0008
+#define J2K_STATE_TPH 0x0010
+#define J2K_STATE_MT 0x0020
+
+#define START_NB 5
+#define INCREMENT 5
+
+jmp_buf j2k_error;
+
+static int j2k_state;
+static int j2k_curtileno;
+static j2k_tcp_t j2k_default_tcp;
+static unsigned char *j2k_eot;
+
+static j2k_image_t *j2k_img;
+static j2k_cp_t *j2k_cp;
+
+static unsigned char **j2k_tile_data;
+static int *j2k_tile_len;
+
+static info_image_t img;
+
+
+void j2k_clean() {
+  int tileno = 0;
+  int compno=0, resno=0, precno=0;
+
+  tcd_free(j2k_img, j2k_cp);
+  for (tileno = 0; tileno < j2k_cp->tw * j2k_cp->th; tileno++) {
+    info_tile_t *tile_Idx = &img.tile[tileno];
+    
+    for (compno = 0; compno < img.Comp; compno++)
+      {
+       info_compo_t *compo_Idx = &tile_Idx->compo[compno];
+       for(resno = 0; resno < img.Decomposition + 1; resno++)
+         {
+           info_reso_t *reso_Idx = &compo_Idx->reso[resno];
+           for (precno = 0; precno < img.tile[tileno].pw * img.tile[tileno].ph; precno++)
+             {
+               info_prec_t *prec_Idx = &reso_Idx->prec[precno];
+               free(prec_Idx->layer);
+             }
+           free(reso_Idx->prec);
+         }
+       free(compo_Idx->reso);
+      }
+    free(tile_Idx->compo);
+    free(tile_Idx->marker);
+    free(tile_Idx->tile_parts);
+    free(tile_Idx->marker_mul.COC);
+    free(tile_Idx->marker_mul.RGN);
+    free(tile_Idx->marker_mul.QCC);
+    free(tile_Idx->marker_mul.PLT);
+    free(tile_Idx->marker_mul.PPT);
+    free(tile_Idx->marker_mul.COM);
+}
+  free(img.tile);
+  free(img.marker);
+  free(img.marker_mul.COC);
+  free(img.marker_mul.RGN);
+  free(img.marker_mul.QCC);
+  free(img.marker_mul.PLM);
+  free(img.marker_mul.PPM);
+  free(img.marker_mul.COM);
+}
+
+
+
+void j2k_read_soc() {
+  j2k_state=J2K_STATE_MHSIZ;
+}
+
+
+
+void j2k_read_siz() {
+    int len, i;
+    info_tile_t *tile;
+
+    len = cio_read(2);
+
+    /* <INDEX> [MHIX BOX] */
+    img.marker[img.num_marker].type = J2K_MS_SIZ;
+    img.marker[img.num_marker].start_pos = cio_tell()-2;
+    img.marker[img.num_marker].len = len;
+    img.num_marker++;
+    /* </INDEX> [MHIX BOX] */
+    
+    cio_read(2);                      /* Rsiz (capabilities) */
+    j2k_img->x1 = cio_read(4);        /* Xsiz                */
+    j2k_img->y1 = cio_read(4);        /* Ysiz                */
+    j2k_img->x0 = cio_read(4);        /* X0siz               */
+    j2k_img->y0 = cio_read(4);        /* Y0siz               */
+    j2k_cp->tdx = cio_read(4);        /* XTsiz               */
+    j2k_cp->tdy = cio_read(4);        /* YTsiz               */
+    j2k_cp->tx0 = cio_read(4);        /* XT0siz              */
+    j2k_cp->ty0 = cio_read(4);        /* YTOsiz              */
+
+    j2k_img->numcomps = cio_read(2);  /* Csiz                */
+    j2k_img->comps = (j2k_comp_t*)malloc(j2k_img->numcomps * sizeof(j2k_comp_t));
+    for (i = 0; i < j2k_img->numcomps; i++) {
+        int tmp, w, h;
+        tmp = cio_read(1);
+        j2k_img->comps[i].prec = (tmp & 0x7f) + 1;
+        j2k_img->comps[i].sgnd = tmp >> 7;
+        j2k_img->comps[i].dx = cio_read(1);
+        j2k_img->comps[i].dy = cio_read(1);
+        w = int_ceildiv(j2k_img->x1-j2k_img->x0, j2k_img->comps[i].dx);
+        h = int_ceildiv(j2k_img->y1-j2k_img->y0, j2k_img->comps[i].dy);
+        j2k_img->comps[i].data = (int*)malloc(sizeof(int) * w * h);
+    }
+    j2k_cp->tw = int_ceildiv(j2k_img->x1 - j2k_cp->tx0, j2k_cp->tdx);
+    j2k_cp->th = int_ceildiv(j2k_img->y1 - j2k_cp->ty0, j2k_cp->tdy);
+
+    j2k_cp->tcps = (j2k_tcp_t*)calloc((j2k_cp->tw * j2k_cp->th), sizeof(j2k_tcp_t));
+
+    for (i = 0; i < j2k_cp->tw * j2k_cp->th; i++)
+      {
+       j2k_cp->tcps[i].POC = 0;
+       j2k_cp->tcps[i].numpocs = 0;
+       // j2k_cp->tcps[i].first=1;
+      }
+
+    /* Initialization for PPM marker */
+    j2k_cp->ppm = 0;
+    j2k_cp->ppm_data = NULL;
+    j2k_cp->ppm_previous = 0;
+    j2k_cp->ppm_store = 0;
+
+    j2k_default_tcp.tccps = (j2k_tccp_t*)malloc(j2k_img->numcomps * sizeof(j2k_tccp_t));
+    for (i = 0; i < j2k_cp->tw * j2k_cp->th; i++) {
+       j2k_cp->tcps[i].tccps = (j2k_tccp_t*)malloc(j2k_img->numcomps * sizeof(j2k_tccp_t));
+    }
+    j2k_tile_data = (unsigned char**)calloc(j2k_cp->tw * j2k_cp->th, sizeof(char*));
+    j2k_tile_len = (int*)calloc(j2k_cp->tw * j2k_cp->th, sizeof(int));
+    j2k_state = J2K_STATE_MH;
+
+    /* <INDEX> */
+    img.Im_w = j2k_img->x1 - j2k_img->x0;
+    img.Im_h = j2k_img->y1 - j2k_img->y0;
+    img.Tile_x = j2k_cp->tdx;
+    img.Tile_y = j2k_cp->tdy;
+    img.Comp = j2k_img->numcomps;
+    img.tw = j2k_cp->tw;
+    img.th = j2k_cp->th;
+    img.tile = (info_tile_t*)malloc(img.tw * img.th * sizeof(info_tile_t));
+
+    for (i = 0; i < img.tw * img.th; i++)
+      {
+       tile = &img.tile[i];
+       tile->marker = (info_marker_t*)malloc(32 * sizeof(info_marker_t));
+       tile->num_marker = 0;
+       tile->marker_mul.num_COC = 0;
+       tile->marker_mul.CzCOC = START_NB;
+       tile->marker_mul.num_RGN = 0;
+       tile->marker_mul.CzRGN = START_NB;
+       tile->marker_mul.num_QCC = 0;
+       tile->marker_mul.CzQCC = START_NB;
+       tile->marker_mul.num_PLT = 0;
+       tile->marker_mul.CzPLT = START_NB;
+       tile->marker_mul.num_PPT = 0;
+       tile->marker_mul.CzPPT = START_NB;
+       tile->marker_mul.num_COM = 0;
+       tile->marker_mul.CzCOM = START_NB;
+      }
+    /* </INDEX> */
+
+
+ }
+
+void j2k_read_com() {
+    int len;
+    info_tile_t *tile;
+    info_marker_t *tmp;
+
+    len = cio_read(2);
+
+    /* <INDEX> [MHIX BOX] */
+    if (j2k_state == J2K_STATE_MH)
+      {
+       if (!img.marker_mul.num_COM) 
+         img.marker_mul.COM = (info_marker_t*)malloc(img.marker_mul.CzCOM * sizeof(info_marker_t));
+       if (img.marker_mul.num_COM >= img.marker_mul.CzCOM)
+         {
+           tmp = (info_marker_t*)malloc(2 * img.marker_mul.CzCOM * sizeof(info_marker_t));
+           memcpy(tmp,img.marker_mul.COM,img.marker_mul.CzCOM);
+           img.marker_mul.CzCOM *= 2;
+           free(img.marker_mul.COM);
+           img.marker_mul.COM = tmp;
+         }
+
+       img.marker_mul.COM[img.marker_mul.num_COM].type = J2K_MS_COM;
+       img.marker_mul.COM[img.marker_mul.num_COM].start_pos = cio_tell()-2;
+       img.marker_mul.COM[img.marker_mul.num_COM].len = len;
+       img.marker_mul.num_COM++;
+      } else
+       {
+         tile = &img.tile[j2k_curtileno];
+         if (!tile->marker_mul.num_COM)
+           tile->marker_mul.COM = (info_marker_t*)calloc(START_NB, sizeof(info_marker_t));
+         if (tile->marker_mul.num_COM >= tile->marker_mul.CzCOM)
+           {
+             tmp = (info_marker_t*)malloc(2 * tile->marker_mul.CzCOM * sizeof(info_marker_t));
+             memcpy(tmp,tile->marker_mul.COM,tile->marker_mul.CzCOM);
+             tile->marker_mul.CzCOM *= 2;
+             free(tile->marker_mul.COM);
+             tile->marker_mul.COM = tmp;
+           }
+         tile->marker_mul.COM[tile->marker_mul.num_COM].type = J2K_MS_COM;
+         tile->marker_mul.COM[tile->marker_mul.num_COM].start_pos = cio_tell()-2;
+         tile->marker_mul.COM[tile->marker_mul.num_COM].len = len;
+         tile->marker_mul.num_COM++;
+       }
+    /* </INDEX> [MHIX BOX] */
+
+    cio_skip(len - 2);
+}
+
+
+
+
+void j2k_read_cox(int compno) {
+    int i;
+    j2k_tcp_t *tcp;
+    j2k_tccp_t *tccp;
+
+    tcp = j2k_state == J2K_STATE_TPH ? &j2k_cp->tcps[j2k_curtileno] : &j2k_default_tcp;
+    tccp = &tcp->tccps[compno];
+    tccp->numresolutions = cio_read(1) + 1;
+
+    img.Decomposition = tccp->numresolutions - 1; /* <INDEX> */
+
+    tccp->cblkw = cio_read(1) + 2;
+    tccp->cblkh = cio_read(1) + 2;
+    tccp->cblksty = cio_read(1);
+    tccp->qmfbid = cio_read(1);
+    if (tccp->csty&J2K_CP_CSTY_PRT) {
+        for (i = 0; i < tccp->numresolutions; i++) {
+            int tmp = cio_read(1);
+            tccp->prcw[i] = tmp&0xf;
+            tccp->prch[i] = tmp>>4; 
+        }
+    }
+}
+
+
+
+
+void j2k_read_cod() {
+    int len, i, pos;
+    j2k_tcp_t *tcp;
+    info_tile_t *tile;
+
+    tcp = j2k_state == J2K_STATE_TPH ? &j2k_cp->tcps[j2k_curtileno] : &j2k_default_tcp;
+    len = cio_read(2);
+
+    /* <INDEX> [MHIX BOX] */
+    if (j2k_state == J2K_STATE_MH)
+      {
+       img.marker[img.num_marker].type = J2K_MS_SIZ;
+       img.marker[img.num_marker].start_pos = cio_tell()-2;
+       img.marker[img.num_marker].len = len;
+       img.num_marker++;
+      }
+    else
+      {
+       tile = &img.tile[j2k_curtileno];
+       tile->marker[tile->num_marker].type = J2K_MS_SIZ;
+       tile->marker[tile->num_marker].start_pos = cio_tell()-2;
+       tile->marker[tile->num_marker].len = len;
+       tile->num_marker++;
+  }
+    /* </INDEX> [MHIX BOX] */
+    
+    tcp->csty = cio_read(1);
+    tcp->prg = cio_read(1);
+    tcp->numlayers = cio_read(2);
+    tcp->mct = cio_read(1);
+
+    pos = cio_tell();
+    for (i = 0; i < j2k_img->numcomps; i++) {
+        tcp->tccps[i].csty = tcp->csty&J2K_CP_CSTY_PRT;
+        cio_seek(pos);
+        j2k_read_cox(i);
+    }
+    
+    /* <INDEX> */
+    img.Prog = tcp->prg;
+    img.Layer = tcp->numlayers;
+    /* </INDEX> */
+}
+
+
+
+
+void j2k_read_coc() {
+    int len, compno;
+    j2k_tcp_t *tcp;
+    info_tile_t *tile;
+    info_marker_t *tmp;
+
+    tcp = j2k_state == J2K_STATE_TPH ? &j2k_cp->tcps[j2k_curtileno] : &j2k_default_tcp;
+    len = cio_read(2);
+    
+    /* <INDEX> [MHIX BOX] */
+    if (j2k_state == J2K_STATE_MH)
+      {
+       if (!img.marker_mul.num_COC)
+         img.marker_mul.COC = (info_marker_t*)malloc(img.marker_mul.CzCOC * sizeof(info_marker_t));
+       if (img.marker_mul.num_COC >= img.marker_mul.CzCOC)
+         {
+           tmp = (info_marker_t*)malloc((INCREMENT + img.marker_mul.CzCOC) * sizeof(info_marker_t));
+           memcpy(tmp,img.marker_mul.COC,img.marker_mul.CzCOC);
+           img.marker_mul.CzCOC += INCREMENT;
+           free(img.marker_mul.COC);
+           img.marker_mul.COC = tmp;
+         }
+       img.marker_mul.COC[img.marker_mul.num_COC].type = J2K_MS_COC;
+       img.marker_mul.COC[img.marker_mul.num_COC].start_pos = cio_tell()-2;
+       img.marker_mul.COC[img.marker_mul.num_COC].len = len;
+       img.marker_mul.num_COC++;
+      } else
+       {
+         tile = &img.tile[j2k_curtileno];
+         if (!tile->marker_mul.num_COC)
+           tile->marker_mul.COC = (info_marker_t*)malloc(tile->marker_mul.CzCOC * sizeof(info_marker_t));
+         if (tile->marker_mul.num_COC >= tile->marker_mul.CzCOC)
+           {
+             tmp = (info_marker_t*)malloc((INCREMENT + tile->marker_mul.CzCOC) * sizeof(info_marker_t));
+             memcpy(tmp,tile->marker_mul.COC,tile->marker_mul.CzCOC);
+             tile->marker_mul.CzCOC += INCREMENT;
+             free(tile->marker_mul.COC);
+             tile->marker_mul.COC = tmp;
+           }
+         tile->marker_mul.COC[tile->marker_mul.num_COC].type = J2K_MS_COC;
+         tile->marker_mul.COC[tile->marker_mul.num_COC].start_pos = cio_tell() - 2;
+         tile->marker_mul.COC[tile->marker_mul.num_COC].len = len;
+         tile->marker_mul.num_COC++;
+       }
+    /* </INDEX> [MHIX BOX] */
+    
+    compno =cio_read(j2k_img->numcomps <= 256 ? 1 : 2);
+
+    tcp->tccps[compno].csty = cio_read(1);
+    j2k_read_cox(compno);
+}
+
+
+
+
+void j2k_read_qcx(int compno, int len) {
+    int tmp;
+    j2k_tcp_t *tcp;
+    j2k_tccp_t *tccp;
+    int bandno, numbands;
+
+    tcp = j2k_state == J2K_STATE_TPH ? &j2k_cp->tcps[j2k_curtileno] : &j2k_default_tcp;
+    tccp = &tcp->tccps[compno];
+    tmp = cio_read(1);
+    tccp->qntsty = tmp & 0x1f;
+    tccp->numgbits = tmp >> 5;
+    numbands = tccp->qntsty == J2K_CCP_QNTSTY_SIQNT ? 1 : (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT ? len - 1 : (len - 1) / 2);
+    for (bandno = 0; bandno < numbands; bandno++) {
+        int expn, mant;
+        if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) { /* WHY STEPSIZES WHEN NOQNT ? */
+            expn = cio_read(1) >> 3;
+            mant = 0;
+        } else {
+            tmp = cio_read(2);
+            expn = tmp >> 11;
+            mant = tmp & 0x7ff;
+        }
+        tccp->stepsizes[bandno].expn = expn;
+        tccp->stepsizes[bandno].mant = mant;
+    }
+}
+
+
+
+
+void j2k_read_qcd() {
+    int len, i, pos;
+    info_tile_t *tile;
+
+    len = cio_read(2);    
+
+    /* <INDEX> [MHIX BOX] */
+    if (j2k_state == J2K_STATE_MH)
+      {
+       img.marker[img.num_marker].type = J2K_MS_QCD;
+       img.marker[img.num_marker].start_pos = cio_tell()-2;
+       img.marker[img.num_marker].len = len;
+       img.num_marker++;
+      }         else
+       {
+         tile = &img.tile[j2k_curtileno];
+         tile->marker[tile->num_marker].type = J2K_MS_QCD;
+         tile->marker[tile->num_marker].start_pos = cio_tell()-2;
+         tile->marker[tile->num_marker].len = len;
+         tile->num_marker++;
+       }
+    /* </INDEX> [MHIX BOX] */
+    
+    
+    pos=cio_tell();
+    for (i = 0; i < j2k_img->numcomps; i++) {
+        cio_seek(pos);
+        j2k_read_qcx(i, len - 2);
+    }
+}
+
+
+
+
+void j2k_read_qcc() {
+  int len, compno;
+  info_tile_t *tile;
+  info_marker_t *tmp;
+
+  len = cio_read(2);  
+  /* <INDEX> [MHIX BOX] */
+  if (j2k_state == J2K_STATE_MH)
+    {
+      if (!img.marker_mul.num_QCC)
+       img.marker_mul.QCC = (info_marker_t*)malloc(img.marker_mul.CzQCC * sizeof(info_marker_t));
+       if (img.marker_mul.num_QCC >= img.marker_mul.CzQCC)
+         {
+           tmp = (info_marker_t*)malloc((INCREMENT + img.marker_mul.CzQCC) * sizeof(info_marker_t));
+           memcpy(tmp,img.marker_mul.QCC,img.marker_mul.CzQCC);
+           img.marker_mul.CzQCC += INCREMENT;
+           free(img.marker_mul.QCC);
+           img.marker_mul.QCC = tmp;
+         }
+      img.marker_mul.QCC[img.marker_mul.num_QCC].type = J2K_MS_QCC;
+      img.marker_mul.QCC[img.marker_mul.num_QCC].start_pos = cio_tell() - 2;
+      img.marker_mul.QCC[img.marker_mul.num_QCC].len = len;
+      img.marker_mul.num_QCC++;
+    } else
+      {
+       tile = &img.tile[j2k_curtileno];
+       if (!tile->marker_mul.num_QCC)
+         tile->marker_mul.QCC = (info_marker_t*)malloc(tile->marker_mul.CzQCC * sizeof(info_marker_t));
+       if (tile->marker_mul.num_QCC >= tile->marker_mul.CzQCC)
+         {
+           tmp = (info_marker_t*)malloc((INCREMENT + tile->marker_mul.CzQCC) * sizeof(info_marker_t));
+           memcpy(tmp,tile->marker_mul.QCC,tile->marker_mul.CzQCC);
+           tile->marker_mul.CzQCC += INCREMENT;
+           free(tile->marker_mul.QCC);
+           tile->marker_mul.QCC = tmp;
+         }
+       tile->marker_mul.QCC[tile->marker_mul.num_QCC].type = J2K_MS_QCC;
+       tile->marker_mul.QCC[tile->marker_mul.num_QCC].start_pos = cio_tell()-2;
+       tile->marker_mul.QCC[tile->marker_mul.num_QCC].len = len;
+       tile->marker_mul.num_QCC++;
+      }
+  /* </INDEX> [MHIX BOX] */
+  compno = cio_read(j2k_img->numcomps <= 256 ? 1 : 2);
+  j2k_read_qcx(compno, len - 2 - (j2k_img->numcomps <= 256 ? 1 : 2));
+}
+
+
+
+
+void j2k_read_poc() {
+  int len, numpchgs, i, old_poc;
+  j2k_tcp_t *tcp;
+  j2k_tccp_t *tccp;
+  info_tile_t *tile;
+
+  tcp = j2k_state == J2K_STATE_TPH ? &j2k_cp->tcps[j2k_curtileno] : &j2k_default_tcp;
+  old_poc = tcp->POC ? tcp->numpocs+1 : 0;
+  tcp->POC = 1;
+  tccp = &tcp->tccps[0];
+  len = cio_read(2);
+  
+  /* <INDEX> [MHIX BOX] */
+  if (j2k_state == J2K_STATE_MH)
+    {
+      img.marker[img.num_marker].type = J2K_MS_POC;
+      img.marker[img.num_marker].start_pos = cio_tell()-2;
+      img.marker[img.num_marker].len = len;
+      img.num_marker++;
+    } else
+      {
+       tile = &img.tile[j2k_curtileno];
+       tile->marker[tile->num_marker].type = J2K_MS_POC;
+       tile->marker[tile->num_marker].start_pos = cio_tell()-2;
+       tile->marker[tile->num_marker].len = len;
+       tile->num_marker++;
+      }
+  /* </INDEX> [MHIX BOX] */
+
+    numpchgs = (len - 2) / (5 + 2 * (j2k_img->numcomps <= 256 ? 1 : 2));
+    for (i = 0; i < numpchgs; i++) {
+      j2k_poc_t *poc;
+      poc = &tcp->pocs[i];
+      poc->resno0 = cio_read(1);
+      poc->compno0 = cio_read(j2k_img->numcomps <= 256 ? 1 : 2);
+      poc->layno1 = int_min(cio_read(2), tcp->numlayers);
+      poc->resno1 = int_min(cio_read(1), tccp->numresolutions);
+      poc->compno1 = int_min(cio_read(j2k_img->numcomps <= 256 ? 1 : 2), j2k_img->numcomps);
+      poc->prg = cio_read(1);
+    }
+
+    tcp->numpocs = numpchgs + old_poc - 1;
+}
+
+
+
+
+void j2k_read_crg() {
+    int len, i, Xcrg_i, Ycrg_i;
+
+    len = cio_read(2);
+
+    /* <INDEX> [MHIX BOX] */
+    img.marker[img.num_marker].type = J2K_MS_CRG;
+    img.marker[img.num_marker].start_pos = cio_tell()-2;
+    img.marker[img.num_marker].len = len;
+    img.num_marker++;
+    /* </INDEX> [MHIX BOX] */
+
+    for (i = 0; i < j2k_img->numcomps; i++)
+      {  
+       Xcrg_i = cio_read(2);
+       Ycrg_i = cio_read(2);
+      }
+}
+
+
+
+
+void j2k_read_tlm() {
+    int len, Ztlm, Stlm, ST, SP, tile_tlm, i;
+    long int Ttlm_i, Ptlm_i;
+    info_marker_t *tmp;
+
+    len = cio_read(2);
+
+    /* <INDEX> [MHIX BOX] */
+    if (!img.marker_mul.num_TLM)
+      img.marker_mul.TLM = (info_marker_t*)malloc(img.marker_mul.CzTLM * sizeof(info_marker_t));
+    if (img.marker_mul.num_TLM >= img.marker_mul.CzTLM)
+      {
+       tmp = (info_marker_t*)malloc((INCREMENT + img.marker_mul.CzTLM) * sizeof(info_marker_t));
+       memcpy(tmp,img.marker_mul.TLM,img.marker_mul.CzTLM);
+       img.marker_mul.CzTLM += INCREMENT;
+       free(img.marker_mul.TLM);
+       img.marker_mul.TLM = tmp;
+      }
+    img.marker_mul.TLM[img.marker_mul.num_TLM].type = J2K_MS_TLM;
+    img.marker_mul.TLM[img.marker_mul.num_TLM].start_pos = cio_tell()-2;
+    img.marker_mul.TLM[img.marker_mul.num_TLM].len = len;
+    img.marker_mul.num_TLM++;
+    /* </INDEX> [MHIX BOX] */
+    
+    Ztlm = cio_read(1);
+    Stlm = cio_read(1);
+    ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
+    SP = (Stlm >> 6) & 0x01;
+    tile_tlm = (len - 4) / ((SP + 1) * 2 + ST);
+    for (i = 0; i < tile_tlm; i++)
+      {
+       Ttlm_i = cio_read(ST);
+       Ptlm_i = cio_read(SP ? 4 : 2);
+      }
+}
+
+
+
+
+void j2k_read_plm() {
+    int len, i, Z_plm, N_plm, add, packet_len=0;
+    info_marker_t *tmp;
+
+    len=cio_read(2);
+
+    /* <INDEX> [MHIX BOX] */
+    if (!img.marker_mul.num_PLM)
+      img.marker_mul.PLM = (info_marker_t*)malloc(img.marker_mul.CzPLM * sizeof(info_marker_t));
+    if (img.marker_mul.num_PLM >= img.marker_mul.CzPLM)
+      {
+       tmp = (info_marker_t*)malloc((INCREMENT + img.marker_mul.CzPLM) * sizeof(info_marker_t));
+       memcpy(tmp,img.marker_mul.PLM,img.marker_mul.CzPLM);
+       img.marker_mul.CzPLM += INCREMENT;
+       free(img.marker_mul.PLM);
+       img.marker_mul.PLM = tmp;
+      }
+    img.marker_mul.PLM[img.marker_mul.num_PLM].type = J2K_MS_PLM;
+    img.marker_mul.PLM[img.marker_mul.num_PLM].start_pos = cio_tell()-2;
+    img.marker_mul.PLM[img.marker_mul.num_PLM].len = len;
+    img.marker_mul.num_PLM++;
+    /* </INDEX> [MHIX BOX] */
+
+    Z_plm = cio_read(1);
+    len -= 3;
+    while (len > 0)
+      {
+       N_plm = cio_read(4);
+       len -= 4;
+       for (i = N_plm ; i > 0 ; i--)
+         {
+           add = cio_read(1);
+           len--;
+           packet_len = (packet_len << 7) + add;
+           if ((add & 0x80) == 0)
+             {
+               /* New packet */
+               packet_len = 0;
+             }
+           if (len <= 0) break;
+         } 
+      }
+}
+
+
+
+
+void j2k_read_plt() {
+    int len, i, Zplt, packet_len=0, add;
+    info_tile_t *tile;
+    info_marker_t *tmp;
+;
+    len = cio_read(2);
+    /* <INDEX> [MHIX BOX] */
+    tile = &img.tile[j2k_curtileno];
+    if (!tile->marker_mul.num_PLT)
+      tile->marker_mul.PLT = (info_marker_t*)malloc(tile->marker_mul.CzPLT * sizeof(info_marker_t));
+    if (tile->marker_mul.num_PLT >= tile->marker_mul.CzPLT)
+      {
+       tmp = (info_marker_t*)malloc((INCREMENT + tile->marker_mul.CzPLT) * sizeof(info_marker_t));
+       memcpy(tmp,tile->marker_mul.PLT,tile->marker_mul.CzPLT);
+       tile->marker_mul.CzPLT += INCREMENT;
+       free(tile->marker_mul.PLT);
+       tile->marker_mul.PLT = tmp;
+      }
+
+    tile->marker_mul.PLT[tile->marker_mul.num_PLT].type = J2K_MS_PLT;
+    tile->marker_mul.PLT[tile->marker_mul.num_PLT].start_pos = cio_tell()-2;
+    tile->marker_mul.PLT[tile->marker_mul.num_PLT].len = len;
+    tile->marker_mul.num_PLT++;
+    /* </INDEX> [MHIX BOX] */
+    
+    Zplt = cio_read(1);
+    for (i = len-3; i > 0; i--)
+      {
+       add = cio_read(1);
+       packet_len = (packet_len << 7) + add;
+       if ((add & 0x80) == 0)
+         {
+           /* New packet */
+           packet_len = 0;
+         }
+      }
+}
+
+
+
+
+void j2k_read_ppm() {
+    int len, Z_ppm, i, j;
+    int N_ppm;
+    info_marker_t *tmp;
+
+    len = cio_read(2);
+    
+    /* <INDEX> [MHIX BOX] */
+    if (!img.marker_mul.num_PPM)
+      img.marker_mul.PPM = (info_marker_t*)malloc(img.marker_mul.CzPPM * sizeof(info_marker_t));
+    if (img.marker_mul.num_PPM >= img.marker_mul.CzPPM)
+      {
+       tmp = (info_marker_t*)malloc((INCREMENT + img.marker_mul.CzPPM) * sizeof(info_marker_t));
+       memcpy(tmp,img.marker_mul.PPM,img.marker_mul.CzPPM);
+       img.marker_mul.CzPPM += INCREMENT;
+       free(img.marker_mul.PPM);
+       img.marker_mul.PPM = tmp;
+      }
+    img.marker_mul.PLM[img.marker_mul.num_PPM].type = J2K_MS_PPM;
+    img.marker_mul.PLM[img.marker_mul.num_PPM].start_pos = cio_tell()-2;
+    img.marker_mul.PLM[img.marker_mul.num_PPM].len = len;
+    img.marker_mul.num_PPM++;
+    /* </INDEX> [MHIX BOX] */
+    
+    j2k_cp->ppm = 1;
+    
+    Z_ppm = cio_read(1); /* Z_ppm */
+    len -= 3;
+    while (len > 0)
+      {
+       if (j2k_cp->ppm_previous == 0)
+         {
+           N_ppm = cio_read(4); /* N_ppm */
+           len -= 4;
+         } else
+           {
+             N_ppm = j2k_cp->ppm_previous;
+           }
+       
+       j = j2k_cp->ppm_store;
+       if (Z_ppm == 0) /* First PPM marker */
+         j2k_cp->ppm_data = (unsigned char*)calloc(N_ppm, sizeof(unsigned char));
+       else      /* NON-first PPM marker */
+         j2k_cp->ppm_data = (unsigned char*)realloc(j2k_cp->ppm_data, (N_ppm + j2k_cp->ppm_store) * sizeof(unsigned char));
+       
+       for (i = N_ppm ; i > 0 ; i--) /* Read packet header */
+         {
+           j2k_cp->ppm_data[j] = cio_read(1);
+           j++;
+           len--;
+           if (len == 0) break; /* Case of non-finished packet header in present marker but finished in next one */
+         }
+       
+       j2k_cp->ppm_previous = i - 1;
+       j2k_cp->ppm_store = j;
+      }
+}
+
+
+
+
+void j2k_read_ppt() {
+    int len, Z_ppt, i, j = 0;
+    j2k_tcp_t *tcp;
+    info_tile_t *tile;
+    len=cio_read(2);
+
+    /* <INDEX> [MHIX BOX] */
+    tile = & img.tile[j2k_curtileno];
+    tile->marker[tile->num_marker].type = J2K_MS_PPT;
+    tile->marker[tile->num_marker].start_pos = cio_tell()-2;
+    tile->marker[tile->num_marker].len = len;
+    tile->num_marker++;
+    /* </INDEX> [MHIX BOX] */
+
+    Z_ppt = cio_read(1);
+    tcp = &j2k_cp->tcps[j2k_curtileno];
+    tcp->ppt = 1;
+    if (Z_ppt == 0) /* First PPT marker */
+      {
+       tcp->ppt_data = (unsigned char*)calloc(len - 3, sizeof(unsigned char));
+       tcp->ppt_store = 0;
+      }
+    else      /* NON-first PPT marker */
+      tcp->ppt_data = (unsigned char*)realloc(tcp->ppt_data, (len - 3 + tcp->ppt_store) * sizeof(unsigned char));
+    
+    j = tcp->ppt_store;
+    for (i = len - 3 ; i > 0 ; i--)
+      {
+       tcp->ppt_data[j] = cio_read(1);
+       j++;
+      }
+    tcp->ppt_store = j;
+}
+
+
+
+
+void j2k_read_sot() {
+    int len, tileno, totlen, partno, numparts, i;
+    j2k_tcp_t *tcp;
+    j2k_tccp_t *tmp;
+    info_tile_t *tile;
+    info_tile_part_t *tilepart_tmp;
+    
+    //fprintf(stderr,"SOT\n");
+    len = cio_read(2);
+    tileno = cio_read(2);
+    /* <INDEX> [MHIX BOX] */
+    tile = & img.tile[tileno];
+    tile->marker[tile->num_marker].type = J2K_MS_SOT;
+    tile->marker[tile->num_marker].start_pos = cio_tell() - 4;
+    tile->marker[tile->num_marker].len = len;
+    tile->num_marker++;
+    /* </INDEX> [MHIX BOX] */
+    totlen = cio_read(4);
+    if (!totlen) totlen = cio_numbytesleft() + 8;
+    partno = cio_read(1);
+    numparts = cio_read(1);
+
+    /* <INDEX> */
+    if (tileno == 0 && partno == 0 ) 
+      img.Main_head_end = cio_tell() - 7;  /* Correction End = First byte of first SOT */
+    
+    img.tile[tileno].num_tile = tileno;
+    /* </INDEX> */
+  
+    tile->numparts = partno + 1;                                               /* INDEX : Number of tile_parts for the tile */ 
+    img.num_max_tile_parts = int_max(tile->numparts, img.num_max_tile_parts);  /* INDEX : Maximum number of tile_part per tile */
+
+    if (partno == 0)
+    {
+      tile->tile_parts = (info_tile_part_t*)malloc(START_NB * sizeof(info_tile_part_t*));
+      tile->Cztile_parts = START_NB;
+    }
+    if (partno >= tile->Cztile_parts)
+      {
+       tilepart_tmp = (info_tile_part_t*)malloc((INCREMENT + tile->Cztile_parts) * sizeof(info_tile_part_t));
+       memcpy(tilepart_tmp, tile->tile_parts, tile->Cztile_parts);
+       tile->Cztile_parts += INCREMENT;
+       free(tile->tile_parts);
+       tile->tile_parts = tilepart_tmp;
+      }
+
+    tile->tile_parts[partno].start_pos = cio_tell() - 12;        /* INDEX : start_pos of the tile_part       */
+    tile->tile_parts[partno].length = totlen;                    /* INDEX : length of the tile_part          */  
+    tile->tile_parts[partno].end_pos = totlen + cio_tell() - 12; /* INDEX : end position of the tile_part    */
+
+
+    j2k_curtileno = tileno;
+    j2k_eot = cio_getbp() - 12 + totlen;
+    j2k_state = J2K_STATE_TPH;
+    tcp = &j2k_cp->tcps[j2k_curtileno];
+    
+    tile->tile_parts[numparts].num_reso_AUX = tcp->tccps[0].numresolutions; /* INDEX : AUX value for TPIX       */
+
+     if (partno == 0)
+       //  if (tcp->first == 1) 
+      {
+       tmp = tcp->tccps;
+       *tcp = j2k_default_tcp;
+       /* Initialization PPT */
+       tcp->ppt = 0; 
+       tcp->ppt_data = NULL;
+       
+       tcp->tccps = tmp;
+       for (i = 0; i < j2k_img->numcomps; i++) {
+         tcp->tccps[i] = j2k_default_tcp.tccps[i];
+       }
+       //j2k_cp->tcps[j2k_curtileno].first=0;
+      }
+}
+
+
+
+void j2k_read_rgn() {
+    int len, compno, roisty;
+    j2k_tcp_t *tcp;
+    info_tile_t *tile;
+    info_marker_t *tmp;
+    // fprintf(stderr,"RGN\n");
+    tcp = j2k_state == J2K_STATE_TPH ? &j2k_cp->tcps[j2k_curtileno] : &j2k_default_tcp;
+    len = cio_read(2);
+    
+    /* <INDEX> [MHIX BOX]*/
+    if (j2k_state == J2K_STATE_MH)
+      {
+       if (!img.marker_mul.num_RGN)
+         img.marker_mul.RGN = (info_marker_t*)malloc(img.marker_mul.CzRGN * sizeof(info_marker_t));
+       if (img.marker_mul.num_RGN >= img.marker_mul.CzRGN)
+         {
+           tmp = (info_marker_t*)malloc((INCREMENT + img.marker_mul.CzRGN) * sizeof(info_marker_t));
+           memcpy(tmp,img.marker_mul.RGN, img.marker_mul.CzRGN);
+           img.marker_mul.CzRGN += INCREMENT;
+           free(img.marker_mul.RGN);
+           img.marker_mul.RGN = tmp;
+         }
+       img.marker_mul.RGN[img.marker_mul.num_RGN].type = J2K_MS_RGN;
+       img.marker_mul.RGN[img.marker_mul.num_RGN].start_pos = cio_tell() - 2;
+       img.marker_mul.RGN[img.marker_mul.num_RGN].len = len;
+       img.marker_mul.num_RGN++;
+      } else
+      {
+       tile = &img.tile[j2k_curtileno];
+       if (!tile->marker_mul.num_RGN)
+         tile->marker_mul.RGN = (info_marker_t*)malloc(tile->marker_mul.CzRGN * sizeof(info_marker_t));
+       if (tile->marker_mul.num_RGN >= tile->marker_mul.CzRGN)
+         {
+           tmp = (info_marker_t*)malloc((INCREMENT + tile->marker_mul.CzRGN) * sizeof(info_marker_t));
+           memcpy(tmp,tile->marker_mul.RGN,tile->marker_mul.CzRGN);
+           tile->marker_mul.CzRGN += INCREMENT;
+           free(tile->marker_mul.RGN);
+           tile->marker_mul.RGN = tmp;
+         }
+
+       tile->marker_mul.RGN[tile->marker_mul.num_RGN].type = J2K_MS_RGN;
+       tile->marker_mul.RGN[tile->marker_mul.num_RGN].start_pos = cio_tell() - 2;
+        tile->marker_mul.RGN[tile->marker_mul.num_RGN].len = len;
+       tile->marker_mul.num_RGN++;
+      }
+    /* </INDEX> [MHIX BOX] */
+    
+    compno = cio_read(j2k_img->numcomps <= 256 ? 1 : 2);
+    roisty = cio_read(1);
+    tcp->tccps[compno].roishift = cio_read(1);
+}
+
+
+
+
+
+void j2k_read_sod() {
+    int len;
+    unsigned char *data;
+    info_tile_t *tile;
+    info_tile_part_t *tile_part;
+    // fprintf(stderr,"SOD\n");
+    /* <INDEX> [MHIX BOX] */
+    tile = &img.tile[j2k_curtileno];
+    tile->marker[tile->num_marker].type = J2K_MS_SOD;
+    tile->marker[tile->num_marker].start_pos = cio_tell();
+    tile->marker[tile->num_marker].len = 0;
+    tile->num_marker++;
+    /* </INDEX> [MHIX BOX] */
+
+    tile_part = &tile->tile_parts[tile->numparts - 1];                   /* INDEX : Current tilepart of a tile                  */
+    tile_part->length_header = cio_tell() - 1 - tile_part->start_pos;    /* INDEX : length of the tile-part header              */
+    tile_part->end_header = cio_tell() - 1;                              /* INDEX : end header position of the tile-part header */
+
+    len = int_min(j2k_eot - cio_getbp(), cio_numbytesleft());
+    
+    j2k_tile_len[j2k_curtileno] += len;
+    data = (unsigned char*)realloc(j2k_tile_data[j2k_curtileno], j2k_tile_len[j2k_curtileno]);   
+    memcpy(data, cio_getbp(), len);
+    j2k_tile_data[j2k_curtileno] = data;
+    cio_skip(len);
+    j2k_state = J2K_STATE_TPHSOT;
+}
+
+void j2k_read_eoc() {
+    int tileno;
+    tcd_init(j2k_img, j2k_cp, &img);
+    for (tileno = 0; tileno<j2k_cp->tw * j2k_cp->th; tileno++) {
+        tcd_decode_tile(j2k_tile_data[tileno], j2k_tile_len[tileno], tileno, &img);
+    }
+
+    j2k_state = J2K_STATE_MT;
+     longjmp(j2k_error, 1);
+}
+
+
+
+
+void j2k_read_unk() {
+    fprintf(stderr, "warning: unknown marker\n");
+}
+
+
+
+
+int j2k_index_JPIP(char *Idx_file, char *J2K_file, int len, int version){
+  FILE *dest;
+  unsigned char *index;
+  int pos_iptr, end_pos;
+  int len_cidx, pos_cidx;
+  int len_jp2c, pos_jp2c;
+  int len_fidx, pos_fidx;
+
+  dest=fopen(Idx_file, "wb");
+  if (!dest) {
+    fprintf(stderr, "Failed to open %s for reading !!\n", Idx_file);
+    return 0;
+  }
+
+  /* INDEX MODE JPIP */
+ index = (unsigned char*)malloc(len); 
+ cio_init(index, len);
+ jp2_write_jp();
+ jp2_write_ftyp();
+ jp2_write_jp2h(j2k_img);
+ jp2_write_dbtl(Idx_file);
+
+ pos_iptr=cio_tell();
+ cio_skip(24); /* IPTR further ! */
+ pos_jp2c = cio_tell();
+ len_jp2c = jp2_write_jp2c(J2K_file);
+
+ pos_cidx = cio_tell();
+ len_cidx = jpip_write_cidx(pos_jp2c + 8,img, j2k_cp, version); /* Correction len_jp2C --> pos_jp2c + 8 */  
+
+ pos_fidx = cio_tell();
+ len_fidx = jpip_write_fidx(pos_jp2c, len_jp2c, pos_cidx, len_cidx);
+
+end_pos = cio_tell();
+
+ cio_seek(pos_iptr);
+ jpip_write_iptr(pos_fidx,len_fidx);
+ cio_seek(end_pos);
+ fwrite(index, 1, cio_tell(), dest);
+ free(index);
+
+ fclose(dest);
+ return 1;
+}
+
+
+
+typedef struct {
+  int id;
+    int states;
+    void (*handler)();
+} j2k_dec_mstabent_t;
+
+j2k_dec_mstabent_t j2k_dec_mstab[]={
+    {J2K_MS_SOC, J2K_STATE_MHSOC, j2k_read_soc},
+    {J2K_MS_SOT, J2K_STATE_MH|J2K_STATE_TPHSOT, j2k_read_sot},
+    {J2K_MS_SOD, J2K_STATE_TPH, j2k_read_sod},
+    {J2K_MS_EOC, J2K_STATE_TPHSOT, j2k_read_eoc},
+    {J2K_MS_SIZ, J2K_STATE_MHSIZ, j2k_read_siz},
+    {J2K_MS_COD, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_cod},
+    {J2K_MS_COC, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_coc},
+    {J2K_MS_RGN, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_rgn},
+    {J2K_MS_QCD, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_qcd},
+    {J2K_MS_QCC, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_qcc},
+    {J2K_MS_POC, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_poc},
+    {J2K_MS_TLM, J2K_STATE_MH, j2k_read_tlm},
+    {J2K_MS_PLM, J2K_STATE_MH, j2k_read_plm},
+    {J2K_MS_PLT, J2K_STATE_TPH, j2k_read_plt},
+    {J2K_MS_PPM, J2K_STATE_MH, j2k_read_ppm},
+    {J2K_MS_PPT, J2K_STATE_TPH, j2k_read_ppt},
+    {J2K_MS_SOP, 0, 0},
+    {J2K_MS_CRG, J2K_STATE_MH, j2k_read_crg},
+    {J2K_MS_COM, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_com},
+    {0, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_unk}
+};
+
+j2k_dec_mstabent_t *j2k_dec_mstab_lookup(int id) {
+  j2k_dec_mstabent_t *e;
+  for (e = j2k_dec_mstab; e->id != 0; e++) {
+    if (e->id == id) {
+      break;
+    }
+  }
+  return e;
+}
+
+int j2k_decode(unsigned char *src, int len, j2k_image_t **image, j2k_cp_t **cp) {
+    if (setjmp(j2k_error)) {
+        if (j2k_state != J2K_STATE_MT) {
+            fprintf(stderr, "WARNING: incomplete bitstream\n");
+            return 0;
+        }
+        return cio_numbytes();
+    }
+    j2k_img = (j2k_image_t*)calloc(1, sizeof(j2k_image_t));
+    j2k_cp = (j2k_cp_t*)calloc(1, sizeof(j2k_cp_t));
+    *image = j2k_img;
+    *cp = j2k_cp;
+    j2k_state = J2K_STATE_MHSOC;
+    cio_init(src, len);
+    for (;;) {
+        j2k_dec_mstabent_t *e;
+        int id = cio_read(2);
+        if (id >> 8 != 0xff) {
+            fprintf(stderr, "%.8x: expected a marker instead of %x\n", cio_tell() - 2, id);
+            return 0;
+        }
+        e = j2k_dec_mstab_lookup(id);
+        if (!(j2k_state & e->states)) {
+            fprintf(stderr, "%.8x: unexpected marker %x\n", cio_tell() - 2, id);
+            return 0;
+        }
+        if (e->handler) {
+            (*e->handler)();
+        }
+    }
+
+}
+
+
+#ifdef _WIN32
+#include <windows.h>
+
+BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
+    switch (ul_reason_for_call) {
+               case DLL_PROCESS_ATTACH:
+               case DLL_THREAD_ATTACH:
+               case DLL_THREAD_DETACH:
+               case DLL_PROCESS_DETACH:
+                       break;
+    }
+    return TRUE;
+}
+#endif /* _WIN32 */
+
+int main(int argc, char **argv)
+{  
+  FILE *src;
+  int totlen;
+  unsigned char *j2kfile;
+  j2k_image_t *imgg;
+  j2k_cp_t *cp;
+  int version;
+
+  if (argc != 4)
+    {
+      fprintf(stderr,"\nUSAGE : ./index_create J2K-file JP2-file version\n\nVersion : 0, 1, 2 or 3\n  0 : [faix] 4-byte and no AUX fields\n  1 : [faix] 8-byte and no AUX fields\n  2 : [faix] 4-byte and AUX fields\n  3 : [faix] 8-byte and AUX fields\n\nReference Document : annex I from JPIP-FCD-version 2 (SC 29 N5727)\n\n");
+      return 1;
+    }
+
+  src=fopen(argv[1], "rb");
+  if (!src) {
+    fprintf(stderr, "Failed to open %s for reading !!\n", argv[1]);
+    return 1;
+  }
+
+  /* length of the codestream */
+  fseek(src, 0, SEEK_END);
+  totlen = ftell(src);
+  fseek(src, 0, SEEK_SET);
+  
+  j2kfile = (unsigned char*)malloc(totlen);
+  fread(j2kfile, 1, totlen, src);
+  fclose(src);
+
+  img.marker = (info_marker_t*)malloc(32 * sizeof(info_marker_t));
+  img.num_marker = 0;
+  img.num_max_tile_parts = 0;
+  img.marker_mul.num_COC = 0;
+  img.marker_mul.CzCOC = START_NB;
+  img.marker_mul.num_RGN = 0;
+  img.marker_mul.CzRGN = START_NB;
+  img.marker_mul.num_QCC = 0;
+  img.marker_mul.CzQCC = START_NB;
+  img.marker_mul.num_TLM = 0;
+  img.marker_mul.CzTLM = START_NB;
+  img.marker_mul.num_PLM = 0;
+  img.marker_mul.CzPLM = START_NB;
+  img.marker_mul.num_PPM = 0;
+  img.marker_mul.CzPPM = START_NB;
+  img.marker_mul.num_COM = 0;
+  img.marker_mul.CzCOM = START_NB;
+
+  /* decode */ 
+
+  if (!j2k_decode(j2kfile, totlen, &imgg, &cp)) {
+    fprintf(stderr, "Index_creator: failed to decode image!\n");
+    free(j2kfile);
+    return 1;
+  }
+  free(j2kfile);
+  
+  // fseek(src, 0, SEEK_SET);
+  img.codestream_size = totlen;
+  sscanf(argv[3], "%d", &version);
+  if (version > 3)
+    {
+      fprintf(stderr,"Error : value of version unauthorized !!  Value accepted : 0, 1, 2 or 3 !!\n");
+      return 0;
+    }
+
+  j2k_index_JPIP(argv[2], argv[1], totlen * 2 > 60000 ? totlen * 2 : 60000, version);
+  
+  j2k_clean();
+  return 0;
+}
diff --git a/applications/indexer_JPIP/int.c b/applications/indexer_JPIP/int.c
new file mode 100644 (file)
index 0000000..29f778c
--- /dev/null
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/// <summary>
+/// Get the minimum of two integers.
+/// </summary>
+int int_min(int a, int b) {
+    return a<b?a:b;
+}
+
+/// <summary>
+/// Get the maximum of two integers.
+/// </summary>
+int int_max(int a, int b) {
+    return a>b?a:b;
+}
+
+/// <summary>
+/// Clamp an integer inside an interval.
+/// </summary>
+int int_clamp(int a, int min, int max) {
+    if (a<min) return min;
+    if (a>max) return max;
+    return a;
+}
+
+/// <summary>
+/// Get absolute value of integer.
+/// </summary>
+int int_abs(int a) {
+    return a<0?-a:a;
+}
+
+/// <summary>
+/// Divide an integer and round upwards.
+/// </summary>
+int int_ceildiv(int a, int b) {
+    return (a+b-1)/b;
+}
+
+/// <summary>
+/// Divide an integer by a power of 2 and round upwards.
+/// </summary>
+int int_ceildivpow2(int a, int b) {
+    return (a+(1<<b)-1)>>b;
+}
+
+/// <summary>
+/// Divide an integer by a power of 2 and round downwards.
+/// </summary>
+int int_floordivpow2(int a, int b) {
+    return a>>b;
+}
+
+/// <summary>
+/// Get logarithm of an integer and round downwards.
+/// </summary>
+int int_floorlog2(int a) {
+    int l;
+    for (l=0; a>1; l++) {
+        a>>=1;
+    }
+    return l;
+}
diff --git a/applications/indexer_JPIP/int.h b/applications/indexer_JPIP/int.h
new file mode 100644 (file)
index 0000000..4921ff4
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __INT_H
+#define __INT_H
+
+int int_min(int a, int b);
+int int_max(int a, int b);
+int int_clamp(int a, int min, int max);
+int int_abs(int a);
+int int_ceildiv(int a, int b);
+int int_ceildivpow2(int a, int b);
+int int_floordivpow2(int a, int b);
+int int_floorlog2(int a);
+
+#endif
diff --git a/applications/indexer_JPIP/j2k.h b/applications/indexer_JPIP/j2k.h
new file mode 100644 (file)
index 0000000..6c9a3c6
--- /dev/null
@@ -0,0 +1,288 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003-2004, Yannick Verschueren
+ * Copyright (c) 2003-2004, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved. 
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#define VERSION "0.0.8"
+
+#ifdef _WIN32
+#ifdef LIBJ2K_EXPORTS
+#define LIBJ2K_API __declspec(dllexport)
+#else
+#define LIBJ2K_API __declspec(dllimport)
+#endif
+#else
+#define LIBJ2K_API
+#endif
+
+#ifndef __J2K_H
+#define __J2K_H
+
+#define J2K_MAXRLVLS 33
+#define J2K_MAXBANDS (3*J2K_MAXRLVLS+1)
+
+#define J2K_CP_CSTY_PRT 0x01
+#define J2K_CP_CSTY_SOP 0x02
+#define J2K_CP_CSTY_EPH 0x04
+#define J2K_CCP_CSTY_PRT 0x01
+#define J2K_CCP_CBLKSTY_LAZY 0x01
+#define J2K_CCP_CBLKSTY_RESET 0x02
+#define J2K_CCP_CBLKSTY_TERMALL 0x04
+#define J2K_CCP_CBLKSTY_VSC 0x08
+#define J2K_CCP_CBLKSTY_PTERM 0x10
+#define J2K_CCP_CBLKSTY_SEGSYM 0x20
+#define J2K_CCP_QNTSTY_NOQNT 0
+#define J2K_CCP_QNTSTY_SIQNT 1
+#define J2K_CCP_QNTSTY_SEQNT 2
+
+typedef struct 
+{
+  int dx, dy;   /* XRsiz, YRsiz            */
+  int prec;     /* precision               */
+  int bpp;      /* deapth of image in bits */
+  int sgnd;     /* signed                  */
+  int *data;    /* image-component data    */
+} j2k_comp_t;
+
+typedef struct {
+  int version;
+  int x0, y0;          /* XOsiz, YOsiz              */
+  int x1, y1;          /* Xsiz, Ysiz                */ 
+  int numcomps;        /* number of components      */
+  int index_on;        /* 0 = no index || 1 = index */
+  j2k_comp_t *comps;   /* image-components          */
+} j2k_image_t;
+
+typedef struct {
+  int expn;     /* exponent */
+  int mant;     /* mantissa */
+} j2k_stepsize_t;
+
+typedef struct {
+  int csty;                                /* coding style                          */
+  int numresolutions;                      /* number of resolutions                 */
+  int cblkw;                               /* width of code-blocks                  */
+  int cblkh;                               /* height of code-blocks                 */
+  int cblksty;                             /* code-block coding style               */
+  int qmfbid;                              /* discrete wavelet transform identifier */
+  int qntsty;                              /* quantisation style                    */
+  j2k_stepsize_t stepsizes[J2K_MAXBANDS];  /* stepsizes used for quantisation       */
+  int numgbits;                            /* number of guard bits                  */
+  int roishift;                            /* Region of Interest shift              */
+  int prcw[J2K_MAXRLVLS];                  /* Precinct width                        */
+  int prch[J2K_MAXRLVLS];                  /* Precinct height                       */
+} j2k_tccp_t;
+
+typedef struct {
+    int resno0, compno0; 
+    int layno1, resno1, compno1;
+    int prg;
+    int tile;
+    char progorder[4];
+} j2k_poc_t;
+
+typedef struct {
+  int csty;                  /* coding style                                                            */  
+  int prg;                   /* progression order                                                       */
+  int numlayers;             /* number of layers                                                        */
+  int mct;                   /* multi-component transform identifier                                    */
+  int rates[100];            /* rates of layers                                                         */
+  int numpocs;               /* number of progression order changes                                     */
+  int POC;                   /* Precise if a POC marker has been used O:NO, 1:YES                       */
+  j2k_poc_t pocs[32];        /* progression order changes                                               */
+  unsigned char *ppt_data;   /* packet header store there for futur use in t2_decode_packet             */
+  int ppt;                   /* If ppt == 1 --> there was a PPT marker for the present tile             */
+  int ppt_store;             /* Use in case of multiple marker PPT (number of info already store)       */
+  j2k_tccp_t *tccps;         /* tile-component coding parameters                                        */
+} j2k_tcp_t;
+
+typedef struct {
+  int tx0, ty0;              /* XTOsiz, YTOsiz                                                          */
+  int tdx, tdy;              /* XTsiz, YTsiz                                                            */
+  int tw, th;
+  unsigned char *ppm_data;   /* packet header store there for futur use in t2_decode_packet             */
+  int ppm;                   /* If ppm == 1 --> there was a PPM marker for the present tile             */
+  int ppm_store;             /* Use in case of multiple marker PPM (number of info already store)       */
+  int ppm_previous;          /* Use in case of multiple marker PPM (case on non-finished previous info) */
+  j2k_tcp_t *tcps;           /* tile coding parameters                                                  */
+} j2k_cp_t;
+
+
+
+
+
+/* Packet information : Layer level */
+typedef struct {  
+  int len;               /* Length of the body of the packet   */
+  int len_header;        /* Length of the header of the packet */
+  int offset;            /* Offset of the body of the packet   */
+  int offset_header;     /* Offset of the header of the packet */
+} info_layer_t;
+
+
+/* Access to packet information : precinct level */
+typedef struct {  
+  info_layer_t *layer;
+} info_prec_t;
+
+
+/* Access to packet information : resolution level */
+typedef struct {  
+  info_prec_t *prec;
+} info_reso_t;
+
+
+/* Access to packet information : component level */
+typedef struct {  
+  info_reso_t *reso;
+} info_compo_t;
+
+
+/* Information about the marker */
+typedef struct {
+  int type;       /* type of marker [SIZ, QCD, POC, PPM, CRG, COD] appearing only once */
+  int start_pos;  /* Start position of the marker                                      */
+  int len;        /* Length of the marker                                              */
+} info_marker_t;
+
+
+/* Multiple marker in tile header */
+typedef struct{
+  info_marker_t *COC;    /* COC markers                    */
+  int num_COC;           /* Number of COC marker           */
+  int CzCOC;             /* Current size of the vector COC */
+  
+  info_marker_t *RGN;    /* RGN markers                    */
+  int num_RGN;           /* Number of RGN marker           */
+  int CzRGN;             /* Current size of the vector RGN */
+  
+  info_marker_t *QCC;    /* QCC markers                    */
+  int num_QCC;           /* Number of QCC marker           */
+  int CzQCC;             /* Current size of the vector QCC */
+  
+  info_marker_t *PLT;    /* PLT markers                    */
+  int num_PLT;           /* Number of PLT marker           */
+  int CzPLT;             /* Current size of the vector PLT */
+  
+  info_marker_t *PPT;    /* PPT markers                    */
+  int num_PPT;           /* Number of PPT marker           */
+  int CzPPT;             /* Current size of the vector PPT */
+  
+  info_marker_t *COM;    /* COM markers                    */
+  int num_COM;           /* Number of COM marker           */
+  int CzCOM;             /* Current size of the vector COC */
+} info_marker_mul_tile_t; 
+
+
+/* Information about each tile_part for a particulary tile */
+typedef struct{
+  int start_pos;                      /* Start position of the tile_part       */ 
+  int length;                         /* Length of the tile_part header + body */
+  int length_header;                  /* Length of the header                  */
+  int end_pos;                        /* End position of the tile part         */
+  int end_header;                     /* End position of the tile part header  */
+
+  int num_reso_AUX;                   /* Number of resolution level completed  */
+} info_tile_part_t;
+
+
+/* Information about each tile */
+typedef struct {
+  int num_tile;                       /* Number of Tile                                                    */
+  int pw, ph;                         /* number of precinct by tile                                        */
+  int num_packet;                     /* number of packet in the tile                                      */
+  info_compo_t *compo;                /* component [packet]                                                */
+  
+  info_marker_t *marker;              /* information concerning markers inside image [only one apparition] */
+  info_marker_mul_tile_t marker_mul;  /* information concerning markers inside image [multiple apparition] */ 
+  int num_marker;                     /* number of marker                                                  */
+  
+  int numparts;                       /* number of tile_part for this tile                                 */
+  info_tile_part_t *tile_parts;       /* Information about each tile_part                                  */
+  int Cztile_parts;                   /* Current size of the tile_parts vector                             */
+} info_tile_t;                        /* index struct                                                      */
+
+
+/* Multiple marker in main header */
+typedef struct{
+  info_marker_t *COC;    /* COC markers                    */
+  int num_COC;           /* Number of COC marker           */
+  int CzCOC;             /* Current size of the vector COC */
+  info_marker_t *RGN;    /* RGN markers                    */
+  int num_RGN;           /* Number of RGN marker           */
+  int CzRGN;             /* Current size of the vector RGN */
+  
+  info_marker_t *QCC;    /* QCC markers                    */
+  int num_QCC;           /* Number of QCC marker           */
+  int CzQCC;             /* Current size of the vector QCC */
+  
+  info_marker_t *TLM;    /* TLM markers                    */
+  int num_TLM;           /* Number of TLM marker           */
+  int CzTLM;             /* Current size of the vector TLM */
+  
+  info_marker_t *PLM;    /* PLM markers                    */
+  int num_PLM;           /* Number of PLM marker           */
+  int CzPLM;             /* Current size of the vector PLM */
+  
+  info_marker_t *PPM;    /* PPM markers                    */
+  int num_PPM;           /* Number of PPM marker           */
+  int CzPPM;             /* Current size of the vector PPM */
+  
+  info_marker_t *COM;    /* COM markers                    */
+  int num_COM;           /* Number of COM marker           */
+  int CzCOM;             /* Current size of the vector COM */
+} info_marker_mul_t; /* index struct */
+
+
+/* Information about image */
+typedef struct {
+  int Im_w, Im_h;                /* Image width and Height                                            */
+  int Tile_x, Tile_y;            /* Number of Tile in X and Y                                         */
+  int tw, th;
+  int pw, ph;                    /* nombre precinct in X and Y                                        */
+  int pdx, pdy;                  /* size of precinct in X and Y                                       */
+
+  int Prog;                      /* progression order                                                 */
+  int Comp;                      /* Component numbers                                                 */
+  int Layer;                     /* number of layer                                                   */
+  int Decomposition;             /* number of decomposition                                           */
+
+  int Main_head_end;             /* Main header position                                              */
+  int codestream_size;           /* codestream's size                                                 */
+
+  info_marker_t *marker;         /* information concerning markers inside image [only one apparition] */
+  info_marker_mul_t marker_mul;  /* information concerning markers inside image [multiple apparition] */ 
+  int num_marker;                /* number of marker                                                  */
+
+  int num_packet_max;            /* Maximum number of packet                                          */
+
+  int num_max_tile_parts;        /* Maximum number of tile-part                                       */
+  info_tile_t *tile;             /* information concerning tiles inside image                         */
+} info_image_t; /* index struct */
+
+
+#endif
diff --git a/applications/indexer_JPIP/jp2.c b/applications/indexer_JPIP/jp2.c
new file mode 100644 (file)
index 0000000..ff2d22e
--- /dev/null
@@ -0,0 +1,302 @@
+/*
+ * Copyright (c) 2003-2004, Yannick Verschueren
+ * Copyright (c) 2003-2004,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "j2k.h"
+#include "cio.h"
+#include "tcd.h"
+#include "int.h"
+
+#define JPIP_JPIP 0x6a706970
+
+#define JP2_JP   0x6a502020
+#define JP2_FTYP 0x66747970
+#define JP2_JP2H 0x6a703268
+#define JP2_IHDR 0x69686472
+#define JP2_COLR 0x636f6c72
+#define JP2_JP2C 0x6a703263
+#define JP2_URL  0x75726c20
+#define JP2_DBTL 0x6474626c
+#define JP2_BPCC 0x62706363
+#define JP2      0x6a703220
+
+
+void jp2_write_url(char *Idx_file)
+{
+  int len, lenp; 
+  unsigned int i;
+  char str[256];
+
+  sprintf(str, "%s", Idx_file);
+  lenp=cio_tell();
+  cio_skip(4);
+  cio_write(JP2_URL, 4);  // DBTL
+  cio_write(0,1);          // VERS
+  cio_write(0,3);          // FLAG
+
+  for (i=0; i<strlen(str); i++) {
+        cio_write(str[i], 1);
+    }
+
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len,4);         // L
+  cio_seek(lenp+len);
+}
+
+void jp2_write_dbtl(char *Idx_file)
+{
+  int len, lenp;
+
+  lenp=cio_tell();
+  cio_skip(4);
+  cio_write(JP2_DBTL, 4);  // DBTL
+  cio_write(1,2);           // NDR : Only 1
+  
+  jp2_write_url(Idx_file); // URL Box
+
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len,4);         // L
+  cio_seek(lenp+len);
+}
+
+int jp2_write_ihdr(j2k_image_t *j2k_img)
+{
+  int len, lenp,i; 
+  int depth_0,depth, sign, BPC_ok=1;
+
+  lenp=cio_tell();
+  cio_skip(4);
+  cio_write(JP2_IHDR, 4);  // IHDR
+
+  cio_write(j2k_img->y1-j2k_img->x0,4);   // HEIGHT
+  cio_write(j2k_img->x1-j2k_img->x0,4);   // WIDTH
+  cio_write(j2k_img->numcomps,2);   // NC
+
+  depth_0=j2k_img->comps[0].prec-1;
+  sign=j2k_img->comps[0].sgnd;
+
+  for(i=1;i<j2k_img->numcomps;i++)
+    {
+      depth=j2k_img->comps[i].prec-1;
+      sign=j2k_img->comps[i].sgnd;
+      if(depth_0!=depth) BPC_ok=0;
+    }
+  
+  if (BPC_ok)
+    cio_write(depth_0+(sign<<7),1);
+  else
+    cio_write(255,1);
+
+  cio_write(7,1);          // C : Always 7
+  cio_write(1,1);          // UnkC, colorspace unknow
+  cio_write(0,1);          // IPR, no intellectual property
+
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len,4);         // L
+  cio_seek(lenp+len);
+
+  return BPC_ok;
+}
+
+void jp2_write_bpcc(j2k_image_t *j2k_img)
+{
+  int len, lenp, i;
+  
+  lenp=cio_tell();
+  cio_skip(4);
+  cio_write(JP2_BPCC, 4);  // BPCC
+  
+  for(i=0;i<j2k_img->numcomps;i++)
+    cio_write(j2k_img->comps[i].prec-1+(j2k_img->comps[i].sgnd<<7),1);
+
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len,4);         // L
+  cio_seek(lenp+len);
+}
+
+void jp2_write_colr(int BPC_ok, j2k_image_t *j2k_img)
+{
+  int len, lenp, meth;
+  
+  lenp=cio_tell();
+  cio_skip(4);
+  cio_write(JP2_COLR, 4);  // COLR
+
+  if ((j2k_img->numcomps==1 || j2k_img->numcomps==3) && (BPC_ok && j2k_img->comps[0].prec==8))
+    meth=1;
+  else
+    meth=2;
+
+  cio_write(meth,1);       // METH
+  cio_write(0,1);          // PREC
+  cio_write(0,1);          // APPROX
+  
+  if (meth==1)
+    cio_write(j2k_img->numcomps>1?16:17,4);          // EnumCS
+
+  if (meth==2)
+    cio_write(0,1);        // PROFILE (??) 
+
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len,4);         // L
+  cio_seek(lenp+len);
+}
+
+/*
+ * Write the JP2H box
+ *
+ * JP2 Header box
+ *
+ */
+void jp2_write_jp2h(j2k_image_t *j2k_img)
+{
+  int len, lenp, BPC_ok;
+  
+  lenp=cio_tell();
+  cio_skip(4);
+  cio_write(JP2_JP2H, 4);           /* JP2H */
+
+  BPC_ok=jp2_write_ihdr(j2k_img);
+
+  if (!BPC_ok)
+    jp2_write_bpcc(j2k_img);
+  jp2_write_colr(BPC_ok, j2k_img);
+
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len,4);         /* L */
+  cio_seek(lenp+len);
+}
+
+/*
+ * Write the FTYP box
+ *
+ * File type box
+ *
+ */
+void jp2_write_ftyp()
+{
+  int len, lenp;
+  
+  lenp=cio_tell();
+  cio_skip(4);
+  cio_write(JP2_FTYP, 4);   /* FTYP       */
+
+  cio_write(JP2,4);         /* BR         */
+  cio_write(0,4);           /* MinV       */
+  cio_write(JP2,4);         /* CL0 : JP2  */
+  cio_write(JPIP_JPIP,4);   /* CL1 : JPIP */
+
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len,4);         /* L          */
+  cio_seek(lenp+len);
+}
+
+/*
+ * Read the FTYP box
+ *
+ * File type box
+ *
+ */
+void jp2_read_ftyp(int length)
+{
+  int BR, MinV, type, i;
+
+  BR = cio_read(4);         /* BR              */
+  MinV = cio_read(4);       /* MinV            */
+  length-=8;
+  
+  for (i=length/4;i>0;i--)
+    type = cio_read(4);     /* CLi : JP2, JPIP */
+}
+
+int jp2_write_jp2c(char *J2K_file)
+{
+  int len, lenp, totlen, i;
+  FILE *src;
+  char *j2kfile;
+
+  lenp=cio_tell();
+  cio_skip(4);
+  cio_write(JP2_JP2C, 4);  // JP2C
+
+  src=fopen(J2K_file, "rb");
+  fseek(src, 0, SEEK_END);
+  totlen=ftell(src);
+  fseek(src, 0, SEEK_SET);
+  
+  j2kfile=(char*)malloc(totlen);
+  fread(j2kfile, 1, totlen, src);
+  fclose(src);
+
+  for (i=0;i<totlen;i++)
+    cio_write(j2kfile[i],1);
+  
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len,4);         // L
+  cio_seek(lenp+len);
+  return lenp;
+}
+
+void jp2_write_jp()
+{
+  int len, lenp;
+  
+  lenp=cio_tell();
+  cio_skip(4);
+  cio_write(JP2_JP, 4);  // JP
+  cio_write(0x0d0a870a,4);
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len,4);         // L
+  cio_seek(lenp+len);
+}
+
+/*
+ * Read the JP box
+ *
+ * JPEG 2000 signature
+ *
+ * return 1 if error else 0
+ */
+int jp2_read_jp()
+{
+  if (0x0d0a870a!=cio_read(4))
+    return 1;
+  else
+    return 0;
+}
diff --git a/applications/indexer_JPIP/jp2.h b/applications/indexer_JPIP/jp2.h
new file mode 100644 (file)
index 0000000..d5510f5
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef __JP2_H
+#define __JP2_H
+
+#include "j2k.h"
+
+void jp2_write_url(char *Idx_file);
+
+void jp2_write_dbtl(char *Idx_file);
+
+void jp2_write_jp2h(j2k_image_t *j2k_img);
+
+void jp2_write_ftyp();
+
+int jp2_write_jp2c(char *J2K_file);
+
+void jp2_write_jp();
+
+#endif
diff --git a/applications/indexer_JPIP/jpip.c b/applications/indexer_JPIP/jpip.c
new file mode 100644 (file)
index 0000000..a86fbca
--- /dev/null
@@ -0,0 +1,768 @@
+/*
+ * Copyright (c) 2003-2004, Yannick Verschueren
+ * Copyright (c) 2003-2004, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <setjmp.h>
+#include <math.h>
+
+#include "j2k.h"
+#include "cio.h"
+#include "tcd.h"
+#include "int.h"
+
+#define JPIP_CIDX 0x63696478   /* Codestream index                */
+#define JPIP_CPTR 0x63707472   /* Codestream Finder Box           */
+#define JPIP_MANF 0x6d616e66   /* Manifest Box                    */
+#define JPIP_FAIX 0x66616978   /* Fragment array Index box        */
+#define JPIP_MHIX 0x6d686978   /* Main Header Index Table         */
+#define JPIP_TPIX 0x74706978   /* Tile-part Index Table box       */
+#define JPIP_THIX 0x74686978   /* Tile header Index Table box     */
+#define JPIP_PPIX 0x70706978   /* Precinct Packet Index Table box */
+#define JPIP_PHIX 0x70686978   /* Packet Header index Table       */
+#define JPIP_FIDX 0x66696478   /* File Index                      */
+#define JPIP_FPTR 0x66707472   /* File Finder                     */
+#define JPIP_PRXY 0x70727879   /* Proxy boxes                     */
+#define JPIP_IPTR 0x69707472   /* Index finder box                */
+#define JPIP_PHLD 0x70686c64   /* Place holder                    */
+
+#define JP2C      0x6a703263
+
+//static info_marker_t marker_jpip[32], marker_local_jpip[32];  /* SIZE to precise ! */
+//static int num_marker_jpip, num_marker_local_jpip;
+
+/* 
+ * Write the CPTR box
+ *
+ * Codestream finder box (box)
+ *
+ */
+void jpip_write_cptr(int offset, info_image_t img)
+{
+  int len, lenp;
+
+  lenp=cio_tell(); 
+  cio_skip(4);                       /* L [at the end]     */
+  cio_write(JPIP_CPTR,4);            /* T                  */
+  cio_write(0,2);                    /* DR  A PRECISER !!  */
+  cio_write(0,2);                    /* CONT               */
+  cio_write(offset,8);               /* COFF A PRECISER !! */
+  cio_write(img.codestream_size,8);  /* CLEN               */
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len, 4);                 /* L                  */
+  cio_seek(lenp+len);
+}
+
+/* 
+ * Read the CPTR box
+ *
+ * Codestream finder box (box)
+ *
+ */
+void jpip_read_cptr()
+{
+  int DR, CONT;
+  long long Coff, codestream_size;
+
+  DR = cio_read(2);               /* DR   */
+  CONT = cio_read(2);             /* CONT */
+  Coff = cio_read(8);             /* COFF */
+  codestream_size = cio_read(8);  /* CLEN */
+}
+
+/* 
+ * Write the MANF box
+ *
+ * Manifest box (box)
+ *
+ */
+void jpip_write_manf(int second, int v, info_marker_t *marker)
+{
+  int len, lenp, i;
+  lenp=cio_tell(); 
+  cio_skip(4);                         /* L [at the end]                    */
+  cio_write(JPIP_MANF,4);              /* T                                 */
+
+  if (second)                          /* Write only during the second pass */
+    {
+      for(i=0;i<v;i++)
+       {
+         cio_write(marker[i].len,4);  /* Marker length                     */ 
+         cio_write(marker[i].type,4); /* Marker type                       */
+       }
+    }
+
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len, 4);                   /* L                                 */
+  cio_seek(lenp+len);
+}
+
+/* 
+ * Read the MANF box
+ *
+ * Manifest box (box)
+ *
+ */
+void jpip_read_manf(int len)
+{
+  int i, v, marker_len, marker_type;
+  
+  v = (len - 8)/ 8;
+  
+  for(i=0;i<v;i++)
+    {
+      marker_len = cio_read(4);       /* Marker length */ 
+      marker_type = cio_read(4);      /* Marker type   */
+    }
+}
+
+/* 
+ * Write the MHIX box
+ *
+ * Main Header Index Table (box)
+ *
+ */
+int jpip_write_mhix(info_image_t img, int status, int tileno)
+{
+  int len, lenp, i;
+  info_tile_t *tile;
+  lenp=cio_tell();
+  cio_skip(4);                               /* L [at the end]                    */
+  cio_write(JPIP_MHIX, 4);                   /* MHIX                              */
+
+  if (status) /* MAIN HEADER */
+    {
+      cio_write(img.Main_head_end,8);        /* TLEN                              */
+      
+      for(i = 0; i < img.num_marker; i++)    /* Marker restricted to 1 apparition */
+       {
+         cio_write(img.marker[i].type, 2);
+         cio_write(0, 2);
+         cio_write(img.marker[i].start_pos, 8);
+         cio_write(img.marker[i].len, 2);
+       }
+      
+      /* Marker NOT restricted to 1 apparition */
+      for(i = img.marker_mul.num_COC - 1; i >= 0; i--) /* COC */
+       {
+         cio_write(img.marker_mul.COC[i].type, 2);
+         cio_write(i, 2);
+         cio_write(img.marker_mul.COC[i].start_pos, 8);
+         cio_write(img.marker_mul.COC[i].len, 2);
+       }
+      
+      for(i = img.marker_mul.num_RGN - 1; i >= 0; i--) /* RGN */
+       {
+         cio_write(img.marker_mul.RGN[i].type, 2);
+         cio_write(i, 2);
+         cio_write(img.marker_mul.RGN[i].start_pos, 8);
+         cio_write(img.marker_mul.RGN[i].len, 2);
+       }
+      
+      for(i = img.marker_mul.num_QCC - 1; i >= 0; i--) /* QCC */
+       {
+         cio_write(img.marker_mul.QCC[i].type, 2);
+         cio_write(i, 2);
+         cio_write(img.marker_mul.QCC[i].start_pos, 8);
+         cio_write(img.marker_mul.QCC[i].len, 2);
+       }
+      
+      for(i = img.marker_mul.num_TLM - 1; i >= 0; i--) /* TLM */
+       {
+         cio_write(img.marker_mul.TLM[i].type, 2);
+         cio_write(i, 2);
+         cio_write(img.marker_mul.TLM[i].start_pos, 8);
+         cio_write(img.marker_mul.TLM[i].len, 2);
+       }
+      
+      for(i = img.marker_mul.num_PLM - 1; i >= 0; i--) /* PLM */
+       {
+         cio_write(img.marker_mul.PLM[i].type, 2);
+         cio_write(i, 2);
+         cio_write(img.marker_mul.PLM[i].start_pos, 8);
+         cio_write(img.marker_mul.PLM[i].len, 2);
+       }
+      
+      for(i = img.marker_mul.num_PPM - 1; i >= 0; i--) /* PPM */
+       {
+         cio_write(img.marker_mul.PPM[i].type, 2);
+         cio_write(i, 2);
+         cio_write(img.marker_mul.PPM[i].start_pos, 8);
+         cio_write(img.marker_mul.PPM[i].len, 2);
+       }
+
+      for(i = img.marker_mul.num_COM - 1; i >= 0; i--) /* COM */
+       {
+         cio_write(img.marker_mul.COM[i].type, 2);
+         cio_write(i, 2);
+         cio_write(img.marker_mul.COM[i].start_pos, 8);
+         cio_write(img.marker_mul.COM[i].len, 2);
+       }
+    } 
+  else /* TILE HEADER */
+    {
+      tile = &img.tile[tileno];
+      cio_write(tile->tile_parts[0].length_header, 8);  /* TLEN                              */ 
+      
+      for(i = 0; i < tile->num_marker; i++)             /* Marker restricted to 1 apparition */
+       {
+         cio_write(tile->marker[i].type, 2);
+         cio_write(0, 2);
+         cio_write(tile->marker[i].start_pos, 8);
+         cio_write(tile->marker[i].len, 2);
+       }
+      
+      /* Marker NOT restricted to 1 apparition */
+      for(i = tile->marker_mul.num_COC - 1; i >= 0; i--) /* COC */
+       {
+         cio_write(tile->marker_mul.COC[i].type, 2);
+         cio_write(i, 2);
+         cio_write(tile->marker_mul.COC[i].start_pos, 8);
+         cio_write(tile->marker_mul.COC[i].len, 2);
+       }
+      
+      for(i = tile->marker_mul.num_RGN - 1; i >= 0; i--) /* RGN */
+       {
+         cio_write(tile->marker_mul.RGN[i].type, 2);
+         cio_write(i, 2);
+         cio_write(tile->marker_mul.RGN[i].start_pos, 8);
+         cio_write(tile->marker_mul.RGN[i].len, 2);
+       }
+      
+      for(i = tile->marker_mul.num_QCC - 1; i >= 0; i--) /* QCC */
+       {
+         cio_write(tile->marker_mul.QCC[i].type, 2);
+         cio_write(i, 2);
+         cio_write(tile->marker_mul.QCC[i].start_pos, 8);
+         cio_write(tile->marker_mul.QCC[i].len, 2);
+       }
+      
+      for(i = tile->marker_mul.num_PLT - 1; i >= 0; i--) /* PLT */
+       {
+         cio_write(tile->marker_mul.PLT[i].type,2);
+         cio_write(i,2);
+         cio_write(tile->marker_mul.PLT[i].start_pos,8);
+         cio_write(tile->marker_mul.PLT[i].len,2);
+       }
+      
+      for(i = tile->marker_mul.num_PPT - 1; i >= 0; i--) /* PPT */
+       {
+         cio_write(tile->marker_mul.PPT[i].type, 2);
+         cio_write(i, 2);
+         cio_write(tile->marker_mul.PPT[i].start_pos, 8);
+         cio_write(tile->marker_mul.PPT[i].len, 2);
+       }
+      
+      for(i = tile->marker_mul.num_COM - 1; i >= 0; i--) /* COM */
+       {
+         cio_write(tile->marker_mul.COM[i].type, 2);
+         cio_write(i, 2);
+         cio_write(tile->marker_mul.COM[i].start_pos, 8);
+         cio_write(tile->marker_mul.COM[i].len, 2);
+       } 
+    }      
+  
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len, 4);        /* L           */
+  cio_seek(lenp+len);
+  
+  return len;
+}
+
+/* 
+ * Read the MHIX box
+ *
+ * Main Header Index Table (box)
+ *
+ */
+void jpip_read_mhix(int len)
+{
+  int i, v, marker_type, marker_start_pos, marker_len, marker_remains;
+
+  v = (len - 8) / 14;
+
+  for (i=0; i<v ; i++)
+    {
+      marker_type = cio_read(2);       /* Type of the marker               */ 
+      marker_remains = cio_read(2);    /* Number of same markers following */
+      marker_start_pos = cio_read(2);  /* Start position of the marker     */
+      marker_len = cio_read(2);        /* Length of the marker             */
+    }
+}
+
+/* 
+ * Write the FAIX box
+ *
+ * Fragment array Index box (box)
+ *
+ */
+int jpip_write_faix(int v, int compno, info_image_t img, j2k_cp_t *j2k_cp, int version)
+{
+  int len, lenp, i, j;
+  /*int version = 0;*/
+  int tileno, resno, precno, layno, num_packet=0;
+
+  lenp=cio_tell();
+  cio_skip(4);              /* L [at the end]      */
+  cio_write(JPIP_FAIX, 4);  /* FAIX                */ 
+  cio_write(version,1);     /* Version 0 = 4 bytes */
+  
+  switch(v)
+    {
+    case 0:   /* TPIX */
+      cio_write(img.num_max_tile_parts,(version & 0x01)?8:4);                      /* NMAX           */
+      cio_write(img.tw*img.th,(version & 0x01)?8:4);                               /* M              */
+      for (i = 0; i < img.tw*img.th; i++)
+       {
+         for (j = 0; j < img.tile[i].numparts ; j++)
+           {
+             cio_write(img.tile[i].tile_parts[j].start_pos,(version & 0x01)?8:4); /* start position */
+             cio_write(img.tile[i].tile_parts[j].length,(version & 0x01)?8:4);    /* length         */
+             if (version & 0x02)
+               cio_write(img.tile[i].tile_parts[j].num_reso_AUX,4); /* Aux_i,j : Auxiliary value */
+             //cio_write(0,4);
+           }
+         /* PADDING */
+         while (j < img.num_max_tile_parts)
+           {
+             cio_write(0,(version & 0x01)?8:4); /* start position            */
+             cio_write(0,(version & 0x01)?8:4); /* length                    */
+             if (version & 0x02)
+               cio_write(0,4);                  /* Aux_i,j : Auxiliary value */
+             j++;
+           }
+       }
+      break;
+      
+      /*   case 1: */   /* THIX */
+      /* cio_write(1,(version & 0x01)?8:4);  */           /* NMAX */
+      /* cio_write(img.tw*img.th,(version & 0x01)?8:4); */ /* M    */
+      /* for (i=0;i<img.tw*img.th;i++) */
+      /* { */
+      /* cio_write(img.tile[i].start_pos,(version & 0x01)?8:4); */                         /* start position */
+      /* cio_write(img.tile[i].end_header-img.tile[i].start_pos,(version & 0x01)?8:4); */  /* length         */
+      /* if (version & 0x02)*/
+      /* cio_write(0,4); */ /* Aux_i,j : Auxiliary value */
+      /* } */
+      /* break; */
+
+    case 2:  /* PPIX  NOT FINISHED !! */
+      cio_write(img.num_packet_max,(version & 0x01)?8:4); /* NMAX */
+      cio_write(img.tw*img.th,(version & 0x01)?8:4);      /* M    */
+      for(tileno=0;tileno<img.tw*img.th;tileno++)
+       {
+         info_tile_t *tile_Idx = &img.tile[tileno];
+         info_compo_t *compo_Idx = &tile_Idx->compo[compno];
+         int correction;
+         
+         num_packet=0;
+         
+         if(j2k_cp->tcps[tileno].csty&J2K_CP_CSTY_EPH)
+           correction=3;
+         else
+           correction=1;
+         for(resno=0;resno<img.Decomposition+1;resno++)
+           {
+             info_reso_t *reso_Idx = &compo_Idx->reso[resno];
+             for (precno=0;precno<img.tile[tileno].pw*img.tile[tileno].ph;precno++)
+               {
+                 info_prec_t *prec_Idx = &reso_Idx->prec[precno];
+                 for(layno=0;layno<img.Layer;layno++)
+                   {
+                     info_layer_t *layer_Idx = &prec_Idx->layer[layno];
+                     cio_write(layer_Idx->offset,(version & 0x01)?8:4);                                   /* start position */
+                     cio_write((layer_Idx->len_header-correction)?0:layer_Idx->len,(version & 0x01)?8:4); /* length         */
+                     if (version & 0x02)
+                       cio_write(0,4); /* Aux_i,j : Auxiliary value */
+                     num_packet++;
+                   }
+               }
+           }
+         /* PADDING */
+         while (num_packet < img.num_packet_max)
+           {
+             cio_write(0,(version & 0x01)?8:4); /* start position            */
+             cio_write(0,(version & 0x01)?8:4); /* length                    */
+             if (version & 0x02)
+               cio_write(0,4);                  /* Aux_i,j : Auxiliary value */
+             num_packet++;
+           }
+       }
+      
+      break;
+      
+    case 3:  /* PHIX NOT FINISHED !! */
+      cio_write(img.num_packet_max,(version & 0x01)?8:4); /* NMAX */
+      cio_write(img.tw*img.th,(version & 0x01)?8:4);      /* M    */
+      for(tileno=0;tileno<img.tw*img.th;tileno++)
+       {
+         info_tile_t *tile_Idx = &img.tile[tileno];
+         info_compo_t *compo_Idx = &tile_Idx->compo[compno];
+         int correction;
+
+         num_packet = 0;
+         if(j2k_cp->tcps[tileno].csty&J2K_CP_CSTY_EPH)
+           correction=3;
+         else
+           correction=1;
+         for(resno=0;resno<img.Decomposition+1;resno++)
+           {
+             info_reso_t *reso_Idx = &compo_Idx->reso[resno];
+             for (precno=0;precno<img.tile[tileno].pw*img.tile[tileno].ph;precno++)
+               {
+                 info_prec_t *prec_Idx = &reso_Idx->prec[precno];
+                 for(layno=0;layno<img.Layer;layno++)
+                   {
+                     info_layer_t *layer_Idx = &prec_Idx->layer[layno];
+                     cio_write(layer_Idx->offset_header,(version & 0x01)?8:4);                                   /* start position */
+                     cio_write((layer_Idx->len_header-correction)?0:layer_Idx->len_header,(version & 0x01)?8:4); /* length         */
+                     if (version & 0x02)
+                       cio_write(0,4); /* Aux_i,j : Auxiliary value */
+                     num_packet++;
+                   }
+               }
+           }
+         /* PADDING */
+         while (num_packet<img.num_packet_max)
+           {
+             cio_write(0,(version & 0x01)?8:4); /* start position            */
+             cio_write(0,(version & 0x01)?8:4); /* length                    */
+             if (version & 0x02)
+               cio_write(0,4);                  /* Aux_i,j : Auxiliary value */
+             num_packet++;
+           }
+       }
+      break;
+    }
+  
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len, 4);        /* L  */
+  cio_seek(lenp+len);
+
+  return len;
+}
+
+/* 
+ * Write the TPIX box
+ *
+ * Tile-part Index table box (superbox)
+ *
+ */
+int jpip_write_tpix(info_image_t img, j2k_cp_t *j2k_cp, int version)
+{
+  int len, lenp;
+  lenp=cio_tell();
+  cio_skip(4);              /* L [at the end] */
+  cio_write(JPIP_TPIX, 4);  /* TPIX           */
+  
+  jpip_write_faix(0,0,img, j2k_cp, version);
+
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len, 4);        /* L              */
+  cio_seek(lenp+len);
+
+  return len;
+}
+
+/* 
+ * Write the THIX box
+ *
+ * Tile header Index table box (superbox)
+ *
+ */
+//int jpip_write_thix(info_image_t img, j2k_cp_t *j2k_cp)
+//  {
+//  int len, lenp;
+//  lenp=cio_tell();
+//  cio_skip(4);              /* L [at the end] */
+//  cio_write(JPIP_THIX, 4);  /* THIX           */
+  
+//  jpip_write_faix(1,0,img, j2k_cp);
+
+//  len=cio_tell()-lenp;
+//  cio_seek(lenp);
+//  cio_write(len, 4);        /* L              */
+//  cio_seek(lenp+len);
+
+//  return len;
+//}
+
+int jpip_write_thix(info_image_t img, j2k_cp_t *j2k_cp)
+{
+  int len, lenp, i;
+  int tileno;
+  info_marker_t *marker;
+  int num_marker_local_jpip;
+
+  marker = (info_marker_t*)calloc(sizeof(info_marker_t), j2k_cp->tw*j2k_cp->th);
+
+  for ( i = 0; i < 2 ; i++ )
+    {
+      if (i) cio_seek(lenp);
+      
+      lenp = cio_tell();
+      cio_skip(4);              /* L [at the end] */
+      cio_write(JPIP_THIX, 4);  /* THIX           */
+      jpip_write_manf(i, j2k_cp->tw*j2k_cp->th, marker);
+      num_marker_local_jpip=img.Comp;
+      
+      for (tileno = 0; tileno < j2k_cp->tw*j2k_cp->th; tileno++)
+       {
+         marker[tileno].len = jpip_write_mhix(img, 1, tileno);
+         marker[tileno].type = JPIP_MHIX;
+       }
+      
+      len=cio_tell()-lenp;
+      cio_seek(lenp);
+      cio_write(len, 4);        /* L              */
+      cio_seek(lenp+len);
+    }
+
+  free(marker);
+
+  return len;
+}
+/* 
+ * Write the PPIX box
+ *
+ * Precinct Packet Index table box (superbox)
+ *
+ */
+int jpip_write_ppix(info_image_t img,j2k_cp_t *j2k_cp)
+{
+  int len, lenp, compno, i;
+  info_marker_t *marker;
+  int num_marker_local_jpip;
+  marker = (info_marker_t*)calloc(sizeof(info_marker_t), img.Comp);
+  
+  for (i=0;i<2;i++)
+    {
+      if (i) cio_seek(lenp);
+      
+      lenp=cio_tell();
+      cio_skip(4);              /* L [at the end] */
+      cio_write(JPIP_PPIX, 4);  /* PPIX           */
+      jpip_write_manf(i,img.Comp,marker);
+      num_marker_local_jpip=img.Comp;
+      
+      for (compno=0; compno<img.Comp; compno++)
+       {
+         marker[compno].len=jpip_write_faix(2,compno,img, j2k_cp, 0);
+         marker[compno].type=JPIP_FAIX;
+       }
+   
+      len=cio_tell()-lenp;
+      cio_seek(lenp);
+      cio_write(len, 4);        /* L              */
+      cio_seek(lenp+len);
+    }
+  
+  free(marker);
+
+  return len;
+}
+
+/* 
+ * Write the PHIX box
+ *
+ * Packet Header Index table box (superbox)
+ *
+ */
+int jpip_write_phix(info_image_t img, j2k_cp_t *j2k_cp)
+{
+  int len, lenp=0, compno, i;
+  info_marker_t *marker;
+
+  marker = (info_marker_t*)calloc(sizeof(info_marker_t), img.Comp);
+
+  for (i=0;i<2;i++)
+    {
+      if (i) cio_seek(lenp);
+      
+      lenp=cio_tell();
+      cio_skip(4);              /* L [at the end] */
+      cio_write(JPIP_PHIX, 4);  /* PHIX           */
+      
+      jpip_write_manf(i,img.Comp,marker);
+
+      for (compno=0; compno<img.Comp; compno++)
+       {       
+         marker[compno].len=jpip_write_faix(3,compno,img, j2k_cp, 0);
+         marker[compno].type=JPIP_FAIX;
+       }
+
+      len=cio_tell()-lenp;
+      cio_seek(lenp);
+      cio_write(len, 4);        /* L              */
+      cio_seek(lenp+len);
+    }
+
+  free(marker);
+
+  return len;
+}
+
+/* 
+ * Write the CIDX box
+ *
+ * Codestream Index box (superbox)
+ *
+ */
+int jpip_write_cidx(int offset, info_image_t img, j2k_cp_t *j2k_cp, int version)
+{
+  int len, lenp = 0, i;
+  info_marker_t *marker_jpip;
+  int num_marker_jpip = 0;
+
+  marker_jpip = (info_marker_t*)calloc(sizeof(info_marker_t), 32);
+
+  for (i=0;i<2;i++)
+    {
+      if(i)
+       cio_seek(lenp);
+
+      lenp=cio_tell();
+
+      cio_skip(4);              /* L [at the end] */
+      cio_write(JPIP_CIDX, 4);  /* CIDX           */
+      jpip_write_cptr(offset, img);
+
+      jpip_write_manf(i,num_marker_jpip, marker_jpip);
+
+      num_marker_jpip=0;
+      marker_jpip[num_marker_jpip].len=jpip_write_mhix(img, 0, 0);
+      marker_jpip[num_marker_jpip].type=JPIP_MHIX;
+      num_marker_jpip++;
+
+      marker_jpip[num_marker_jpip].len=jpip_write_tpix(img, j2k_cp, version);
+      marker_jpip[num_marker_jpip].type=JPIP_TPIX;
+      num_marker_jpip++;
+
+      marker_jpip[num_marker_jpip].len=jpip_write_thix(img, j2k_cp);
+      marker_jpip[num_marker_jpip].type=JPIP_THIX;
+      num_marker_jpip++;
+
+      marker_jpip[num_marker_jpip].len=jpip_write_ppix(img, j2k_cp);
+      marker_jpip[num_marker_jpip].type=JPIP_PPIX;
+      num_marker_jpip++;
+
+      marker_jpip[num_marker_jpip].len=jpip_write_phix(img, j2k_cp);
+      marker_jpip[num_marker_jpip].type=JPIP_PHIX;
+      num_marker_jpip++;
+
+      len=cio_tell()-lenp;
+      cio_seek(lenp);
+      cio_write(len, 4);        /* L             */
+      cio_seek(lenp+len);
+    }
+
+  free(marker_jpip);
+
+  return len;
+
+}
+
+/* 
+ * Write the IPTR box
+ *
+ * Index Finder box
+ *
+ */
+void jpip_write_iptr(int offset, int length)
+{
+  int len, lenp;
+  lenp=cio_tell();
+  cio_skip(4);              /* L [at the end] */
+  cio_write(JPIP_IPTR, 4);  /* IPTR           */
+  
+  cio_write(offset,8);
+  cio_write(length,8);
+
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len, 4);        /* L             */
+  cio_seek(lenp+len);
+}
+
+/* 
+ * Write the PRXY box
+ *
+ * proxy (box)
+ *
+ */
+void jpip_write_prxy(int offset_jp2c, int length_jp2c, int offset_idx, int length_idx)
+{
+  int len, lenp;
+  lenp=cio_tell();
+  cio_skip(4);              /* L [at the end] */
+  cio_write(JPIP_PRXY, 4);  /* IPTR           */
+  
+  cio_write(offset_jp2c,8); /* OOFF           */
+  cio_write(length_jp2c,4); /* OBH part 1     */
+  cio_write(JP2C,4);        /* OBH part 2     */
+  
+  cio_write(1,1);           /* NI             */
+
+  cio_write(offset_idx,8);  /* IOFF           */
+  cio_write(length_idx,4);  /* IBH part 1     */
+  cio_write(JPIP_CIDX,4);   /* IBH part 2     */
+
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len, 4);        /* L              */
+  cio_seek(lenp+len);
+}
+
+
+/* 
+ * Write the FIDX box
+ *
+ * File Index (superbox)
+ *
+ */
+int jpip_write_fidx(int offset_jp2c, int length_jp2c, int offset_idx, int length_idx)
+{
+  int len, lenp;
+  lenp=cio_tell();
+  cio_skip(4);              /* L [at the end] */
+  cio_write(JPIP_FIDX, 4);  /* IPTR           */
+  
+  jpip_write_prxy(offset_jp2c, length_jp2c, offset_idx, offset_jp2c);
+
+  len=cio_tell()-lenp;
+  cio_seek(lenp);
+  cio_write(len, 4);        /* L              */
+  cio_seek(lenp+len);
+
+  return len;
+}
diff --git a/applications/indexer_JPIP/jpip.h b/applications/indexer_JPIP/jpip.h
new file mode 100644 (file)
index 0000000..84df355
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __JPIP_H
+#define __JPIP_H
+
+#include "j2k.h"
+
+// Codestream index box (superbox)
+int jpip_write_cidx(int offset, info_image_t img, j2k_cp_t *j2k_cp, int version);
+
+// Index Finder Box
+void jpip_write_iptr(int offset, int length);
+
+// File Index Box
+int jpip_write_fidx(int offset_jp2c, int length_jp2c, int offset_idx, int length_idx);
+
+#endif
diff --git a/applications/indexer_JPIP/pi.c b/applications/indexer_JPIP/pi.c
new file mode 100644 (file)
index 0000000..691ef49
--- /dev/null
@@ -0,0 +1,465 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003-2004, Yannick Verschueren
+ * Copyright (c) 2003-2004, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "pi.h"
+#include "int.h"
+#include <stdlib.h>
+#include <stdio.h>
+
+
+/* <summary> */
+/* Create a packet iterator.   */
+/* </summary> */
+pi_iterator_t *pi_create(j2k_image_t * img, j2k_cp_t * cp, int tileno)
+{
+       int p, q;
+       int compno, resno, pino;
+       int maxres = 0;
+       pi_iterator_t *pi;
+       j2k_tcp_t *tcp;
+       j2k_tccp_t *tccp;
+
+       tcp = &cp->tcps[tileno];
+       pi = (pi_iterator_t *) malloc((tcp->numpocs + 1) * sizeof(pi_iterator_t));
+
+       for (pino = 0; pino < tcp->numpocs + 1; pino++) {       /* change */
+               p = tileno % cp->tw;
+               q = tileno / cp->tw;
+
+               pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, img->x0);
+               pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, img->y0);
+               pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, img->x1);
+               pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, img->y1);
+               pi[pino].numcomps = img->numcomps;
+               pi[pino].comps = (pi_comp_t *) malloc(img->numcomps * sizeof(pi_comp_t));
+
+               for (compno = 0; compno < pi->numcomps; compno++) {
+                       int tcx0, tcy0, tcx1, tcy1;
+                       pi_comp_t *comp = &pi[pino].comps[compno];
+                       tccp = &tcp->tccps[compno];
+                       comp->dx = img->comps[compno].dx;
+                       comp->dy = img->comps[compno].dy;
+                       comp->numresolutions = tccp->numresolutions;
+                       comp->resolutions =
+                               (pi_resolution_t *) malloc(comp->numresolutions *
+                                                                                                                                        sizeof(pi_resolution_t));
+                       tcx0 = int_ceildiv(pi->tx0, comp->dx);
+                       tcy0 = int_ceildiv(pi->ty0, comp->dy);
+                       tcx1 = int_ceildiv(pi->tx1, comp->dx);
+                       tcy1 = int_ceildiv(pi->ty1, comp->dy);
+                       if (comp->numresolutions > maxres) {
+                               maxres = comp->numresolutions;
+                       }
+                       for (resno = 0; resno < comp->numresolutions; resno++) {
+                               int levelno;
+                               int rx0, ry0, rx1, ry1;
+                               int px0, py0, px1, py1;
+                               pi_resolution_t *res = &comp->resolutions[resno];
+                               if (tccp->csty & J2K_CCP_CSTY_PRT) {
+                                       res->pdx = tccp->prcw[resno];
+                                       res->pdy = tccp->prch[resno];
+                               } else {
+                                       res->pdx = 15;
+                                       res->pdy = 15;
+                               }
+                               levelno = comp->numresolutions - 1 - resno;
+                               rx0 = int_ceildivpow2(tcx0, levelno);
+                               ry0 = int_ceildivpow2(tcy0, levelno);
+                               rx1 = int_ceildivpow2(tcx1, levelno);
+                               ry1 = int_ceildivpow2(tcy1, levelno);
+                               px0 = int_floordivpow2(rx0, res->pdx) << res->pdx;
+                               py0 = int_floordivpow2(ry0, res->pdy) << res->pdy;
+                               px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx;
+                               py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy;
+                               res->pw = (px1 - px0) >> res->pdx;
+                               res->ph = (py1 - py0) >> res->pdy;
+                       }
+               }
+               
+               tccp = &tcp->tccps[0];
+               pi[pino].step_p=1;
+               pi[pino].step_c=100*pi[pino].step_p;
+               pi[pino].step_r=img->numcomps*pi[pino].step_c;
+               pi[pino].step_l=maxres*pi[pino].step_r;
+               
+               if (pino==0)
+                 pi[pino].include=(short int*)calloc(img->numcomps*maxres*tcp->numlayers*100,sizeof(short int));
+               else
+                 pi[pino].include=pi[pino-1].include;
+
+               /*if (pino == tcp->numpocs) {*/
+                 if (tcp->POC == 0) {
+                       pi[pino].first = 1;
+                       pi[pino].poc.resno0 = 0;
+                       pi[pino].poc.compno0 = 0;
+                       pi[pino].poc.layno1 = tcp->numlayers;
+                       pi[pino].poc.resno1 = maxres;
+                       pi[pino].poc.compno1 = img->numcomps;
+                       pi[pino].poc.prg = tcp->prg;
+               } else {
+                       pi[pino].first = 1;
+                       pi[pino].poc.resno0 = tcp->pocs[pino].resno0;
+                       pi[pino].poc.compno0 = tcp->pocs[pino].compno0;
+                       pi[pino].poc.layno1 = tcp->pocs[pino].layno1;
+                       pi[pino].poc.resno1 = tcp->pocs[pino].resno1;
+                       pi[pino].poc.compno1 = tcp->pocs[pino].compno1;
+                       pi[pino].poc.prg = tcp->pocs[pino].prg;
+               }
+       }
+       return pi;
+}
+
+/* <summary> */
+/* Get next packet in layer=resolution-component-precinct order.   */
+/* </summary> */
+int pi_next_lrcp(pi_iterator_t * pi)
+{
+       pi_comp_t *comp;
+       pi_resolution_t *res;
+
+       if (!pi->first) {
+               comp = &pi->comps[pi->compno];
+               res = &comp->resolutions[pi->resno];
+               goto skip;
+       } else {
+               pi->first = 0;
+       }
+       for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {
+               for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1;
+                                pi->resno++) {
+                       for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1;
+                                        pi->compno++) {
+                               comp = &pi->comps[pi->compno];
+                               if (pi->resno >= comp->numresolutions) {
+
+                                       continue;
+                               }
+                               res = &comp->resolutions[pi->resno];
+                               for (pi->precno = 0; pi->precno < res->pw * res->ph; pi->precno++) {
+                                 if (!pi->include[pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p]){
+                                   pi->include[pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p] = 1;
+                                   return 1;
+                                       }
+                               skip:;
+                               }
+                       }
+               }
+       }
+       return 0;
+}
+
+/* <summary> */
+/* Get next packet in resolution-layer-component-precinct order.   */
+/* </summary> */
+int pi_next_rlcp(pi_iterator_t * pi)
+{
+       pi_comp_t *comp;
+       pi_resolution_t *res;
+       if (!pi->first) {
+               comp = &pi->comps[pi->compno];
+               res = &comp->resolutions[pi->resno];
+               goto skip;
+       } else {
+               pi->first = 0;
+       }
+       for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
+               for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {
+                       for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1;
+                                        pi->compno++) {
+                               comp = &pi->comps[pi->compno];
+                               if (pi->resno >= comp->numresolutions) {
+                                       continue;
+                               }
+                               res = &comp->resolutions[pi->resno];
+                               for (pi->precno = 0; pi->precno < res->pw * res->ph; pi->precno++) {
+                                 if (!pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p]){
+                                   pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p] = 1;
+                                   return 1;
+                                 }
+                               skip:;
+                               }
+                       }
+               }
+       }
+       return 0;
+}
+
+/* <summary> */
+/* Get next packet in resolution-precinct-component-layer order.   */
+/* </summary> */
+int pi_next_rpcl(pi_iterator_t * pi)
+{
+       pi_comp_t *comp;
+       pi_resolution_t *res;
+       if (!pi->first) {
+               goto skip;
+       } else {
+               int compno, resno;
+               pi->first = 0;
+               pi->dx = 0;
+               pi->dy = 0;
+               for (compno = 0; compno < pi->numcomps; compno++) {
+                       comp = &pi->comps[compno];
+                       for (resno = 0; resno < comp->numresolutions; resno++) {
+                               int dx, dy;
+                               res = &comp->resolutions[resno];
+                               dx =
+                                       comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
+                               dy =
+                                       comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
+                               pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
+                               pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
+                       }
+               }
+       }
+       for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
+               for (pi->y = pi->ty0; pi->y < pi->ty1;
+                                pi->y += pi->dy - (pi->y % pi->dy)) {
+                       for (pi->x = pi->tx0; pi->x < pi->tx1;
+                                        pi->x += pi->dx - (pi->x % pi->dx)) {
+                               for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1;
+                                                pi->compno++) {
+                                       int levelno;
+                                       int trx0, try0;
+                                       int rpx, rpy;
+                                       int prci, prcj;
+                                       comp = &pi->comps[pi->compno];
+                                       if (pi->resno >= comp->numresolutions) {
+                                               continue;
+                                       }
+                                       res = &comp->resolutions[pi->resno];
+                                       levelno = comp->numresolutions - 1 - pi->resno;
+                                       trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
+                                       try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
+                                       rpx = res->pdx + levelno;
+                                       rpy = res->pdy + levelno;
+                                       if (!
+                                                       (pi->x % (comp->dx << rpx) == 0
+                                                        || (pi->x == pi->tx0 && (trx0 << levelno) % (1 << rpx)))) {
+                                               continue;
+                                       }
+                                       if (!
+                                                       (pi->y % (comp->dy << rpy) == 0
+                                                        || (pi->y == pi->ty0 && (try0 << levelno) % (1 << rpx)))) {
+                                               continue;
+                                       }
+                                       prci =
+                                               int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno),
+                                                                                                                res->pdx) - int_floordivpow2(trx0, res->pdx);
+                                       prcj =
+                                               int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno),
+                                                                                                                res->pdy) - int_floordivpow2(try0, res->pdy);
+                                       pi->precno = prci + prcj * res->pw;
+                                       for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {
+                                         if (!pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p]){
+                                           pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p] = 1;
+                                           return 1;
+                                               }
+                                       skip:;
+                                       }
+                               }
+                       }
+               }
+       }
+       return 0;
+}
+
+/* <summary> */
+/* Get next packet in precinct-component-resolution-layer order.   */
+/* </summary> */
+int pi_next_pcrl(pi_iterator_t * pi)
+{
+       pi_comp_t *comp;
+       pi_resolution_t *res;
+       if (!pi->first) {
+               comp = &pi->comps[pi->compno];
+               goto skip;
+       } else {
+               int compno, resno;
+               pi->first = 0;
+               pi->dx = 0;
+               pi->dy = 0;
+               for (compno = 0; compno < pi->numcomps; compno++) {
+                       comp = &pi->comps[compno];
+                       for (resno = 0; resno < comp->numresolutions; resno++) {
+                               int dx, dy;
+                               res = &comp->resolutions[resno];
+                               dx =
+                                       comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
+                               dy =
+                                       comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
+                               pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
+                               pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
+                       }
+               }
+       }
+       for (pi->y = pi->ty0; pi->y < pi->ty1;
+                        pi->y += pi->dy - (pi->y % pi->dy)) {
+               for (pi->x = pi->tx0; pi->x < pi->tx1;
+                                pi->x += pi->dx - (pi->x % pi->dx)) {
+                       for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1;
+                                        pi->compno++) {
+                               comp = &pi->comps[pi->compno];
+                               for (pi->resno = pi->poc.resno0;
+                                                pi->resno < int_min(pi->poc.resno1, comp->numresolutions);
+                                                pi->resno++) {
+                                       int levelno;
+                                       int trx0, try0;
+                                       int rpx, rpy;
+                                       int prci, prcj;
+                                       res = &comp->resolutions[pi->resno];
+                                       levelno = comp->numresolutions - 1 - pi->resno;
+                                       trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
+                                       try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
+                                       rpx = res->pdx + levelno;
+                                       rpy = res->pdy + levelno;
+                                       if (!
+                                                       (pi->x % (comp->dx << rpx) == 0
+                                                        || (pi->x == pi->tx0 && (trx0 << levelno) % (1 << rpx)))) {
+                                               continue;
+                                       }
+                                       if (!
+                                                       (pi->y % (comp->dy << rpy) == 0
+                                                        || (pi->y == pi->ty0 && (try0 << levelno) % (1 << rpx)))) {
+                                               continue;
+                                       }
+                                       prci =
+                                               int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno),
+                                                                                                                res->pdx) - int_floordivpow2(trx0, res->pdx);
+                                       prcj =
+                                               int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno),
+                                                                                                                res->pdy) - int_floordivpow2(try0, res->pdy);
+                                       pi->precno = prci + prcj * res->pw;
+                                       for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {
+                                         if (! pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p]){
+                                           pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p] = 1;
+                                                       return 1;
+                                               }
+                                       skip:;
+                                       }
+                               }
+                       }
+               }
+       }
+       return 0;
+}
+
+/* <summary> */
+/* Get next packet in component-precinct-resolution-layer order.   */
+/* </summary> */
+int pi_next_cprl(pi_iterator_t * pi)
+{
+       pi_comp_t *comp;
+       pi_resolution_t *res;
+       if (!pi->first) {
+               comp = &pi->comps[pi->compno];
+               goto skip;
+       } else {
+               pi->first = 0;
+       }
+       for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1;
+                        pi->compno++) {
+               int resno;
+               comp = &pi->comps[pi->compno];
+               pi->dx = 0;
+               pi->dy = 0;
+               for (resno = 0; resno < comp->numresolutions; resno++) {
+                       int dx, dy;
+                       res = &comp->resolutions[resno];
+                       dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
+                       dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
+                       pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
+                       pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
+               }
+               for (pi->y = pi->ty0; pi->y < pi->ty1;
+                                pi->y += pi->dy - (pi->y % pi->dy)) {
+                       for (pi->x = pi->tx0; pi->x < pi->tx1;
+                                        pi->x += pi->dx - (pi->x % pi->dx)) {
+                               for (pi->resno = pi->poc.resno0;
+                                                pi->resno < int_min(pi->poc.resno1, comp->numresolutions);
+                                                pi->resno++) {
+                                       int levelno;
+                                       int trx0, try0;
+                                       int rpx, rpy;
+                                       int prci, prcj;
+                                       res = &comp->resolutions[pi->resno];
+                                       levelno = comp->numresolutions - 1 - pi->resno;
+                                       trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
+                                       try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
+                                       rpx = res->pdx + levelno;
+                                       rpy = res->pdy + levelno;
+                                       if (!
+                                                       (pi->x % (comp->dx << rpx) == 0
+                                                        || (pi->x == pi->tx0 && (trx0 << levelno) % (1 << rpx)))) {
+                                               continue;
+                                       }
+                                       if (!
+                                                       (pi->y % (comp->dy << rpy) == 0
+                                                        || (pi->y == pi->ty0 && (try0 << levelno) % (1 << rpx)))) {
+                                               continue;
+                                       }
+                                       prci =
+                                               int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno),
+                                                                                                                res->pdx) - int_floordivpow2(trx0, res->pdx);
+                                       prcj =
+                                               int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno),
+                                                                                                                res->pdy) - int_floordivpow2(try0, res->pdy);
+                                       pi->precno = prci + prcj * res->pw;
+                                       for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {
+                                         if (! pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p]){
+                                           pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p] = 1;
+                                           return 1;
+                                               }
+                                       skip:;
+                                       }
+                               }
+                       }
+               }
+       }
+       return 0;
+}
+
+/* <summary> */
+/* Get next packet.   */
+/* </summary> */
+int pi_next(pi_iterator_t * pi)
+{
+       switch (pi->poc.prg) {
+       case 0:
+               return pi_next_lrcp(pi);
+       case 1:
+               return pi_next_rlcp(pi);
+       case 2:
+               return pi_next_rpcl(pi);
+       case 3:
+               return pi_next_pcrl(pi);
+       case 4:
+               return pi_next_cprl(pi);
+       }
+       return 0;
+}
diff --git a/applications/indexer_JPIP/pi.h b/applications/indexer_JPIP/pi.h
new file mode 100644 (file)
index 0000000..b300b9e
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __PI_H
+#define __PI_H
+
+#include "j2k.h"
+#include "tcd.h"
+
+typedef struct {
+       int pdx, pdy;
+       int pw, ph;
+} pi_resolution_t;
+
+typedef struct {
+       int dx, dy;
+       int numresolutions;
+       pi_resolution_t *resolutions;
+} pi_comp_t;
+
+typedef struct {
+       short int *include;
+  int step_l, step_r, step_c, step_p; 
+       int compno, resno, precno, layno;       /* component, resolution, precinct and layer that indentify the packet */
+       int first;
+       j2k_poc_t poc;
+       int numcomps;
+       pi_comp_t *comps;
+       int tx0, ty0, tx1, ty1;
+       int x, y, dx, dy;
+} pi_iterator_t;                                                               /* packet iterator */
+
+/*
+ * Create a packet iterator
+ * img: raw image for which the packets will be listed
+ * cp: coding paremeters
+ * tileno: number that identifies the tile for which to list the packets
+ * return value: returns a packet iterator that points to the first packet of the tile
+ */
+pi_iterator_t *pi_create(j2k_image_t * img, j2k_cp_t * cp, int tileno);
+
+/* 
+ * Modify the packet iterator to point to the next packet
+ * pi: packet iterator to modify
+ * return value: returns 0 if pi pointed to the last packet or else returns 1 
+ */
+int pi_next(pi_iterator_t * pi);
+
+#endif
diff --git a/applications/indexer_JPIP/t2.c b/applications/indexer_JPIP/t2.c
new file mode 100644 (file)
index 0000000..14a44be
--- /dev/null
@@ -0,0 +1,389 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "t2.h"
+#include "tcd.h"
+#include "bio.h"
+#include "j2k.h"
+#include "pi.h"
+#include "tgt.h"
+#include "int.h"
+#include "cio.h"
+#include <stdio.h>
+#include <setjmp.h>
+#include <string.h>
+#include <stdlib.h> 
+
+#define RESTART 0x04
+
+extern jmp_buf j2k_error;
+
+int t2_getcommacode() {
+    int n;
+    for (n=0; bio_read(1); n++) {}
+    return n;
+}
+
+int t2_getnumpasses()
+{
+    int n;
+    if (!bio_read(1)) return 1;
+    if (!bio_read(1)) return 2;
+    if ((n=bio_read(2))!=3) return 3+n;
+    if ((n=bio_read(5))!=31) return 6+n;
+    return 37+bio_read(7);
+}
+
+void t2_init_seg(tcd_seg_t *seg, int cblksty) {
+    seg->numpasses=0;
+    seg->len=0;
+    seg->maxpasses=cblksty&J2K_CCP_CBLKSTY_TERMALL?1:100;
+}
+
+int t2_decode_packet(unsigned char *src, int len, tcd_tile_t *tile, j2k_cp_t * cp, j2k_tcp_t *tcp, int compno, int resno, int precno, int layno, info_layer_t *layer_Idx) {
+    int bandno, cblkno;
+    tcd_tilecomp_t *tilec = &tile->comps[compno];
+    tcd_resolution_t *res = &tilec->resolutions[resno];
+    unsigned char *c = src;
+    unsigned char *d = c;
+    int e;
+    int present;
+
+    if (layno == 0) {
+        for (bandno = 0; bandno < res->numbands; bandno++) {
+            tcd_band_t *band = &res->bands[bandno];
+            tcd_precinct_t *prc = &band->precincts[precno];
+            tgt_reset(prc->incltree);
+            tgt_reset(prc->imsbtree);
+            for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
+                tcd_cblk_t *cblk = &prc->cblks[cblkno];
+                cblk->numsegs = 0;
+            }
+        }  
+    }
+    /* INDEX */
+    layer_Idx->len_header = 0;
+
+    /* When the marker PPT/PPM is used the packet header are store in PPT/PPM marker
+       This part deal with this caracteristic
+       step 1: Read packet header in the saved structure
+       step 2: (futher) return to codestream for decoding */
+    if (cp->ppm == 1) /* PPM */
+      {            
+       c = cp->ppm_data;
+       d = c;
+       bio_init_dec(c, 1000);
+      } else 
+       {
+         if (tcp->ppt == 1) /* PPT */
+           {
+             c = tcp->ppt_data;
+             d = c;
+             bio_init_dec(c, 1000);
+           } else /* Normal Case */
+             {
+               if (tcp->csty & J2K_CP_CSTY_SOP) 
+                 {
+                   if ((*c) != 255 || (*(c+1) != 145)) {printf("Error : expected SOP marker [1]!!!\n");}
+                   c += 6;
+                 }
+               bio_init_dec(c, src + len - c);
+               layer_Idx->len_header = -6;
+             }
+       }
+    
+    present = bio_read(1);
+    
+    if (!present) 
+      {
+       bio_inalign();
+       /* Normal case */
+       c += bio_numbytes();
+       if (tcp->csty & J2K_CP_CSTY_EPH) 
+         {
+           if ((*c) != 255 || (*(c+1) != 146)) {printf("Error : expected EPH marker [1]!!!\n");}
+           c += 2;
+         }
+       /* INDEX */
+       layer_Idx->len_header += (c-d);
+
+       /* PPT and PPM dealing */
+       if (cp->ppm == 1) /* PPM */
+         {     
+           cp->ppm_data = c;       
+           return 0;
+         }
+       if (tcp->ppt == 1) /* PPT */
+         {
+           tcp->ppt_data = c;
+           return 0;
+         }
+       return c - src;
+      }
+    
+    for (bandno=0; bandno<res->numbands; bandno++) {
+        tcd_band_t *band = &res->bands[bandno];
+        tcd_precinct_t *prc = &band->precincts[precno];
+        for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
+            int included, increment, n;
+            tcd_cblk_t *cblk = &prc->cblks[cblkno];
+            tcd_seg_t *seg;
+            if (!cblk->numsegs) {
+                included = tgt_decode(prc->incltree, cblkno, layno+1);
+            } else {
+                included = bio_read(1);
+            }
+            if (!included) {
+                cblk->numnewpasses = 0;
+                continue;
+            }
+            if (!cblk->numsegs) {
+                int i, numimsbs;
+                for (i = 0; !tgt_decode(prc->imsbtree, cblkno, i); i++) {}
+                numimsbs = i-1;
+                cblk->numbps = band->numbps - numimsbs;
+                cblk->numlenbits = 3;
+            }
+            cblk->numnewpasses = t2_getnumpasses();
+            increment = t2_getcommacode();
+            cblk->numlenbits += increment;
+            if (!cblk->numsegs) {
+                seg = &cblk->segs[0];
+                t2_init_seg(seg, tcp->tccps[compno].cblksty);
+            } else {
+                seg = &cblk->segs[cblk->numsegs - 1];
+                if (seg->numpasses == seg->maxpasses) {
+                    t2_init_seg(++seg, tcp->tccps[compno].cblksty);
+                }
+            }
+            n = cblk->numnewpasses;
+            do {
+                seg->numnewpasses = int_min(seg->maxpasses-seg->numpasses, n);
+                seg->newlen = bio_read(cblk->numlenbits + int_floorlog2(seg->numnewpasses));
+                n -= seg->numnewpasses;
+                if (n > 0) {
+                    t2_init_seg(++seg, tcp->tccps[compno].cblksty);
+                }
+            } while (n > 0);
+        }
+    }
+    if(bio_inalign()) return -999;
+    c += bio_numbytes();
+
+    if (tcp->csty & J2K_CP_CSTY_EPH) { /* EPH marker */
+      if ((*c) != 255 || (*(c+1) != 146)) {printf("Error : expected EPH marker [2]!!!\n"); }
+      c += 2;
+    }
+    
+    /* INDEX */
+    layer_Idx->len_header += (c-d);
+
+    /* PPT Step 2 : see above for details */
+    if (cp->ppm == 1)
+      {
+       cp->ppm_data = c; /* Update pointer */
+
+       /* INDEX */
+       layer_Idx->len_header = c-d;
+
+       c = src;
+       d = c;
+       if (tcp->csty & J2K_CP_CSTY_SOP) 
+         {
+           if ((*c) != 255 || (*(c+1) != 145)) {printf("Error : expected SOP marker [2] !!!\n"); }
+           c += 6;
+         }
+       bio_init_dec(c, src + len - c);
+      } else 
+       {
+         if (tcp->ppt == 1)
+           { 
+             tcp->ppt_data = c; /* Update pointer */
+             /* INDEX */
+             layer_Idx->len_header = c-d;
+
+             c = src;
+             d = c;
+             if (tcp->csty & J2K_CP_CSTY_SOP) /* SOP marker */
+               { 
+                 if ((*c) != 255 || (*(c+1) != 145)) {printf("Error : expected SOP marker [2] !!!\n"); }
+                 c += 6;
+               }
+             bio_init_dec(c, src + len - c);
+             
+           }
+       }
+
+    for (bandno = 0; bandno < res->numbands; bandno++) {
+        tcd_band_t *band = &res->bands[bandno];
+        tcd_precinct_t *prc = &band->precincts[precno];
+        for (cblkno = 0; cblkno < prc->cw*prc->ch; cblkno++) {
+            tcd_cblk_t *cblk = &prc->cblks[cblkno];
+            tcd_seg_t *seg;
+            if (!cblk->numnewpasses) continue;
+            if (!cblk->numsegs) {
+                seg = &cblk->segs[cblk->numsegs++];
+                cblk->len = 0;
+            } else {
+                seg = &cblk->segs[cblk->numsegs-1];
+                if (seg->numpasses == seg->maxpasses) {
+                    seg++;
+                    cblk->numsegs++;
+                }
+            }
+            do {
+             if (c + seg->newlen > src + len) return -999;
+                memcpy(cblk->data + cblk->len, c, seg->newlen);
+                if (seg->numpasses == 0) {
+                    seg->data = cblk->data + cblk->len;
+                }
+                c += seg->newlen;
+                cblk->len += seg->newlen;
+                seg->len += seg->newlen;
+                seg->numpasses += seg->numnewpasses;
+                cblk->numnewpasses -= seg->numnewpasses;
+                if (cblk->numnewpasses > 0) {
+                    seg++;
+                    cblk->numsegs++;
+                }
+            } while (cblk->numnewpasses > 0);
+        }
+    }
+    /* <INDEX> */
+    e = c-d;
+    layer_Idx->len = e;
+    /* </INDEX> */
+
+    return c-src;
+}
+
+void t2_init_info_packets(info_image_t *img, j2k_cp_t *cp)
+{
+  int compno, tileno, resno, precno, layno;
+
+  for(compno = 0; compno < img->Comp; compno++)
+    {
+      for(tileno = 0; tileno < img->tw*img->th; tileno++)
+       {
+         info_tile_t *tile_Idx = &img->tile[tileno];
+         info_compo_t *compo_Idx = &tile_Idx->compo[compno];
+         for(resno = 0; resno < img->Decomposition + 1 ; resno++)
+           {
+             info_reso_t *reso_Idx = &compo_Idx->reso[resno];
+             for (precno = 0; precno < img->tile[tileno].pw * img->tile[tileno].ph; precno++)
+               {
+                 info_prec_t *prec_Idx = &reso_Idx->prec[precno];
+                 for(layno = 0; layno < img->Layer ; layno++)
+                   {
+                     info_layer_t *layer_Idx = &prec_Idx->layer[layno];
+                     layer_Idx->offset = 0;        /* start position */
+                     layer_Idx->len_header = 0;    /* length         */
+                   }
+               }
+           }
+       }
+    }
+}
+
+int t2_decode_packets(unsigned char *src, int len, j2k_image_t *img, j2k_cp_t *cp, int tileno, tcd_tile_t *tile, info_image_t *imgg) {
+    unsigned char *c = src;
+    pi_iterator_t *pi;
+    int pino, compno,e;
+    int partno;
+    info_tile_part_t *tile_part;
+    int position;
+    int length_read;
+    info_tile_t *tile_Idx;
+    info_compo_t *compo_Idx;
+    info_reso_t *reso_Idx;
+    info_prec_t *prec_Idx;
+    info_layer_t *layer_Idx;
+
+    t2_init_info_packets(imgg, cp); /* Initialize the packets information : LEN and OFFSET to 0 */
+
+    tile_Idx = &imgg->tile[tileno];
+    tile_Idx->num_packet = 0;
+    pi = pi_create(img, cp, tileno);
+    partno = 0;
+    tile_part = &tile_Idx->tile_parts[partno];
+    position = tile_part->end_header + 1;
+    length_read = 0;
+
+    for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++)
+      {
+       while (pi_next(&pi[pino])) 
+         {   
+           compo_Idx = &tile_Idx->compo[pi[pino].compno];
+           reso_Idx = &compo_Idx->reso[pi[pino].resno];
+           prec_Idx = &reso_Idx->prec[pi[pino].precno];
+           layer_Idx = &prec_Idx->layer[pi[pino].layno];
+           
+           layer_Idx->offset = position;
+           layer_Idx->offset_header = position;
+           
+           e = t2_decode_packet(c, src+len-c, tile, cp, &cp->tcps[tileno], pi[pino].compno, pi[pino].resno, pi[pino].precno, pi[pino].layno,layer_Idx);
+           if (e == -999)
+             {
+               break;
+             } else
+               c += e;
+           position += e;
+           
+           /* Update position in case of multiple tile-parts for a tile >> */
+           length_read += e;
+           if (length_read >= (tile_part->end_pos - tile_part->end_header))
+             {
+               partno++;
+               tile_part = &tile_Idx->tile_parts[partno];
+               position = tile_part->end_header + 1;
+               length_read = 0;
+             }
+           /* << end_update */
+           
+           tile_Idx->num_packet++;
+         }
+       
+       // FREE space memory taken by pi
+       for (compno = 0; compno < pi[pino].numcomps; compno++) 
+         { 
+           free(pi[pino].comps[compno].resolutions);
+         } 
+       free(pi[pino].comps);
+      }
+    
+    free(pi[0].include);
+    free(pi);
+    if (e==-999)
+      return e;
+    else
+      {
+       imgg->num_packet_max=int_max(imgg->num_packet_max,tile_Idx->num_packet);
+       return c-src;
+      }
+}
diff --git a/applications/indexer_JPIP/t2.h b/applications/indexer_JPIP/t2.h
new file mode 100644 (file)
index 0000000..f495107
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __T2_H
+#define __T2_H
+
+#include "tcd.h"
+#include "j2k.h"
+
+/*
+ * Decode the packets of a tile from a source buffer
+ * src: the source buffer
+ * len: length of the source buffer
+ * img: destination image
+ * cp: image coding parameters
+ * tileno: number that identifies the tile for which to decode the packets
+ * tile: tile for which to decode the packets
+ */
+int t2_decode_packets(unsigned char *src, int len, j2k_image_t *img, j2k_cp_t *cp, int tileno, tcd_tile_t *tile, info_image_t *imgg);
+
+#endif
diff --git a/applications/indexer_JPIP/tcd.c b/applications/indexer_JPIP/tcd.c
new file mode 100644 (file)
index 0000000..c4045c7
--- /dev/null
@@ -0,0 +1,285 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "tcd.h"
+#include "int.h"
+#include "t2.h"
+#include <setjmp.h>
+#include <float.h>
+#include <stdio.h>
+#include <time.h>
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+
+static tcd_image_t tcd_image;
+
+static j2k_image_t *tcd_img;
+static j2k_cp_t *tcd_cp;
+
+extern jmp_buf j2k_error;
+
+void tcd_init(j2k_image_t *img, j2k_cp_t *cp, info_image_t *imgg) {
+    int tileno, compno, resno, bandno, precno, cblkno;
+    tcd_img=img;
+    tcd_cp=cp;
+    tcd_image.tw=cp->tw;
+    tcd_image.th=cp->th;
+    tcd_image.tiles=(tcd_tile_t*)malloc(cp->tw*cp->th*sizeof(tcd_tile_t));
+    for (tileno=0; tileno<cp->tw*cp->th; tileno++) {
+        j2k_tcp_t *tcp=&cp->tcps[tileno];
+        tcd_tile_t *tile=&tcd_image.tiles[tileno];
+        // cfr p59 ISO/IEC FDIS15444-1 : 2000 (18 august 2000)
+        int p=tileno%cp->tw;  // si numerotation matricielle ..
+        int q=tileno/cp->tw;  // .. coordonnees de la tile (q,p) q pour ligne et p pour colonne
+       info_tile_t *tile_Idx=&imgg->tile[tileno]; // INDEX
+
+       // 4 borders of the tile rescale on the image if necessary
+        tile->x0=int_max(cp->tx0+p*cp->tdx, img->x0);
+        tile->y0=int_max(cp->ty0+q*cp->tdy, img->y0);
+        tile->x1=int_min(cp->tx0+(p+1)*cp->tdx, img->x1);
+        tile->y1=int_min(cp->ty0+(q+1)*cp->tdy, img->y1);
+       
+        tile->numcomps=img->numcomps;
+        tile->comps=(tcd_tilecomp_t*)malloc(img->numcomps*sizeof(tcd_tilecomp_t));
+        tile_Idx->compo=(info_compo_t*)malloc(img->numcomps*sizeof(info_compo_t)); // INDEX
+       for (compno=0; compno<tile->numcomps; compno++) {
+            j2k_tccp_t *tccp=&tcp->tccps[compno];
+            tcd_tilecomp_t *tilec=&tile->comps[compno];
+           info_compo_t *compo_Idx=&tile_Idx->compo[compno]; // INDEX
+
+           // border of each tile component (global)
+            tilec->x0=int_ceildiv(tile->x0, img->comps[compno].dx);
+            tilec->y0=int_ceildiv(tile->y0, img->comps[compno].dy);
+           tilec->x1=int_ceildiv(tile->x1, img->comps[compno].dx);
+            tilec->y1=int_ceildiv(tile->y1, img->comps[compno].dy);
+           
+            tilec->data=(int*)malloc(sizeof(int)*(tilec->x1-tilec->x0)*(tilec->y1-tilec->y0));
+            tilec->numresolutions=tccp->numresolutions;
+            tilec->resolutions=(tcd_resolution_t*)malloc(tilec->numresolutions*sizeof(tcd_resolution_t));
+           compo_Idx->reso=(info_reso_t*)malloc(tilec->numresolutions*sizeof(info_reso_t)); // INDEX
+            for (resno=0; resno<tilec->numresolutions; resno++) {
+                int pdx, pdy;
+                int levelno=tilec->numresolutions-1-resno;
+                int tlprcxstart, tlprcystart, brprcxend, brprcyend;
+                int tlcbgxstart, tlcbgystart, brcbgxend, brcbgyend;
+                int cbgwidthexpn, cbgheightexpn;
+                int cblkwidthexpn, cblkheightexpn;
+                tcd_resolution_t *res=&tilec->resolutions[resno];
+               info_reso_t *res_Idx=&compo_Idx->reso[resno]; // INDEX
+               int precno_Idx; // INDEX
+
+               // border for each resolution level (global)
+                res->x0=int_ceildivpow2(tilec->x0, levelno);
+                res->y0=int_ceildivpow2(tilec->y0, levelno);
+                res->x1=int_ceildivpow2(tilec->x1, levelno);
+                res->y1=int_ceildivpow2(tilec->y1, levelno);
+               
+               res->numbands=resno==0?1:3;
+               // p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000)
+                if (tccp->csty&J2K_CCP_CSTY_PRT) {
+                    pdx=tccp->prcw[resno];
+                    pdy=tccp->prch[resno];
+               } else {
+                    pdx=15;
+                    pdy=15;
+                }
+               // p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000) 
+                tlprcxstart=int_floordivpow2(res->x0, pdx)<<pdx;
+                tlprcystart=int_floordivpow2(res->y0, pdy)<<pdy;
+                brprcxend=int_ceildivpow2(res->x1, pdx)<<pdx;
+                brprcyend=int_ceildivpow2(res->y1, pdy)<<pdy;
+                res->pw=(brprcxend-tlprcxstart)>>pdx;
+                res->ph=(brprcyend-tlprcystart)>>pdy;
+
+               // <INDEX>
+               imgg->tile[tileno].pw=res->pw;
+               imgg->tile[tileno].ph=res->ph;
+               
+               res_Idx->prec=(info_prec_t*)malloc(res->pw*res->ph*sizeof(info_prec_t));
+               for (precno_Idx=0;precno_Idx<res->pw*res->ph;precno_Idx++)
+                 {
+                   info_prec_t *prec_Idx = &res_Idx->prec[precno_Idx];
+                   prec_Idx->layer=(info_layer_t*)malloc(imgg->Layer*sizeof(info_layer_t));
+                 }
+               
+               imgg->pw=res->pw;  // old parser version
+               imgg->ph=res->ph;  // old parser version
+               imgg->pdx=1<<pdx;
+               imgg->pdy=1<<pdy;
+               // </INDEX>
+
+                if (resno==0) {
+                    tlcbgxstart=tlprcxstart;
+                    tlcbgystart=tlprcystart;
+                    brcbgxend=brprcxend;
+                    brcbgyend=brprcyend;
+                    cbgwidthexpn=pdx;
+                    cbgheightexpn=pdy;
+                } else {
+                    tlcbgxstart=int_ceildivpow2(tlprcxstart, 1);
+                    tlcbgystart=int_ceildivpow2(tlprcystart, 1);
+                    brcbgxend=int_ceildivpow2(brprcxend, 1);
+                    brcbgyend=int_ceildivpow2(brprcyend, 1);
+                    cbgwidthexpn=pdx-1;
+                    cbgheightexpn=pdy-1;
+                }
+
+                cblkwidthexpn=int_min(tccp->cblkw, cbgwidthexpn);
+                cblkheightexpn=int_min(tccp->cblkh, cbgheightexpn);
+
+                for (bandno=0; bandno<res->numbands; bandno++) {
+                    int x0b, y0b;
+                    tcd_band_t *band=&res->bands[bandno];
+                    band->bandno=resno==0?0:bandno+1;
+                    x0b=(band->bandno==1)||(band->bandno==3)?1:0;
+                    y0b=(band->bandno==2)||(band->bandno==3)?1:0;
+
+                    if (band->bandno==0) {
+                     // band border (global)
+                     band->x0=int_ceildivpow2(tilec->x0, levelno);
+                     band->y0=int_ceildivpow2(tilec->y0, levelno);
+                     band->x1=int_ceildivpow2(tilec->x1, levelno);
+                     band->y1=int_ceildivpow2(tilec->y1, levelno);
+                    } else {
+                     // band border (global)
+                     band->x0=int_ceildivpow2(tilec->x0-(1<<levelno)*x0b, levelno+1);
+                     band->y0=int_ceildivpow2(tilec->y0-(1<<levelno)*y0b, levelno+1);
+                     band->x1=int_ceildivpow2(tilec->x1-(1<<levelno)*x0b, levelno+1);
+                     band->y1=int_ceildivpow2(tilec->y1-(1<<levelno)*y0b, levelno+1);
+                    }
+
+                    band->precincts=(tcd_precinct_t*)malloc(res->pw*res->ph*sizeof(tcd_precinct_t));
+
+                    for (precno=0; precno<res->pw*res->ph; precno++) {
+                        int tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend;
+                        int cbgxstart=tlcbgxstart+(precno%res->pw)*(1<<cbgwidthexpn);
+                        int cbgystart=tlcbgystart+(precno/res->pw)*(1<<cbgheightexpn);
+                        int cbgxend=cbgxstart+(1<<cbgwidthexpn);
+                        int cbgyend=cbgystart+(1<<cbgheightexpn);
+                        tcd_precinct_t *prc=&band->precincts[precno];
+                       // precinct size (global)
+                        prc->x0=int_max(cbgxstart, band->x0);
+                        prc->y0=int_max(cbgystart, band->y0);
+                        prc->x1=int_min(cbgxend, band->x1);
+                        prc->y1=int_min(cbgyend, band->y1);
+
+                        tlcblkxstart=int_floordivpow2(prc->x0, cblkwidthexpn)<<cblkwidthexpn;
+                        tlcblkystart=int_floordivpow2(prc->y0, cblkheightexpn)<<cblkheightexpn;
+                        brcblkxend=int_ceildivpow2(prc->x1, cblkwidthexpn)<<cblkwidthexpn;
+                        brcblkyend=int_ceildivpow2(prc->y1, cblkheightexpn)<<cblkheightexpn;
+                        prc->cw=(brcblkxend-tlcblkxstart)>>cblkwidthexpn;
+                        prc->ch=(brcblkyend-tlcblkystart)>>cblkheightexpn;
+
+                        prc->cblks=(tcd_cblk_t*)malloc(prc->cw*prc->ch*sizeof(tcd_cblk_t));
+
+                        prc->incltree=tgt_create(prc->cw, prc->ch);
+                        prc->imsbtree=tgt_create(prc->cw, prc->ch);
+
+                        for (cblkno=0; cblkno<prc->cw*prc->ch; cblkno++) {
+                            int cblkxstart=tlcblkxstart+(cblkno%prc->cw)*(1<<cblkwidthexpn);
+                            int cblkystart=tlcblkystart+(cblkno/prc->cw)*(1<<cblkheightexpn);
+                            int cblkxend=cblkxstart+(1<<cblkwidthexpn);
+                            int cblkyend=cblkystart+(1<<cblkheightexpn);
+                            tcd_cblk_t *cblk=&prc->cblks[cblkno];
+                           // code-block size (global)
+                            cblk->x0=int_max(cblkxstart, prc->x0);
+                            cblk->y0=int_max(cblkystart, prc->y0);
+                            cblk->x1=int_min(cblkxend, prc->x1);
+                            cblk->y1=int_min(cblkyend, prc->y1);
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
+
+
+void tcd_free(j2k_image_t *img, j2k_cp_t *cp) {
+  int tileno, compno, resno, bandno, precno;
+  tcd_img=img;
+  tcd_cp=cp;
+  tcd_image.tw=cp->tw;
+  tcd_image.th=cp->th;
+  for (tileno=0; tileno<tcd_image.tw*tcd_image.th; tileno++) 
+    {
+      //  j2k_tcp_t *tcp=&cp->tcps[curtileno];
+      tcd_tile_t *tile=&tcd_image.tiles[tileno];
+      for (compno=0; compno<tile->numcomps; compno++) 
+       {
+        tcd_tilecomp_t *tilec=&tile->comps[compno];
+         for (resno=0; resno<tilec->numresolutions; resno++) 
+           {
+             tcd_resolution_t *res=&tilec->resolutions[resno];
+             for (bandno=0; bandno<res->numbands; bandno++) 
+               {
+                tcd_band_t *band=&res->bands[bandno];
+                 for (precno=0; precno<res->pw*res->ph; precno++) 
+                   {
+                    tcd_precinct_t *prc=&band->precincts[precno];
+                     
+                     if (prc->incltree!=NULL)
+                       tgt_destroy(prc->incltree);
+                     if (prc->imsbtree!=NULL)
+                       tgt_destroy(prc->imsbtree);
+                     free(prc->cblks);
+                   } // for (precno
+                 free(band->precincts);
+               } // for (bandno
+           }   // for (resno
+         free(tilec->resolutions);
+       }       // for (compno
+      free(tile->comps);
+    }  // for (tileno
+  free(tcd_image.tiles);
+}
+
+
+int tcd_decode_tile(unsigned char *src, int len, int tileno, info_image_t *imgg) {
+    int l;
+    int eof=0;
+    tcd_tile_t *tile;
+
+    tile = &tcd_image.tiles[tileno];
+
+    l = t2_decode_packets(src, len, tcd_img, tcd_cp, tileno, tile, imgg);
+
+    if (l==-999)
+      {
+       eof=1;
+       fprintf(stderr, "tcd_decode: incomplete bistream\n");
+      }
+    
+     if (eof) {
+       longjmp(j2k_error, 1);
+     }
+
+    l=1;
+    return l;
+}
diff --git a/applications/indexer_JPIP/tcd.h b/applications/indexer_JPIP/tcd.h
new file mode 100644 (file)
index 0000000..9a31723
--- /dev/null
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __TCD_H
+#define __TCD_H
+
+#include "j2k.h"
+#include "tgt.h"
+
+typedef struct {
+    int numpasses;
+    int len;
+    unsigned char *data;
+    int maxpasses;
+    int numnewpasses;
+    int newlen;
+} tcd_seg_t;
+
+typedef struct {
+    int rate;
+    double distortiondec;
+} tcd_pass_t;
+
+typedef struct {
+    int numpasses;
+    int len;
+    unsigned char *data;
+} tcd_layer_t;
+
+typedef struct {
+    int x0, y0, x1, y1;
+    int numbps;
+    int numlenbits;
+    int len;
+    int numpasses;
+    int numnewpasses;
+    int numsegs;
+    tcd_seg_t segs[100];
+    unsigned char data[8192];
+    int numpassesinlayers;
+    tcd_layer_t layers[100];
+    int totalpasses;
+    tcd_pass_t passes[100];
+} tcd_cblk_t;
+
+typedef struct {
+    int x0, y0, x1, y1;
+    int cw, ch;
+    tcd_cblk_t *cblks;
+    tgt_tree_t *incltree;
+    tgt_tree_t *imsbtree;
+} tcd_precinct_t;
+
+typedef struct {
+    int x0, y0, x1, y1;
+    int bandno;
+    tcd_precinct_t *precincts;
+    int numbps;
+    int stepsize;
+} tcd_band_t;
+
+typedef struct {
+    int x0, y0, x1, y1;  
+  int previous_x0, previous_y0, previous_x1, previous_y1; // usefull for the DWT
+  int cas_col, cas_row; // usefull for the DWT
+    int pw, ph;
+    int numbands;
+    tcd_band_t bands[3];
+} tcd_resolution_t;
+
+typedef struct {
+    int x0, y0, x1, y1;
+  int previous_row, previous_col; // usefull for the DWT
+    int numresolutions;
+    tcd_resolution_t *resolutions;
+    int *data;
+} tcd_tilecomp_t;
+
+typedef struct {
+    int x0, y0, x1, y1;
+    int numcomps;
+  //int PPT;
+  //int len_ppt;
+    tcd_tilecomp_t *comps;
+} tcd_tile_t;
+
+typedef struct {
+    int tw, th;
+    tcd_tile_t *tiles;
+} tcd_image_t;
+
+/*
+ * Initialize the tile coder/decoder
+ * img: raw image
+ * cp: coding parameters
+ * imgg: creation of index file
+ */
+
+void tcd_init(j2k_image_t *img, j2k_cp_t *cp, info_image_t *imgg);
+
+void tcd_free(j2k_image_t *img, j2k_cp_t *cp);
+
+/*
+ * Decode a tile from a buffer into a raw image
+ * src: source buffer
+ * len: length of the source buffer
+ * tileno: number that identifies the tile that will be decoded
+ * imgg : Structure for index file
+ */
+int tcd_decode_tile(unsigned char *src, int len, int tileno, info_image_t *imgg);
+
+#endif
diff --git a/applications/indexer_JPIP/tgt.c b/applications/indexer_JPIP/tgt.c
new file mode 100644 (file)
index 0000000..c2b4682
--- /dev/null
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "tgt.h"
+#include "bio.h"
+#include <stdlib.h>
+#include <stdio.h>
+
+/// <summary>
+/// Reset tag-tree.
+/// </summary>
+void tgt_reset(tgt_tree_t *tree)
+{
+    int i;
+    for (i=0; i<tree->numnodes; i++) {
+        tree->nodes[i].value=999;
+        tree->nodes[i].low=0;
+        tree->nodes[i].known=0;
+    }
+}
+
+/// <summary>
+/// Create tag-tree.
+/// </summary>
+tgt_tree_t *tgt_create(int numleafsh, int numleafsv)
+{
+    int nplh[32];
+    int nplv[32];
+    tgt_node_t *node;
+    tgt_node_t *parentnode;
+    tgt_node_t *parentnode0;
+    tgt_tree_t *tree;
+    int i, j, k;
+    int numlvls;
+    int n;
+
+    tree=(tgt_tree_t*)malloc(sizeof(tgt_tree_t));
+    tree->numleafsh=numleafsh;
+    tree->numleafsv=numleafsv;
+
+    numlvls=0;
+    nplh[0]=numleafsh;
+    nplv[0]=numleafsv;
+    tree->numnodes=0;
+    do {
+        n=nplh[numlvls]*nplv[numlvls];
+        nplh[numlvls+1]=(nplh[numlvls]+1)/2;
+        nplv[numlvls+1]=(nplv[numlvls]+1)/2;
+        tree->numnodes+=n;
+        ++numlvls;
+    } while (n>1);
+
+    tree->nodes=(tgt_node_t*)malloc(tree->numnodes*sizeof(tgt_node_t));
+
+    node=tree->nodes;
+    parentnode=&tree->nodes[tree->numleafsh*tree->numleafsv];
+    parentnode0=parentnode;
+
+    for (i=0; i<numlvls-1; ++i) {
+        for (j=0; j<nplv[i]; ++j) {
+            k=nplh[i];
+            while (--k>=0) {
+                node->parent=parentnode;
+                ++node;
+                if (--k >= 0) {
+                    node->parent=parentnode;
+                    ++node;
+                }
+                ++parentnode;
+            }
+            if ((j&1)||j==nplv[i]-1) {
+                parentnode0=parentnode;
+            } else {
+                parentnode=parentnode0;
+                parentnode0+=nplh[i];
+            }
+        }
+    }
+    node->parent=0;
+
+    tgt_reset(tree);
+
+    return tree;
+}
+
+/// <summary>
+/// Destroy tag-tree.
+/// </summary>
+void tgt_destroy(tgt_tree_t *t) {
+    free(t->nodes);
+    free(t);
+}
+
+/// <summary>
+/// Set the value of a leaf of the tag-tree.
+/// </summary>
+void tgt_setvalue(tgt_tree_t *tree, int leafno, int value) {
+    tgt_node_t *node;
+    node=&tree->nodes[leafno];
+    while (node && node->value>value) {
+        node->value=value;
+        node=node->parent;
+    }
+}
+
+/// <summary>
+/// Decode the value of a leaf of the tag-tree.
+/// </summary>
+int tgt_decode(tgt_tree_t *tree, int leafno, int threshold)
+{
+    tgt_node_t *stk[31];
+    tgt_node_t **stkptr;
+    tgt_node_t *node;
+    int low;
+
+    stkptr=stk;
+    node=&tree->nodes[leafno];
+    while (node->parent) {
+        *stkptr++=node;
+        node=node->parent;
+    }
+
+    low=0;
+    for (;;) {
+        if (low>node->low) {
+            node->low=low;
+        } else {
+            low=node->low;
+        }
+        while (low<threshold && low<node->value) {
+            if (bio_read(1)) {
+                node->value=low;
+            } else {
+                ++low;
+            }
+        }
+        node->low=low;
+        if (stkptr==stk) {
+            break;
+        }
+        node=*--stkptr;
+    }
+
+    return (node->value<threshold)?1:0;
+}
diff --git a/applications/indexer_JPIP/tgt.h b/applications/indexer_JPIP/tgt.h
new file mode 100644 (file)
index 0000000..9d85ade
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2001-2002, David Janssens
+ * Copyright (c) 2003, Yannick Verschueren
+ * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __TGT_H
+#define __TGT_H
+
+typedef struct tgt_node {
+       struct tgt_node *parent;
+       int value;
+       int low;
+       int known;
+} tgt_node_t;
+
+typedef struct {
+       int numleafsh;
+       int numleafsv;
+       int numnodes;
+       tgt_node_t *nodes;
+} tgt_tree_t;
+
+/*
+ * Create a tag-tree
+ * numleafsh: width of the array of leafs of the tree
+ * numleafsv: height of the array of leafs of the tree
+ */
+tgt_tree_t *tgt_create(int numleafsh, int numleafsv);
+
+/*
+ * Reset a tag-tree (set all leafs to 0)
+ * tree: tag-tree to reset
+ */
+void tgt_reset(tgt_tree_t *tree);
+
+/*
+ * Destroy a tag-tree, liberating memory
+ * tree: tag-tree to destroy
+ */
+void tgt_destroy(tgt_tree_t *tree);
+
+/*
+ * Set the value of a leaf of a tag-tree
+ * tree: tag-tree to modify
+ * leafno: number that identifies the leaf to modify
+ * value: new value of the leaf
+ */
+void tgt_setvalue(tgt_tree_t *tree, int leafno, int value);
+
+/*
+ * Decode the value of a leaf of the tag-tree up to a given threshold
+ * leafno: number that identifies the leaf to decode
+ * threshold: threshold to use when decoding value of the leaf
+ */
+int tgt_decode(tgt_tree_t *tree, int leafno, int threshold);
+
+#endif
diff --git a/applications/mj2/CMakeLists.txt b/applications/mj2/CMakeLists.txt
new file mode 100644 (file)
index 0000000..6fd63dd
--- /dev/null
@@ -0,0 +1,95 @@
+# Makefile for the MJ2 codecs of the OpenJPEG library: frames_to_mj2, mj2_to_frames, extract_j2k_from_mj2 and wrap_j2k_in_mj2
+
+SET(common_SRCS "")
+IF(DONT_HAVE_GETOPT)
+  SET(common_SRCS ${OPENJPEG_SOURCE_DIR}/common/getopt.c)
+ENDIF(DONT_HAVE_GETOPT)
+
+# While mj2 executables do not use the API correctly, we do not link with the library but rather compile the sources files.
+SET(OPJ_SRCS
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/bio.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/cio.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/dwt.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/event.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/image.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/j2k.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/j2k_lib.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/jp2.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/jpt.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/mct.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/mqc.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/openjpeg.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/pi.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/raw.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/t1.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/t2.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/tcd.c
+${OPENJPEG_SOURCE_DIR}/libopenjpeg/tgt.c
+)
+
+SET(MJ2_SRCS mj2.c mj2_convert.c)
+
+IF(WIN32)
+  ADD_DEFINITIONS(-DOPJ_STATIC)
+ENDIF(WIN32)
+
+# Headers file are located here:
+INCLUDE_DIRECTORIES(
+  ${OPENJPEG_SOURCE_DIR}/libopenjpeg
+  ${OPENJPEG_SOURCE_DIR}/common
+  ${LCMS_INCLUDE_DIRNAME}
+  )
+
+ADD_EXECUTABLE(frames_to_mj2
+  frames_to_mj2.c
+  ${common_SRCS}
+  ${OPJ_SRCS}
+  ${MJ2_SRCS}
+  )
+IF(LCMS_FOUND OR LCMS2_FOUND)
+  TARGET_LINK_LIBRARIES(frames_to_mj2 ${LCMS_LIBNAME})
+ENDIF(LCMS_FOUND OR LCMS2_FOUND)
+IF(UNIX)
+  TARGET_LINK_LIBRARIES(frames_to_mj2 m)
+ENDIF(UNIX)
+
+ADD_EXECUTABLE(mj2_to_frames
+    mj2_to_frames.c
+    ${common_SRCS}
+    ${OPJ_SRCS}
+    ${MJ2_SRCS}
+    ${OPENJPEG_SOURCE_DIR}/common/color.c
+    )
+IF(LCMS_FOUND OR LCMS2_FOUND)
+  TARGET_LINK_LIBRARIES(mj2_to_frames ${LCMS_LIBNAME})
+ENDIF(LCMS_FOUND OR LCMS2_FOUND)
+IF(UNIX)
+  TARGET_LINK_LIBRARIES(mj2_to_frames m)
+ENDIF(UNIX)
+
+ADD_EXECUTABLE(extract_j2k_from_mj2
+    extract_j2k_from_mj2.c
+    ${OPJ_SRCS}
+    ${MJ2_SRCS}
+    )
+IF(LCMS_FOUND OR LCMS2_FOUND)
+  TARGET_LINK_LIBRARIES(extract_j2k_from_mj2 ${LCMS_LIBNAME})
+ENDIF(LCMS_FOUND OR LCMS2_FOUND)
+IF(UNIX)
+  TARGET_LINK_LIBRARIES(extract_j2k_from_mj2 m)
+ENDIF(UNIX)
+
+ADD_EXECUTABLE(wrap_j2k_in_mj2
+    wrap_j2k_in_mj2.c
+    ${OPJ_SRCS}
+    ${MJ2_SRCS}
+    )
+IF(LCMS_FOUND OR LCMS2_FOUND)
+  TARGET_LINK_LIBRARIES(wrap_j2k_in_mj2 ${LCMS_LIBNAME})
+ENDIF(LCMS_FOUND OR LCMS2_FOUND)
+IF(UNIX)
+  TARGET_LINK_LIBRARIES(wrap_j2k_in_mj2 m)
+ENDIF(UNIX)
+
+INSTALL(TARGETS frames_to_mj2 mj2_to_frames extract_j2k_from_mj2 wrap_j2k_in_mj2
+       DESTINATION bin)
diff --git a/applications/mj2/Makefile.am b/applications/mj2/Makefile.am
new file mode 100644 (file)
index 0000000..c96bd97
--- /dev/null
@@ -0,0 +1,113 @@
+MAINTAINERCLEANFILES = Makefile.in
+
+OPJ_SRC = \
+../libopenjpeg/bio.c \
+../libopenjpeg/cio.c \
+../libopenjpeg/dwt.c \
+../libopenjpeg/event.c \
+../libopenjpeg/image.c \
+../libopenjpeg/j2k.c \
+../libopenjpeg/j2k_lib.c \
+../libopenjpeg/jp2.c \
+../libopenjpeg/jpt.c \
+../libopenjpeg/mct.c \
+../libopenjpeg/mqc.c \
+../libopenjpeg/openjpeg.c \
+../libopenjpeg/pi.c \
+../libopenjpeg/raw.c \
+../libopenjpeg/t1.c \
+../libopenjpeg/t2.c \
+../libopenjpeg/tcd.c \
+../libopenjpeg/tgt.c
+
+bin_PROGRAMS = \
+frames_to_mj2 \
+mj2_to_frames \
+extract_j2k_from_mj2 \
+wrap_j2k_in_mj2
+
+frames_to_mj2_CPPFLAGS = \
+-I. \
+-I$(top_srcdir)/common \
+-I$(top_builddir)/common \
+-I$(top_srcdir)/libopenjpeg \
+-I$(top_builddir)/libopenjpeg \
+-I$(top_srcdir)/mj2 \
+-I$(top_builddir)/mj2 \
+-DOPJ_STATIC
+frames_to_mj2_CFLAGS = 
+frames_to_mj2_LDADD = -lm
+frames_to_mj2_SOURCES = \
+$(OPJ_SRC) \
+../common/getopt.c \
+mj2_convert.c \
+mj2.c \
+frames_to_mj2.c \
+mj2.h \
+mj2_convert.h
+
+mj2_to_frames_CPPFLAGS = \
+-I. \
+-I$(top_srcdir)/common \
+-I$(top_builddir)/common \
+-I$(top_srcdir)/libopenjpeg \
+-I$(top_builddir)/libopenjpeg \
+-I$(top_srcdir)/mj2 \
+-I$(top_builddir)/mj2 \
+@LCMS2_CFLAGS@ \
+@LCMS1_CFLAGS@ \
+-DOPJ_STATIC
+mj2_to_frames_CFLAGS = 
+mj2_to_frames_LDADD = @LCMS2_LIBS@ @LCMS1_LIBS@
+mj2_to_frames_SOURCES = \
+$(OPJ_SRC) \
+../common/color.c \
+../common/getopt.c \
+mj2_convert.c \
+mj2.c \
+mj2_to_frames.c \
+mj2.h \
+mj2_convert.h
+
+extract_j2k_from_mj2_CPPFLAGS = \
+-I. \
+-I$(top_srcdir)/common \
+-I$(top_builddir)/common \
+-I$(top_srcdir)/libopenjpeg \
+-I$(top_builddir)/libopenjpeg \
+-I$(top_srcdir)/mj2 \
+-I$(top_builddir)/mj2 \
+-DOPJ_STATIC
+extract_j2k_from_mj2_CFLAGS = 
+extract_j2k_from_mj2_LDADD = -lm
+extract_j2k_from_mj2_SOURCES = \
+$(OPJ_SRC) \
+mj2.c \
+extract_j2k_from_mj2.c \
+mj2.h
+
+wrap_j2k_in_mj2_CPPFLAGS = \
+-I. \
+-I$(top_srcdir)/common \
+-I$(top_builddir)/common \
+-I$(top_srcdir)/libopenjpeg \
+-I$(top_builddir)/libopenjpeg \
+-I$(top_srcdir)/mj2 \
+-I$(top_builddir)/mj2 \
+-DOPJ_STATIC
+wrap_j2k_in_mj2_CFLAGS = 
+wrap_j2k_in_mj2_LDADD = -lm
+wrap_j2k_in_mj2_SOURCES = \
+$(OPJ_SRC) \
+mj2.c \
+wrap_j2k_in_mj2.c \
+mj2.h
+
+EXTRA_DIST = \
+CMakeLists.txt
+
+install-data-hook:
+       @echo -e " (B)\t$(bindir)/frames_to_mj2$(EXEEXT)" >> $(top_builddir)/report.txt
+       @echo -e " (B)\t$(bindir)/mj2_to_frames$(EXEEXT)" >> $(top_builddir)/report.txt
+       @echo -e " (B)\t$(bindir)/extract_j2k_from_mj2$(EXEEXT)" >> $(top_builddir)/report.txt
+       @echo -e " (B)\t$(bindir)/wrap_j2k_in_mj2$(EXEEXT)" >> $(top_builddir)/report.txt
diff --git a/applications/mj2/Makefile.nix b/applications/mj2/Makefile.nix
new file mode 100644 (file)
index 0000000..75302bd
--- /dev/null
@@ -0,0 +1,64 @@
+#mj2 Makefile.nix
+include ../config.nix
+
+CFLAGS = -Wall
+
+INSTALL_BIN = $(prefix)/bin
+USERLIBS = -lm
+INCLUDE = -I.. -I. -I../libopenjpeg -I../common
+
+ifeq ($(WITH_LCMS2),yes)
+INCLUDE += $(LCMS2_INCLUDE)
+USERLIBS += $(LCMS2_LIB)
+endif
+
+ifeq ($(WITH_LCMS1),yes)
+INCLUDE += $(LCMS1_INCLUDE)
+USERLIBS += $(LCMS1_LIB)
+endif
+
+CFLAGS += $(INCLUDE) -lstdc++ # -g -p -pg
+
+ifeq ($(ENABLE_SHARED),yes)
+ELIB = ../libopenjpeg.so.$(MAJOR).$(MINOR).$(BUILD)
+else
+ELIB = ../libopenjpeg.a
+endif
+
+all: frames_to_mj2 mj2_to_frames extract_j2k_from_mj2 wrap_j2k_in_mj2
+       install -d ../bin
+       install frames_to_mj2 mj2_to_frames extract_j2k_from_mj2 \
+       wrap_j2k_in_mj2 ../bin
+
+frames_to_mj2: frames_to_mj2.c $(ELIB)
+       $(CC) $(CFLAGS) ../common/getopt.c mj2_convert.c mj2.c frames_to_mj2.c \
+       -o frames_to_mj2 $(ELIB) $(USERLIBS)
+
+mj2_to_frames: mj2_to_frames.c $(ELIB)
+       $(CC) $(CFLAGS) ../common/getopt.c mj2_convert.c mj2.c \
+       ../common/color.c mj2_to_frames.c \
+       -o mj2_to_frames $(ELIB) $(USERLIBS)
+
+extract_j2k_from_mj2: extract_j2k_from_mj2.c $(ELIB)
+       $(CC) $(CFLAGS) mj2.c extract_j2k_from_mj2.c \
+       -o extract_j2k_from_mj2 $(ELIB) $(USERLIBS)
+
+wrap_j2k_in_mj2: wrap_j2k_in_mj2.c $(ELIB)
+       $(CC) $(CFLAGS) mj2.c wrap_j2k_in_mj2.c \
+       -o wrap_j2k_in_mj2 $(ELIB) $(USERLIBS)
+
+clean:
+       rm -f frames_to_mj2 mj2_to_frames extract_j2k_from_mj2 wrap_j2k_in_mj2
+
+install: all
+       install -d $(DESTDIR)$(INSTALL_BIN)
+       install -m 755 -o root -g root frames_to_mj2 $(DESTDIR)$(INSTALL_BIN)
+       install -m 755 -o root -g root mj2_to_frames $(DESTDIR)$(INSTALL_BIN)
+       install -m 755 -o root -g root extract_j2k_from_mj2 $(DESTDIR)$(INSTALL_BIN)
+       install -m 755 -o root -g root wrap_j2k_in_mj2 $(DESTDIR)$(INSTALL_BIN)
+
+uninstall:
+       rm -f $(DESTDIR)$(INSTALL_BIN)/frames_to_mj2
+       rm -f $(DESTDIR)$(INSTALL_BIN)/mj2_to_frames
+       rm -f $(DESTDIR)$(INSTALL_BIN)/extract_j2k_from_mj2
+       rm -f $(DESTDIR)$(INSTALL_BIN)/wrap_j2k_in_mj2
diff --git a/applications/mj2/extract_j2k_from_mj2.c b/applications/mj2/extract_j2k_from_mj2.c
new file mode 100644 (file)
index 0000000..0872df1
--- /dev/null
@@ -0,0 +1,149 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux 
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "openjpeg.h"
+#include "../libopenjpeg/j2k.h"
+#include "../libopenjpeg/jp2.h"
+#include "mj2.h"
+
+/* -------------------------------------------------------------------------- */
+
+/**
+sample error callback expecting a FILE* client object
+*/
+void error_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[ERROR] %s", msg);
+}
+/**
+sample warning callback expecting a FILE* client object
+*/
+void warning_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[WARNING] %s", msg);
+}
+/**
+sample debug callback expecting a FILE* client object
+*/
+void info_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[INFO] %s", msg);
+}
+
+/* -------------------------------------------------------------------------- */
+
+
+int main(int argc, char *argv[]) {
+       opj_dinfo_t* dinfo; 
+       opj_event_mgr_t event_mgr;              /* event manager */
+  int tnum;
+  unsigned int snum;
+  opj_mj2_t *movie;
+  mj2_tk_t *track;
+  mj2_sample_t *sample;
+  unsigned char* frame_codestream;
+  FILE *file, *outfile;
+  char outfilename[50];
+       mj2_dparameters_t parameters;
+
+  if (argc != 3) {
+    printf("Usage: %s mj2filename output_location\n",argv[0]); 
+    printf("Example: %s foreman.mj2 output/foreman\n",argv[0]);
+    return 1;
+  }
+  
+  file = fopen(argv[1], "rb");
+  
+  if (!file) {
+    fprintf(stderr, "failed to open %s for reading\n", argv[1]);
+    return 1;
+  }
+
+       /*
+       configure the event callbacks (not required)
+       setting of each callback is optionnal
+       */
+       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
+       event_mgr.error_handler = error_callback;
+       event_mgr.warning_handler = warning_callback;
+       event_mgr.info_handler = info_callback;
+
+       /* get a MJ2 decompressor handle */
+       dinfo = mj2_create_decompress();
+
+       /* catch events using our callbacks and give a local context */
+       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);           
+
+       /* setup the decoder decoding parameters using user parameters */
+       memset(&parameters, 0, sizeof(mj2_dparameters_t));
+       movie = (opj_mj2_t*) dinfo->mj2_handle;
+       mj2_setup_decoder(movie, &parameters);
+
+  if (mj2_read_struct(file, movie)) // Creating the movie structure
+    return 1;
+
+  // Decode first video track 
+  tnum = 0;
+  while (movie->tk[tnum].track_type != 0)
+    tnum ++;
+
+  track = &movie->tk[tnum];
+
+  fprintf(stdout,"Extracting %d frames from file...\n",track->num_samples);
+
+  for (snum=0; snum < track->num_samples; snum++)
+  {
+    sample = &track->sample[snum];
+    frame_codestream = (unsigned char*) malloc (sample->sample_size-8); // Skipping JP2C marker
+    fseek(file,sample->offset+8,SEEK_SET);
+    fread(frame_codestream,sample->sample_size-8,1, file);  // Assuming that jp and ftyp markers size do
+
+    sprintf(outfilename,"%s_%05d.j2k",argv[2],snum);
+    outfile = fopen(outfilename, "wb");
+    if (!outfile) {
+      fprintf(stderr, "failed to open %s for writing\n",outfilename);
+      return 1;
+    }
+    fwrite(frame_codestream,sample->sample_size-8,1,outfile);
+    fclose(outfile);
+    free(frame_codestream);
+    }
+  fclose(file);
+  fprintf(stdout, "%d frames correctly extracted\n", snum);
+       
+       /* free remaining structures */
+       if(dinfo) {
+               mj2_destroy_decompress((opj_mj2_t*)dinfo->mj2_handle);
+       }
+       
+  return 0;
+}
diff --git a/applications/mj2/frames_to_mj2.c b/applications/mj2/frames_to_mj2.c
new file mode 100644 (file)
index 0000000..f6b7765
--- /dev/null
@@ -0,0 +1,843 @@
+/*
+* Copyright (c) 2003-2004, Fran�ois-Olivier Devaux
+* Copyright (c) 2002-2004,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+* 1. Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+* 2. Redistributions in binary form must reproduce the above copyright
+*    notice, this list of conditions and the following disclaimer in the
+*    documentation and/or other materials provided with the distribution.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+* POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "openjpeg.h"
+#include "../libopenjpeg/j2k_lib.h"
+#include "../libopenjpeg/j2k.h"
+#include "../libopenjpeg/jp2.h"
+#include "../libopenjpeg/cio.h"
+#include "mj2.h"
+#include "mj2_convert.h"
+#include "getopt.h"
+
+/**
+Size of memory first allocated for MOOV box
+*/
+#define TEMP_BUF 10000 
+
+#define ENUMCS_GRAY 16
+#define ENUMCS_SRGB 17
+#define ENUMCS_SYCC 18
+
+/* -------------------------------------------------------------------------- */
+
+/**
+sample error callback expecting a FILE* client object
+*/
+void error_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[ERROR] %s", msg);
+}
+/**
+sample warning callback expecting a FILE* client object
+*/
+void warning_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[WARNING] %s", msg);
+}
+/**
+sample debug callback expecting a FILE* client object
+*/
+void info_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[INFO] %s", msg);
+}
+
+/* -------------------------------------------------------------------------- */
+
+
+void help_display()
+{
+  fprintf(stdout,"HELP for frames_to_mj2\n----\n\n");
+  fprintf(stdout,"- the -h option displays this help information on screen\n\n");
+  
+  
+  fprintf(stdout,"List of parameters for the MJ2 encoder:\n");
+  fprintf(stdout,"\n");
+  fprintf(stdout,"REMARKS:\n");
+  fprintf(stdout,"---------\n");
+  fprintf(stdout,"\n");
+  fprintf
+    (stdout,"The markers written to the main_header are : SOC SIZ COD QCD COM.\n");
+  fprintf
+    (stdout,"COD and QCD never appear in the tile_header.\n");
+  fprintf(stdout,"\n");
+  fprintf(stdout,"By default:\n");
+  fprintf(stdout,"------------\n");
+  fprintf(stdout,"\n");
+  fprintf(stdout," * Lossless\n");
+  fprintf(stdout," * 1 tile\n");
+  fprintf(stdout," * Size of precinct : 2^15 x 2^15 (means 1 precinct)\n");
+  fprintf(stdout," * Size of code-block : 64 x 64\n");
+  fprintf(stdout," * Number of resolutions: 6\n");
+  fprintf(stdout," * No SOP marker in the codestream\n");
+  fprintf(stdout," * No EPH marker in the codestream\n");
+  fprintf(stdout," * No sub-sampling in x or y direction\n");
+  fprintf(stdout," * No mode switch activated\n");
+  fprintf(stdout," * Progression order: LRCP\n");
+  fprintf(stdout," * No index file\n");
+  fprintf(stdout," * No ROI upshifted\n");
+  fprintf(stdout," * No offset of the origin of the image\n");
+  fprintf(stdout," * No offset of the origin of the tiles\n");
+  fprintf(stdout," * Reversible DWT 5-3\n");
+  fprintf(stdout,"\n");
+  fprintf(stdout,"Parameters:\n");
+  fprintf(stdout,"------------\n");
+  fprintf(stdout,"\n");
+  fprintf
+    (stdout,"Required Parameters (except with -h):\n");
+  fprintf
+    (stdout,"-i : source file      (-i source.yuv) \n");
+  fprintf
+    (stdout,"-o : destination file (-o dest.mj2) \n");
+  fprintf
+    (stdout,"Optional Parameters:\n");
+  fprintf(stdout,"-h : display the help information \n");
+  fprintf(stdout,"-r : different compression ratios for successive layers (-r 20,10,5)\n");
+  fprintf(stdout,"     - The rate specified for each quality level is the desired \n");
+  fprintf(stdout,"       compression factor.\n");
+  fprintf(stdout,"       Example: -r 20,10,1 means quality 1: compress 20x, \n");
+  fprintf(stdout,"       quality 2: compress 10x and quality 3: compress lossless\n");
+  fprintf(stdout,"       (options -r and -q cannot be used together)\n");
+  
+  fprintf(stdout,"-q : different psnr for successive layers (-q 30,40,50) \n");
+  fprintf(stdout,"        (options -r and -q cannot be used together)\n");
+  
+  fprintf(stdout,"-n : number of resolutions (-n 3) \n");
+  fprintf(stdout,"-b : size of code block (-b 32,32) \n");
+  fprintf(stdout,"-c : size of precinct (-c 128,128) \n");
+  fprintf(stdout,"-t : size of tile (-t 512,512) \n");
+  fprintf
+    (stdout,"-p : progression order (-p LRCP) [LRCP, RLCP, RPCL, PCRL, CPRL] \n");
+  fprintf
+    (stdout,"-s : subsampling factor (-s 2,2) [-s X,Y] \n");
+  fprintf(stdout,"     Remark: subsampling bigger than 2 can produce error\n");
+  fprintf
+    (stdout,"-S : write SOP marker before each packet \n");
+  fprintf
+    (stdout,"-E : write EPH marker after each header packet \n");
+  fprintf
+    (stdout,"-M : mode switch (-M 3) [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
+  fprintf
+    (stdout,"             8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)] \n");
+  fprintf
+    (stdout,"             Indicate multiple modes by adding their values. \n");
+  fprintf
+    (stdout,"             Example: RESTART(4) + RESET(2) + SEGMARK(32) = -M 38\n");
+  fprintf
+    (stdout,"-R : c=%%d,U=%%d : quantization indices upshifted \n");
+  fprintf
+    (stdout,"             for component c=%%d [%%d = 0,1,2]\n");
+  fprintf
+    (stdout,"             with a value of U=%%d [0 <= %%d <= 37] (i.e. -ROI:c=0,U=25) \n");
+  fprintf
+    (stdout,"-d : offset of the origin of the image (-d 150,300) \n");
+  fprintf
+    (stdout,"-T : offset of the origin of the tiles (-T 100,75) \n");
+  fprintf(stdout,"-I : use the irreversible DWT 9-7 (-I) \n");
+  fprintf(stdout,"-W : image width, height and the dx and dy subsampling \n");
+  fprintf(stdout,"        of the Cb and Cr components for YUV files \n");
+  fprintf(stdout,"        (default is '352,288,2,2' for CIF format's 352x288 and 4:2:0)\n");
+  fprintf(stdout,"-F : video frame rate (set to 25 by default)\n");
+  fprintf(stdout,"-D : depth, precision in bits [8 .. 16]; default:8\n");
+  fprintf(stdout,"-C : comment\n");
+  fprintf(stdout,"\n");
+  fprintf(stdout,"IMPORTANT:\n");
+  fprintf(stdout,"-----------\n");
+  fprintf(stdout,"\n");
+  fprintf(stdout,"The index file has the structure below:\n");
+  fprintf(stdout,"---------------------------------------\n");
+  fprintf(stdout,"\n");
+  fprintf(stdout,"Image_height Image_width\n");
+  fprintf(stdout,"progression order\n");
+  fprintf(stdout,"Tiles_size_X Tiles_size_Y\n");
+  fprintf(stdout,"Components_nb\n");
+  fprintf(stdout,"Layers_nb\n");
+  fprintf(stdout,"decomposition_levels\n");
+  fprintf(stdout,"[Precincts_size_X_res_Nr Precincts_size_Y_res_Nr]...\n");
+  fprintf(stdout,"   [Precincts_size_X_res_0 Precincts_size_Y_res_0]\n");
+  fprintf(stdout,"Main_header_end_position\n");
+  fprintf(stdout,"Codestream_size\n");
+  fprintf(stdout,"Tile_0 start_pos end_Theader end_pos TotalDisto NumPix MaxMSE\n");
+  fprintf(stdout,"Tile_1   ''           ''        ''        ''       ''    ''\n");
+  fprintf(stdout,"...\n");
+  fprintf(stdout,"Tile_Nt   ''           ''        ''        ''       ''    ''\n");
+  fprintf(stdout,"Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");
+  fprintf(stdout,"...\n");
+  fprintf(stdout,"Tpacket_Np ''   ''    ''   ''    ''       ''       ''     ''\n");
+  
+  fprintf(stdout,"MaxDisto\n");
+  
+  fprintf(stdout,"TotalDisto\n\n");
+}
+
+int give_progression(char progression[4])
+{
+  if (progression[0] == 'L' && progression[1] == 'R'
+    && progression[2] == 'C' && progression[3] == 'P') {
+    return 0;
+  } else {
+    if (progression[0] == 'R' && progression[1] == 'L'
+      && progression[2] == 'C' && progression[3] == 'P') {
+      return 1;
+    } else {
+      if (progression[0] == 'R' && progression[1] == 'P'
+                               && progression[2] == 'C' && progression[3] == 'L') {
+                               return 2;
+      } else {
+                               if (progression[0] == 'P' && progression[1] == 'C'
+                                       && progression[2] == 'R' && progression[3] == 'L') {
+                                       return 3;
+                               } else {
+                                       if (progression[0] == 'C' && progression[1] == 'P'
+                                               && progression[2] == 'R' && progression[3] == 'L') {
+                                               return 4;
+                                       } else {
+                                               return -1;
+                                       }
+                               }
+      }
+    }
+  }
+}
+
+
+
+
+int main(int argc, char **argv)
+{
+       mj2_cparameters_t mj2_parameters;       /* MJ2 compression parameters */
+       opj_cparameters_t *j2k_parameters;      /* J2K compression parameters */
+       opj_event_mgr_t event_mgr;              /* event manager */
+       opj_cio_t *cio;
+       int value;
+       opj_mj2_t *movie;
+       opj_image_t *img;
+       int i, j;
+       char *s, S1, S2, S3;
+       unsigned char *buf;
+       int x1, y1,  len;
+       long mdat_initpos, offset;
+       FILE *mj2file;
+       int sampleno;  
+       opj_cinfo_t* cinfo;
+       bool bSuccess;
+       int numframes;
+       int prec = 8;/* DEFAULT */
+       double total_time = 0;  
+
+       memset(&mj2_parameters, 0, sizeof(mj2_cparameters_t));
+  /* default value */
+  /* ------------- */
+       mj2_parameters.w = 352;                 // CIF default value
+       mj2_parameters.h = 288;                 // CIF default value
+       mj2_parameters.CbCr_subsampling_dx = 2; // CIF default value
+       mj2_parameters.CbCr_subsampling_dy = 2; // CIF default value
+       mj2_parameters.frame_rate = 25;
+       mj2_parameters.prec = 8; /* DEFAULT */
+       mj2_parameters.enumcs = ENUMCS_SYCC; /* FIXME: ENUMCS_YUV420 */
+       mj2_parameters.meth = 1; /* enumerated color space */
+
+/*
+       configure the event callbacks (not required)
+       setting of each callback is optionnal
+*/
+       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
+       event_mgr.error_handler = error_callback;
+       event_mgr.warning_handler = warning_callback;
+       event_mgr.info_handler = NULL;
+    
+       /* set J2K encoding parameters to default values */
+       opj_set_default_encoder_parameters(&mj2_parameters.j2k_parameters);
+       j2k_parameters = &mj2_parameters.j2k_parameters;
+
+       /* Create comment for codestream */
+       if(j2k_parameters->cp_comment == NULL) {
+    const char comment[] = "Created by OpenJPEG version ";
+               const size_t clen = strlen(comment);
+    const char *version = opj_version();
+               j2k_parameters->cp_comment = (char*)malloc(clen+strlen(version)+1);
+               sprintf(j2k_parameters->cp_comment,"%s%s", comment, version);
+       }
+
+  while (1) {
+    int c = getopt(argc, argv,
+      "i:o:r:q:f:t:n:c:b:p:s:d:P:S:E:M:R:T:C:I:W:F:D:h");
+    if (c == -1)
+      break;
+    switch (c) {
+    case 'i':                  /* IN fill */
+                       {
+                               char *infile = optarg;
+                               s = optarg;
+                               while (*s) {
+                                       s++;
+                               }
+                               s--;
+                               S3 = *s;
+                               s--;
+                               S2 = *s;
+                               s--;
+                               S1 = *s;
+                               
+                               if ((S1 == 'y' && S2 == 'u' && S3 == 'v')
+                                       || (S1 == 'Y' && S2 == 'U' && S3 == 'V')) {
+                                       mj2_parameters.decod_format = YUV_DFMT;                         
+                               }
+                               else {
+                                       fprintf(stderr,
+                                               "!! Unrecognized format for infile : %c%c%c [accept only *.yuv] !!\n\n",
+                                               S1, S2, S3);
+                                       return 1;
+                               }
+                               strncpy(mj2_parameters.infile, infile, sizeof(mj2_parameters.infile)-1);
+                       }
+      break;
+      /* ----------------------------------------------------- */
+    case 'o':                  /* OUT fill */
+                       {
+                               char *outfile = optarg;
+                               while (*outfile) {
+                                       outfile++;
+                               }
+                               outfile--;
+                               S3 = *outfile;
+                               outfile--;
+                               S2 = *outfile;
+                               outfile--;
+                               S1 = *outfile;
+                               
+                               outfile = optarg;
+                               
+                               if ((S1 == 'm' && S2 == 'j' && S3 == '2')
+                                       || (S1 == 'M' && S2 == 'J' && S3 == '2'))
+                                       mj2_parameters.cod_format = MJ2_CFMT;
+                               else {
+                                       fprintf(stderr,
+                                               "Unknown output format image *.%c%c%c [only *.mj2]!! \n",
+                                               S1, S2, S3);
+                                       return 1;
+                               }
+                               strncpy(mj2_parameters.outfile, outfile, sizeof(mj2_parameters.outfile)-1);      
+      }
+      break;
+      /* ----------------------------------------------------- */
+    case 'r':                  /* rates rates/distorsion */
+                       {
+                               float rate;
+                               s = optarg;
+                               while (sscanf(s, "%f", &rate) == 1) {
+                                       j2k_parameters->tcp_rates[j2k_parameters->tcp_numlayers] = rate * 2;
+                                       j2k_parameters->tcp_numlayers++;
+                                       while (*s && *s != ',') {
+                                               s++;
+                                       }
+                                       if (!*s)
+                                               break;
+                                       s++;
+                               }
+                               j2k_parameters->cp_disto_alloc = 1;
+                       }
+      break;
+      /* ----------------------------------------------------- */
+    case 'q':                  /* add fixed_quality */
+      s = optarg;
+                       while (sscanf(s, "%f", &j2k_parameters->tcp_distoratio[j2k_parameters->tcp_numlayers]) == 1) {
+                               j2k_parameters->tcp_numlayers++;
+                               while (*s && *s != ',') {
+                                       s++;
+                               }
+                               if (!*s)
+                                       break;
+                               s++;
+                       }
+                       j2k_parameters->cp_fixed_quality = 1;
+      break;
+      /* dda */
+      /* ----------------------------------------------------- */
+    case 'f':                  /* mod fixed_quality (before : -q) */
+                       {
+                               int *row = NULL, *col = NULL;
+                               int numlayers = 0, numresolution = 0, matrix_width = 0;
+                               
+                               s = optarg;
+                               sscanf(s, "%d", &numlayers);
+                               s++;
+                               if (numlayers > 9)
+                                       s++;
+                               
+                               j2k_parameters->tcp_numlayers = numlayers;
+                               numresolution = j2k_parameters->numresolution;
+                               matrix_width = numresolution * 3;
+                               j2k_parameters->cp_matrice = (int *) malloc(numlayers * matrix_width * sizeof(int));
+                               s = s + 2;
+                               
+                               for (i = 0; i < numlayers; i++) {
+                                       row = &j2k_parameters->cp_matrice[i * matrix_width];
+                                       col = row;
+                                       j2k_parameters->tcp_rates[i] = 1;
+                                       sscanf(s, "%d,", &col[0]);
+                                       s += 2;
+                                       if (col[0] > 9)
+                                               s++;
+                                       col[1] = 0;
+                                       col[2] = 0;
+                                       for (j = 1; j < numresolution; j++) {
+                                               col += 3;
+                                               sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);
+                                               s += 6;
+                                               if (col[0] > 9)
+                                                       s++;
+                                               if (col[1] > 9)
+                                                       s++;
+                                               if (col[2] > 9)
+                                                       s++;
+                                       }
+                                       if (i < numlayers - 1)
+                                               s++;
+                               }
+                               j2k_parameters->cp_fixed_alloc = 1;
+                       }
+                       break;
+      /* ----------------------------------------------------- */
+    case 't':                  /* tiles */
+      sscanf(optarg, "%d,%d", &j2k_parameters->cp_tdx, &j2k_parameters->cp_tdy);
+                       j2k_parameters->tile_size_on = true;
+      break;
+      /* ----------------------------------------------------- */
+    case 'n':                  /* resolution */
+      sscanf(optarg, "%d", &j2k_parameters->numresolution);
+      break;
+      /* ----------------------------------------------------- */
+    case 'c':                  /* precinct dimension */
+                       {
+                               char sep;
+                               int res_spec = 0;
+
+                               char *s = optarg;
+                               do {
+                                       sep = 0;
+                                       sscanf(s, "[%d,%d]%c", &j2k_parameters->prcw_init[res_spec],
+                                 &j2k_parameters->prch_init[res_spec], &sep);
+                                       j2k_parameters->csty |= 0x01;
+                                       res_spec++;
+                                       s = strpbrk(s, "]") + 2;
+                               }
+                               while (sep == ',');
+                               j2k_parameters->res_spec = res_spec;
+                       }
+                       break;
+
+      /* ----------------------------------------------------- */
+    case 'b':                  /* code-block dimension */
+                       {
+                               int cblockw_init = 0, cblockh_init = 0;
+                               sscanf(optarg, "%d,%d", &cblockw_init, &cblockh_init);
+                               if (cblockw_init * cblockh_init > 4096 || cblockw_init > 1024
+                                       || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {
+                                       fprintf(stderr,
+                                               "!! Size of code_block error (option -b) !!\n\nRestriction :\n"
+            "    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");
+                                       return 1;
+                               }
+                               j2k_parameters->cblockw_init = cblockw_init;
+                               j2k_parameters->cblockh_init = cblockh_init;
+                       }
+                       break;
+      /* ----------------------------------------------------- */
+    case 'p':                  /* progression order */
+                       {
+                               char progression[4];
+                               
+                               strncpy(progression, optarg, 4);
+                               j2k_parameters->prog_order = give_progression(progression);
+                               if (j2k_parameters->prog_order == -1) {
+                                       fprintf(stderr, "Unrecognized progression order "
+            "[LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
+                                       return 1;
+                               }
+                       }
+                       break;
+      /* ----------------------------------------------------- */
+    case 's':                  /* subsampling factor */
+      {
+                               if (sscanf(optarg, "%d,%d", &j2k_parameters->subsampling_dx,
+                                    &j2k_parameters->subsampling_dy) != 2) {
+                                       fprintf(stderr, "'-s' sub-sampling argument error !  [-s dx,dy]\n");
+                                       return 1;
+                               }
+                       }
+                       break;
+      /* ----------------------------------------------------- */
+    case 'd':                  /* coordonnate of the reference grid */
+      {
+                               if (sscanf(optarg, "%d,%d", &j2k_parameters->image_offset_x0,
+                                    &j2k_parameters->image_offset_y0) != 2) {
+                                       fprintf(stderr, "-d 'coordonnate of the reference grid' argument "
+            "error !! [-d x0,y0]\n");
+                                       return 1;
+                               }
+                       }
+                       break;
+      /* ----------------------------------------------------- */
+    case 'h':                  /* Display an help description */
+      help_display();
+      return 0;
+      break;
+      /* ----------------------------------------------------- */
+    case 'P':                  /* POC */
+      {
+                               int numpocs = 0;                /* number of progression order change (POC) default 0 */
+                               opj_poc_t *POC = NULL;  /* POC : used in case of Progression order change */
+
+                               char *s = optarg;
+                               POC = j2k_parameters->POC;
+
+                               while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%4s", &POC[numpocs].tile,
+                                       &POC[numpocs].resno0, &POC[numpocs].compno0,
+                                       &POC[numpocs].layno1, &POC[numpocs].resno1,
+                                       &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
+                                       POC[numpocs].prg1 = give_progression(POC[numpocs].progorder);
+                                       numpocs++;
+                                       while (*s && *s != '/') {
+                                               s++;
+                                       }
+                                       if (!*s) {
+                                               break;
+                                       }
+                                       s++;
+                               }
+                               j2k_parameters->numpocs = numpocs;
+                       }
+                       break;
+      /* ------------------------------------------------------ */
+    case 'S':                  /* SOP marker */
+      j2k_parameters->csty |= 0x02;
+      break;
+      /* ------------------------------------------------------ */
+    case 'E':                  /* EPH marker */
+      j2k_parameters->csty |= 0x04;
+      break;
+      /* ------------------------------------------------------ */
+    case 'M':                  /* Mode switch pas tous au point !! */
+      if (sscanf(optarg, "%d", &value) == 1) {
+                               for (i = 0; i <= 5; i++) {
+                                       int cache = value & (1 << i);
+                                       if (cache)
+                                               j2k_parameters->mode |= (1 << i);
+                               }
+      }
+      break;
+      /* ------------------------------------------------------ */
+    case 'R':                  /* ROI */
+      {
+                               if (sscanf(optarg, "OI:c=%d,U=%d", &j2k_parameters->roi_compno,
+                                           &j2k_parameters->roi_shift) != 2) {
+                                       fprintf(stderr, "ROI error !! [-ROI:c='compno',U='shift']\n");
+                                       return 1;
+                               }
+                       }
+                       break;
+      /* ------------------------------------------------------ */
+    case 'T':                  /* Tile offset */
+                       {
+                               if (sscanf(optarg, "%d,%d", &j2k_parameters->cp_tx0, &j2k_parameters->cp_ty0) != 2) {
+                                       fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");
+                                       return 1;
+                               }
+                       }
+                       break;
+      /* ------------------------------------------------------ */
+    case 'C':                  /* Add a comment */
+                       {
+                               j2k_parameters->cp_comment = (char*)malloc(strlen(optarg) + 1);
+                               if(j2k_parameters->cp_comment) {
+                                       strcpy(j2k_parameters->cp_comment, optarg);
+                               }
+                       }
+                       break;
+      /* ------------------------------------------------------ */
+    case 'I':                  /* reversible or not */
+                       {
+                               j2k_parameters->irreversible = 1;
+                       }
+                       break;
+      /* ------------------------------------------------------ */
+    case 'W':                  /* Width and Height and Cb and Cr subsampling in case of YUV format files */
+      if (sscanf
+                               (optarg, "%d,%d,%d,%d", &mj2_parameters.w, &mj2_parameters.h, &mj2_parameters.CbCr_subsampling_dx,
+                               &mj2_parameters.CbCr_subsampling_dy) != 4) {
+                               fprintf(stderr, "-W argument error");
+                               return 1;
+      }
+      break;
+      /* ------------------------------------------------------ */
+    case 'F':                  /* Video frame rate */
+      if (sscanf(optarg, "%d", &mj2_parameters.frame_rate) != 1) {
+                               fprintf(stderr, "-F argument error");
+                               return 1;
+      }
+      break;
+      /* ------------------------------------------------------ */
+       case 'D': /* Depth: the precision */
+               if(sscanf(optarg, "%d", &prec) != 1) prec = 0;
+               break;
+
+    default:
+      return 1;
+    }
+  }
+    
+  /* Error messages */
+  /* -------------- */
+       if (!mj2_parameters.cod_format || !mj2_parameters.decod_format) {
+    fprintf(stderr,
+      "Usage: %s -i yuv-file -o mj2-file (+ options)\n",argv[0]);
+    return 1;
+  }
+    if(prec < 1 || prec > 16)
+  {
+       fprintf(stderr, "Error: Depth %d must be in the range 8 .. 16\n",prec);
+       return 1;       
+  }
+       if ((j2k_parameters->cp_disto_alloc || j2k_parameters->cp_fixed_alloc || j2k_parameters->cp_fixed_quality)
+               && (!(j2k_parameters->cp_disto_alloc ^ j2k_parameters->cp_fixed_alloc ^ j2k_parameters->cp_fixed_quality))) {
+               fprintf(stderr, "Error: options -r -q and -f cannot be used together !!\n");
+               return 1;
+       }                               /* mod fixed_quality */
+
+       /* if no rate entered, lossless by default */
+       if (j2k_parameters->tcp_numlayers == 0) {
+               j2k_parameters->tcp_rates[0] = 0;       /* MOD antonin : losslessbug */
+               j2k_parameters->tcp_numlayers++;
+               j2k_parameters->cp_disto_alloc = 1;
+       }
+
+       if((j2k_parameters->cp_tx0 > j2k_parameters->image_offset_x0) || (j2k_parameters->cp_ty0 > j2k_parameters->image_offset_y0)) {
+               fprintf(stderr,
+                       "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
+                       j2k_parameters->cp_tx0, j2k_parameters->image_offset_x0, j2k_parameters->cp_ty0, j2k_parameters->image_offset_y0);
+               return 1;
+       }
+
+       for (i = 0; i < j2k_parameters->numpocs; i++) {
+               if (j2k_parameters->POC[i].prg == -1) {
+                       fprintf(stderr,
+                               "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
+                               i + 1);
+               }
+       }
+  
+  if (j2k_parameters->cp_tdx > mj2_parameters.Dim[0] || j2k_parameters->cp_tdy > mj2_parameters.Dim[1]) {
+    fprintf(stderr,
+      "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
+      j2k_parameters->cp_tdx, mj2_parameters.Dim[0], j2k_parameters->cp_tdy, mj2_parameters.Dim[1]);
+    return 1;
+  }
+    
+  /* to respect profile - 0 */
+  /* ---------------------- */
+  
+  x1 = !mj2_parameters.Dim[0] ? (mj2_parameters.w - 1) * j2k_parameters->subsampling_dx 
+               + 1 : mj2_parameters.Dim[0] + (mj2_parameters.w - 1) * j2k_parameters->subsampling_dx + 1;
+  y1 = !mj2_parameters.Dim[1] ? (mj2_parameters.h - 1) * j2k_parameters->subsampling_dy 
+               + 1 : mj2_parameters.Dim[1] + (mj2_parameters.h - 1) * j2k_parameters->subsampling_dy + 1;   
+       mj2_parameters.numcomps = 3; /* YUV files only have 3 components */ 
+
+       mj2_parameters.prec = prec;
+
+       j2k_parameters->tcp_mct = 0;
+    
+       mj2file = fopen(mj2_parameters.outfile, "wb");
+  
+       if (!mj2file) {
+    fprintf(stderr, "failed to open %s for writing\n", argv[2]);
+    return 1;
+       }
+    
+       /* get a MJ2 decompressor handle */
+       cinfo = mj2_create_compress();
+       movie = (opj_mj2_t*)cinfo->mj2_handle;
+       
+       /* catch events using our callbacks and give a local context */
+       opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
+
+       /* setup encoder parameters */
+       mj2_setup_encoder(movie, &mj2_parameters);   
+  
+       movie->tk[0].num_samples = 
+        yuv_num_frames(&movie->tk[0],mj2_parameters.infile);
+
+       if (movie->tk[0].num_samples == -1) {
+               return 1;
+       }
+
+  // One sample per chunk
+       movie->tk[0].chunk = (mj2_chunk_t*) 
+        malloc(movie->tk[0].num_samples * sizeof(mj2_chunk_t));     
+       movie->tk[0].sample = (mj2_sample_t*) 
+        malloc(movie->tk[0].num_samples * sizeof(mj2_sample_t));
+  
+       if (mj2_init_stdmovie(movie)) {
+    fprintf(stderr, "Error with movie initialization");
+    return 1;
+       }    
+  
+// Writing JP, FTYP and MDAT boxes 
+// Assuming that the JP and FTYP boxes won't be longer than 300 bytes:
+       buf = (unsigned char*) 
+        malloc (300 * sizeof(unsigned char));
+
+       cio = opj_cio_open((opj_common_ptr)movie->cinfo, buf, 300);
+
+       mj2_write_jp(cio);
+       mj2_write_ftyp(movie, cio);
+
+       mdat_initpos = cio_tell(cio);
+       cio_skip(cio, 4);
+
+       cio_write(cio, MJ2_MDAT, 4);    
+
+       fwrite(buf,cio_tell(cio),1,mj2file);
+
+       offset = cio_tell(cio);
+       opj_cio_close(cio);
+       free(buf);
+
+       for(i = 0; i < movie->num_stk + movie->num_htk + movie->num_vtk; i++) 
+   {
+    if(movie->tk[i].track_type != 0) 
+  {
+       fprintf(stderr, "Unable to write sound or hint tracks\n");
+  }
+       else 
+  {
+       mj2_tk_t *tk;
+       int buflen = 0;
+  
+       tk = &movie->tk[i];     
+       tk->num_chunks = tk->num_samples;
+       numframes = tk->num_samples;
+       tk->depth = prec; 
+
+       fprintf(stderr, "Video Track number %d\n", i);
+
+       img = mj2_image_create(tk, j2k_parameters);          
+
+       buflen = 2 * (tk->w * tk->h * 8);
+       buf = (unsigned char *) malloc(buflen*sizeof(unsigned char));   
+
+       for(sampleno = 0; sampleno < numframes; sampleno++) 
+ {
+       double init_time = opj_clock();
+       double elapsed_time;
+
+               if(yuvtoimage(tk, img, sampleno, j2k_parameters, 
+                       mj2_parameters.infile))
+          {
+               fprintf(stderr, "Error with frame number %d in YUV file\n", sampleno);
+               return 1;
+          }
+
+/* setup the encoder parameters using the current image and user parameters */
+       opj_setup_encoder(cinfo, j2k_parameters, img);
+
+       cio = opj_cio_open((opj_common_ptr)movie->cinfo, buf, buflen);
+                                                               
+       cio_skip(cio, 4);
+       cio_write(cio, JP2_JP2C, 4);    // JP2C
+
+/* encode the image */
+       bSuccess = opj_encode(cinfo, cio, img, NULL);
+
+       if (!bSuccess) {
+       opj_cio_close(cio);
+       fprintf(stderr, "failed to encode image\n");
+       return 1;
+       }
+
+       len = cio_tell(cio) - 8;
+       cio_seek(cio, 0);
+       cio_write(cio, len+8,4);
+       opj_cio_close(cio);
+
+       tk->sample[sampleno].sample_size = len+8;                               
+       tk->sample[sampleno].offset = offset;
+       tk->chunk[sampleno].offset = offset;    // There is one sample per chunk 
+       fwrite(buf, 1, len+8, mj2file);                         
+       offset += len+8;                                
+
+       elapsed_time = opj_clock()-init_time;
+       fprintf(stderr, "Frame number %d/%d encoded in %.2f mseconds\n", 
+               sampleno + 1, numframes, elapsed_time*1000);
+       total_time += elapsed_time;
+ }     /* for(sampleno */
+
+       free(buf);
+       opj_image_destroy(img);
+  }
+   }/* for(i */
+  
+       fseek(mj2file, mdat_initpos, SEEK_SET);
+       
+       buf = (unsigned char*) malloc(4*sizeof(unsigned char));
+
+// Init a cio to write box length variable in a little endian way 
+       cio = opj_cio_open(NULL, buf, 4);
+       cio_write(cio, offset - mdat_initpos, 4);
+       fwrite(buf, 4, 1, mj2file);
+       fseek(mj2file,0,SEEK_END);
+       free(buf);
+
+// Writing MOOV box 
+       buf = (unsigned char*) 
+        malloc ((TEMP_BUF+numframes*20) * sizeof(unsigned char));
+       cio = opj_cio_open(movie->cinfo, buf, (TEMP_BUF+numframes*20));
+       mj2_write_moov(movie, cio);
+       fwrite(buf,cio_tell(cio),1,mj2file);
+       free(buf);
+
+       fprintf(stdout,"Total encoding time: %.2f s for %d frames (%.1f fps)\n",
+        total_time, numframes, (float)numframes/total_time);
+
+  // Ending program 
+  
+       fclose(mj2file);
+/* free remaining compression structures */
+       mj2_destroy_compress(movie);
+       free(cinfo);
+
+       if(j2k_parameters->cp_comment) free(j2k_parameters->cp_comment);
+       if(j2k_parameters->cp_matrice) free(j2k_parameters->cp_matrice);
+       opj_cio_close(cio);
+
+       return 0;
+}
diff --git a/applications/mj2/meta_out.c b/applications/mj2/meta_out.c
new file mode 100644 (file)
index 0000000..ff80b5e
--- /dev/null
@@ -0,0 +1,2181 @@
+/* meta_out.c */
+/* Dump MJ2, JP2 metadata (partial so far) to xml file */
+/* Callable from mj2_to_metadata */
+/* Contributed to Open JPEG by Glenn Pearson, contract software developer, U.S. National Library of Medicine.
+
+The base code in this file was developed by the author as part of a video archiving
+project for the U.S. National Library of Medicine, Bethesda, MD. 
+It is the policy of NLM (and U.S. government) to not assert copyright.
+
+A non-exclusive copy of this code has been contributed to the Open JPEG project.
+Except for copyright, inclusion of the code within Open JPEG for distribution and use
+can be bound by the Open JPEG open-source license and disclaimer, expressed elsewhere.
+*/
+
+#include <windows.h> /* for time functions */
+
+#include "../libopenjpeg/opj_includes.h"
+#include "mj2.h"
+
+#include <time.h>
+#include "meta_out.h"
+
+static BOOL notes = TRUE;
+static BOOL sampletables = FALSE;
+static BOOL raw = TRUE;
+static BOOL derived = TRUE;
+
+opj_tcp_t *j2k_default_tcp;
+
+/* Forwards */
+int xml_write_overall_header(FILE *file, FILE *xmlout, opj_mj2_t * movie, unsigned int sampleframe, opj_event_mgr_t *event_mgr);
+int xml_write_moov(FILE *file, FILE *xmlout, opj_mj2_t * movie, unsigned int sampleframe, opj_event_mgr_t *event_mgr);
+
+void uint_to_chars(unsigned int value, char* buf);
+
+void xml_write_trak(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum, unsigned int sampleframe, opj_event_mgr_t *event_mgr);
+void xml_write_tkhd(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum);
+void xml_write_udta(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum);
+void xml_write_mdia(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum);
+void xml_write_stbl(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum);
+
+void UnixTimeToFileTime(time_t t, LPFILETIME pft);
+void UnixTimeToSystemTime(time_t t, LPSYSTEMTIME pst);
+void xml_time_out(FILE* xmlout, time_t t);
+
+void int16_to_3packedchars(short int value, char* buf);
+
+void xml_write_moov_udta(FILE* xmlout, opj_mj2_t * movie);
+void xml_write_free_and_skip(FILE* xmlout, opj_mj2_t * movie);
+void xml_write_uuid(FILE* xmlout, opj_mj2_t * movie);
+
+int xml_out_frame(FILE* file, FILE* xmlout, mj2_sample_t *sample, unsigned int snum, opj_event_mgr_t *event_mgr);
+
+void xml_out_frame_siz(FILE* xmlout, opj_image_t *img, opj_cp_t *cp);
+void xml_out_frame_cod(FILE* xmlout, opj_tcp_t *tcp);
+void xml_out_frame_coc(FILE* xmlout, opj_tcp_t *tcp, int numcomps); /* opj_image_t *img); */
+BOOL same_component_style(opj_tccp_t *tccp1, opj_tccp_t *tccp2);
+void xml_out_frame_qcd(FILE* xmlout, opj_tcp_t *tcp);
+void xml_out_frame_qcc(FILE* xmlout, opj_tcp_t *tcp, int numcomps); /* opj_image_t *img); */
+BOOL same_component_quantization(opj_tccp_t *tccp1, opj_tccp_t *tccp2);
+void xml_out_frame_rgn(FILE* xmlout, opj_tcp_t *tcp, int numcomps);/* opj_image_t *img);*/
+void xml_out_frame_poc(FILE* xmlout, opj_tcp_t *tcp);
+void xml_out_frame_ppm(FILE* xmlout, opj_cp_t *cp);
+void xml_out_frame_ppt(FILE* xmlout, opj_tcp_t *tcp);
+void xml_out_frame_tlm(FILE* xmlout); /* j2k_default_tcp is passed globally */ /* NO-OP.  TLM NOT SAVED IN DATA STRUCTURE */
+void xml_out_frame_plm(FILE* xmlout); /* j2k_default_tcp is passed globally */ /* NO-OP.  PLM NOT SAVED IN DATA STRUCTURE.  opt in main; can be used in conjunction with PLT */
+void xml_out_frame_plt(FILE* xmlout, opj_tcp_t *tcp); /* NO-OP.  PLM NOT SAVED IN DATA STRUCTURE.  opt in main; can be used in conjunction with PLT */
+void xml_out_frame_crg(FILE* xmlout); /* j2k_default_tcp is passed globally */ /* opt in main; */
+void xml_out_frame_com(FILE* xmlout, opj_tcp_t *tcp); /* NO-OP.  COM NOT SAVED IN DATA STRUCTURE */ /* opt in main; */
+void xml_out_dump_hex(FILE* xmlout, char *data, int data_len, char* s);
+void xml_out_dump_hex_and_ascii(FILE* xmlout, char *data, int data_len, char* s);
+void xml_out_frame_jp2h(FILE* xmlout, opj_jp2_t *jp2_struct);
+#ifdef NOTYET
+/* Shown with cp, extended, as data structure... but it could be a new different one */
+void xml_out_frame_jp2i(FILE* xmlout, opj_cp_t *cp);/* IntellectualProperty 'jp2i' (no restrictions on location) */
+void xml_out_frame_xml(FILE* xmlout, opj_cp_t *cp); /* XML 'xml\040' (0x786d6c20).  Can appear multiply */
+void xml_out_frame_uuid(FILE* xmlout, opj_cp_t *cp); /* UUID 'uuid' (top level only) */
+void xml_out_frame_uinf(FILE* xmlout, opj_cp_t *cp); /* UUIDInfo 'uinf', includes UUIDList 'ulst' and URL 'url\40' */
+void xml_out_frame_unknown_type(FILE* xmlout, opj_cp_t *cp);
+#endif
+
+
+void xml_write_init(BOOL n, BOOL t, BOOL r, BOOL d)
+{
+  /* Init file globals */
+  notes = n;
+  sampletables = t;
+  raw = r;
+  derived = d;
+}
+
+int xml_write_struct(FILE* file, FILE *xmlout, opj_mj2_t * movie, unsigned int sampleframe, char* stringDTD, opj_event_mgr_t *event_mgr) {
+
+  if(stringDTD != NULL)
+  {
+    fprintf(xmlout,"<?xml version=\"1.0\" standalone=\"no\"?>\n");
+       /* stringDTD is known to start with "SYSTEM " or "PUBLIC " */
+       /* typical: SYSTEM mj2_to_metadata.dtd */
+       stringDTD[6] = '\0'; /* Break into two strings at space, so quotes can be inserted. */
+    fprintf(xmlout,"<!DOCTYPE MJ2_File %s \"%s\">\n", stringDTD, stringDTD+7); 
+       stringDTD[6] = ' '; /* restore for sake of debugger or memory allocator */
+  } else
+    fprintf(xmlout,"<?xml version=\"1.0\" standalone=\"yes\"?>\n");    
+
+  fprintf(xmlout, "<MJ2_File>\n");
+  xml_write_overall_header(file, xmlout, movie, sampleframe, event_mgr);
+  fprintf(xmlout, "</MJ2_File>");
+  return 0;
+}
+
+/* ------------- */
+
+int xml_write_overall_header(FILE *file, FILE *xmlout, opj_mj2_t * movie, unsigned int sampleframe, opj_event_mgr_t *event_mgr)
+{
+  int i;
+  char buf[5];
+  buf[4] = '\0';
+
+  fprintf(xmlout,   "  <JP2 BoxType=\"jP[space][space]\" Signature=\"0x0d0a870a\" />\n");
+  // Called after structure initialized by mj2_read_ftyp
+  fprintf(xmlout,   "  <FileType BoxType=\"ftyp\">\n");
+  uint_to_chars(movie->brand, buf);
+  fprintf(xmlout,   "    <Brand>%s</Brand>\n", buf);    /* 4 character; BR              */
+  fprintf(xmlout,   "    <MinorVersion>%u</MinorVersion>\n", movie->minversion);    /* 4 char; MinV            */
+  fprintf(xmlout,   "    <CompatibilityList Count=\"%d\">\n",movie->num_cl);
+  for (i = movie->num_cl - 1; i > -1; i--) /* read routine stored in reverse order, so let's undo damage */
+  {
+    uint_to_chars(movie->cl[i], buf);
+    fprintf(xmlout, "      <CompatibleBrand>%s</CompatibleBrand>\n", buf);    /*4 characters, each CLi */
+  }
+  fprintf(xmlout,   "    </CompatibilityList>\n");
+  fprintf(xmlout,   "  </FileType>\n");
+  xml_write_moov(file, xmlout, movie, sampleframe, event_mgr);
+  // To come?              <mdat>  // This is the container for media data that can also be accessed through track structures,
+                                   // so is redundant, and simply not of interest as metadata
+  //                       <moof>  // Allows incremental build up of movie.  Probably not in Simple Profile
+  xml_write_free_and_skip(xmlout, movie); /* NO OP so far */ /* May be a place where user squirrels metadata */
+  xml_write_uuid(xmlout, movie); /* NO OP so far */ /* May be a place where user squirrels metadata */
+  return 0;
+}
+
+/* ------------- */
+
+int xml_write_moov(FILE *file, FILE *xmlout, opj_mj2_t * movie, unsigned int sampleframe, opj_event_mgr_t *event_mgr)
+{
+  unsigned int tnum;
+  mj2_tk_t *track;
+
+  fprintf(xmlout,   "  <MovieBox BoxType=\"moov\">\n");
+  fprintf(xmlout,   "    <MovieHeader BoxType=\"mvhd\">\n");
+  fprintf(xmlout,   "      <CreationTime>\n");
+  if(raw)
+    fprintf(xmlout, "        <InSeconds>%u</InSeconds>\n", movie->creation_time);
+  if(notes)
+    fprintf(xmlout, "        <!-- Seconds since start of Jan. 1, 1904 UTC (Greenwich) -->\n");
+  /*  2082844800 = seconds between 1/1/04 and 1/1/70 */
+  /* There's still a time zone offset problem not solved... but spec is ambigous as to whether stored time
+     should be local or UTC */
+  if(derived) {
+    fprintf(xmlout, "        <AsLocalTime>"); 
+                             xml_time_out(xmlout, movie->creation_time - 2082844800);
+                                                     fprintf(xmlout,"</AsLocalTime>\n");
+  }
+  fprintf(xmlout,   "      </CreationTime>\n");
+  fprintf(xmlout,   "      <ModificationTime>\n");
+  if(raw)
+    fprintf(xmlout, "        <InSeconds>%u</InSeconds>\n", movie->modification_time);
+  if(derived) {
+    fprintf(xmlout, "        <AsLocalTime>"); 
+                             xml_time_out(xmlout, movie->modification_time - 2082844800);
+                                                     fprintf(xmlout,"</AsLocalTime>\n");
+  }
+  fprintf(xmlout,   "      </ModificationTime>\n");
+  fprintf(xmlout,   "      <Timescale>%d</Timescale>\n", movie->timescale);
+  if(notes)
+    fprintf(xmlout, "      <!-- Timescale defines time units in one second -->\n");
+  fprintf(xmlout,   "      <Rate>\n");        /* Rate to play presentation  (default = 0x00010000)          */
+  if(notes) {
+    fprintf(xmlout, "      <!-- Rate to play presentation is stored as fixed-point binary 16.16 value. Decimal value is approximation. -->\n");
+    fprintf(xmlout, "      <!-- Rate is expressed relative to normal (default) value of 0x00010000 (1.0) -->\n");
+  }
+  if(raw)
+    fprintf(xmlout, "        <AsHex>0x%08x</AsHex>\n", movie->rate);
+  if(derived)
+    fprintf(xmlout, "        <AsDecimal>%12.6f</AsDecimal>\n", (double)movie->rate/(double)0x00010000);
+  fprintf(xmlout,   "      </Rate>\n");
+  fprintf(xmlout,   "      <Duration>\n");
+  if(raw)
+    fprintf(xmlout, "        <InTimeUnits>%u</InTimeUnits>\n", movie->duration);
+  if(derived)
+    fprintf(xmlout, "        <InSeconds>%12.3f</InSeconds>\n", (double)movie->duration/(double)movie->timescale);    // Make this double later to get fractional seconds
+  fprintf(xmlout,   "      </Duration>\n");
+#ifdef CURRENTSTRUCT
+  movie->volume = movie->volume << 8;
+#endif
+  fprintf(xmlout,   "      <Volume>\n");
+  if(notes) {
+    fprintf(xmlout, "      <!-- Audio volume stored as fixed-point binary 8.8 value. Decimal value is approximation. -->\n");
+    fprintf(xmlout, "      <!-- Full, normal (default) value is 0x0100 (1.0) -->\n");
+  }
+  if(raw)
+    fprintf(xmlout, "        <AsHex>0x%04x</AsHex>\n", movie->volume);
+  if(derived)
+    fprintf(xmlout, "        <AsDecimal>%6.3f</AsDecimal>\n", (double)movie->volume/(double)0x0100);
+  fprintf(xmlout,   "      </Volume>\n");
+#ifdef CURRENTSTRUCT
+  if(notes)
+    fprintf(xmlout, "      <!-- Current m2j_to_metadata implementation always shows bits to right of decimal as zeroed. -->\n");
+  movie->volume = movie->volume >> 8;
+#endif
+  /* Transformation matrix for video                            */
+  fprintf(xmlout,   "      <TransformationMatrix>\n");
+  if(notes) {
+    fprintf(xmlout, "      <!-- 3 x 3 Video Transformation Matrix {a,b,u,c,d,v,x,y,w}.  Required: u=0, v=0, w=1 -->\n");
+    fprintf(xmlout, "      <!-- Maps decompressed point (p,q) to rendered point (ap + cq + x, bp + dq + y) -->\n");
+    fprintf(xmlout, "      <!-- Stored as Fixed Point Hex: all are binary 16.16, except u,v,w are 2.30 -->\n");
+    fprintf(xmlout, "      <!-- Unity = 0x00010000,0,0,0,0x00010000,0,0,0,0x40000000 -->\n");
+  }
+  fprintf(xmlout,   "        <TMa>0x%08x</TMa>\n", movie->trans_matrix[0]);    
+  fprintf(xmlout,   "        <TMb>0x%08x</TMb>\n", movie->trans_matrix[1]);    
+  fprintf(xmlout,   "        <TMu>0x%08x</TMu>\n", movie->trans_matrix[2]);    
+  fprintf(xmlout,   "        <TMc>0x%08x</TMc>\n", movie->trans_matrix[3]);    
+  fprintf(xmlout,   "        <TMd>0x%08x</TMd>\n", movie->trans_matrix[4]);    
+  fprintf(xmlout,   "        <TMv>0x%08x</TMv>\n", movie->trans_matrix[5]);    
+  fprintf(xmlout,   "        <TMx>0x%08x</TMx>\n", movie->trans_matrix[6]);    
+  fprintf(xmlout,   "        <TMy>0x%08x</TMy>\n", movie->trans_matrix[7]);    
+  fprintf(xmlout,   "        <TMw>0x%08x</TMw>\n", movie->trans_matrix[8]);
+  fprintf(xmlout,   "      </TransformationMatrix>\n");
+  fprintf(xmlout,   "    </MovieHeader>\n");
+  
+  fprintf(xmlout,   "    <Statistics>\n");
+  fprintf(xmlout,   "      <TracksFound>\n");
+  fprintf(xmlout,   "        <Video>%d</Video>\n", movie->num_vtk);
+  fprintf(xmlout,   "        <Audio>%d</Audio>\n", movie->num_stk);
+  fprintf(xmlout,   "        <Hint>%d</Hint>\n", movie->num_htk);
+  if(notes)
+    fprintf(xmlout, "        <!-- Hint tracks for streaming video are not part of MJ2, but are a defined extension. -->\n");
+  /* See Part 3 Amend 2 Section 4.2 for relation of MJ2 to Part 12 Sections 7 and 10 hints */
+  fprintf(xmlout,   "      </TracksFound>\n");
+  fprintf(xmlout,   "    </Statistics>\n");
+  /* Idea for the future:  It would be possible to add code to verify that the file values:
+    1) are legal and self-consistent
+       2) comply with particular JP2 and/or MJ2 profiles.
+       This could be reported here as additional XML elements */
+
+  // Find first video track 
+  tnum = 0;
+  while (movie->tk[tnum].track_type != 0)
+    tnum ++;
+
+  track = &(movie->tk[tnum]);
+  // For now, output info on first video track
+  xml_write_trak(file, xmlout, track, tnum, sampleframe, event_mgr);
+
+  // to come:                <MovieExtends mvek> // possibly not in Simple Profile
+  xml_write_moov_udta(xmlout, movie); /* NO OP so far */ /* <UserDataBox udta> contains <CopyrightBox cprt> */
+  fprintf(xmlout,   "  </MovieBox>\n");
+  return 0;
+}
+
+/* --------------- */
+
+void uint_to_chars(unsigned int value, char* buf)
+{
+       /* buf is at least char[5] */
+    int i;
+    for (i = 3; i >= 0; i--)
+    {
+        buf[i] = (value & 0x000000ff);
+        value = (value >> 8);
+    }
+       buf[4] = '\0'; /* Precautionary */
+}
+
+/* ------------- */
+
+/* WINDOWS SPECIFIC */
+
+void UnixTimeToFileTime(time_t t, LPFILETIME pft)
+{
+  /* Windows specific.  From MS Q167296 */
+  /* 'time_t' represents seconds since midnight January 1, 1970 UTC (coordinated universal time). */
+  /* 64-bit FILETIME structure represents the number of 100-nanosecond intervals since January 1, 1601 UTC (coordinate universal time). */
+  LONGLONG ll; /* LONGLONG is a 64-bit value. */
+  ll = Int32x32To64(t, 10000000) + 116444736000000000;
+  pft->dwLowDateTime = (DWORD)ll;
+  /* pft->dwLowDateTime = (DWORD)(0x00000000ffffffff & ll); */
+  pft->dwHighDateTime = (DWORD)(ll >> 32);
+} 
+// Once the UNIX time is converted to a FILETIME structure,
+// other Win32 time formats can be easily obtained by using Win32 functions such
+// as FileTimeToSystemTime() and FileTimeToDosDateTime().
+
+/* ------------- */
+
+void UnixTimeToSystemTime(time_t t, LPSYSTEMTIME pst)
+{
+  /* Windows specific */
+  FILETIME ft;
+  UnixTimeToFileTime(t, &ft);
+  FileTimeToLocalFileTime( &ft, &ft ); /* Adjust from UTC to local time zone */
+  FileTimeToSystemTime(&ft, pst);
+}
+
+/* ------------- */
+
+void xml_time_out(FILE* xmlout, time_t t)
+{
+  /* Windows specific */
+  SYSTEMTIME st;
+  char szLocalDate[255], szLocalTime[255];
+  UnixTimeToSystemTime( t, &st );
+  GetDateFormat( LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, szLocalDate, 255 );
+  GetTimeFormat( LOCALE_USER_DEFAULT, 0, &st, NULL, szLocalTime, 255 );
+  fprintf(xmlout, "%s %s", szLocalDate, szLocalTime ); 
+}
+
+/* END WINDOWS SPECIFIC */
+
+/* ------------- */
+
+void xml_write_moov_udta(FILE* xmlout, opj_mj2_t * movie) {
+  /* Compare with xml_write_udta */
+#ifdef NOTYET
+  /* NO-OP so far.  Optional UserData 'udta' (zero or one in moov or each trak)
+     can contain multiple Copyright 'cprt' with different language codes */
+  /* There may be nested non-standard boxes within udta */
+  IMAGINE movie->udta, movie->copyright_count, movie->copyright_language[i] (array of 16bit ints), movie->copyright_notice[i] (array of buffers)
+  PROBABLY ALSO NEED movie->udta_len or special handler for non-standard boxes
+  char buf[5];
+  int i;
+
+  if(movie->udta != 1)
+         return; /* Not present */
+
+  fprintf(xmlout,    "    <UserData BoxType=\"udta\">\n");
+  for(i = 0; i < movie->copyright_count; i++) {
+    fprintf(xmlout,  "      <Copyright BoxType=\"cprt\"> Instance=\"%d\">\n", i+1);
+    int16_to_3packedchars((short int)movie->copyright_languages[i], buf);
+    fprintf(xmlout,  "        <Language>%s</Language>\n", buf);    /* 3 chars */
+    fprintf(xmlout,  "        <Notice>%s</Notice>\n",movie->copyright_notices[i]);
+    fprintf(xmlout,  "      </Copyright>\n", i+1);
+  }
+  /* TO DO: Non-standard boxes */
+  fprintf(xmlout,    "    </UserData>\n");
+#endif
+}
+
+void xml_write_free_and_skip(FILE* xmlout, opj_mj2_t * movie) {
+#ifdef NOTYET
+  /* NO-OP so far.  There can be zero or more instances of free and/or skip
+     at the top level of the file.  This may be a place where the user squirrel's metadata.
+        Let's assume unstructured, and do a dump */
+  IMAGINE movie->free_and_skip, movie->free_and_skip_count, movie->free_and_skip_content[i] (array of buffers),
+         movie->free_and_skip_len[i] (array of ints), movie->is_skip[i] (array of BOOL)
+  int i;
+
+  if(movie->free_and_skip != 1)
+         return; /* Not present */
+
+  for(i = 0; i < movie->free_and_skip_count; i++) {
+    if(movie->is_skip[i])
+      fprintf(xmlout,    "  <Skip BoxType=\"skip\">\n");
+       else
+      fprintf(xmlout,    "  <Free BoxType=\"free\">\n");
+
+    xml_out_dump_hex_and_ascii(xmlout, movie->free_and_skip_contents[i], movie->free_and_skip_len[i]);
+
+    if(movie->is_skip[i])
+      fprintf(xmlout,    "  </Skip>\n");
+       else
+      fprintf(xmlout,    "  </Free>\n");
+  }
+#endif
+}
+
+void xml_write_uuid(FILE* xmlout, opj_mj2_t * movie) {
+/* Univeral Unique IDs of 16 bytes.  */
+#ifdef NOTYET
+  /* NO-OP so far.  There can be zero or more instances of private uuid boxes in a file.
+     This function supports the top level of the file, but uuid may be elsewhere [not yet supported].
+        This may be a place where the user squirrel's metadata.  Let's assume unstructured, and do a dump */
+  IMAGINE movie->uuid, movie->uuid_count, movie->uuid_content[i] (array of buffers),
+         movie->uuid_len[i] (array of ints), movie->uuid_type[i] (array of 17-byte (16+null termination) buffers)
+  int i;
+
+  if(movie->uuid != 1)
+         return; /* Not present */
+
+  for(i = 0; i < movie->uuid_count; i++) {
+    fprintf(xmlout,    "  <PrivateExtension BoxType=\"uuid\" UUID=\"%s\">\n", movie->uuid_type[i]);
+       // See Part III section 5.2.1, 6.1, 6.2
+    xml_out_dump_hex_and_ascii(xmlout, movie->uuid_contents[i], movie->uuid_len[i]);
+    fprintf(xmlout,    "  </PrivateExtension>\n");
+  }
+#endif
+}
+
+/* ------------- */
+
+void xml_write_trak(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum, unsigned int sampleframe, opj_event_mgr_t *event_mgr)
+{
+  fprintf(xmlout,    "    <Track BoxType=\"trak\" Instance=\"%d\">\n", tnum);
+  xml_write_tkhd(file, xmlout, track, tnum);
+  // TO DO: TrackReferenceContainer 'tref'  just used in hint track
+  // TO DO: EditListContainer 'edts', contains EditList 'elst' with media-time, segment-duration, media-rate
+  xml_write_mdia(file, xmlout, track, tnum);
+  xml_write_udta(file, xmlout, track, tnum); // NO-OP so far.  Optional UserData 'udta', can contain multiple Copyright 'cprt'
+
+  if(track->track_type==0) { /* Only do for visual track */
+       /* sampleframe is from user option -f.  1 = first frame */
+    /* sampleframe of 0 is a user requests: no jp2 header */
+       /* Treat out-of-bounds values in the same way */
+       if(sampleframe > 0 && sampleframe <= track->num_samples) 
+    {
+      mj2_sample_t *sample;
+      unsigned int snum;
+
+      snum = sampleframe-1;
+      // Someday maybe do a smart range scan... for (snum=0; snum < track->num_samples; snum++){
+      //  fprintf(stdout,"Frame %d: ",snum+1);
+      sample = &track->sample[snum];
+         if(xml_out_frame(file, xmlout, sample, snum, event_mgr))
+           return; /* Not great error handling here */
+    }
+  }
+  fprintf(xmlout,    "    </Track>\n");
+}
+
+/* ------------- */
+
+void xml_write_tkhd(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum)
+{
+  fprintf(xmlout,    "      <TrackHeader BoxType=\"tkhd\">\n");
+  if(notes) {
+    fprintf(xmlout,  "      <!-- Not shown here: CreationTime, ModificationTime, Duration. -->\n");
+    fprintf(xmlout,  "      <!-- These 3 fields are reported under MediaHeader below.   When reading these 3, -->\n");
+    fprintf(xmlout,  "      <!-- m2j_to_metadata currently doesn't distinguish between TrackHeader and MediaHeader source. -->\n");
+    fprintf(xmlout,  "      <!-- If both found, value read from MediaHeader is used. -->\n");
+  }
+  fprintf(xmlout,    "        <TrackID>%u</TrackID>\n", track->track_ID);
+  if(track->track_type==0) /* For visual track */
+  {
+    fprintf(xmlout,  "        <TrackLayer>%d</TrackLayer>\n", track->layer);
+    if(notes)
+      fprintf(xmlout,"        <!-- front-to-back ordering of video tracks. 0 = normal, -1 is closer, etc. -->\n");
+  }
+  if(track->track_type!=0) /* volume irrelevant for visual track */
+  {
+#ifdef CURRENTSTRUCT
+    track->volume = track->volume << 8;
+#endif
+    fprintf(xmlout,  "        <Volume>\n");
+       if(notes) {
+      fprintf(xmlout,"          <!-- Track audio volume stored as fixed-point binary 8.8 value. Decimal value is approximation. -->\n");
+      fprintf(xmlout,"          <!-- Full, normal (default) value is 0x0100 (1.0) -->\n");
+       }
+       if(raw)
+      fprintf(xmlout,"          <AsHex>0x%04x</AsHex>\n", track->volume);
+       if(derived)
+      fprintf(xmlout,"          <AsDecimal>%6.3f</AsDecimal>\n", (double)track->volume/(double)0x0100);
+    fprintf(xmlout,  "        </Volume>\n");
+#ifdef CURRENTSTRUCT
+  if(notes)
+    fprintf(xmlout,  "        <!-- Current m2j_to_metadata implementation always shows bits to right of decimal as zeroed. -->\n");
+       track->volume = track->volume >> 8;
+#endif
+  }
+  if(track->track_type==0)
+  {
+    /* Transformation matrix for video                            */
+    fprintf(xmlout,  "        <TransformationMatrix>\n");
+       if(notes) {
+      fprintf(xmlout,"          <!-- Comments about matrix in MovieHeader apply here as well. -->\n");
+      fprintf(xmlout,"          <!-- This matrix is applied before MovieHeader one. -->\n");
+       }
+    fprintf(xmlout,  "          <TMa>0x%08x</TMa>\n", track->trans_matrix[0]);    
+    fprintf(xmlout,  "          <TMb>0x%08x</TMb>\n", track->trans_matrix[1]);    
+    fprintf(xmlout,  "          <TMu>0x%08x</TMu>\n", track->trans_matrix[2]);    
+    fprintf(xmlout,  "          <TMc>0x%08x</TMc>\n", track->trans_matrix[3]);    
+    fprintf(xmlout,  "          <TMd>0x%08x</TMd>\n", track->trans_matrix[4]);    
+    fprintf(xmlout,  "          <TMv>0x%08x</TMv>\n", track->trans_matrix[5]);    
+    fprintf(xmlout,  "          <TMx>0x%08x</TMx>\n", track->trans_matrix[6]);    
+    fprintf(xmlout,  "          <TMy>0x%08x</TMy>\n", track->trans_matrix[7]);    
+    fprintf(xmlout,  "          <TMw>0x%08x</TMw>\n", track->trans_matrix[8]);
+    fprintf(xmlout,  "        </TransformationMatrix>\n");
+  }
+#ifdef CURRENTSTRUCT
+  track->w = track->w << 16;
+  track->h = track->h << 16;
+#endif
+  if(notes) {
+    fprintf(xmlout,  "        <!-- Width and Height in pixels are for the presentation; frames will be scaled to this. -->\n");
+    fprintf(xmlout,  "        <!-- Both stored as fixed-point binary 16.16 values. Decimal values are approximations. -->\n");
+  }
+  fprintf(xmlout,    "        <Width>\n");
+  if(raw)
+    fprintf(xmlout,  "          <AsHex>0x%08x</AsHex>\n", track->w);
+  if(derived)
+    fprintf(xmlout,  "          <AsDecimal>%12.6f</AsDecimal>\n", (double)track->w/(double)0x00010000);        /* Rate to play presentation  (default = 0x00010000)          */
+  fprintf(xmlout,    "        </Width>\n");
+  fprintf(xmlout,    "        <Height>\n");
+  if(raw)
+    fprintf(xmlout,  "          <AsHex>0x%08x</AsHex>\n", track->h);
+  if(derived)
+    fprintf(xmlout,  "          <AsDecimal>%12.6f</AsDecimal>\n", (double)track->h/(double)0x00010000);        /* Rate to play presentation  (default = 0x00010000)          */
+  fprintf(xmlout,    "        </Height>\n");
+#ifdef CURRENTSTRUCT
+  if(notes) {
+    fprintf(xmlout,  "        <!-- Current m2j_to_metadata implementation always shows bits to right of decimal as zeroed. -->\n");
+    fprintf(xmlout,  "        <!-- Also, width and height values shown here will actually be those read from track's <VisualSampleEntry> if given. -->\n");
+  }
+  track->w = track->w >> 16;
+  track->h = track->h >> 16;
+#endif
+  fprintf(xmlout,    "      </TrackHeader>\n");
+}
+
+/* ------------- */
+
+void xml_write_udta(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum) {
+  /* NO-OP so far.  Optional UserData 'udta' (zero or one in moov or each trak)
+     can contain multiple Copyright 'cprt' with different language codes */
+  /* There may be nested non-standard boxes within udta */
+#ifdef NOTYET
+  IMAGINE track->udta, track->copyright_count, track->copyright_language[i] (array of 16bit ints), track->copyright_notice[i] (array of buffers)
+  PROBABLY ALSO NEED track->udta_len or special handler for non-standard boxes
+  char buf[5];
+  int i;
+
+  if(track->udta != 1)
+         return; /* Not present */
+
+  fprintf(xmlout,    "      <UserData BoxType=\"udta\">\n");
+  for(i = 0; i < track->copyright_count; i++) {
+    fprintf(xmlout,  "        <Copyright BoxType=\"cprt\"> Instance=\"%d\">\n", i+1);
+    int16_to_3packedchars((short int)track->copyright_languages[i], buf);
+    fprintf(xmlout,  "          <Language>%s</Language>\n", buf);    /* 3 chars */
+    fprintf(xmlout,  "          <Notice>%s</Notice>\n",track->copyright_notices[i]);
+    fprintf(xmlout,  "        </Copyright>\n", i+1);
+  }
+  /* TO DO: Non-standard boxes */
+  fprintf(xmlout,    "      </UserData>\n");
+#endif
+}
+
+/* ------------- */
+
+void xml_write_mdia(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum)
+{
+  char buf[5];
+  int i, k;
+  buf[4] = '\0';
+
+  fprintf(xmlout,    "      <Media BoxType=\"mdia\">\n");
+  fprintf(xmlout,    "        <MediaHeader BoxType=\"mdhd\">\n");
+  fprintf(xmlout,    "          <CreationTime>\n");
+  if(raw)
+    fprintf(xmlout,  "            <InSeconds>%u</InSeconds>\n", track->creation_time);
+  if(notes)
+    fprintf(xmlout,  "            <!-- Seconds since start of Jan. 1, 1904 UTC (Greenwich) -->\n");
+  /*  2082844800 = seconds between 1/1/04 and 1/1/70 */
+  /* There's still a time zone offset problem not solved... but spec is ambigous as to whether stored time
+     should be local or UTC */
+  if(derived) {
+    fprintf(xmlout,  "            <AsLocalTime>"); 
+                                xml_time_out(xmlout, track->creation_time - 2082844800);
+                                                     fprintf(xmlout,"</AsLocalTime>\n");
+  }
+  fprintf(xmlout,    "          </CreationTime>\n");
+  fprintf(xmlout,    "          <ModificationTime>\n");
+  if(raw)
+    fprintf(xmlout,  "            <InSeconds>%u</InSeconds>\n", track->modification_time);
+  if(derived) {
+    fprintf(xmlout,  "            <AsLocalTime>"); 
+                                xml_time_out(xmlout, track->modification_time - 2082844800);
+                                                     fprintf(xmlout,"</AsLocalTime>\n");
+  }
+  fprintf(xmlout,    "          </ModificationTime>\n");
+  fprintf(xmlout,    "          <Timescale>%d</Timescale>\n", track->timescale);
+  if(notes)
+    fprintf(xmlout,  "          <!-- Timescale defines time units in one second -->\n");
+  fprintf(xmlout,    "          <Duration>\n");
+  if(raw)
+    fprintf(xmlout,  "            <InTimeUnits>%u</InTimeUnits>\n", track->duration);
+  if(derived)
+    fprintf(xmlout,  "            <InSeconds>%12.3f</InSeconds>\n", (double)track->duration/(double)track->timescale);    // Make this double later to get fractional seconds
+  fprintf(xmlout,    "          </Duration>\n");
+  int16_to_3packedchars((short int)track->language, buf);
+  fprintf(xmlout,    "          <Language>%s</Language>\n", buf);    /* 3 chars */
+  fprintf(xmlout,    "        </MediaHeader>\n");
+  fprintf(xmlout,    "        <HandlerReference BoxType=\"hdlr\">\n");
+  switch(track->track_type)
+  {
+  case 0:
+    fprintf(xmlout,  "          <HandlerType Code=\"vide\">video media track</HandlerType>\n"); break;
+  case 1:
+    fprintf(xmlout,  "          <HandlerType Code=\"soun\">Sound</HandlerType>\n"); break;
+  case 2:
+    fprintf(xmlout,  "          <HandlerType Code=\"hint\">Hint</HandlerType>\n"); break;
+  }
+  if(notes) {
+    fprintf(xmlout,  "          <!-- String value shown is not actually read from file. -->\n");
+    fprintf(xmlout,  "          <!-- Shown value is one used for our encode. -->\n");
+  }
+  fprintf(xmlout,    "        </HandlerReference>\n");
+  fprintf(xmlout,    "        <MediaInfoContainer BoxType=\"minf\">\n");
+  switch(track->track_type)
+  {
+  case 0:
+    fprintf(xmlout,  "          <VideoMediaHeader BoxType=\"vmhd\">\n");
+    fprintf(xmlout,  "            <GraphicsMode>0x%02x</GraphicsMode>\n", track->graphicsmode);
+       if(notes) {
+      fprintf(xmlout,"            <!-- Enumerated values of graphics mode: -->\n");
+      fprintf(xmlout,"            <!--  0x00 = copy (over existing image); -->\n");
+      fprintf(xmlout,"            <!--  0x24 = transparent; 'blue-screen' this image using opcolor; -->\n");
+      fprintf(xmlout,"            <!--  0x100 = alpha; alpha-blend this image -->\n");
+/*    fprintf(xmlout,"            <!--  0x101 = whitealpha; alpha-blend this image, which has been blended with white; -->\n"); This was evidently dropped upon amendment */
+      fprintf(xmlout,"            <!--  0x102 = pre-multiplied black alpha; image has been already been alpha-blended with black. -->\n");
+      fprintf(xmlout,"            <!--  0x110 = component alpha; blend alpha channel(s) and color channels individually. -->\n");
+       }
+    fprintf(xmlout,  "            <Opcolor>\n");
+    fprintf(xmlout,  "              <Red>0x%02x</Red>\n", track->opcolor[0]);
+    fprintf(xmlout,  "              <Green>0x%02x</Green>\n",track->opcolor[1]);
+    fprintf(xmlout,  "              <Blue>0x%02x</Blue>\n",track->opcolor[2]);
+    fprintf(xmlout,  "            </Opcolor>\n");
+    fprintf(xmlout,  "          </VideoMediaHeader>\n");
+    break;
+  case 1:
+    fprintf(xmlout,  "          <SoundMediaHeader BoxType=\"smhd\">\n");
+#ifdef CURRENTSTRUCT
+       track->balance = track->balance << 8;
+#endif
+    fprintf(xmlout,  "            <Balance>\n");
+       if(notes) {
+      fprintf(xmlout,"              <!-- Track audio balance fixes mono track in stereo space. -->\n");
+      fprintf(xmlout,"              <!-- Stored as fixed-point binary 8.8 value. Decimal value is approximation. -->\n");
+      fprintf(xmlout,"              <!-- 0.0 = center, -1.0 = full left, 1.0 = full right -->\n");
+       }
+       if(raw)
+      fprintf(xmlout,"              <AsHex>0x%04x</AsHex>\n", track->balance);
+    if(derived)
+         fprintf(xmlout,"              <AsDecimal>%6.3f</AsDecimal>\n", (double)track->balance/(double)0x0100);
+    fprintf(xmlout,  "            </Balance>\n");
+#ifdef CURRENTSTRUCT
+    if(notes)
+         fprintf(xmlout,"            <!-- Current m2j_to_metadata implementation always shows bits to right of decimal as zeroed. -->\n");
+       track->balance = track->balance >> 8;
+#endif
+    fprintf(xmlout,  "          </SoundMediaHeader>\n");
+    break;
+  case 2:
+    fprintf(xmlout,  "          <HintMediaHeader BoxType=\"hmhd\">\n");
+    fprintf(xmlout,  "            <MaxPDU_Size>%d</MaxPDU_Size>\n", track->maxPDUsize);
+    if(notes)
+      fprintf(xmlout,"            <!-- Size in bytes of largest PDU in this hint stream. -->\n");
+    fprintf(xmlout,  "            <AvgPDU_Size>%d</AvgPDU_Size>\n", track->avgPDUsize);
+    if(notes)
+      fprintf(xmlout,"            <!-- Average size in bytes of a PDU over the entire presentation. -->\n");
+    fprintf(xmlout,  "            <MaxBitRate>%d</MaxBitRate>\n", track->maxbitrate);
+    if(notes)
+      fprintf(xmlout,"            <!-- Maximum rate in bits per second over any window of 1 second. -->\n");
+    fprintf(xmlout,  "            <AvgBitRate>%d</AvgBitRate>\n", track->avgbitrate);
+    if(notes)
+      fprintf(xmlout,"            <!-- Averate rate in bits per second over the entire presentation. -->\n");
+    fprintf(xmlout,  "            <SlidingAvgBit>%d</SlidingAvgBitRate>\n", track->slidingavgbitrate);
+    if(notes)
+      fprintf(xmlout,"            <!-- Maximum rate in bits per second over any window of one minute. -->\n");
+    fprintf(xmlout,  "          </HintMediaHeader>\n");
+    break;
+  }
+  fprintf(xmlout,    "          <DataInfo BoxType=\"dinf\">\n");
+  fprintf(xmlout,    "            <DataReference BoxType=\"dref\"  URL_Count=\"%d\" URN_Count=\"%d\">\n", track->num_url, track->num_urn); // table w. flags, URLs, URNs
+  // Data structure does not distinguish between single URL, single URN, or DREF table or URLs & URNs.
+  // We could infer those, but for now just present everything as a DREF table.
+  if(notes)
+    fprintf(xmlout,  "              <!-- No entries here mean that file is self-contained, as required by Simple Profile. -->\n");
+  for(k = 0; k < track->num_url; k++) {
+    fprintf(xmlout,  "            <DataEntryUrlBox BoxType=\"url[space]\">\n"); // table w. flags, URLs, URNs
+    if(notes)
+      fprintf(xmlout,"              <!-- Only the first 16 bytes of URL location are recorded in mj2_to_metadata data structure. -->\n");
+    for(i = 0; i < 4; i++) {
+      uint_to_chars(track->url[track->num_url].location[i], buf);
+    fprintf(xmlout,  "              <Location>%s</Location>\n");
+    }
+    fprintf(xmlout,  "            </DataEntryUrlBox>\n"); // table w. flags, URLs, URNs
+  }
+  for(k = 0; k < track->num_urn; k++) {
+    fprintf(xmlout,"            <DataEntryUrnBox BoxType=\"urn[space]\">\n"); // table w. flags, URLs, URNs
+    // Only the first 16 bytes are recorded in the data structure currently.
+    if(notes)
+      fprintf(xmlout,"              <!-- Only the first 16 bytes each of URN name and optional location are recorded in mj2_to_metadata data structure. -->\n");
+    fprintf(xmlout,  "              <Name>");
+    for(i = 0; i < 4; i++) {
+      uint_to_chars(track->urn[track->num_urn].name[i], buf);
+      fprintf(xmlout,"%s", buf);
+    }
+    fprintf(xmlout,  "</Name>\n");
+    fprintf(xmlout,  "              <Location>");
+    for(i = 0; i < 4; i++) {
+      uint_to_chars(track->urn[track->num_urn].location[i], buf);
+      fprintf(xmlout,"%s");
+    }
+    fprintf(xmlout,  "</Location>\n");
+    fprintf(xmlout,  "            </DataEntryUrnBox>\n");
+  }
+  fprintf(xmlout,    "            </DataReference>\n");
+  fprintf(xmlout,    "          </DataInfo>\n");
+
+  xml_write_stbl(file, xmlout, track, tnum); /* SampleTable */
+
+  fprintf(xmlout,    "        </MediaInfoContainer>\n");  
+  fprintf(xmlout,    "      </Media>\n");
+}
+
+/* ------------- */
+
+void xml_write_stbl(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum)
+{
+  char buf[5], buf33[33];
+  int i, len;
+  buf[4] = '\0';
+
+  fprintf(xmlout,      "          <SampleTable BoxType=\"stbl\">\n");
+  if(notes)
+    fprintf(xmlout,    "            <!-- What follows are specific instances of generic SampleDescription BoxType=\"stsd\" -->\n");
+  switch(track->track_type)
+  {
+  case 0:
+    // There could be multiple instances of this, but "entry_count" is just a local at read-time.
+    // And it's used wrong, too, as count of just visual type, when it's really all 3 types.
+    // This is referred to as "smj2" within mj2.c
+    fprintf(xmlout,    "            <VisualSampleEntry BoxType=\"mjp2\">\n");
+       if(notes) {
+      fprintf(xmlout,  "            <!-- If multiple instances of this box, only first is shown here. -->\n");
+         fprintf(xmlout,  "            <!-- Width and Height are in pixels.  Unlike the Track Header, there is no fractional part. -->\n");
+         fprintf(xmlout,  "            <!-- In mj2_to_metadata implementation, the values are not represented separately from Track Header's values. -->\n");
+       }
+       /* No shifting required.  If CURRENTSTRUCT gets changed, then may need to revisit treatment of these */
+    fprintf(xmlout,    "              <WidthAsInteger>%d</WidthAsInteger>\n", track->w);
+    fprintf(xmlout,    "              <HeightAsInteger>%d</HeightAsInteger>\n", track->h);
+// Horizresolution and vertresolution don't require shifting, already stored right in CURRENTSTRUCT
+    if(notes) {
+      fprintf(xmlout,  "              <!-- Resolutions are in pixels per inch, for the highest-resolution component (typically luminance). -->\n");
+      fprintf(xmlout,  "              <!-- Both stored as fixed-point binary 16.16 values. Decimal values are approximations. -->\n");
+      fprintf(xmlout,  "              <!-- Typical value for both resolutions is 0x00480000  (72.0) -->\n");
+       }
+    fprintf(xmlout,    "              <HorizontalRes>\n");
+       if(raw)
+      fprintf(xmlout,  "                <AsHex>0x%08x</AsHex>\n", track->horizresolution);
+       if(derived)
+      fprintf(xmlout,  "                <AsDecimal>%12.6f</AsDecimal>\n", (double)track->horizresolution/(double)0x00010000);        /* Rate to play presentation  (default = 0x00010000)          */
+    fprintf(xmlout,    "              </HorizontalRes>\n");
+    fprintf(xmlout,    "              <VerticalRes>\n");
+       if(raw)
+      fprintf(xmlout,  "                <AsHex>0x%08x</AsHex>\n", track->vertresolution);
+       if(derived)
+      fprintf(xmlout,  "                <AsDecimal>%12.6f</AsDecimal>\n", (double)track->vertresolution/(double)0x00010000);        /* Rate to play presentation  (default = 0x00010000)          */
+    fprintf(xmlout,    "              </VerticalRes>\n");
+
+    buf33[0] = '\0';
+    for(i = 0; i < 8; i++) {
+      uint_to_chars((unsigned int)track->compressorname[i], buf);
+      strcat(buf33, buf); /* This loads up (4 * 8) + 1 chars, but trailing ones are usually junk */
+    }
+    len = (int)buf33[0]; /* First byte has string length in bytes.  There may be garbage beyond it. */
+    buf33[len+1] = '\0'; /* Suppress it */
+    fprintf(xmlout,    "              <CompressorName>%s</CompressorName>\n", buf33+1); /* Start beyond first byte */
+       if(notes) {
+      fprintf(xmlout,  "              <!-- Compressor name for debugging.  Standard restricts max length to 31 bytes. -->\n");
+      fprintf(xmlout,  "              <!-- Usually blank or \"Motion JPEG2000\" -->\n");
+       }
+    fprintf(xmlout,    "              <Depth>0x%02x</Depth>\n",track->depth);
+       if(notes) {
+      fprintf(xmlout,  "              <!-- Depth is: -->\n");
+      fprintf(xmlout,  "              <!--   0x20: alpha channels present (color or grayscale) -->\n");
+      fprintf(xmlout,  "              <!--   0x28: grayscale without alpha -->\n");
+      fprintf(xmlout,  "              <!--   0x18: color without alpha -->\n");
+       }
+
+    xml_out_frame_jp2h(xmlout, &(track->jp2_struct));  /* JP2 Header */
+    
+  /* Following subboxes are optional */
+    fprintf(xmlout,    "              <FieldCoding BoxType=\"fiel\">\n");
+    fprintf(xmlout,    "                <FieldCount>%d</FieldCount>\n", (unsigned int)track->fieldcount); /* uchar as 1 byte uint */
+    if(notes)
+      fprintf(xmlout,  "                <!-- Must be either 1 or 2 -->\n");
+    fprintf(xmlout,    "                <FieldOrder>%d</FieldOrder>\n", (unsigned int)track->fieldorder); /* uchar as 1 byte uint */
+       if(notes) {
+      fprintf(xmlout,  "                <!-- When FieldCount=2, FieldOrder means: -->\n");
+      fprintf(xmlout,  "                <!--   0: Field coding unknown -->\n");
+      fprintf(xmlout,  "                <!--   1: Field with topmost line is stored first in sample; fields are in temporal order -->\n");
+      fprintf(xmlout,  "                <!--   6: Field with topmost line is stored second in sample; fields are in temporal order -->\n");
+      fprintf(xmlout,  "                <!-- Defaults: FieldCount=1, FieldOrder=0 if FieldCoding box not present -->\n");
+      fprintf(xmlout,  "                <!-- Current implementation doesn't retain whether box was actually present. -->\n");
+       }
+    fprintf(xmlout,    "              </FieldCoding>\n");
+
+    fprintf(xmlout,    "              <MJP2_Profile BoxType=\"jp2p\" Count=\"%d\">\n",track->num_br);
+    for (i = 0; i < track->num_br; i++) /* read routine stored in reverse order, so let's undo damage */
+    {
+      uint_to_chars(track->br[i], buf);
+      fprintf(xmlout,  "                <CompatibleBrand>%s</CompatibleBrand>\n", buf);    /*4 characters, each CLi */
+    }
+    fprintf(xmlout,    "              </MJP2_Profile>\n");
+
+    fprintf(xmlout,    "              <MJP2_Prefix BoxType=\"jp2x\" Count=\"%d\">\n",track->num_jp2x);
+    for (i = 0; i < track->num_jp2x; i++)
+    { // We'll probably need better formatting than this
+      fprintf(xmlout,  "                <Data>0x%02x</Data>\n", track->jp2xdata[i]);    /* Each entry is single byte */
+    }
+    fprintf(xmlout,    "              </MJP2_Prefix>\n");
+
+    fprintf(xmlout,    "              <MJP2_SubSampling BoxType=\"jsub\">\n"); /* These values are all 1 byte */
+    if(notes)
+         fprintf(xmlout,  "              <!-- Typical subsample value is 2 for 4:2:0 -->\n");
+    fprintf(xmlout,    "                <HorizontalSub>%d</HorizontalSub>\n", track->hsub);
+    fprintf(xmlout,    "                <VerticalSub>%d</VerticalSub>\n", track->vsub);
+    fprintf(xmlout,    "                <HorizontalOffset>%d</HorizontalOffset>\n", track->hoff);
+    fprintf(xmlout,    "                <VerticalOffset>%d</VerticalOffset>\n", track->voff);
+       if(notes) {
+         fprintf(xmlout,  "                <!-- Typical {horizontal, vertical} chroma offset values: -->\n");
+         fprintf(xmlout,  "                <!-- 4:2:2 format (CCIR601, H.262, MPEG2, MPEG4, recom. Exif): {0, 0} -->\n");
+         fprintf(xmlout,  "                <!-- 4:2:2 format (JFIF):                                      {1, 0} -->\n");
+         fprintf(xmlout,  "                <!-- 4:2:0 format (H.262, MPEG2, MPEG4):                       {0, 1} -->\n");
+         fprintf(xmlout,  "                <!-- 4:2:0 format (MPEG1, H.261, JFIF, recom. Exif):           {1, 1} -->\n");
+       }
+    fprintf(xmlout,    "              </MJP2_SubSampling>\n"); /* These values are all 1 byte */
+
+    fprintf(xmlout,    "              <MJP2_OriginalFormat BoxType=\"orfo\">\n"); /* Part III Appx. 2 */
+    fprintf(xmlout,    "                <OriginalFieldCount>%u</OriginalFieldCount>\n", (unsigned int)track->or_fieldcount); /* uchar as 1-byte uint */
+    if(notes)
+      fprintf(xmlout,  "                <!-- In original material before encoding.  Must be either 1 or 2 -->\n");
+    fprintf(xmlout,    "                <OriginalFieldOrder>%u</OriginalFieldOrder>\n", (unsigned int)track->or_fieldorder); /* uchar as 1-byte uint */
+       if(notes) {
+      fprintf(xmlout,  "                <!-- When FieldCount=2, FieldOrder means: -->\n");
+      fprintf(xmlout,  "                <!--   0: Field coding unknown -->\n");
+      fprintf(xmlout,  "                <!--   11: Topmost line came from the earlier field; -->\n");
+      fprintf(xmlout,  "                <!--   16:  Topmost line came form the later field. -->\n");
+      fprintf(xmlout,  "                <!-- Defaults: FieldCount=1, FieldOrder=0 if FieldCoding box not present -->\n");
+      fprintf(xmlout,  "                <!-- Current implementation doesn't retain whether box was actually present. -->\n");
+       }
+    fprintf(xmlout,    "              </MJP2_OriginalFormat>\n");
+    fprintf(xmlout,    "            </VisualSampleEntry>\n");
+    break;
+  case 1: case 2:
+    if(notes)
+      fprintf(xmlout,  "            <!-- mj2_to_metadata's data structure doesn't record this currently. -->\n"); break;
+  }
+  fprintf(xmlout,      "            <TimeToSample BoxType=\"stts\">\n");  
+  fprintf(xmlout,      "              <SampleStatistics>\n");  
+  fprintf(xmlout,      "                <TotalSamples>%d</TotalSamples>\n", track->num_samples);
+  if(notes)
+    fprintf(xmlout,    "                <!-- For video, gives the total frames in the track, by summing all entries in the Sample Table -->\n");
+  fprintf(xmlout,      "              </SampleStatistics>\n"); 
+  fprintf(xmlout,      "              <SampleEntries EntryCount=\"%d\">\n", track->num_tts);
+  for (i = 0; i < track->num_tts; i++) {
+    fprintf(xmlout,    "                <Table Entry=\"%u\" SampleCount=\"%d\" SampleDelta=\"%u\" />\n",
+                                      i+1, track->tts[i].sample_count, track->tts[i].sample_delta);
+  }
+  fprintf(xmlout,      "              </SampleEntries>\n");
+  fprintf(xmlout,      "            </TimeToSample>\n");
+
+  fprintf(xmlout,      "            <SampleToChunk BoxType=\"stsc\" Count=\"%d\">\n", track->num_samplestochunk);
+  for (i = 0; i < track->num_samplestochunk; i++) {
+    fprintf(xmlout,    "              <FirstChunk>%u</FirstChunk>\n",track->sampletochunk[i].first_chunk); /* 4 bytes */
+    fprintf(xmlout,    "              <SamplesPerChunk>%u</SamplesPerChunk>\n",track->sampletochunk[i].samples_per_chunk); /* 4 bytes */
+    fprintf(xmlout,    "              <SampleDescrIndex>%u</SampleDescrIndex>\n",track->sampletochunk[i].sample_descr_idx); /* 4 bytes */
+  }
+  fprintf(xmlout,      "            </SampleToChunk>\n");
+  // After reading this info in, track->num_chunks is calculated and a decompressed table established internally.
+
+  fprintf(xmlout,      "            <SampleSize BoxType=\"stsz\">\n");
+  if(track->same_sample_size) {
+    // all values in track->sample[i].sample_size are equal.  Grab the first one.
+    fprintf(xmlout,    "              <Sample_Size>%u</Sample_Size>\n", track->sample[0].sample_size);
+       if(notes) {
+      fprintf(xmlout,  "              <!-- Non-zero value means all samples have that size. -->\n");
+         fprintf(xmlout,  "              <!-- So <Sample_Count> (aka Entry_Count in std.) has no meaning, is suppressed from this output, and no table follows. -->\n");
+       }
+  } else {
+    fprintf(xmlout,    "              <Sample_Size>0</Sample_Size>\n");
+    if(notes)
+         if(sampletables)
+        fprintf(xmlout,"              <!-- Zero value means samples have different sizes, given in table next of length Sample_Count (aka Entry_Count in std). -->\n");
+         else
+        fprintf(xmlout,"              <!-- Zero value means samples have different sizes, given in table (not shown) of length Sample_Count (aka Entry_Count in std). -->\n");
+       fprintf(xmlout,    "              <Sample_Count>%u</Sample_Count>\n", track->num_samples);
+       if(sampletables)
+     for (i = 0; i < (int)track->num_samples; i++) {
+      fprintf(xmlout,  "              <EntrySize Num=\"%u\">%u</EntrySize>\n", i+1, track->sample[i].sample_size);
+     }
+  }  
+  fprintf(xmlout,      "            </SampleSize>\n");
+
+  fprintf(xmlout,      "            <ChunkOffset BoxType=\"stco\">\n");
+  // Structure not yet - Variant ChunkLargeOffset 'co64'
+  fprintf(xmlout,      "              <EntryCount>%u</EntryCount>\n", track->num_chunks);
+  if(notes) {
+    fprintf(xmlout,    "              <!-- For this implementation, EntryCount shown is one calculated during file read of <SampleToChunk> data. -->\n");
+    fprintf(xmlout,    "              <!-- Implementation will report failure during file read of <ChunkOffset> data if read entry-count disagrees. -->\n");
+  }
+  if(sampletables)
+    for (i = 0; i < (int)track->num_chunks; i++)
+      fprintf(xmlout,  "              <Chunk_Offset Num=\"%d\">%u</Chunk_Offset>\n", i+1, track->chunk[i].offset);
+  fprintf(xmlout,      "            </ChunkOffset>\n");
+
+  fprintf(xmlout,      "          </SampleTable>\n");
+}
+
+/* ------------- */
+
+int xml_out_frame(FILE* file, FILE* xmlout, mj2_sample_t *sample, unsigned int snum, opj_event_mgr_t *event_mgr)
+{
+       opj_dparameters_t parameters;   /* decompression parameters */
+  opj_image_t *img;
+  opj_cp_t *cp;
+  int i;
+  int numcomps;
+  unsigned char* frame_codestream;
+       opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */
+       opj_cio_t *cio = NULL;  
+       opj_j2k_t *j2k;
+
+       /* JPEG 2000 compressed image data */
+
+       /* get a decoder handle */
+       dinfo = opj_create_decompress(CODEC_J2K);
+
+       /* catch events using our callbacks and give a local context */
+       opj_set_event_mgr((opj_common_ptr)dinfo, event_mgr, stderr);
+
+       /* setup the decoder decoding parameters using the current image and user parameters */
+       parameters.cp_limit_decoding = DECODE_ALL_BUT_PACKETS;
+       opj_setup_decoder(dinfo, &parameters);  
+
+  frame_codestream = (unsigned char*) malloc (sample->sample_size-8); /* Skipping JP2C marker */
+  if(frame_codestream == NULL)
+         return 1;
+
+  fseek(file,sample->offset+8,SEEK_SET);
+  fread(frame_codestream,sample->sample_size-8,1, file);  /* Assuming that jp and ftyp markers size do */
+
+       /* open a byte stream */
+       cio = opj_cio_open((opj_common_ptr)dinfo, frame_codestream, sample->sample_size-8);
+
+  /* Decode J2K to image: */
+       img = opj_decode(dinfo, cio);
+  if (!img) {
+               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
+               opj_destroy_decompress(dinfo);
+               opj_cio_close(cio);
+               return 1;
+       }
+
+       j2k = (opj_j2k_t*)dinfo->j2k_handle;
+       j2k_default_tcp = j2k->default_tcp;
+       cp = j2k->cp;
+
+  numcomps = img->numcomps;
+  /*  Alignments:        "      <       To help maintain xml pretty-printing */  
+  fprintf(xmlout,      "      <JP2_Frame Num=\"%d\">\n", snum+1);
+  fprintf(xmlout,      "        <MainHeader>\n");
+  /* There can be multiple codestreams; a particular image is entirely within a single codestream */
+  /* TO DO:  A frame can be represented by two I-guess-contigious codestreams if its interleaved. */
+  fprintf(xmlout,      "          <StartOfCodestream Marker=\"SOC\" />\n");
+  /* "cp" stands for "coding parameter"; "tcp" is tile coding parameters, "tccp" is tile-component coding parameters */
+  xml_out_frame_siz(xmlout, img, cp); /* reqd in main */
+  xml_out_frame_cod(xmlout, j2k_default_tcp); /* reqd in main */
+  xml_out_frame_coc(xmlout, j2k_default_tcp, numcomps); /* opt in main, at most 1 per component */
+  xml_out_frame_qcd(xmlout, j2k_default_tcp); /* reqd in main */
+  xml_out_frame_qcc(xmlout, j2k_default_tcp, numcomps);        /* opt in main, at most 1 per component */
+  xml_out_frame_rgn(xmlout, j2k_default_tcp, numcomps); /* opt, at most 1 per component */
+  xml_out_frame_poc(xmlout, j2k_default_tcp); /*  opt (but reqd in main or tile for any progression order changes) */
+  /* Next four get j2k_default_tcp passed globally: */
+#ifdef SUPPRESS_FOR_NOW
+  xml_out_frame_ppm(xmlout, cp); /* opt (but either PPM or PPT [distributed in tile headers] or codestream packet header reqd) */
+#endif
+  xml_out_frame_tlm(xmlout); /* NO-OP.  TLM NOT SAVED IN DATA STRUCTURE */ /* opt */
+  xml_out_frame_plm(xmlout); /* NO-OP.  PLM NOT SAVED IN DATA STRUCTURE */ /* opt in main; can be used in conjunction with PLT */
+  xml_out_frame_crg(xmlout); /* NO-OP.  CRG NOT SAVED IN DATA STRUCTURE */ /* opt in main; */
+  xml_out_frame_com(xmlout, j2k_default_tcp); /* NO-OP.  COM NOT SAVED IN DATA STRUCTURE */ /* opt in main; */
+
+  fprintf(xmlout,      "        </MainHeader>\n");
+
+  /*   TO DO: all the tile headers (sigh)  */
+  fprintf(xmlout,      "        <TilePartHeaders Count=\"%d\">\n", cp->tileno_size);           /* size of the vector tileno */
+  for(i = 0; i < cp->tileno_size; i++) { /* I think cp->tileno_size will be same number as (cp->tw * cp->th) or as global j2k_curtileno */
+    // Standard seems to use zero-based # for tile-part.
+    fprintf(xmlout,    "          <TilePartHeader Num=\"%d\" ID=\"%d\">\n", i, cp->tileno[i]);                 /* ID number of the tiles present in the codestream */
+    fprintf(xmlout,    "            <StartOfTilePart Marker=\"SOT\" />\n");
+       /* All markers in tile-part headers (between SOT and SOD) are optional, unless structure requires. */
+    if(i == 0) {
+      xml_out_frame_cod(xmlout, &(cp->tcps[i])); /* No more than 1 per tile */
+      xml_out_frame_coc(xmlout, &(cp->tcps[i]), numcomps); /* No more than 1 per component */
+      xml_out_frame_qcd(xmlout, &(cp->tcps[i])); /* No more than 1 per tile */
+      xml_out_frame_qcc(xmlout, &(cp->tcps[i]), numcomps);     /* No more than 1 per component */
+      xml_out_frame_rgn(xmlout, &(cp->tcps[i]), numcomps); /* No more than 1 per component */
+    }
+    xml_out_frame_poc(xmlout, &(cp->tcps[i])); /* Reqd only if any progression order changes different from main POC */
+#ifdef SUPPRESS_FOR_NOW
+    xml_out_frame_ppt(xmlout, &(cp->tcps[i])); /* Either PPT [distributed in tile headers] or PPM or codestream packet header reqd. */
+#endif
+    xml_out_frame_plt(xmlout, &(cp->tcps[i])); /* NO-OP.  PLT NOT SAVED IN DATA STRUCTURE */ /* Can be used in conjunction with main's PLM */
+    xml_out_frame_com(xmlout, &(cp->tcps[i])); /* NO-OP.  COM NOT SAVED IN DATA STRUCTURE */
+    /* opj_tcp_t * cp->tcps; "tile coding parameters" */
+    /* Maybe not: fprintf(xmlout,  "        <>%d</>, cp->matrice[i];                   */ /* Fixed layer    */
+    fprintf(xmlout,    "            <StartOfData Marker=\"SOD\" />\n");
+    if(notes)
+      fprintf(xmlout,  "            <!-- Tile-part bitstream, not shown, follows tile-part header and SOD marker. -->\n");
+    fprintf(xmlout,    "          </TilePartHeader>\n");
+  }
+  fprintf(xmlout,      "        </TilePartHeaders>\n");                /* size of the vector tileno */
+
+#ifdef NOTYET
+  IMAGINE the cp object has data to support the following... but we could use an new different data structure instead
+  /* I'm unclear if the span of the original fread(frame_codestream...) included the following items if they're trailing. */
+  /* ALSO TO DO, BUT DATA STRUCTURE DOESN'T HANDLE YET: boxes (anywhere in file except before the Filetype box): */
+  xml_out_frame_jp2i(xmlout, &cp); /* IntellectualProperty 'jp2i' (no restrictions on location) */
+  xml_out_frame_xml(xmlout, &cp); /* XML 'xml\040' (0x786d6c20).  Can appear multiply */
+  xml_out_frame_uuid(xmlout, &cp); /* UUID 'uuid' (top level only) */
+  xml_out_frame_uinf(xmlout, &cp); /* UUIDInfo 'uinf', includes UUIDList 'ulst' and URL 'url\40' */
+#endif
+
+  fprintf(xmlout,      "      </JP2_Frame>\n");
+
+  /* Extra commentary: */
+  if(notes) {
+    fprintf(xmlout,    "      <!-- Given the number and size of components, mj2_to_frame would try to convert this -->\n");
+    if (((img->numcomps == 3) && (img->comps[0].dx == img->comps[1].dx / 2) 
+      && (img->comps[0].dx == img->comps[2].dx / 2 ) && (img->comps[0].dx == 1)) 
+      || (img->numcomps == 1)) {
+      fprintf(xmlout,  "      <!-- file to a YUV movie in the normal manner. -->\n");
+    }
+    else if ((img->numcomps == 3) && 
+      (img->comps[0].dx == 1) && (img->comps[1].dx == 1)&&
+         (img->comps[2].dx == 1))  {// If YUV 4:4:4 input --> to bmp
+         fprintf(xmlout,  "      <!-- YUV 4:4:4 file to a series of .bmp files. -->\n");
+    }
+    else {
+         fprintf(xmlout,  "      <!-- file whose image component dimension are unknown, to a series of .j2k files. -->\n");
+    }
+  }
+
+       opj_destroy_decompress(dinfo);
+       opj_cio_close(cio);
+  free(frame_codestream);
+
+  return 0;
+}
+
+/* ------------- */
+
+void int16_to_3packedchars(short int value, char* buf)
+{
+    /* This is to retrieve the 3-letter ASCII language code */
+    /* Each char is packed into 5 bits, as difference from 0x60 */
+    int i;
+    for (i = 2; i >= 0; i--)
+    {
+        buf[i] = (value & 0x001f) + 0x60;
+        value = (value >>5);
+    }
+    buf[3] = '\0';
+}
+
+/* ------------- */
+
+void xml_out_frame_siz(FILE* xmlout, opj_image_t *img, opj_cp_t *cp)
+{
+  opj_image_comp_t *comp;
+  int i;
+
+  fprintf(xmlout,    "          <ImageAndFileSize Marker=\"SIZ\">\n");
+  // This is similar to j2k.c's j2k_dump_image.
+  // Not of interest: Lsiz, Rsiz
+  fprintf(xmlout,    "            <Xsiz>%d</Xsiz>\n", img->x1);
+  fprintf(xmlout,    "            <Ysiz>%d</Ysiz>\n", img->y1);
+  if(notes)
+    fprintf(xmlout,  "            <!-- Xsiz, Ysiz is the size of the reference grid. -->\n");
+  fprintf(xmlout,    "            <XOsiz>%d</XOsiz>\n", img->x0);
+  fprintf(xmlout,    "            <YOsiz>%d</YOsiz>\n", img->y0);
+  if(notes)
+    fprintf(xmlout,  "            <!-- XOsiz, YOsiz are offsets from grid origin to image origin. -->\n");
+  fprintf(xmlout,    "            <XTsiz>%d</XTsiz>\n", cp->tdx);
+  fprintf(xmlout,    "            <YTsiz>%d</YTsiz>\n", cp->tdy);
+  if(notes)
+    fprintf(xmlout,  "            <!-- XTsiz, YTsiz is the size of one tile with respect to the grid. -->\n");
+  fprintf(xmlout,    "            <XTOsiz>%d</XTOsiz>\n", cp->tx0);
+  fprintf(xmlout,    "            <YTOsiz>%d</YTOsiz>\n", cp->ty0);
+  if(notes)
+    fprintf(xmlout,  "            <!-- XTOsiz, YTOsiz are offsets from grid origin to first tile origin. -->\n");
+  fprintf(xmlout,    "            <Csiz>%d</Csiz>\n", img->numcomps);
+  if(notes) {
+    fprintf(xmlout,  "            <!-- Csiz is the number of components in the image. -->\n");
+    fprintf(xmlout,  "            <!-- For image components next: -->\n");
+    fprintf(xmlout,  "            <!--   XRsiz, YRsiz denote pixel-sample-spacing on the grid, per Part I Annex B. -->\n");
+    //fprintf(xmlout,"            <!--   XO, YO is offset of the component compared to the whole image. -->\n");
+    fprintf(xmlout,  "            <!--   Bits per pixel (bpp) is the pixel depth. -->\n");
+    fprintf(xmlout,  "            <!--   WidthOfData and HeightOfData are calculated values, e.g.: w = roundup((Xsiz - XOsiz)/ XRsiz) -->\n");
+  }
+
+  for (i = 0; i < img->numcomps; i++) {/* image-components */
+    comp = &(img->comps[i]);
+    fprintf(xmlout,  "            <Component Num=\"%d\">\n", i+1);
+    fprintf(xmlout,  "              <Ssiz>\n");
+       if(raw)
+      fprintf(xmlout,"                <AsHex>0x%02x</AsHex>\n", (comp->sgnd << 7) & (comp->prec - 1));
+       if(derived) {
+      fprintf(xmlout,"                <Signed>%d</Signed>\n", comp->sgnd);
+      fprintf(xmlout,"                <PrecisionInBits>%d</PrecisionInBits>\n", comp->prec);
+       }
+    fprintf(xmlout,  "              </Ssiz>\n");
+    fprintf(xmlout,  "              <XRsiz>%d</XRsiz>\n", comp->dx);
+    fprintf(xmlout,  "              <YRsiz>%d</YRsiz>\n", comp->dy);
+    fprintf(xmlout,  "              <WidthOfData>%d</WidthOfData>\n", comp->w);
+    fprintf(xmlout,  "              <HeightOfData>%d</HeightOfData>\n", comp->h);
+    /* Rest of these aren't calculated when SIZ is read:
+    fprintf(xmlout,  "              <XO>%d</XO>\n", comp->x0);
+    fprintf(xmlout,  "              <YO>%d</YO>\n", comp->y0);
+       if(notes)
+         fprintf(xmlout,"              <!--  XO, YO is offset of the component compared to the whole image. -->\n");
+    fprintf(xmlout,  "              <BitsPerPixel>%d</BitsPerPixel>\n", comp->bpp);
+    fprintf(xmlout,  "              <NumberOfDecodedResolution>%d</NumberOfDecodedResolution>\n", comp->resno_decoded); */
+    // SUPPRESS: n/a to mj2_to_metadata.  fprintf(xmlout,"        <Factor>%d</Factor\n", comp->factor);
+    /* factor = number of division by 2 of the out image  compare to the original size of image */
+    // TO DO comp->data:  int *data;                   /* image-component data      */
+
+    fprintf(xmlout,  "            </Component>\n");
+  }
+  fprintf(xmlout,    "          </ImageAndFileSize>\n");
+}
+
+/* ------------- */
+
+void xml_out_frame_cod(FILE* xmlout, opj_tcp_t *tcp)
+{
+/* Could be called with tcp = &j2k_default_tcp;
+/* Or, for tile-part header, with &j2k_cp->tcps[j2k_curtileno]
+/*  Alignment for main:"          < < < <   To help maintain xml pretty-printing */  
+/*  Alignment for tile:"            < < <   To help maintain xml pretty-printing */  
+  opj_tccp_t *tccp;
+  int i;
+  char spaces[13] = "            "; /* 12 spaces if tilepart*/
+  char* s = spaces;
+  if(tcp == j2k_default_tcp) {
+    s++;s++; /* shorten s to 10 spaces if main */
+  }
+  tccp = &(tcp->tccps[0]);
+
+  fprintf(xmlout,      "%s<CodingStyleDefault Marker=\"COD\">\n",s); /* Required in main header */
+  /* Not retained or of interest: Lcod */
+  fprintf(xmlout,      "%s  <Scod>0x%02x</Scod>\n", s, tcp->csty); /* 1 byte */
+  if(notes) {
+    fprintf(xmlout,    "%s  <!-- For Scod, specific bits mean (where bit 0 is lowest or rightmost): -->\n",s);
+    fprintf(xmlout,    "%s  <!-- bit 0: Defines entropy coder precincts -->\n",s);
+    fprintf(xmlout,    "%s  <!--        0 = (PPx=15, PPy=15); 1 = precincts defined below. -->\n",s);
+    fprintf(xmlout,    "%s  <!-- bit 1: 1 = SOP marker may be used; 0 = not. -->\n",s);
+    fprintf(xmlout,    "%s  <!-- bit 2: 1 = EPH marker may be used; 0 = not. -->\n",s);
+  }
+  fprintf(xmlout,      "%s  <SGcod>\n",s);
+  fprintf(xmlout,      "%s    <ProgressionOrder>%d</ProgressionOrder>\n", s, tcp->prg); /* 1 byte, SGcod (A) */
+  if(notes) {
+    fprintf(xmlout,    "%s    <!-- Defined Progression Order Values are: -->\n",s);
+    fprintf(xmlout,    "%s    <!-- 0 = LRCP; 1 = RLCP; 2 = RPCL; 3 = PCRL; 4 = CPRL -->\n",s);
+    fprintf(xmlout,    "%s    <!-- where L = \"layer\", R = \"resolution level\", C = \"component\", P = \"position\". -->\n",s);
+  }
+  fprintf(xmlout,      "%s    <NumberOfLayers>%d</NumberOfLayers>\n", s, tcp->numlayers); /* 2 bytes, SGcod (B) */
+  fprintf(xmlout,      "%s    <MultipleComponentTransformation>%d</MultipleComponentTransformation>\n", s, tcp->mct); /* 1 byte, SGcod (C).  More or less boolean */
+  if(notes)
+    fprintf(xmlout,    "%s    <!-- For MCT, 0 = none, 1 = transform first 3 components for efficiency, per Part I Annex G -->\n",s);
+  fprintf(xmlout,      "%s  </SGcod>\n",s);
+  /* This code will compile only if declaration of j2k_default_tcp is changed from static (to implicit extern) in j2k.c */
+  fprintf(xmlout,      "%s  <SPcod>\n",s);
+  /* Internal data structure tccp defines separate defaults for each component, but they all get the same values */
+  /* So we only have to report the first component's values here. */
+  /* Compare j2k_read_cox(...) */
+  fprintf(xmlout,      "%s    <NumberOfDecompositionLevels>%d</NumberOfDecompositionLevels>\n", s, tccp->numresolutions - 1);  /* 1 byte, SPcox (D) */
+  fprintf(xmlout,      "%s    <CodeblockWidth>%d</CodeblockWidth>\n", s, tccp->cblkw - 2);     /* 1 byte, SPcox (E) */
+  fprintf(xmlout,      "%s    <CodeblockHeight>%d</CodeblockHeight>\n", s, tccp->cblkh - 2);   /* 1 byte, SPcox (F) */
+  if(notes) {
+    fprintf(xmlout,    "%s    <!-- CBW and CBH are non-negative, and summed cannot exceed 8 -->\n",s);
+    fprintf(xmlout,    "%s    <!-- Codeblock dimension is 2^(value + 2) -->\n", s);
+  }
+  fprintf(xmlout,      "%s    <CodeblockStyle>0x%02x</CodeblockStyle>\n", s, tccp->cblksty);   /* 1 byte, SPcox (G) */
+  if(notes) {
+    fprintf(xmlout,    "%s    <!-- For CodeblockStyle, bits mean (with value 1=feature on, 0=off): -->\n",s);
+    fprintf(xmlout,    "%s    <!-- bit 0: Selective arithmetic coding bypass. -->\n",s);
+    fprintf(xmlout,    "%s    <!-- bit 1: Reset context probabilities on coding pass boundaries. -->\n",s);
+    fprintf(xmlout,    "%s    <!-- bit 2: Termination on each coding pass. -->\n",s);
+    fprintf(xmlout,    "%s    <!-- bit 3: Vertically causal context. -->\n",s);
+    fprintf(xmlout,    "%s    <!-- bit 4: Predictable termination. -->\n",s);
+    fprintf(xmlout,    "%s    <!-- bit 5: Segmentation symbols are used. -->\n",s);
+  }
+  fprintf(xmlout,      "%s    <Transformation>%d</Transformation>\n", s, tccp->qmfbid);        /* 1 byte, SPcox (H) */
+  if(notes)
+    fprintf(xmlout,    "%s    <!-- For Transformation, 0=\"9-7 irreversible filter\", 1=\"5-3 reversible filter\" -->\n",s);
+  if (tccp->csty & J2K_CP_CSTY_PRT) {
+    fprintf(xmlout,    "%s    <PrecinctSize>\n",s); /* 1 byte, SPcox (I_i) */
+    if(notes)
+      fprintf(xmlout,  "%s    <!-- These are size exponents PPx and PPy. May be zero only for first level (aka N(L)LL subband)-->\n",s);
+    for (i = 0; i < tccp->numresolutions; i++) {       
+      fprintf(xmlout,  "%s      <PrecinctHeightAndWidth  ResolutionLevel=\"%d\">\n", s, i);
+         if(raw)
+        fprintf(xmlout,"%s        <AsHex>0x%02x</AsHex>\n", s, (tccp->prch[i] << 4) | tccp->prcw[i]);  /* packed into 1 byte, SPcox (G) */
+         if(derived) {
+        fprintf(xmlout,"%s        <WidthAsDecimal>%d</WidthAsDecimal>\n", s, tccp->prcw[i]);
+        fprintf(xmlout,"%s        <HeightAsDecimal>%d</HeightAsDecimal>\n", s, tccp->prch[i]);
+         }
+      fprintf(xmlout,  "%s      </PrecinctHeightAndWidth>\n", s, i);
+    }
+    fprintf(xmlout,    "%s    </PrecinctSize>\n",s); /* 1 byte, SPcox (I_i) */
+  }
+  fprintf(xmlout,      "%s  </SPcod>\n",s);
+  fprintf(xmlout,      "%s</CodingStyleDefault>\n",s);
+}
+
+/* ------------- */
+
+void xml_out_frame_coc(FILE* xmlout, opj_tcp_t *tcp, int numcomps) /* Optional in main & tile-part headers */
+{
+/* Uses global j2k_default_tcp */
+  opj_tccp_t *tccp, *firstcomp_tccp;
+  int i, compno;
+  char spaces[13] = "            "; /* 12 spaces if tilepart*/
+  char* s = spaces;
+  if(tcp == j2k_default_tcp) {
+    s++;s++; /* shorten s to 10 spaces if main */
+  }
+
+  firstcomp_tccp = &(tcp->tccps[0]);
+    /* Internal data structure tccp defines separate defaults for each component, set from main */
+       /* default, then selectively overwritten. */
+    /* Compare j2k_read_cox(...) */
+  /* We don't really know which was the default, and which were not */
+  /* Let's pretend that [0] is the default and all others are not */
+  if(notes) {
+    fprintf(xmlout,    "%s<!-- mj2_to_metadata implementation always reports component[0] as using default COD, -->\n", s);
+    if(tcp == j2k_default_tcp)
+      fprintf(xmlout,  "%s<!-- and any other component, with main-header style values different from [0], as COC. -->\n", s);
+    else
+      fprintf(xmlout,  "%s<!-- and any other component, with tile-part-header style values different from [0], as COC. -->\n", s);
+  }
+  for (compno = 1; compno < numcomps; compno++) /* spec says components are zero-based */
+  {
+    tccp = &tcp->tccps[compno];
+    if(same_component_style(firstcomp_tccp, tccp))
+               continue;
+
+/*  Alignments:          "      < < < < <   To help maintain xml pretty-printing */  
+    fprintf(xmlout,      "%s<CodingStyleComponent Marker=\"COC\">\n", s); /* Optional in main header, at most 1 per component */
+    if(notes)
+      fprintf(xmlout,    "%s  <!-- See Ccoc below for zero-based component number. -->\n", s);
+    /* Overrides the main COD for the specific component */
+    /* Not retained or of interest: Lcod */
+    fprintf(xmlout,      "%s  <Scoc>0x%02x</Scoc>\n", s, tccp->csty); /* 1 byte */
+       if(notes) {
+         fprintf(xmlout,    "%s  <!-- Scoc defines entropy coder precincts: -->\n", s);
+      fprintf(xmlout,    "%s  <!--   0 = maximum, namely (PPx=15, PPy=15); 1 = precincts defined below. -->\n", s);
+       }
+    fprintf(xmlout,      "%s  <Ccoc>%d</Ccoc>\n", s, compno); /* 1 or 2 bytes */
+    /* Unfortunately compo isn't retained in j2k_read_coc:  compno = cio_read(j2k_img->numcomps <= 256 ? 1 : 2);       /* Ccoc */
+    /*if(j2k_img_numcomps <=256)
+         component is 1 byte
+    else
+      compno is 2 byte */
+
+    /* This code will compile only if declaration of j2k_default_tcp is changed from static (to implicit extern) in j2k.c */
+    fprintf(xmlout,      "%s  <SPcoc>\n", s);
+    fprintf(xmlout,      "%s    <NumberOfDecompositionLevels>%d</NumberOfDecompositionLevels>\n", s, tccp->numresolutions - 1);        /* 1 byte, SPcox (D) */
+    fprintf(xmlout,      "%s    <CodeblockWidth>%d</CodeblockWidth>\n", s, tccp->cblkw - 2);   /* 1 byte, SPcox (E) */
+    fprintf(xmlout,      "%s    <CodeblockHeight>%d</CodeblockHeight>\n", s, tccp->cblkh - 2); /* 1 byte, SPcox (F) */
+       if(notes) {
+      fprintf(xmlout,    "%s    <!-- CBW and CBH are non-negative, and summed cannot exceed 8 -->\n", s);
+      fprintf(xmlout,    "%s    <!-- Codeblock dimension is 2^(value + 2) -->\n", s);
+       }
+    fprintf(xmlout,      "%s    <CodeblockStyle>0x%02x</CodeblockStyle>\n", s, tccp->cblksty); /* 1 byte, SPcox (G) */
+       if(notes) {
+      fprintf(xmlout,    "%s    <!-- For CodeblockStyle, bits mean (with value 1=feature on, 0=off): -->\n", s);
+      fprintf(xmlout,    "%s    <!-- bit 0: Selective arithmetic coding bypass. -->\n", s);
+      fprintf(xmlout,    "%s    <!-- bit 1: Reset context probabilities on coding pass boundaries. -->\n", s);
+      fprintf(xmlout,    "%s    <!-- bit 2: Termination on each coding pass. -->\n", s);
+      fprintf(xmlout,    "%s    <!-- bit 3: Vertically causal context. -->\n", s);
+      fprintf(xmlout,    "%s    <!-- bit 4: Predictable termination. -->\n", s);
+      fprintf(xmlout,    "%s    <!-- bit 5: Segmentation symbols are used. -->\n", s);
+       }
+    fprintf(xmlout,      "%s    <Transformation>%d</Transformation>\n", s, tccp->qmfbid);      /* 1 byte, SPcox (H) */
+    if(notes)
+      fprintf(xmlout,    "%s    <!-- For Transformation, 0=\"9-7 irreversible filter\", 1=\"5-3 reversible filter\" -->\n", s);
+    if (tccp->csty & J2K_CP_CSTY_PRT) {
+      fprintf(xmlout,    "%s    <PrecinctSize>\n", s); /* 1 byte, SPcox (I_i) */
+      if(notes)
+        fprintf(xmlout,  "%s      <!-- These are size exponents PPx and PPy. May be zero only for first level (aka N(L)LL subband)-->\n", s);
+      for (i = 0; i < tccp->numresolutions-1; i++) { /* subtract 1 to get # of decomposition levels */ 
+        fprintf(xmlout,  "%s      <PrecinctHeightAndWidth  ResolutionLevel=\"%d\">\n", s, i);
+               if(raw)
+          fprintf(xmlout,"%s        <AsHex>0x%02x</AsHex>\n", s, (tccp->prch[i] << 4) | tccp->prcw[i]);        /* packed into 1 byte, SPcox (G) */
+               if(derived) {
+          fprintf(xmlout,"%s        <WidthAsDecimal>%d</WidthAsDecimal>\n", s, tccp->prcw[i]);
+          fprintf(xmlout,"%s        <HeightAsDecimal>%d</HeightAsDecimal>\n", s, tccp->prch[i]);
+               }
+        fprintf(xmlout,  "%s      </PrecinctHeightAndWidth>\n", s, i);
+      }
+      fprintf(xmlout,    "%s    </PrecinctSize>\n", s); /* 1 byte, SPcox (I_i) */
+    }
+    fprintf(xmlout,      "%s  </SPcoc>\n", s);
+    fprintf(xmlout,      "%s</CodingStyleComponent>\n", s);
+  }
+}
+
+/* ------------- */
+
+BOOL same_component_style(opj_tccp_t *tccp1, opj_tccp_t *tccp2)
+{
+  int i;
+
+  if(tccp1->numresolutions != tccp2->numresolutions)
+         return FALSE;
+  if(tccp1->cblkw != tccp2->cblkw)
+         return FALSE;
+  if(tccp1->cblkh != tccp2->cblkh)
+         return FALSE;
+  if(tccp1->cblksty != tccp2->cblksty)
+         return FALSE;
+  if(tccp1->csty != tccp2->csty)
+         return FALSE;
+  
+  if (tccp1->csty & J2K_CP_CSTY_PRT) {
+      for (i = 0; i < tccp1->numresolutions; i++) {    
+         if(tccp1->prcw[i] != tccp2->prcw[i] || tccp1->prch[i] != tccp2->prch[i])
+                        return FALSE;
+      }
+  }
+  return TRUE;
+}
+
+/* ------------- */
+
+void xml_out_frame_qcd(FILE* xmlout, opj_tcp_t *tcp)
+{
+  /* This code will compile only if declaration of j2k_default_tcp is changed from static (to implicit extern) in j2k.c */
+  opj_tccp_t *tccp;
+  int bandno, numbands;
+  char spaces[13] = "            "; /* 12 spaces if tilepart*/
+  char* s = spaces;
+  if(tcp == j2k_default_tcp) {
+    s++;s++; /* shorten s to 10 spaces if main */
+  }
+
+  /* Compare j2k_read_qcx */
+  fprintf(xmlout,      "%s<QuantizationDefault Marker=\"QCD\">\n", s); /* Required in main header, single occurrence */
+  tccp = &(tcp->tccps[0]);
+  /* Not retained or of interest: Lqcd */
+  fprintf(xmlout,      "%s  <Sqcd>\n", s);             /* 1 byte */
+  if(notes)
+    fprintf(xmlout,    "%s  <!-- Default quantization style for all components. -->\n", s);
+  if(raw)
+    fprintf(xmlout,    "%s    <AsHex>0x%02x</AsHex>\n", s, (tccp->numgbits) << 5 | tccp->qntsty);
+  if(derived)
+    fprintf(xmlout,    "%s    <QuantizationStyle>%d</QuantizationStyle>\n", s, tccp->qntsty);
+  if(notes) {
+    fprintf(xmlout,    "%s    <!-- Quantization style (in Sqcd's low 5 bits) may be: -->\n", s);
+    fprintf(xmlout,    "%s    <!--   0 = No quantization. SPqcd size = 8 bits-->\n", s);
+    fprintf(xmlout,    "%s    <!--   1 = Scalar derived (values signaled for N(L)LL subband only). Use Eq. E.5. SPqcd size = 16. -->\n", s);
+    fprintf(xmlout,    "%s    <!--   2 = Scalar expounded (values signaled for each subband). SPqcd size = 16. -->\n", s);
+  }
+  if(derived)
+    fprintf(xmlout,    "%s    <NumberOfGuardBits>%d</NumberOfGuardBits>\n", s, tccp->numgbits);
+  if(notes)
+    fprintf(xmlout,    "%s    <!-- 0-7 guard bits allowed (stored in Sqcd's high 3 bits) -->\n", s);
+  fprintf(xmlout,      "%s  </Sqcd>\n", s);
+         
+  /* Problem: numbands in some cases is calculated from len, which is not retained or available here at this time */
+  /* So we'll just dump all internal values */
+  /* We could calculate it, but I'm having trouble believing the length equations in the standard */
+  
+  fprintf(xmlout,      "%s  <SPqcd>\n", s);
+  switch(tccp->qntsty) {
+  case J2K_CCP_QNTSTY_NOQNT: /* no quantization */
+    /* This is what standard says, but I don't believe it: len = 4 + (3*decomp); */
+    numbands = J2K_MAXBANDS; /* should be: numbands = len - 1; */
+       /* Better: IMAGINE numbands = tccp->stepsize_numbands; */
+    /* Instead look for first zero exponent, quit there.  Adequate? */
+    fprintf(xmlout,    "%s    <ReversibleStepSizeValue>\n", s);
+       if(notes) {
+      fprintf(xmlout,  "%s    <!-- Current mj2_to_metadata implementation dumps entire internal table, -->\n", s);
+         fprintf(xmlout,  "%s    <!-- until an exponent with zero value is reached. -->\n", s);
+         fprintf(xmlout,  "%s    <!-- Exponent epsilon(b) of reversible dynamic range. -->\n", s);
+         fprintf(xmlout,  "%s    <!-- Hex value is as stored, in high-order 5 bits. -->\n", s);
+       }
+    for (bandno = 0; bandno < numbands; bandno++) {
+      if(tccp->stepsizes[bandno].expn == 0)
+        break; /* Remove when we have real numbands */
+      fprintf(xmlout,  "%s      <DynamicRangeExponent Subband=\"%d\">\n", s, bandno);
+         if(raw)
+        fprintf(xmlout,"%s        <AsHex>0x%02x</AsHex>\n", s, tccp->stepsizes[bandno].expn << 3);
+         if(derived)
+        fprintf(xmlout,"%s        <AsDecimal>%d</AsDecimal>\n", s, tccp->stepsizes[bandno].expn);
+      fprintf(xmlout,  "%s      </DynamicRangeExponent>\n", s);
+    }
+    fprintf(xmlout,    "%s    </ReversibleStepSizeValue>\n", s);
+    break;
+  case J2K_CCP_QNTSTY_SIQNT:  /* scalar quantization derived */
+    /* This is what standard says.  Should I believe it:: len = 5;
+    /* numbands = 1; */
+    fprintf(xmlout,    "%s    <QuantizationStepSizeValues>\n", s);
+    if(notes)
+      fprintf(xmlout,  "%s    <!-- For irreversible transformation only.  See Part I Annex E Equation E.3 -->\n", s);
+    fprintf(xmlout,    "%s      <QuantizationValues Subband=\"0\">\n", s);
+    if(notes)
+      fprintf(xmlout,  "%s      <!-- For N(L)LL subband: >\n", s);
+       if(raw)
+      fprintf(xmlout,  "%s        <AsHex>0x%02x</AsHex>\n", s, (tccp->stepsizes[0].expn << 11) | tccp->stepsizes[0].mant);
+       if(derived) {
+      fprintf(xmlout,  "%s        <Exponent>%d</Exponent>\n", s, tccp->stepsizes[0].expn);
+      fprintf(xmlout,  "%s        <Mantissa>%d</Mantissa>\n", s, tccp->stepsizes[0].mant);
+       }
+    fprintf(xmlout,    "%s      </QuantizationValues>\n", s);
+       if(notes) {
+      fprintf(xmlout,  "%s      <!-- Exponents for subbands beyond 0 are not from header, but calculated per Eq. E.5 -->\n", s);
+      fprintf(xmlout,  "%s      <!-- The mantissa for all subbands is the same, given by the value above. -->\n", s);
+      fprintf(xmlout,  "%s      <!-- Current mj2_to_metadata implementation dumps entire internal table, -->\n", s);
+         fprintf(xmlout,  "%s      <!-- until a subband with exponent of zero value is reached. -->\n", s);
+       }
+
+    for (bandno = 1; bandno < J2K_MAXBANDS; bandno++) {
+      if(tccp->stepsizes[bandno].expn == 0)
+        break;
+
+      fprintf(xmlout,  "%s      <CalculatedExponent Subband=\"%d\">%d</CalculatedExponent>\n", s, bandno, tccp->stepsizes[bandno].expn);
+    }
+
+    fprintf(xmlout,    "%s    </QuantizationStepSizeValues>\n", s);
+    break;
+
+  default: /* J2K_CCP_QNTSTY_SEQNT */ /* scalar quantization expounded */
+    /* This is what standard says, but should I believe it: len = 5 + 6*decomp; */
+    numbands = J2K_MAXBANDS; /* should be: (len - 1) / 2;*/
+       /* Better: IMAGINE numbands = tccp->stepsize_numbands; */
+    fprintf(xmlout,    "%s    <QuantizationStepSizeValues>\n", s);
+       if(notes) {
+      fprintf(xmlout,  "%s    <!-- For irreversible transformation only.  See Part I Annex E Equation E.3 -->\n", s);
+      fprintf(xmlout,  "%s    <!-- Current mj2_to_metadata implementation dumps entire internal table, -->\n", s);
+      fprintf(xmlout,  "%s    <!-- until a subband with mantissa and exponent of zero values is reached. -->\n", s);
+    }
+    for (bandno = 0; bandno < numbands; bandno++) {
+      if(tccp->stepsizes[bandno].expn == 0 && tccp->stepsizes[bandno].mant == 0)
+        break; /* Remove when we have real numbands */
+
+      fprintf(xmlout,  "%s      <QuantizationValues Subband=\"%d\">\n", s, bandno);
+         if(raw)
+        fprintf(xmlout,"%s        <AsHex>0x%02x</AsHex>\n", s, (tccp->stepsizes[bandno].expn << 11) | tccp->stepsizes[bandno].mant);
+         if(derived) {
+        fprintf(xmlout,"%s        <Exponent>%d</Exponent>\n", s, tccp->stepsizes[bandno].expn);
+        fprintf(xmlout,"%s        <Mantissa>%d</Mantissa>\n", s, tccp->stepsizes[bandno].mant);
+         }
+      fprintf(xmlout,  "%s      </QuantizationValues>\n", s);
+    }
+    fprintf(xmlout,    "%s    </QuantizationStepSizeValues>\n", s);
+    break;
+  } /* switch */
+  fprintf(xmlout,      "%s  </SPqcd>\n", s);
+  fprintf(xmlout,      "%s</QuantizationDefault>\n", s);
+
+/*  Alignments:        "    < < < < <   To help maintain xml pretty-printing */  
+}
+
+/* ------------- */
+
+void xml_out_frame_qcc(FILE* xmlout, opj_tcp_t *tcp, int numcomps)
+{
+/* Uses global j2k_default_tcp */
+  /* This code will compile only if declaration of j2k_default_tcp is changed from static (to implicit extern) in j2k.c */
+  opj_tccp_t *tccp, *firstcomp_tccp;
+  int bandno, numbands;
+  int compno;
+  char spaces[13] = "            "; /* 12 spaces if tilepart*/
+  char* s = spaces;
+  if(tcp == j2k_default_tcp) {
+    s++;s++; /* shorten s to 10 spaces if main */
+  }
+
+  firstcomp_tccp = &(tcp->tccps[0]);
+    /* Internal data structure tccp defines separate defaults for each component, set from main */
+       /* default, then selectively overwritten. */
+    /* Compare j2k_read_qcx(...) */
+  /* We don't really know which was the default, and which were not */
+  /* Let's pretend that [0] is the default and all others are not */
+  if(notes) {
+    fprintf(xmlout,      "%s<!-- mj2_to_metadata implementation always reports component[0] as using default QCD, -->\n", s);
+    if(tcp == j2k_default_tcp)
+      fprintf(xmlout,    "%s<!-- and any other component, with main-header quantization values different from [0], as QCC. -->\n", s);
+    else
+      fprintf(xmlout,    "%s<!-- and any other component, with tile-part-header quantization values different from [0], as QCC. -->\n", s);
+  }
+  for (compno = 1; compno < numcomps; compno++) /* spec says components are zero-based */
+  {
+    tccp = &(tcp->tccps[compno]);
+    if(same_component_quantization(firstcomp_tccp, tccp))
+               continue;
+
+    /* Compare j2k_read_qcx */
+    fprintf(xmlout,      "%s<QuantizationComponent Marker=\"QCC\" Component=\"%d\">\n", s, compno); /* Required in main header, single occurrence */
+    tccp = &j2k_default_tcp->tccps[0];
+    /* Not retained or perhaps of interest: Lqcd   It maybe can be calculated.  */
+    fprintf(xmlout,      "%s  <Sqcc>\n", s);           /* 1 byte */
+    if(notes)
+      fprintf(xmlout,    "%s  <!-- Quantization style for this component. -->\n", s);
+       if(raw)
+      fprintf(xmlout,    "%s    <AsHex>0x%02x</AsHex>\n", s, (tccp->numgbits) << 5 | tccp->qntsty);
+       if(derived)
+      fprintf(xmlout,    "%s    <QuantizationStyle>%d</QuantizationStyle>\n", s, tccp->qntsty);
+       if(notes) {
+      fprintf(xmlout,    "%s    <!-- Quantization style (in Sqcc's low 5 bits) may be: -->\n", s);
+      fprintf(xmlout,    "%s    <!--   0 = No quantization. SPqcc size = 8 bits-->\n", s);
+      fprintf(xmlout,    "%s    <!--   1 = Scalar derived (values signaled for N(L)LL subband only). Use Eq. E.5. SPqcc size = 16. -->\n", s);
+      fprintf(xmlout,    "%s    <!--   2 = Scalar expounded (values signaled for each subband). SPqcc size = 16. -->\n", s);
+       }
+       if(derived)
+      fprintf(xmlout,    "%s    <NumberOfGuardBits>%d</NumberOfGuardBits>\n", s,       tccp->numgbits);
+    if(notes)
+      fprintf(xmlout,    "%s    <!-- 0-7 guard bits allowed (stored in Sqcc's high 3 bits) -->\n", s);
+    fprintf(xmlout,      "%s  </Sqcc>\n", s);
+         
+    /* Problem: numbands in some cases is calculated from len, which is not retained or available here at this time */
+    /* So we'll just dump all internal values */
+    fprintf(xmlout,      "%s  <SPqcc>\n", s);
+    switch(tccp->qntsty) {
+    case J2K_CCP_QNTSTY_NOQNT:
+      numbands = J2K_MAXBANDS; /* should be: numbands = len - 1; */
+         /* Better: IMAGINE numbands = tccp->stepsize_numbands; */
+
+      /* Instead look for first zero exponent, quit there.  Adequate? */
+      fprintf(xmlout,    "%s    <ReversibleStepSizeValue>\n", s);
+         if(notes) {
+        fprintf(xmlout,  "%s    <!-- Current mj2_to_metadata implementation dumps entire internal table, -->\n", s);
+           fprintf(xmlout,  "%s    <!-- until an exponent with zero value is reached. -->\n", s);
+           fprintf(xmlout,  "%s    <!-- Exponent epsilon(b) of reversible dynamic range. -->\n", s);
+           fprintf(xmlout,  "%s    <!-- Hex value is as stored, in high-order 5 bits. -->\n", s);
+         }
+      for (bandno = 0; bandno < numbands; bandno++) {
+        if(tccp->stepsizes[bandno].expn == 0)
+          break; /* Remove this once we have real numbands */
+        fprintf(xmlout,  "%s      <Exponent Subband=\"%d\">\n", s, bandno);
+               if(raw)
+          fprintf(xmlout,"%s        <AsHex>0x%02x</AsHex>\n", s, tccp->stepsizes[bandno].expn << 3);
+               if(derived)
+          fprintf(xmlout,"%s        <AsDecimal>%d</AsDecimal>\n", s, tccp->stepsizes[bandno].expn);
+        fprintf(xmlout,  "%s      </Exponent>\n", s);
+      }
+      fprintf(xmlout,    "%s    </ReversibleStepSizeValue>\n", s);
+      break;
+    case J2K_CCP_QNTSTY_SIQNT:
+      /* numbands = 1; */
+      fprintf(xmlout,    "%s    <QuantizationStepSizeValues>\n", s);
+      if(notes)
+        fprintf(xmlout,  "%s    <!-- For irreversible transformation only.  See Part I Annex E Equation E.3 -->\n", s);
+      fprintf(xmlout,    "%s      <QuantizationValuesForSubband0>\n", s);
+      if(notes)
+        fprintf(xmlout,  "%s      <!-- For N(L)LL subband: >\n", s);
+         if(raw)
+        fprintf(xmlout,  "%s        <AsHex>0x%02x</AsHex>\n", s, (tccp->stepsizes[0].expn << 11) | tccp->stepsizes[0].mant);
+         if(derived) {
+        fprintf(xmlout,  "%s        <Exponent>%d</Exponent>\n", s, tccp->stepsizes[0].expn);
+        fprintf(xmlout,  "%s        <Mantissa>%d</Mantissa>\n", s, tccp->stepsizes[0].mant);
+         }
+      fprintf(xmlout,    "%s      </QuantizationValuesForSubband0>\n", s);
+         if(notes) {
+        fprintf(xmlout,  "%s      <!-- Exponents for subbands beyond 0 are not from header, but calculated per Eq. E.5 -->\n", s);
+        fprintf(xmlout,  "%s      <!-- The mantissa for all subbands is the same, given by the value above. -->\n", s);
+        fprintf(xmlout,  "%s      <!-- Current mj2_to_metadata implementation dumps entire internal table, -->\n", s);
+           fprintf(xmlout,  "%s      <!-- until a subband with exponent of zero value is reached. -->\n", s);
+        }
+
+      for (bandno = 1; bandno < J2K_MAXBANDS; bandno++) {
+        if(tccp->stepsizes[bandno].expn == 0)
+          break;
+
+        fprintf(xmlout,  "%s      <CalculatedExponent Subband=\"%d\">%d</CalculatedExponent>\n", s, bandno, tccp->stepsizes[bandno].expn);
+      }
+      fprintf(xmlout,    "%s    </QuantizationStepSizeValues>\n", s);
+      break;
+
+    default: /* J2K_CCP_QNTSTY_SEQNT */
+      numbands = J2K_MAXBANDS; /* should be: (len - 1) / 2;*/
+         /* Better: IMAGINE numbands = tccp->stepsize_numbands; */
+      fprintf(xmlout,    "%s    <QuantizationStepSizeValues>\n", s);
+      if(notes) {
+        fprintf(xmlout,  "%s    <!-- For irreversible transformation only.  See Part I Annex E Equation E.3 -->\n", s);
+        fprintf(xmlout,  "%s    <!-- Current mj2_to_metadata implementation dumps entire internal table, -->\n", s);
+           fprintf(xmlout,  "%s    <!-- until a subband with mantissa and exponent of zero values is reached. -->\n", s);
+         }
+      for (bandno = 0; bandno < numbands; bandno++) {
+        if(tccp->stepsizes[bandno].expn == 0 && tccp->stepsizes[bandno].mant == 0)
+                       break; /* Remove this once we have real numbands count */
+        fprintf(xmlout,  "%s      <QuantizationValues Subband=\"%d\">\n", s, bandno);
+               if(raw)
+          fprintf(xmlout,"%s        <AsHex>0x%02x</AsHex>\n", s, (tccp->stepsizes[bandno].expn << 11) | tccp->stepsizes[bandno].mant);
+               if(derived) {
+          fprintf(xmlout,"%s        <Exponent>%d</Exponent>\n", s, tccp->stepsizes[bandno].expn);
+          fprintf(xmlout,"%s        <Mantissa>%d</Mantissa>\n", s, tccp->stepsizes[bandno].mant);
+               }
+        fprintf(xmlout,  "%s      </QuantizationValues>\n", s);
+      }
+      fprintf(xmlout,    "%s    </QuantizationStepSizeValues>\n", s);
+      break;
+    } /* switch */
+    fprintf(xmlout,      "%s  </SPqcc>\n", s);
+    fprintf(xmlout,      "%s</QuantizationComponent>\n", s);
+  }
+/*  Alignments:          "    < < < < <   To help maintain xml pretty-printing */  
+}
+
+/* ------------- */
+
+BOOL same_component_quantization(opj_tccp_t *tccp1, opj_tccp_t *tccp2)
+{
+  int bandno, numbands;
+
+  if(tccp1->qntsty != tccp2->qntsty)
+         return FALSE;
+  if(tccp1->numgbits != tccp2->numgbits)
+         return FALSE;
+
+  switch(tccp1->qntsty) {
+    case J2K_CCP_QNTSTY_NOQNT:
+      numbands = J2K_MAXBANDS; /* should be: numbands = len - 1; */
+      /* Instead look for first zero exponent, quit there.  Adequate? */
+      for (bandno = 0; bandno < numbands; bandno++) {
+        if(tccp1->stepsizes[bandno].expn == 0)
+          break;
+        if(tccp1->stepsizes[bandno].expn != tccp2->stepsizes[bandno].expn)
+         return FALSE;
+      }
+      break;
+    case J2K_CCP_QNTSTY_SIQNT:
+      /* numbands = 1; */
+      if(tccp1->stepsizes[0].expn != tccp2->stepsizes[0].expn || tccp1->stepsizes[0].mant != tccp2->stepsizes[0].mant)
+        return FALSE;
+         /* Don't need to check remainder, since they are calculated from [0] */
+      break;
+
+    default: /* J2K_CCP_QNTSTY_SEQNT */
+      numbands = J2K_MAXBANDS; /* should be: (len - 1) / 2;*/
+         /* This comparison may cause us problems with trailing junk values. */
+      for (bandno = 0; bandno < numbands; bandno++) {
+        if(tccp1->stepsizes[bandno].expn != tccp2->stepsizes[bandno].expn || tccp1->stepsizes[bandno].mant != tccp2->stepsizes[bandno].mant);
+          return FALSE;
+      }
+      break;
+    } /* switch */
+  return TRUE;
+}
+
+/* ------------- */
+
+void xml_out_frame_rgn(FILE* xmlout, opj_tcp_t *tcp, int numcomps)
+{
+  int compno, SPrgn;
+  /* MJ2 files can have regions of interest if hybridized with JPX Part II */
+  char spaces[13] = "            "; /* 12 spaces if tilepart*/
+  char* s = spaces;
+  if(tcp == j2k_default_tcp) {
+    s++;s++; /* shorten s to 10 spaces if main */
+  }
+
+  for(compno = 0; compno < numcomps; compno++) {
+    SPrgn = tcp->tccps[compno].roishift;       /* 1 byte; SPrgn */
+    if(SPrgn == 0)
+               continue; /* Yet another kludge */
+
+    fprintf(xmlout,    "%s<RegionOfInterest Marker=\"RGN\">\n", s); /* Optional in main header, at most 1 per component */
+    if(notes)
+      fprintf(xmlout,  "%s<!-- See Crgn below for zero-based component number. -->\n", s);
+    /* Not retained or of interest: Lrgd */
+    fprintf(xmlout,    "%s  <Srgn>0</Srgn>\n", s); /* 1 byte */
+    if(notes)
+         fprintf(xmlout,  "%s  <!-- Srgn is ROI style.  Only style=0 defined: Implicit ROI (max. shift) -->\n", s);
+    fprintf(xmlout,    "%s  <Crgn>%d</Crgn>\n", s, compno); /* 1 or 2 bytes */
+    fprintf(xmlout,    "%s  <SPrgn>%d</SPrgn>\n", s, SPrgn); /* 1 byte */
+    if(notes)
+      fprintf(xmlout,  "%s  <!-- SPrgn is implicit ROI shift, i.e., binary shifting of ROI coefficients above background. -->\n", s);
+    fprintf(xmlout,    "</RegionOfInterest\n", s); /* Optional in main header, at most 1 per component */
+  }
+}
+
+/* ------------- */
+
+void xml_out_frame_poc(FILE* xmlout, opj_tcp_t *tcp) { /* Progression Order Change */
+  /* Compare j2k_read_poc() */
+  int i;
+  opj_poc_t *poc;
+  char spaces[13] = "            "; /* 12 spaces if tilepart*/
+  char* s = spaces;
+  if(tcp == j2k_default_tcp) {
+    s++;s++; /* shorten s to 10 spaces if main */
+  }
+  
+  if(tcp->POC != 1)
+         return; /* Not present */
+
+  fprintf(xmlout,    "%s<ProgressionOrderChange Marker=\"POC\">\n", s); /* Optional in main header, at most 1 per component */
+  /* j2k_read_poc seems to allow accumulation of default pocs from multiple POC segments, but does
+  the spec really allow that? */
+  /* 2 bytes, not retained; Lpoc */
+  /* I probably didn't get this dump precisely right. */
+  for (i = 0; i < tcp->numpocs; i++) {
+    poc = &tcp->pocs[i];
+    fprintf(xmlout,  "%s  <Progression Num=\"%d\">\n", s, i+1);
+    fprintf(xmlout,  "%S    <RSpoc>%d</RSpoc>\n", s, poc->resno0);     /* 1 byte, RSpoc_i */
+    if(notes)
+         fprintf(xmlout,"%s    <!-- Resolution level index (inclusive) for progression start. Range: 0 to 33 -->\n", s);
+    fprintf(xmlout,  "%s    <CSpoc>%d</CSpoc>\n", s, poc->compno0);/* j2k_img->numcomps <= 256 ? 1 byte : 2 bytes; CSpoc_i */
+    if(notes)
+      fprintf(xmlout,"%s    <!-- Component index (inclusive) for progression start. -->\n", s);
+    fprintf(xmlout,  "%s    <LYEpoc>%d</LYEpoc>\n", s, poc->layno1); /* int_min(cio_read(2), tcp->numlayers);  /* 2 bytes; LYEpoc_i */
+    if(notes)
+      fprintf(xmlout,"%s    <!-- Layer index (exclusive) for progression end. -->\n", s);
+    fprintf(xmlout,  "%s    <REpoc>%d</REpoc>\n", s, poc->resno1); /*int_min(cio_read(1), tccp->numresolutions);       /* REpoc_i */
+    if(notes)
+      fprintf(xmlout,"%s    <!-- Resolution level index (exclusive) for progression end. Range: RSpoc to 33 -->\n", s);
+    fprintf(xmlout,  "%s    <CEpoc>%d</CEpoc>\n", s, poc->compno1); /* int_min(cio_read(j2k_img->numcomps <= 256 ? 1 : 2), j2k_img->numcomps); /* CEpoc_i */
+    if(notes)
+         fprintf(xmlout,"%s    <!-- Component index (exclusive) for progression end.  Minimum: CSpoc -->\n", s);
+    fprintf(xmlout,  "%s    <Ppoc>%d</Ppoc>\n", s, poc->prg); /* 1 byte Ppoc_i */
+       if(notes) {
+      fprintf(xmlout,"%s    <!-- Defined Progression Order Values are: -->\n", s);
+      fprintf(xmlout,"%s    <!-- 0 = LRCP; 1 = RLCP; 2 = RPCL; 3 = PCRL; 4 = CPRL -->\n", s);
+      fprintf(xmlout,"%s    <!-- where L = \"layer\", R = \"resolution level\", C = \"component\", P = \"position\". -->\n", s);
+       }
+    fprintf(xmlout,  "%s  </Progression>\n", s);
+  }
+  fprintf(xmlout,    "%s</ProgressionOrderChange\n", s);
+}
+
+/* ------------- */
+
+#ifdef SUPPRESS_FOR_NOW
+/* Suppress PPM and PPT since we're not showing data from the third option, namely within the codestream, and
+that's evidently what frames_to_mj2 uses.  And a hex dump isn't so useful anyway */
+
+void xml_out_frame_ppm(FILE *xmlout, opj_cp_t *cp) { /* For main header, not tile-part (which uses PPT instead). */
+/* Either the PPM or PPT is required if the packet headers are not distributed in the bit stream */
+/* Use of PPM and PPT are mutually exclusive. */
+/* Compare j2k_read_ppm() */
+  int j;
+  
+  if(cp->ppm != 1)
+         return; /* Not present */
+/* Main header uses indent of 10 spaces */
+  fprintf(xmlout,    "          <PackedPacketHeadersMainHeader Marker=\"PPM\">\n"); /* Optional in main header, but if not, must be in PPT or codestream */
+  /* 2 bytes Lppm not saved */
+  if(notes) {
+    fprintf(xmlout,  "          <!-- If there are multiple PPM marker segments in the main header, -->\n");
+    fprintf(xmlout,  "          <!-- this mj2_to_metadata implementation will report them as a single consolidated PPM header. -->\n");
+    fprintf(xmlout,  "          <!-- The implementation can't currently segregate by tile-part. -->\n");
+    fprintf(xmlout,  "          <!-- TO DO? further map the packet headers to xml. -->\n");
+  }
+  /* 1 byte, not retained ; Zppm is sequence # of this PPM header */
+  /* 4 bytes, possibly overwritten multiple times in j2k_cp->ppm_previous: Nppm */
+  /* Use j symbol for index instead of i, to make comparable with j2k_read_ppm */
+  /* Not real clear whether to use ppm->store or ppm_len as upper bound */
+  fprintf(xmlout,    "            <PackedData>\n");
+  xml_out_dump_hex(xmlout, cp->ppm_data, cp->ppm_len);
+  /* Dump packet headers 1 byte at a time: lppm[i][j] */
+  fprintf(xmlout,    "            </PackedData>\n");
+  fprintf(xmlout,    "          </PackedPacketHeadersMainHeader>\n"); /* Optional in main header, but if not, must be in PPT or codestream */
+}
+
+/* ------------- */
+
+void xml_out_frame_ppt(FILE *xmlout, opj_tcp_t *tcp) { /* For tile-part header, not main (which uses PPM instead). */
+/* Either the PPM or PPT is required if the packet headers are not distributed in the bit stream */
+/* Use of PPM and PPT are mutually exclusive. */
+/* Compare j2k_read_ppt() */
+  int j;
+  
+  if(tcp->ppt != 1)
+         return; /* Not present */
+
+  /* Tile-part indents are 12 spaces */
+  fprintf(xmlout,    "            <PackedPacketHeadersTilePartHeader Marker=\"PPT\">\n"); /* Optional in main header, but if not, must be in PPT or codestream */
+  /* 2 bytes Lppm not saved */
+  if(notes) {
+    fprintf(xmlout,  "            <!-- If there are multiple PPT marker segments in the tile-part header, -->\n");
+    fprintf(xmlout,  "            <!-- this mj2_to_metadata implementation will report them as a single consolidated PPT header. -->\n");
+    fprintf(xmlout,  "            <!-- The implementation can't currently segregate by tile-part. -->\n");
+    fprintf(xmlout,  "            <!-- TO DO? further map the packet headers to xml. -->\n");
+  }
+  /* 1 byte, not retained ; Zppt is sequence # of this PPT header */
+  /* 4 bytes, possibly overwritten multiple times in j2k_cp->ppt_previous: Nppt */
+  /* Use j symbol for index instead of i, to make comparable with j2k_read_ppt */
+  /* Not real clear whether to use ppt->store or ppt_len as upper bound */
+  fprintf(xmlout,    "              <PackedData>\n");
+  xml_out_dump_hex(xmlout, tcp->ppt_data, tcp->ppt_len);
+  /* Dump packet headers 1 byte at a time: lppt[i][j] */
+  fprintf(xmlout,    "              </PackedData>\n");
+  fprintf(xmlout,    "            </PackedPacketHeadersTileHeader>\n"); /* Optional in tile-part header, but if not, must be in PPM or codestream */
+}
+#endif SUPPRESS_FOR_NOW
+
+/* ------------- */
+
+void xml_out_frame_tlm(FILE* xmlout) { /* opt, main header only.  May be multiple. */
+/* Compare j2k_read_tlm()... which doesn't retain anything! */
+/* Plan:  Since this is only called from main header, not tilepart, use global j2k_default_tcp rather than parameter */
+/* Main header indents are 10 spaces */
+}
+
+/* ------------- */
+
+void xml_out_frame_plm(FILE* xmlout) { /* opt, main header only; can be used in conjunction with tile-part's PLT */
+/* NO-OP.  PLM NOT SAVED IN DATA STRUCTURE */
+       /* Compare j2k_read_plm()... which doesn't retain anything! */
+/* Plan:  Since this is only called from main header, not tilepart, use global j2k_default_tcp rather than parameter */
+/* Main header indents are 10 spaces */
+}
+
+/* ------------- */
+
+void xml_out_frame_plt(FILE* xmlout, opj_tcp_t *tcp) { /* opt, tile-part headers only; can be used in conjunction with main header's PLM */
+/* NO-OP.  PLT NOT SAVED IN DATA STRUCTURE */
+       /* Compare j2k_read_plt()... which doesn't retain anything! */
+/* Tile-part header indents are 12 spaces */
+}
+
+/* ------------- */
+
+void xml_out_frame_crg(FILE* xmlout) { /* NO-OP.  CRG NOT SAVED IN DATA STRUCTURE */ /* opt, main header only; */
+/* Compare j2k_read_crg()... which doesn't retain anything! */
+/* Plan:  Since this is only called from main header, not tilepart, use global j2k_default_tcp rather than parameter */
+#ifdef NOTYET
+  THIS PSEUDOCODE IMAGINES THESE EXIST: j2k_default_tcp->crg, j2k_default_tcp->crg_i, j2k_default_tcp->crg_xcrg*, j2k_default_tcp->crg_ycrg* 
+  (POSSIBLY DON'T NEED crg_i, CAN GET NUMBER OR COMPONENTS FROM ELSEWHERE)
+  if(j2k_default_tcp->crg != 1 || j2k_default_tcp->crg_i == 0)
+         return; /* Not present */
+
+/* Main header indents are 10 spaces */
+  fprintf(xmlout,    "          <ComponentRegistration Marker=\"RG\" Count=\"%d\">\n", j2k_default_tcp->crg_i);
+  if(notes) {
+    fprintf(xmlout,  "          <!-- Fine tuning of registration of components with respect to each other, -->\n");
+    fprintf(xmlout,  "          <!-- not required but potentially helpful for decoder. -->\n");
+    fprintf(xmlout,  "          <!-- These supplementary fractional offsets are in units of 1/65536 of the horizontal -->\n");
+    fprintf(xmlout,  "          <!-- or vertical separation (e.g., XRsiz[i] or YRsiz[i] for component i). -->\n");
+  }
+  /* This isn't the most compact form of table, but is OK when number of components is small, as is likely. */
+  for (i = 0; i < j2k_default_tcp->crg_i; i++) {
+    fprintf(xmlout,  "            <Component Num=\"%d\">\n", i+1);
+    fprintf(xmlout,  "              <Xcrg>\n");
+       if(raw)
+      fprintf(xmlout,"                <AsNumerator>%d</AsNumerator>\n", j2k_default_tcp->crg_xcrg[i]);
+       if(derived) {
+         /* Calculate n * 100%/65536; 4 digits after decimal point is sufficiently accurate */
+      fprintf(xmlout,"                <AsPercentage>%.4f</AsPercentage>\n", ((double)j2k_default_tcp->crg_xcrg[i])/655.36);
+         /* We could do another calculation that include XRsiz[i]; maybe later. */
+       }
+    fprintf(xmlout,  "              </Xcrg>\n");
+    fprintf(xmlout,  "              <Ycrg>\n");
+       if(raw)
+      fprintf(xmlout,"                <AsNumerator>%d</AsNumerator>\n", j2k_default_tcp->crg_ycrg[i]);
+       if(derived) {
+      fprintf(xmlout,"                <AsPercentage>%f</AsPercentage>\n", ((double)j2k_default_tcp->crg_ycrg[i])/655.36);
+       }
+    fprintf(xmlout,  "              </Ycrg>\n");
+    fprintf(xmlout,  "            </Component>\n");
+  }
+
+  fprintf(xmlout,    "          </ComponentRegistration>\n");
+
+#endif
+}
+
+/* ------------- */
+
+/* Regrettably from a metadata point of view, j2k_read_com() skips over any comments in main header or tile-part-header */
+void xml_out_frame_com(FILE* xmlout, opj_tcp_t *tcp) { /* NO-OP.  COM NOT SAVED IN DATA STRUCTURE */ /* opt in main or tile-part headers; */
+/* Compare j2k_read_com()... which doesn't retain anything! */
+#ifdef NOTYET
+  char spaces[13] = "            "; /* 12 spaces if tilepart*/
+  char* s = spaces;
+  if(tcp == &j2k_default_tcp) {
+    s++;s++; /* shorten s to 10 spaces if main */
+  }
+  THIS PSEUDOCODE IMAGINES THESE EXIST: tcp->com, tcp->com_len, tcp->com_data array 
+  if(tcp->com != 1)
+         return; /* Not present */
+
+  fprintf(xmlout,    "%s<Comment Marker=\"COM\">\n", s); /* Optional in main or tile-part header */
+  xml_out_dump_hex_and_ascii(tcp->com_data, tcp->com_len, s);
+  fprintf(xmlout,    "%s</Comment>\n", s);
+#endif
+}
+
+void xml_out_dump_hex(FILE* xmlout, char *data, int data_len, char* s) {
+  /* s is a string of spaces for indent */
+  int i;
+  
+  /* This is called when raw is true, or there is no appropriate derived form */
+  fprintf(xmlout,    "%s<AsHex>\n", s);
+  fprintf(xmlout,    "%s  ", s); /* Inadequate for pretty printing */
+  for (i = 0; i < data_len; i++) {     /* Dump packet headers */
+    fprintf(xmlout,  "%02x", data[i]);
+  }
+  fprintf(xmlout,    "%s</AsHex>\n", s);
+}
+
+/* Define this as an even number: */
+#define BYTES_PER_DUMP_LINE 40
+/* Current total width for Hex and ASCII is : 11 spaces lead + (3 * BPDL) + 2 spaces + BPDL */
+void xml_out_dump_hex_and_ascii(FILE* xmlout, char *data, int data_len, char* s) {
+  /* s is a string of spaces for indent */
+  int i,j;
+  
+  if(raw)
+    xml_out_dump_hex(xmlout, data, data_len, s);
+
+  if(derived) {
+    fprintf(xmlout,  "%s<AsHexAndASCII>\n", s);
+       for (i = 0; i < data_len; ) {
+      fprintf(xmlout,"%s ", s); /* Additional leading space added in loop */
+         /* First column: hex */
+      for (j = 0; j < BYTES_PER_DUMP_LINE; j++)        /* Dump bytes */
+        fprintf(xmlout," %02x", data[i+j]);
+      /* Space between columns... */ fprintf(xmlout,  "  ");
+         /* Second column: ASCII */
+         for (j = 0; j < BYTES_PER_DUMP_LINE; j++, i++) {
+           if(isprint((int)data[i]) && i < data_len)
+          fprintf(xmlout,"%c", data[i]);
+           else
+             fprintf(xmlout," ");
+      }
+      /* If we also wanted to output UCS-2 Unicode as a third column, then entire document
+      must use fwprintf.  Forget about it for now.  As it stands, if data is UCS-2 format but still
+      the ASCII set, then we'll be able to read every other byte as ASCII in column 2.  If
+      data is UTF-8 format but still ASCII, then we'll be able to read every byte as ASCII
+      in column 2. */
+    }
+    fprintf(xmlout,  "%s</AsHexAndASCII>\n", s);
+  }
+}
+
+
+/* ------------- */
+
+void xml_out_frame_jp2h(FILE* xmlout, opj_jp2_t *jp2_struct) {  /* JP2 Header */
+/* Compare jp2_read_jp2h(opj_jp2_t * jp2_struct) */
+  int i;
+
+  fprintf(xmlout,      "              <JP2Header BoxType=\"jp2h\">\n");
+
+/* Compare jp2_read_ihdr(jp2_struct)) */
+  fprintf(xmlout,      "                <ImageHeader BoxType=\"ihdr\">\n");
+  fprintf(xmlout,      "                  <HEIGHT>%d</HEIGHT>\n", jp2_struct->h); /* 4 bytes */
+  fprintf(xmlout,      "                  <WIDTH>%d</WIDTH>\n", jp2_struct->w); /* 4 bytes */
+  if(notes)
+    fprintf(xmlout,    "                  <!-- HEIGHT here, if 2 fields per image, is of total deinterlaced height. -->\n");
+  fprintf(xmlout,      "                  <NC>%d</NC>\n", jp2_struct->numcomps); /* 2 bytes */
+  if(notes)
+    fprintf(xmlout,    "                  <!-- NC is number of components -->\n"); /* 2 bytes */
+  fprintf(xmlout,      "                  <BPC>\n"); /* 1 byte */
+  if(jp2_struct->bpc == 255) {
+    fprintf(xmlout,    "                    <AsHex>0x%02x</AsHex>\n", jp2_struct->bpc); /* 1 byte */
+    if(notes)
+      fprintf(xmlout,  "                    <!-- BPC = 0xff means bits per pixel varies with component; see table below. -->\n");
+  } else { /* Not 0xff */
+    if(raw) {
+      fprintf(xmlout,  "                    <AsHex>0x%02x</AsHex>\n", jp2_struct->bpc); /* 1 byte */
+      if(notes)
+        fprintf(xmlout,"                    <!-- BPC = 0xff means bits per pixel varies with component; see table below. -->\n");
+       }
+    if(derived) {
+      fprintf(xmlout,  "                    <BitsPerPixel>%d</BitsPerPixel>\n", jp2_struct->bpc & 0x7f);
+      fprintf(xmlout,  "                    <Signed>%d</Signed>\n", jp2_struct->bpc >> 7);
+       }
+  }
+  fprintf(xmlout,      "                  </BPC>\n");
+  fprintf(xmlout,      "                  <C>%d</C>\n", jp2_struct->C); /* 1 byte */
+  if(notes)
+    fprintf(xmlout,    "                  <!-- C is compression type.  Only \"7\" is allowed to date. -->\n"); /* 2 bytes */
+  fprintf(xmlout,      "                  <UnkC>%d</UnkC>\n", jp2_struct->UnkC); /* 1 byte */
+  if(notes)
+    fprintf(xmlout,    "                  <!-- Colourspace Unknown. 1 = unknown, 0 = known (e.g., colourspace spec is accurate) -->\n"); /* 1 byte */
+  fprintf(xmlout,      "                  <IPR>%d</IPR>\n", jp2_struct->IPR); /* 1 byte */
+  if(notes)
+    fprintf(xmlout,    "                  <!-- IPR is 1 if frame contains an Intellectual Property box; 0 otherwise. -->\n"); /* 2 bytes */
+  fprintf(xmlout,      "                </ImageHeader>\n");
+
+  if (jp2_struct->bpc == 255)
+  {
+    fprintf(xmlout,    "                <BitsPerComponent BoxType=\"bpcc\">\n");
+    if(notes)
+      fprintf(xmlout,  "                <!-- Pixel depth (range 1 to 38) is low 7 bits of hex value + 1 -->\n");
+       /* Bits per pixel varies with components */
+    /* Compare jp2_read_bpcc(jp2_struct) */
+       for (i = 0; i < (int)jp2_struct->numcomps; i++) {
+         if(raw)
+        fprintf(xmlout,"                  <AsHex>0x%02x</AsHex>\n", jp2_struct->comps[i].bpcc); /* 1 byte */
+         if(derived) {
+        fprintf(xmlout,"                  <BitsPerPixel>%d</BitsPerPixel>\n", (jp2_struct->comps[i].bpcc & 0x7f)+1);
+        fprintf(xmlout,"                  <Signed>%d</Signed>\n", jp2_struct->comps[i].bpcc >> 7);
+         }
+       }
+    fprintf(xmlout,    "                </BitsPerComponent>\n");
+  }
+
+  /* Compare jp2_read_colr(jp2_struct) */
+  fprintf(xmlout,      "                <ColourSpecification BoxType=\"colr\">\n");
+  fprintf(xmlout,      "                  <METH>%d</METH>\n", jp2_struct->meth); /* 1 byte */
+  if(notes) {
+    fprintf(xmlout,    "                  <!-- Valid values of specification method so far: -->\n");
+    fprintf(xmlout,    "                  <!--   1 = Enumerated colourspace, in EnumCS field -->\n");
+    fprintf(xmlout,    "                  <!--   2 = Restricted ICC Profile, in PROFILE field -->\n");
+  }
+  fprintf(xmlout,      "                  <PREC>%d</PREC>\n", jp2_struct->precedence); /* 1 byte */
+  if(notes)
+    fprintf(xmlout,    "                  <!-- 0 is only valid value of precedence so far. -->\n");
+  fprintf(xmlout,      "                  <APPROX>%d</APPROX>\n", jp2_struct->approx); /* 1 byte */
+  if(notes)
+    fprintf(xmlout,    "                  <!-- 0 is only valid value of colourspace approximation so far. -->\n");
+
+  if (jp2_struct->meth == 1) {
+    fprintf(xmlout,    "                  <EnumCS>%d</EnumCS>\n", jp2_struct->enumcs); /* 4 bytes */
+       if(notes) {
+         fprintf(xmlout,  "                  <!-- Valid values of enumerated MJ2 colourspace so far: -->\n");
+         fprintf(xmlout,  "                  <!--   16: sRGB as defined by IEC 61966-2-1. -->\n");
+         fprintf(xmlout,  "                  <!--   17: greyscale (related to sRGB). -->\n");
+         fprintf(xmlout,  "                  <!--   18: sRGB YCC (from JPEG 2000 Part II). -->\n");
+         fprintf(xmlout,  "                  <!-- (Additional JPX values are defined in Part II). -->\n");
+       }
+  }
+  else
+    if(notes)
+      fprintf(xmlout,  "                  <!-- PROFILE is not handled by current OpenJPEG implementation. -->\n");
+    /* only 1 byte is read and nothing stored */
+  fprintf(xmlout,      "                </ColourSpecification>\n");
+
+  /* TO DO?  No OpenJPEG support.
+  Palette 'pclr'
+  ComponentMapping 'cmap'
+  ChannelDefinition 'cdef'
+  Resolution 'res'
+  */
+  fprintf(xmlout,      "              </JP2Header>\n");
+}
+/* ------------- */
+
+#ifdef NOTYET
+IMAGE these use cp structure, extended... but we could use a new data structure instead
+void xml_out_frame_jp2i(FILE* xmlout, opj_cp_t *cp) {
+  /* IntellectualProperty 'jp2i' (no restrictions on location) */
+  int i;
+  IMAGE cp->jp2i, cp->jp2i_count, cp->jp2i_data (array of chars), cp->cp2i_len (array of ints)
+  if(cp->jp2i != 1)
+         return; /* Not present */
+
+  for(i = 0; i < cp->jp2i_count; i++)
+  {
+    fprintf(xmlout,      "            <IntellectualProperty BoxType=\"jp2i\">\n");
+  /* I think this can be anything, including binary, so do a dump */
+    /* Is it better to indent or not indent this content?  Indent is better for reading, but
+    worse for cut/paste. */
+    xml_out_dump_hex_and_ascii(xmlout, cp->jp2i_data[i], cp->jp2i_len[i]);
+    fprintf(xmlout,      "            </IntellectualProperty>\n");
+  }
+}
+
+void xml_out_frame_xml(FILE* xmlout, opj_cp_t *cp) {
+  /* XML 'xml\040' (0x786d6c20).  Can appear multiply, before or after jp2c codestreams */
+  IMAGE cp->xml, cp->xml_count, cp->xml_data (array of chars)
+  MAYBE WE DON'T NEED cp->xml_len (array of ints) IF WE ASSUME xml_data IS NULL-TERMINATED.
+  ASSUME ASSUME EACH LINE IS ENDED BY \n.
+  int i;
+  if(cp->xml != 1)
+         return; /* Not present */
+
+  for(i = 0; i < cp->xml_count; i++)
+  {
+    fprintf(xmlout,      "            <TextFormXML BoxType=\"xml[space]" Instance=\"%d\">\n", i+1);
+    /* Is it better to indent or not indent this content?  Indent is better for reading, but
+    worse for cut/paste. Being lazy, didn't indent here. */
+    fprintf(xmlout,cp->xml_data[i]); /* May be multiple lines */ /* Could check if this is well-formed */
+    fprintf(xmlout,      "            </TextFormXML>\n");
+  }
+}
+
+void xml_out_frame_uuid(FILE* xmlout, opj_cp_t *cp) {
+       /* UUID 'uuid' (top level only) */
+       /* Part I 1.7.2 says: may appear multiply in JP2 file, anywhere except before File Type box */
+       /* Part III 5.2.1 says: Private extensions shall be achieved through the 'uuid' type. */
+       /* A UUID is a 16-byte value.  There is a conventional string representation for it:
+          "0x12345678-9ABC-DEF0-1234-567890ABCDEF".  Let's assume that is what is stored in uuid_value */
+
+       /* Part III 6.1 Any other MJ2 box type could be alternatively written as a 'uuid' box, with value given
+          as : 0xXXXXXXXX-0011-0010-8000-00AA00389B71, where the Xs are the boxtype in hex.  However,
+          such a file is "not compliant; systems may choose to read [such] objects ... as equivalent to the box of
+          the same type, or not."  Here, we choose not to. */
+  int i;
+  IMAGE cp->uuid, cp->uuid_count, cp->uuid_value (array of uuids... let's say fixed-length strings) cp->uuid_data (array of char buffers), cp->uuid_len (array of ints)
+  if(cp->juuid != 1)
+         return; /* Not present */
+
+  for(i = 0; i < cp->uuid_count; i++)
+  {
+    fprintf(xmlout,      "            <UniversalUniqueID BoxType=\"uuid\">
+       fprintf(xmlout,      "              <UUID>%s</UUDI>\n", cp->uuid_value[i]);
+       fprintf(xmlout,      "              <Data>\n");
+  /* I think this can be anything, including binary, so do a dump */
+    /* Is it better to indent or not indent this content?  Indent is better for reading, but
+    worse for cut/paste. */
+    xml_out_dump_hex_and_ascii(xmlout, cp->uuid_data[i], cp->uuid_len[i]);
+       fprintf(xmlout,      "              </Data>\n");
+    fprintf(xmlout,      "            </UniversalUniqueID>\n");
+  }
+}
+
+void xml_out_frame_uinf(FILE* xmlout, opj_cp_t *cp) {
+       /* UUIDInfo 'uinf', includes UUIDList 'ulst' and URL 'url\40' */
+       /* Part I 1.7.3 says: may appear multiply in JP2 file, anywhere at the top level except before File Type box */
+       /* So there may be multiple ulst's, and each can have multiple UUIDs listed (with a single URL) */
+       /* This is not quite as vendor-specific as UUIDs, or at least is meant to be generally readable */
+       /* Assume UUIDs stored in canonical string format */
+  int i, j;
+  IMAGE cp->uinf, cp->uinf_count, cp->uinf_ulst_nu (array of ints)
+    cp->uinf_uuid (2 dimensional array of uuids... let's say fixed-length strings),
+    cp->uinf_url (array of char buffers)
+
+  if(cp->uinf != 1)
+         return; /* Not present */
+
+  for(i = 0; i < cp->uuid_count; i++)
+  {
+    fprintf(xmlout,      "            <UUIDInfo BoxType=\"uinf\">\n");
+    fprintf(xmlout,      "              <UUIDList BoxType=\"ulst\" Count=\"%d\">\n",cp->cp->uinf_ulst_nu[i]);
+       for(j = 0; j < cp->uinf_ulst_nu[i];  j++)
+         fprintf(xmlout,    "              <ID Instance=\"%s\">%s</ID>\n", cp->uuif_uuid[i][j], j+1);
+    fprintf(xmlout,      "              </UUIDList>\n");
+       fprintf(xmlout,      "              <DataEntryURL>\n");
+       /* Could add VERS and FLAG here */
+       fprintf(xmlout,      "                <LOC>\n");
+    fprintf(xmlout,      "                  %s",cp->uinf_url[i]); /* Probably single line, so indent works */ /* In theory, could check if this is well-formed, or good live link */
+       fprintf(xmlout,      "                </LOC>\n");
+       fprintf(xmlout,      "              </DataEntryURL>\n");
+    fprintf(xmlout,      "            </UUIDInfo>\n");
+  }
+}
+
+IMAGE these use cp structure, extended... but we could use a new data structure instead
+void xml_out_frame_unknown_type(FILE* xmlout, opj_cp_t *cp) {
+  /* Part III 5.2.1 says "Type fields not defined here are reserved.  Private extensions
+     shall be acieved through the 'uuid' type." [This implies an unknown
+     type would be an error, but then...] "Boxes not explicitly defined in this standard,
+        or otherwise unrecognized by a reader, may be ignored."
+        Also, it says  "the following types are not and will not be used, or used only in
+        their existing sense, in future versions of this specification, to avoid conflict
+        with existing content using earlier pre-standard versions of this format:
+          clip, crgn, matt, kmat, pnot, ctab, load, imap;
+          track reference types tmcd, chap, sync,scpt, ssrc"
+        [But good luck figuring out the mapping.]
+        Part III Amend. 2 4.1 is stronger: "All these specifications [of this family, e.g.,
+        JP2 Part I, ISO Base format (Part 12) leading to MP4, Quicktime, and possibly including
+        MJ2] require that readers ignore objects that are unrecognizable to them".
+        */
+  int i;
+  IMAGE cp->unknown_type, cp->unknown_type_count, cp->unknown_type_boxtype (array of buf[5]s), cp->unknown_type_data (array of chars), cp->unknown_type_len (array of ints)
+  if(cp->unknown_type != 1)
+         return; /* Not present */
+
+  for(i = 0; i < cp->unknown_type_count; i++)
+  {
+    fprintf(xmlout,      "            <UnknownType BoxType=\"%s\">\n", cp->unknown_type_boxtype[i]);
+    /* Can be anything, including binary, so do a dump */
+    /* Is it better to indent or not indent this content?  Indent is better for reading, but
+    worse for cut/paste. */
+    xml_out_dump_hex_and_ascii(xmlout, cp->unknown_type_data[i], cp->unknown_type_len[i]);
+    fprintf(xmlout,      "            </UnknownType>\n");
+  }
+}
+
+#endif
diff --git a/applications/mj2/meta_out.h b/applications/mj2/meta_out.h
new file mode 100644 (file)
index 0000000..293316d
--- /dev/null
@@ -0,0 +1,13 @@
+/* meta_out.h */
+/* Dump MJ2, JP2 metadata (partial so far) to xml file */
+/* Callable from mj2_to_metadata */
+/* Contributed to Open JPEG by Glenn Pearson, U.S. National Library of Medicine */
+
+#define BOOL int
+#define FALSE 0
+#define TRUE 1
+
+void xml_write_init(BOOL n, BOOL t, BOOL r, BOOL d);
+
+int xml_write_struct(FILE *file, FILE *xmlout, opj_mj2_t * movie, unsigned int sampleframe, char* stringDTD, opj_event_mgr_t *event_mgr);
+
diff --git a/applications/mj2/mj2.c b/applications/mj2/mj2.c
new file mode 100644 (file)
index 0000000..131eace
--- /dev/null
@@ -0,0 +1,2922 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux 
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "../libopenjpeg/opj_includes.h"
+#include "mj2.h"
+
+/** @defgroup JP2 JP2 - JPEG-2000 file format reader/writer */
+/*@{*/
+
+/** @name Local static functions */
+/*@{*/
+
+/**
+Read box headers
+@param cinfo Codec context info
+@param cio Input stream
+@param box
+@return Returns true if successful, returns false otherwise
+*/
+/*-- UNUSED
+static bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_box_t *box);
+--*/
+/*
+* 
+* Read box headers
+*
+*/
+
+int mj2_read_boxhdr(mj2_box_t * box, opj_cio_t *cio)
+{
+  box->init_pos = cio_tell(cio);
+  box->length = cio_read(cio, 4);
+  box->type = cio_read(cio, 4);
+  if (box->length == 1) {
+    if (cio_read(cio, 4) != 0) {
+      opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Cannot handle box sizes higher than 2^32\n");
+      return 1;
+    };
+    box->length = cio_read(cio, 4);
+    if (box->length == 0) 
+      box->length = cio_numbytesleft(cio) + 12;
+  }
+  else if (box->length == 0) {
+    box->length = cio_numbytesleft(cio) + 8;
+  }
+  return 0;
+}
+
+/*
+* 
+* Initialisation of a Standard Movie, given a simple movie structure defined by the user 
+* The movie will have one sample per chunk
+* 
+* Arguments: opj_mj2_t * movie
+* Several variables of "movie" must be defined in order to enable a correct execution of 
+* this function:
+*   - The number of tracks of each type (movie->num_vtk, movie->num_stk, movie->num_htk)
+*   - The memory for each must be allocated (movie->tk)
+*   - For each track:
+*        The track type (tk->track_type)
+*        The number of sample (tk->num_samples)
+*        The sample rate (tk->sample_rate)
+*
+*/
+
+int mj2_init_stdmovie(opj_mj2_t * movie)
+{
+  mj2_tk_t *tk0;
+  int i, w, h, prec;
+  unsigned int j;
+  time_t ltime;
+       
+  movie->brand = MJ2_MJ2;
+  movie->minversion = 0;
+  movie->num_cl = 2;
+  movie->cl = (unsigned int*) opj_malloc(movie->num_cl * sizeof(unsigned int));
+
+  movie->cl[0] = MJ2_MJ2;
+  movie->cl[1] = MJ2_MJ2S;
+  time(&ltime);                        /* Time since 1/1/70 */
+  movie->creation_time = (unsigned int) ltime + 2082844800;    /* Seconds between 1/1/04 and 1/1/70 */
+  movie->timescale = 1000;
+       
+  movie->rate = 1 << 16;               /* Rate to play presentation  (default = 0x00010000)          */
+  movie->volume = 1 << 8;              /* Movie volume (default = 0x0100)                            */
+  movie->trans_matrix[0] = 0x00010000; /* Transformation matrix for video                            */
+  movie->trans_matrix[1] = 0;  /* Unity is { 0x00010000,0,0,0,0x00010000,0,0,0,0x40000000 }  */
+  movie->trans_matrix[2] = 0;
+  movie->trans_matrix[3] = 0;
+  movie->trans_matrix[4] = 0x00010000;
+  movie->trans_matrix[5] = 0;
+  movie->trans_matrix[6] = 0;
+  movie->trans_matrix[7] = 0;
+  movie->trans_matrix[8] = 0x40000000;
+  movie->next_tk_id = 1;
+
+  tk0 = &movie->tk[0];
+  w = tk0->w; h = tk0->h; prec = tk0->depth;
+
+       for (i = 0; i < movie->num_htk + movie->num_stk + movie->num_vtk; i++) 
+   {
+    mj2_tk_t *tk = &movie->tk[i];
+
+    movie->next_tk_id++;
+    tk->jp2_struct.comps = NULL;
+    tk->jp2_struct.cl = NULL;
+  
+    if (tk->track_type == 0) /* no sound or hint track */
+   {
+    if (tk->num_samples == 0)
+                               return 1;
+                       
+    tk->w = w; tk->h = h; tk->depth = prec;
+      tk->Dim[0] = 0;
+      tk->Dim[1] = 0;
+                       
+      tk->timescale = 1000;    /* Timescale = 1 ms                                          */
+                       
+      tk->chunk[0].num_samples = 1;
+      tk->chunk[0].sample_descr_idx = 1;
+                       
+      tk->same_sample_size = 0;
+                       
+      tk->num_samplestochunk = 1;      /* One sample per chunk  */
+               tk->sampletochunk = (mj2_sampletochunk_t*) opj_malloc(tk->num_samplestochunk * sizeof(mj2_sampletochunk_t));
+      tk->sampletochunk[0].first_chunk = 1;
+      tk->sampletochunk[0].samples_per_chunk = 1;
+      tk->sampletochunk[0].sample_descr_idx = 1;
+      
+      if (tk->sample_rate == 0) 
+  {
+       opj_event_msg(tk->cinfo, EVT_ERROR,
+       "Error while initializing MJ2 movie: Sample rate of track"
+       " %d must be different from zero\n", tk->track_ID);
+       return 1;
+  }
+                       
+      for (j = 0; j < tk->num_samples; j++) 
+  {
+       tk->sample[j].sample_delta = tk->timescale / tk->sample_rate;
+  }
+                       
+      tk->num_tts = 1;
+               tk->tts = (mj2_tts_t*) opj_malloc(tk->num_tts * sizeof(mj2_tts_t));
+      tk->tts[0].sample_count = tk->num_samples;
+      tk->tts[0].sample_delta = tk->timescale / tk->sample_rate;
+                       
+      tk->horizresolution = 0x00480000;        /* Horizontal resolution (typically 72)                       */
+      tk->vertresolution = 0x00480000; /* Vertical resolution (typically 72)                         */
+      tk->compressorname[0] = 0x0f4d6f74;      /* Compressor Name[]: Motion JPEG2000                         */
+      tk->compressorname[1] = 0x696f6e20;
+      tk->compressorname[2] = 0x4a504547;
+      tk->compressorname[3] = 0x32303030;
+      tk->compressorname[4] = 0x00120000;
+      tk->compressorname[5] = 0;
+      tk->compressorname[6] = 0x00000042;
+      tk->compressorname[7] = 0x000000DC;
+      tk->num_url = 0;         /* Number of URL                                              */
+      tk->num_urn = 0;         /* Number of URN                                              */
+      tk->graphicsmode = 0;    /* Graphicsmode                                               */
+      tk->opcolor[0] = 0;      /* OpColor                                                    */
+      tk->opcolor[1] = 0;      /* OpColor                                                    */
+      tk->opcolor[2] = 0;      /* OpColor                                                    */
+      tk->creation_time = movie->creation_time;        /* Seconds between 1/1/04 and 1/1/70          */
+      tk->language = 0;                /* Language (undefined)                                       */
+      tk->layer = 0;
+      tk->volume = 1 << 8;             /* Movie volume (default = 0x0100) */
+      tk->trans_matrix[0] = 0x00010000;        /* Transformation matrix for track */
+      tk->trans_matrix[1] = 0; /* Unity is { 0x00010000,0,0,0,0x00010000,0,0,0,0x40000000 }  */
+      tk->trans_matrix[2] = 0;
+      tk->trans_matrix[3] = 0;
+      tk->trans_matrix[4] = 0x00010000;
+      tk->trans_matrix[5] = 0;
+      tk->trans_matrix[6] = 0;
+      tk->trans_matrix[7] = 0;
+      tk->trans_matrix[8] = 0x40000000;
+      tk->fieldcount = 1;
+      tk->fieldorder = 0;
+      tk->or_fieldcount = 1;
+      tk->or_fieldorder = 0;
+      tk->num_br = 2;
+               tk->br = (unsigned int*) opj_malloc(tk->num_br * sizeof(unsigned int));
+      tk->br[0] = MJ2_JP2;
+      tk->br[1] = MJ2_J2P0;
+      tk->num_jp2x = 0;
+      tk->hsub = 2;            /* 4:2:0                                                      */
+      tk->vsub = 2;            /* 4:2:0                                                      */
+      tk->hoff = 0;
+      tk->voff = 0;
+      tk->visual_w = tk->w << 16;
+      tk->visual_h = tk->h << 16;
+    }
+    else {
+      tk->num_br = 0;
+      tk->jp2xdata = NULL;
+    }
+  }
+  return 0;
+}
+
+/*
+* Time To Sample box Decompact
+*
+*/
+void mj2_tts_decompact(mj2_tk_t * tk)
+{
+  int i, j;
+  tk->num_samples = 0;
+  for (i = 0; i < tk->num_tts; i++) {
+    tk->num_samples += tk->tts[i].sample_count;
+  }
+
+  tk->sample = (mj2_sample_t*) opj_malloc(tk->num_samples * sizeof(mj2_sample_t));
+
+  for (i = 0; i < tk->num_tts; i++) {
+    for (j = 0; j < tk->tts[i].sample_count; j++) {
+      tk->sample[j].sample_delta = tk->tts[i].sample_delta;
+    }
+  }
+}
+
+/*
+* Sample To Chunk box Decompact
+*
+*/
+void mj2_stsc_decompact(mj2_tk_t * tk)
+{
+  int j, i;
+  unsigned int k;
+  int sampleno=0;
+  
+  if (tk->num_samplestochunk == 1) {
+    tk->num_chunks =
+      (unsigned int) ceil((double) tk->num_samples /
+      (double) tk->sampletochunk[0].samples_per_chunk);
+        tk->chunk = (mj2_chunk_t*) opj_malloc(tk->num_chunks * sizeof(mj2_chunk_t));
+    for (k = 0; k < tk->num_chunks; k++) {
+      tk->chunk[k].num_samples = tk->sampletochunk[0].samples_per_chunk;
+    }
+    
+  } else {
+    tk->chunk = (mj2_chunk_t*) opj_malloc(tk->num_samples * sizeof(mj2_chunk_t));
+    tk->num_chunks = 0;
+    for (i = 0; i < tk->num_samplestochunk -1 ; i++) {
+      for (j = tk->sampletochunk[i].first_chunk - 1;
+      j < tk->sampletochunk[i + 1].first_chunk - 1; j++) {
+                               tk->chunk[j].num_samples = tk->sampletochunk[i].samples_per_chunk;
+                               tk->num_chunks++;
+                               sampleno += tk->chunk[j].num_samples;
+      }
+    }
+    tk->num_chunks += (int)(tk->num_samples  - sampleno) / tk->sampletochunk[tk->num_samplestochunk - 1].samples_per_chunk;
+    for (k = tk->sampletochunk[tk->num_samplestochunk - 1].first_chunk - 1;
+    k < tk->num_chunks; k++) {
+      tk->chunk[k].num_samples =
+                               tk->sampletochunk[tk->num_samplestochunk - 1].samples_per_chunk;
+    }
+    tk->chunk = (mj2_chunk_t*)
+        opj_realloc(tk->chunk, tk->num_chunks * sizeof(mj2_chunk_t));
+  }
+  
+}
+
+
+/*
+* Chunk offset box Decompact
+*
+*/
+void mj2_stco_decompact(mj2_tk_t * tk)
+{
+  int j;
+  unsigned int i;
+  int k = 0;
+  int intra_chunk_offset;
+       
+  for (i = 0; i < tk->num_chunks; i++) {
+    intra_chunk_offset = 0;
+    for (j = 0; j < tk->chunk[i].num_samples; j++) {
+      tk->sample[k].offset = intra_chunk_offset + tk->chunk[i].offset;
+      intra_chunk_offset += tk->sample[k].sample_size;
+      k++;
+    }
+  }
+}
+
+/*
+* Write the JP box
+*
+* JP Signature box
+*
+*/
+void mj2_write_jp(opj_cio_t *cio)
+{
+  mj2_box_t box;
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+       
+  cio_write(cio, MJ2_JP, 4);           /* JP */
+  cio_write(cio, 0x0d0a870a, 4);       /* 0x0d0a870a required in a JP box */
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the JP box
+*
+* JPEG 2000 signature
+*
+*/
+int mj2_read_jp(opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_JP != box.type) {    /* Check Marker */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected JP Marker\n");
+    return 1;
+  }
+  if (0x0d0a870a != cio_read(cio, 4)) {        /* read the 0x0d0a870a required in a JP box */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with JP Marker\n");
+    return 1;
+  }
+  if (cio_tell(cio) - box.init_pos != box.length) {    /* Check box length */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with JP Box size \n");
+    return 1;
+  }
+  return 0;
+       
+}
+
+/*
+* Write the FTYP box
+*
+* File type box
+*
+*/
+void mj2_write_ftyp(opj_mj2_t * movie, opj_cio_t *cio)
+{
+  int i;
+  mj2_box_t box;
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+       
+  cio_write(cio, MJ2_FTYP, 4); /* FTYP       */
+  cio_write(cio, movie->brand, 4);     /* BR         */
+  cio_write(cio, movie->minversion, 4);        /* MinV       */
+       
+  for (i = 0; i < movie->num_cl; i++)
+    cio_write(cio, movie->cl[i], 4);   /* CL         */
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* Length     */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the FTYP box
+*
+* File type box
+*
+*/
+int mj2_read_ftyp(opj_mj2_t * movie, opj_cio_t *cio)
+{
+  int i;
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);  /* Box Size */
+  if (MJ2_FTYP != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected FTYP Marker\n");
+    return 1;
+  }
+       
+  movie->brand = cio_read(cio, 4);     /* BR              */
+  movie->minversion = cio_read(cio, 4);        /* MinV            */
+  movie->num_cl = (box.length - 16) / 4;
+  movie->cl = (unsigned int*) opj_malloc(movie->num_cl * sizeof(unsigned int));
+
+  for (i = movie->num_cl - 1; i > -1; i--)
+    movie->cl[i] = cio_read(cio, 4);   /* CLi */
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with FTYP Box\n");
+    return 1;
+  }
+  return 0;
+}
+
+
+/*
+* Write the STCO box
+*
+* Chunk Offset Box
+*
+*/
+void mj2_write_stco(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+  unsigned int i;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_STCO, 4); /* STCO       */
+       
+  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
+       
+  cio_write(cio, tk->num_chunks, 4);   /* Entry Count */
+       
+  for (i = 0; i < tk->num_chunks; i++) {
+    cio_write(cio, tk->chunk[i].offset, 4);    /* Entry offset */
+  }
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the STCO box
+*
+* Chunk Offset Box
+*
+*/
+int mj2_read_stco(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  unsigned int i;
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);  /* Box Size */
+  if (MJ2_STCO != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected STCO Marker\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in STCO box\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in STCO box. Expected flag 0\n");
+    return 1;
+  }
+       
+       
+  if (cio_read(cio, 4) != tk->num_chunks) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, 
+                       "Error in STCO box: expecting same amount of entry-count as chunks \n");
+  } else {
+    for (i = 0; i < tk->num_chunks; i++) {
+      tk->chunk[i].offset = cio_read(cio, 4);  /* Entry offset */
+    }
+  }
+       
+  mj2_stco_decompact(tk);
+       
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with STCO Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the STSZ box
+*
+* Sample size box
+*
+*/
+void mj2_write_stsz(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+  unsigned int i;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_STSZ, 4); /* STSZ       */
+       
+  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
+       
+  if (tk->same_sample_size == 1) {     /* If they all have the same size */
+    cio_write(cio, tk->sample[0].sample_size, 4);      /* Size */
+               
+    cio_write(cio, 1, 4);              /* Entry count = 1 */
+  }
+       
+  else {
+    cio_write(cio, 0, 4);              /* Sample Size = 0 becase they all have different sizes */
+               
+    cio_write(cio, tk->num_samples, 4);        /* Sample Count */
+               
+    for (i = 0; i < tk->num_samples; i++) {
+      cio_write(cio, tk->sample[i].sample_size, 4);
+    }
+  }
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the STSZ box
+*
+* Sample size box
+*
+*/
+int mj2_read_stsz(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  int sample_size;
+  unsigned int i;
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);  /* Box Size */
+  if (MJ2_STSZ != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected STSZ Marker\n");
+    return 1;
+  }
+       
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in STSZ box\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in STSZ box. Expected flag 0\n");
+    return 1;
+  }
+       
+  sample_size = cio_read(cio, 4);
+       
+  if (sample_size != 0) {      /* Samples do have the same size */
+    tk->same_sample_size = 1;
+    for (i = 0; i < tk->num_samples; i++) {
+      tk->sample[i].sample_size = sample_size;
+    }
+    cio_skip(cio,4);           /* Sample count = 1 */
+  } else {
+    tk->same_sample_size = 0;
+    if (tk->num_samples != cio_read(cio, 4)) { /* Sample count */
+      opj_event_msg(cio->cinfo, EVT_ERROR,
+                               "Error in STSZ box. Expected that sample-count is number of samples in track\n");
+      return 1;
+    }
+    for (i = 0; i < tk->num_samples; i++) {
+      tk->sample[i].sample_size = cio_read(cio, 4);    /* Sample Size */
+    }
+               
+    if (cio_tell(cio) - box.init_pos != box.length) {
+      opj_event_msg(cio->cinfo, EVT_ERROR, "Error with STSZ Box size\n");
+      return 1;
+    }
+  }
+  return 0;
+       
+}
+
+/*
+* Write the STSC box
+*
+* Sample to Chunk
+*
+*/
+void mj2_write_stsc(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  int i;
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_STSC, 4); /* STSC       */
+       
+  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
+       
+  cio_write(cio, tk->num_samplestochunk, 4);   /* Entry Count */
+       
+  for (i = 0; i < tk->num_samplestochunk; i++) {
+    cio_write(cio, tk->sampletochunk[i].first_chunk, 4);       /* First Chunk */
+    cio_write(cio, tk->sampletochunk[i].samples_per_chunk, 4); /* Samples per chunk */
+    cio_write(cio, tk->sampletochunk[i].sample_descr_idx, 4);  /* Samples description index */
+  }
+       
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the STSC box
+*
+* Sample to Chunk
+*
+*/
+int mj2_read_stsc(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  int i;
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);  /* Box Size */
+  if (MJ2_STSC != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected STSC Marker\n");
+    return 1;
+  }
+       
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in STSC box\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in STSC box. Expected flag 0\n");
+    return 1;
+  }
+       
+  tk->num_samplestochunk = cio_read(cio, 4);
+
+  tk->sampletochunk = (mj2_sampletochunk_t*) opj_malloc(tk->num_samplestochunk * sizeof(mj2_sampletochunk_t));
+
+  for (i = 0; i < tk->num_samplestochunk; i++) {
+    tk->sampletochunk[i].first_chunk = cio_read(cio, 4);
+    tk->sampletochunk[i].samples_per_chunk = cio_read(cio, 4);
+    tk->sampletochunk[i].sample_descr_idx = cio_read(cio, 4);
+  }
+       
+  mj2_stsc_decompact(tk);      /* decompact sample to chunk box */
+       
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with STSC Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the STTS box
+*
+* Time to Sample Box
+*
+*/
+void mj2_write_stts(mj2_tk_t * tk, opj_cio_t *cio)
+{
+       
+  int i;
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_STTS, 4); /* STTS       */
+       
+  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
+       
+  cio_write(cio, tk->num_tts, 4);      /* entry_count */
+  for (i = 0; i < tk->num_tts; i++) {
+    cio_write(cio, tk->tts[i].sample_count, 4);        /* Sample-count */
+    cio_write(cio, tk->tts[i].sample_delta, 4);        /* Sample-Delta */
+  }
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the STTS box
+*
+* 
+*
+*/
+int mj2_read_stts(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  int i;
+       
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_STTS != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected STTS Marker\n");
+    return 1;
+  }
+       
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in STTS box\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in STTS box. Expected flag 0\n");
+    return 1;
+  }
+       
+  tk->num_tts = cio_read(cio, 4);
+
+  tk->tts = (mj2_tts_t*) opj_malloc(tk->num_tts * sizeof(mj2_tts_t));
+
+  for (i = 0; i < tk->num_tts; i++) {
+    tk->tts[i].sample_count = cio_read(cio, 4);
+    tk->tts[i].sample_delta = cio_read(cio, 4);
+  }
+       
+  mj2_tts_decompact(tk);
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with STTS Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the FIEL box
+*
+* Field coding Box
+*
+*/
+void mj2_write_fiel(mj2_tk_t * tk, opj_cio_t *cio)
+{
+       
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_FIEL, 4); /* STTS       */
+       
+  cio_write(cio, tk->fieldcount, 1);   /* Field count */
+  cio_write(cio, tk->fieldorder, 1);   /* Field order */
+       
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the FIEL box
+*
+* Field coding Box
+*
+*/
+int mj2_read_fiel(mj2_tk_t * tk, opj_cio_t *cio)
+{
+       
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_FIEL != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected FIEL Marker\n");
+    return 1;
+  }
+       
+       
+  tk->fieldcount = cio_read(cio, 1);
+  tk->fieldorder = cio_read(cio, 1);
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with FIEL Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the ORFO box
+*
+* Original Format Box
+*
+*/
+void mj2_write_orfo(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_ORFO, 4);
+       
+  cio_write(cio, tk->or_fieldcount, 1);        /* Original Field count */
+  cio_write(cio, tk->or_fieldorder, 1);        /* Original Field order */
+       
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the ORFO box
+*
+* Original Format Box
+*
+*/
+int mj2_read_orfo(mj2_tk_t * tk, opj_cio_t *cio)
+{
+       
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_ORFO != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected ORFO Marker\n");
+    return 1;
+  }
+       
+       
+  tk->or_fieldcount = cio_read(cio, 1);
+  tk->or_fieldorder = cio_read(cio, 1);
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with ORFO Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the JP2P box
+*
+* MJP2 Profile Box
+*
+*/
+void mj2_write_jp2p(mj2_tk_t * tk, opj_cio_t *cio)
+{
+       
+  int i;
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_JP2P, 4);
+       
+  cio_write(cio, 0, 4);                /* Version 0, flags =0 */
+       
+  for (i = 0; i < tk->num_br; i++) {
+    cio_write(cio, tk->br[i], 4);
+  }
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the JP2P box
+*
+* MJP2 Profile Box
+*
+*/
+int mj2_read_jp2p(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  int i;
+       
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_JP2P != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected JP2P Marker\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in JP2P box\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in JP2P box. Expected flag 0\n");
+    return 1;
+  }
+       
+       
+  tk->num_br = (box.length - 12) / 4;
+  tk->br = (unsigned int*) opj_malloc(tk->num_br * sizeof(unsigned int));
+
+  for (i = 0; i < tk->num_br; i++) {
+    tk->br[i] = cio_read(cio, 4);
+  }
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with JP2P Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the JP2X box
+*
+* MJP2 Prefix Box
+*
+*/
+void mj2_write_jp2x(mj2_tk_t * tk, opj_cio_t *cio)
+{
+       
+  int i;
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_JP2X, 4);
+       
+  for (i = 0; i < tk->num_jp2x; i++) {
+    cio_write(cio, tk->jp2xdata[i], 1);
+  }
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the JP2X box
+*
+* MJP2 Prefix Box
+*
+*/
+int mj2_read_jp2x(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  unsigned int i;
+       
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_JP2X != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected JP2X Marker\n");
+    return 1;
+  }
+       
+       
+  tk->num_jp2x = (box.length - 8);
+  tk->jp2xdata = (unsigned char*) opj_malloc(tk->num_jp2x * sizeof(unsigned char));
+
+  for (i = 0; i < tk->num_jp2x; i++) {
+    tk->jp2xdata[i] = cio_read(cio, 1);
+  }
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with JP2X Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the JSUB box
+*
+* MJP2 Subsampling Box
+*
+*/
+void mj2_write_jsub(mj2_tk_t * tk, opj_cio_t *cio)
+{
+       
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_JSUB, 4);
+       
+  cio_write(cio, tk->hsub, 1);
+  cio_write(cio, tk->vsub, 1);
+  cio_write(cio, tk->hoff, 1);
+  cio_write(cio, tk->voff, 1);
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the JSUB box
+*
+* MJP2 Subsampling Box
+*
+*/
+int mj2_read_jsub(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_JSUB != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected JSUB Marker\n");
+    return 1;
+  }
+       
+  tk->hsub = cio_read(cio, 1);
+  tk->vsub = cio_read(cio, 1);
+  tk->hoff = cio_read(cio, 1);;
+  tk->voff = cio_read(cio, 1);
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with JSUB Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the SMJ2 box
+*
+* Visual Sample Entry Description
+*
+*/
+void mj2_write_smj2(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_MJ2, 4);  /* MJ2       */
+       
+  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
+       
+  cio_write(cio, 1, 4);
+       
+  cio_write(cio, 0, 2);                /* Pre-defined */
+       
+  cio_write(cio, 0, 2);                /* Reserved */
+       
+  cio_write(cio, 0, 4);                /* Pre-defined */
+  cio_write(cio, 0, 4);                /* Pre-defined */
+  cio_write(cio, 0, 4);                /* Pre-defined */
+       
+  cio_write(cio, tk->w, 2);            /* Width  */
+  cio_write(cio, tk->h, 2);            /* Height */
+       
+  cio_write(cio, tk->horizresolution, 4);      /* Horizontal resolution */
+  cio_write(cio, tk->vertresolution, 4);       /* Vertical resolution   */
+       
+  cio_write(cio, 0, 4);                /* Reserved */
+       
+  cio_write(cio, 1, 2);                /* Pre-defined = 1 */
+       
+  cio_write(cio, tk->compressorname[0], 4);    /* Compressor Name */
+  cio_write(cio, tk->compressorname[1], 4);
+  cio_write(cio, tk->compressorname[2], 4);
+  cio_write(cio, tk->compressorname[3], 4);
+  cio_write(cio, tk->compressorname[4], 4);
+  cio_write(cio, tk->compressorname[5], 4);
+  cio_write(cio, tk->compressorname[6], 4);
+  cio_write(cio, tk->compressorname[7], 4);
+       
+  cio_write(cio, tk->depth, 2);        /* Depth */
+       
+  cio_write(cio, 0xffff, 2);           /* Pre-defined = -1 */
+       
+  jp2_write_jp2h(&tk->jp2_struct, cio);
+       
+  mj2_write_fiel(tk, cio);
+       
+  if (tk->num_br != 0)
+    mj2_write_jp2p(tk, cio);
+  if (tk->num_jp2x != 0)
+    mj2_write_jp2x(tk, cio);
+       
+  mj2_write_jsub(tk, cio);
+  mj2_write_orfo(tk, cio);
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the SMJ2 box
+*
+* Visual Sample Entry Description
+*
+*/
+int mj2_read_smj2(opj_image_t * img, mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+  mj2_box_t box2;
+  int i;
+  opj_jp2_color_t color;
+       
+  mj2_read_boxhdr(&box, cio);
+       
+  if (MJ2_MJ2 != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error in SMJ2 box: Expected MJ2 Marker\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in MJP2 box\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in MJP2 box. Expected flag 0\n");
+    return 1;
+  }
+       
+  cio_skip(cio,4);
+       
+  cio_skip(cio,2);                     /* Pre-defined */
+       
+  cio_skip(cio,2);                     /* Reserved */
+       
+  cio_skip(cio,4);                     /* Pre-defined */
+  cio_skip(cio,4);                     /* Pre-defined */
+  cio_skip(cio,4);                     /* Pre-defined */
+       
+  tk->w = cio_read(cio, 2);            /* Width  */
+  tk->h = cio_read(cio, 2);            /* Height */
+       
+  tk->horizresolution = cio_read(cio, 4);      /* Horizontal resolution */
+  tk->vertresolution = cio_read(cio, 4);       /* Vertical resolution   */
+       
+  cio_skip(cio,4);                     /* Reserved */
+       
+  cio_skip(cio,2);                     /* Pre-defined = 1 */
+       
+  tk->compressorname[0] = cio_read(cio, 4);    /* Compressor Name */
+  tk->compressorname[1] = cio_read(cio, 4);
+  tk->compressorname[2] = cio_read(cio, 4);
+  tk->compressorname[3] = cio_read(cio, 4);
+  tk->compressorname[4] = cio_read(cio, 4);
+  tk->compressorname[5] = cio_read(cio, 4);
+  tk->compressorname[6] = cio_read(cio, 4);
+  tk->compressorname[7] = cio_read(cio, 4);
+       
+  tk->depth = cio_read(cio, 2);        /* Depth */
+       
+  /* Init std value */
+  tk->num_jp2x = 0;
+  tk->fieldcount = 1;
+  tk->fieldorder = 0;
+  tk->or_fieldcount = 1;
+  tk->or_fieldorder = 0;
+       
+  cio_skip(cio,2);                     /* Pre-defined = -1 */
+  memset(&color, 0, sizeof(opj_jp2_color_t));
+       
+  if (!jp2_read_jp2h(&tk->jp2_struct, cio, &color)) {
+               opj_event_msg(tk->cinfo, EVT_ERROR, "Error reading JP2H Box\n");
+    return 1;
+  }
+
+  tk->jp2_struct.comps = (opj_jp2_comps_t*) opj_malloc(tk->jp2_struct.numcomps * sizeof(opj_jp2_comps_t));
+  tk->jp2_struct.cl = (unsigned int*) opj_malloc(sizeof(unsigned int));
+
+  tk->num_br = 0;
+  tk->num_jp2x = 0;
+       
+  for (i = 0; cio_tell(cio) - box.init_pos < box.length; i++) {
+    mj2_read_boxhdr(&box2, cio);
+    cio_seek(cio, box2.init_pos);
+    switch (box2.type) {
+    case MJ2_FIEL:
+      if (mj2_read_fiel(tk, cio))
+                               return 1;
+      break;
+                       
+    case MJ2_JP2P:
+      if (mj2_read_jp2p(tk, cio))
+                               return 1;
+      break;
+                       
+    case MJ2_JP2X:
+      if (mj2_read_jp2x(tk, cio))
+                               return 1;
+      break;
+                       
+    case MJ2_JSUB:
+      if (mj2_read_jsub(tk, cio))
+                               return 1;
+      break;
+                       
+    case MJ2_ORFO:
+      if (mj2_read_orfo(tk, cio))
+                               return 1;
+      break;
+                       
+    default:
+      opj_event_msg(cio->cinfo, EVT_ERROR, "Error with MJP2 Box size\n");
+      return 1;
+      break;
+                       
+    }
+  }
+  return 0;
+}
+
+
+/*
+* Write the STSD box
+*
+* Sample Description
+*
+*/
+void mj2_write_stsd(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_STSD, 4); /* STSD       */
+       
+  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
+       
+  cio_write(cio, 1, 4);                /* entry_count = 1 (considering same JP2 headerboxes) */
+       
+  if (tk->track_type == 0) {
+    mj2_write_smj2(tk, cio);
+  } else if (tk->track_type == 1) {
+    // Not implemented
+  }
+  if (tk->track_type == 2) {
+    // Not implemented
+  }
+       
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the STSD box
+*
+* Sample Description
+*
+*/
+int mj2_read_stsd(mj2_tk_t * tk, opj_image_t * img, opj_cio_t *cio)
+{
+  int i;
+  int entry_count, len_2skip;
+       
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+       
+  if (MJ2_STSD != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected STSD Marker\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in STSD box\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in STSD box. Expected flag 0\n");
+    return 1;
+  }
+       
+  entry_count = cio_read(cio, 4);
+       
+  if (tk->track_type == 0) {
+    for (i = 0; i < entry_count; i++) {
+      if (mj2_read_smj2(img, tk, cio))
+                               return 1;
+    }
+  } else if (tk->track_type == 1) {
+    len_2skip = cio_read(cio, 4);      // Not implemented -> skipping box
+    cio_skip(cio,len_2skip - 4);
+  } else if (tk->track_type == 2) {
+    len_2skip = cio_read(cio, 4);      // Not implemented -> skipping box
+    cio_skip(cio,len_2skip - 4);
+  }
+       
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with STSD Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the STBL box
+*
+* Sample table box box
+*
+*/
+void mj2_write_stbl(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_STBL, 4); /* STBL       */
+       
+  mj2_write_stsd(tk, cio);
+  mj2_write_stts(tk, cio);
+  mj2_write_stsc(tk, cio);
+  mj2_write_stsz(tk, cio);
+  mj2_write_stco(tk, cio);
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the STBL box
+*
+* Sample table box box
+*
+*/
+int mj2_read_stbl(mj2_tk_t * tk, opj_image_t * img, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_STBL != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected STBL Marker\n");
+    return 1;
+  }
+       
+  if (mj2_read_stsd(tk, img, cio))
+    return 1;
+  if (mj2_read_stts(tk, cio))
+    return 1;
+  if (mj2_read_stsc(tk, cio))
+    return 1;
+  if (mj2_read_stsz(tk, cio))
+    return 1;
+  if (mj2_read_stco(tk, cio))
+    return 1;
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with STBL Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the URL box
+*
+* URL box
+*
+*/
+void mj2_write_url(mj2_tk_t * tk, int url_num, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_URL, 4);  /* URL       */
+       
+  if (url_num == 0)
+    cio_write(cio, 1, 4);              /* Version = 0, flags = 1 because stored in same file */
+  else {
+    cio_write(cio, 0, 4);              /* Version = 0, flags =  0 */
+    cio_write(cio, tk->url[url_num - 1].location[0], 4);
+    cio_write(cio, tk->url[url_num - 1].location[1], 4);
+    cio_write(cio, tk->url[url_num - 1].location[2], 4);
+    cio_write(cio, tk->url[url_num - 1].location[3], 4);
+  }
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the URL box
+*
+* URL box
+*
+*/
+int mj2_read_url(mj2_tk_t * tk, int urn_num, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_URL != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected URL Marker\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in URL box\n");
+    return 1;
+  }
+       
+  if (1 != cio_read(cio, 3)) { /* If flags = 1 --> media data in file */
+    tk->url[urn_num].location[0] = cio_read(cio, 4);
+    tk->url[urn_num].location[1] = cio_read(cio, 4);
+    tk->url[urn_num].location[2] = cio_read(cio, 4);
+    tk->url[urn_num].location[3] = cio_read(cio, 4);
+  } else {
+    tk->num_url--;
+  }
+       
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with URL Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the URN box
+*
+* URN box
+*
+*/
+void mj2_write_urn(mj2_tk_t * tk, int urn_num, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_URN, 4);  /* URN       */
+       
+  cio_write(cio, 0, 4);                /* Version = 0, flags =  0 */
+       
+  cio_write(cio, tk->urn[urn_num].name[0], 4);
+  cio_write(cio, tk->urn[urn_num].name[1], 4);
+  cio_write(cio, tk->urn[urn_num].name[2], 4);
+  cio_write(cio, tk->urn[urn_num].name[3], 4);
+  cio_write(cio, tk->urn[urn_num].location[0], 4);
+  cio_write(cio, tk->urn[urn_num].location[1], 4);
+  cio_write(cio, tk->urn[urn_num].location[2], 4);
+  cio_write(cio, tk->urn[urn_num].location[3], 4);
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the URN box
+*
+* URN box
+*
+*/
+int mj2_read_urn(mj2_tk_t * tk, int urn_num, opj_cio_t *cio)
+{
+       
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_URN != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected URN Marker\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in URN box\n");
+    return 1;
+  }
+       
+  if (1 != cio_read(cio, 3)) { /* If flags = 1 --> media data in file */
+    tk->urn[urn_num].name[0] = cio_read(cio, 4);
+    tk->urn[urn_num].name[1] = cio_read(cio, 4);
+    tk->urn[urn_num].name[2] = cio_read(cio, 4);
+    tk->urn[urn_num].name[3] = cio_read(cio, 4);
+    tk->urn[urn_num].location[0] = cio_read(cio, 4);
+    tk->urn[urn_num].location[1] = cio_read(cio, 4);
+    tk->urn[urn_num].location[2] = cio_read(cio, 4);
+    tk->urn[urn_num].location[3] = cio_read(cio, 4);
+  }
+       
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with URN Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+
+/*
+* Write the DREF box
+*
+* Data reference box
+*
+*/
+void mj2_write_dref(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  int i;
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_DREF, 4); /* DREF       */
+       
+  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
+       
+  if (tk->num_url + tk->num_urn == 0) {        /* Media data in same file */
+    cio_write(cio, 1, 4);              /* entry_count = 1 */
+    mj2_write_url(tk, 0, cio);
+  } else {
+    cio_write(cio, tk->num_url + tk->num_urn, 4);      /* entry_count */
+               
+    for (i = 0; i < tk->num_url; i++)
+      mj2_write_url(tk, i + 1, cio);
+               
+    for (i = 0; i < tk->num_urn; i++)
+      mj2_write_urn(tk, i, cio);
+  }
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the DREF box
+*
+* Data reference box
+*
+*/
+int mj2_read_dref(mj2_tk_t * tk, opj_cio_t *cio)
+{
+       
+  int i;
+  int entry_count, marker;
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_DREF != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected DREF Marker\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in DREF box\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in DREF box. Expected flag 0\n");
+    return 1;
+  }
+       
+  entry_count = cio_read(cio, 4);
+  tk->num_url = 0;
+  tk->num_urn = 0;
+       
+  for (i = 0; i < entry_count; i++) {
+    cio_skip(cio,4);
+    marker = cio_read(cio, 4);
+    if (marker == MJ2_URL) {
+      cio_skip(cio,-8);
+      tk->num_url++;
+      if (mj2_read_url(tk, tk->num_url, cio))
+                               return 1;
+    } else if (marker == MJ2_URN) {
+      cio_skip(cio,-8);
+      tk->num_urn++;
+      if (mj2_read_urn(tk, tk->num_urn, cio))
+                               return 1;
+    } else {
+      opj_event_msg(cio->cinfo, EVT_ERROR, "Error with in DREF box. Expected URN or URL box\n");
+      return 1;
+    }
+               
+  }
+       
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with DREF Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the DINF box
+*
+* Data information box
+*
+*/
+void mj2_write_dinf(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_DINF, 4); /* DINF       */
+       
+  mj2_write_dref(tk, cio);
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the DINF box
+*
+* Data information box
+*
+*/
+int mj2_read_dinf(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_DINF != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected DINF Marker\n");
+    return 1;
+  }
+       
+  if (mj2_read_dref(tk, cio))
+    return 1;
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with DINF Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the VMHD box
+*
+* Video Media information box
+*
+*/
+void mj2_write_vmhd(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_VMHD, 4); /* VMHD       */
+       
+  cio_write(cio, 1, 4);                /* Version = 0, flags = 1 */
+       
+  cio_write(cio, tk->graphicsmode, 2);
+  cio_write(cio, tk->opcolor[0], 2);
+  cio_write(cio, tk->opcolor[1], 2);
+  cio_write(cio, tk->opcolor[2], 2);
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the VMHD box
+*
+* Video Media information box
+*
+*/
+int mj2_read_vmhd(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_VMHD != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected VMHD Marker\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in VMHD box\n");
+    return 1;
+  }
+       
+  if (1 != cio_read(cio, 3)) { /* Flags = 1  */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in VMHD box. Expected flag 1\n");
+    return 1;
+  }
+       
+  tk->track_type = 0;
+  tk->graphicsmode = cio_read(cio, 2);
+  tk->opcolor[0] = cio_read(cio, 2);
+  tk->opcolor[1] = cio_read(cio, 2);
+  tk->opcolor[2] = cio_read(cio, 2);
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with VMHD Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the SMHD box
+*
+* Sound Media information box
+*
+*/
+void mj2_write_smhd(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_SMHD, 4); /* SMHD       */
+       
+  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
+       
+  cio_write(cio, tk->balance, 2);
+       
+  cio_write(cio, 0, 2);                /* Reserved */
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the SMHD box
+*
+* Sound Media information box
+*
+*/
+int mj2_read_smhd(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_SMHD != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected SMHD Marker\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in SMHD box\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in SMHD box. Expected flag 0\n");
+    return 1;
+  }
+       
+  tk->track_type = 1;
+  tk->balance = cio_read(cio, 2);
+       
+  /* Init variables to zero to avoid problems when freeeing memory
+  The values will possibly be overidded when decoding the track structure */
+  tk->num_br = 0;
+  tk->num_url = 0;
+  tk->num_urn = 0;
+  tk->num_chunks = 0;
+  tk->num_tts = 0;
+  tk->num_samplestochunk = 0;
+  tk->num_samples = 0;
+       
+  cio_skip(cio,2);                     /* Reserved */
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with SMHD Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the HMHD box
+*
+* Hint Media information box
+*
+*/
+void mj2_write_hmhd(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_HMHD, 4); /* HMHD       */
+       
+  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
+       
+  cio_write(cio, tk->maxPDUsize, 2);
+  cio_write(cio, tk->avgPDUsize, 2);
+  cio_write(cio, tk->maxbitrate, 4);
+  cio_write(cio, tk->avgbitrate, 4);
+  cio_write(cio, tk->slidingavgbitrate, 4);
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the HMHD box
+*
+* Hint Media information box
+*
+*/
+int mj2_read_hmhd(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_HMHD != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected HMHD Marker\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in HMHD box\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in HMHD box. Expected flag 0\n");
+    return 1;
+  }
+       
+  tk->track_type = 2;
+  tk->maxPDUsize = cio_read(cio, 2);
+  tk->avgPDUsize = cio_read(cio, 2);
+  tk->maxbitrate = cio_read(cio, 4);
+  tk->avgbitrate = cio_read(cio, 4);
+  tk->slidingavgbitrate = cio_read(cio, 4);
+       
+  /* Init variables to zero to avoid problems when freeeing memory
+  The values will possibly be overidded when decoding the track structure */
+  tk->num_br = 0;
+  tk->num_url = 0;
+  tk->num_urn = 0;
+  tk->num_chunks = 0;
+  tk->num_tts = 0;
+  tk->num_samplestochunk = 0;
+  tk->num_samples = 0;
+       
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with HMHD Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the MINF box
+*
+* Media information box
+*
+*/
+void mj2_write_minf(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_MINF, 4); /* MINF       */
+       
+  if (tk->track_type == 0) {
+    mj2_write_vmhd(tk, cio);
+  } else if (tk->track_type == 1) {
+    mj2_write_smhd(tk, cio);
+  } else if (tk->track_type == 2) {
+    mj2_write_hmhd(tk, cio);
+  }
+       
+  mj2_write_dinf(tk, cio);
+  mj2_write_stbl(tk, cio);
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the MINF box
+*
+* Media information box
+*
+*/
+int mj2_read_minf(mj2_tk_t * tk, opj_image_t * img, opj_cio_t *cio)
+{
+       
+  unsigned int box_type;
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_MINF != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected MINF Marker\n");
+    return 1;
+  }
+       
+  cio_skip(cio,4);
+  box_type = cio_read(cio, 4);
+  cio_skip(cio,-8);
+       
+  if (box_type == MJ2_VMHD) {
+    if (mj2_read_vmhd(tk, cio))
+      return 1;
+  } else if (box_type == MJ2_SMHD) {
+    if (mj2_read_smhd(tk, cio))
+      return 1;
+  } else if (box_type == MJ2_HMHD) {
+    if (mj2_read_hmhd(tk, cio))
+      return 1;
+  } else {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error in MINF box expected vmhd, smhd or hmhd\n");
+    return 1;
+  }
+       
+  if (mj2_read_dinf(tk, cio))
+    return 1;
+       
+  if (mj2_read_stbl(tk, img, cio))
+    return 1;
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with MINF Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the HDLR box
+*
+* Handler reference box
+*
+*/
+void mj2_write_hdlr(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_HDLR, 4); /* HDLR       */
+       
+  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
+       
+  cio_write(cio, 0, 4);                /* Predefine */
+       
+  tk->name = 0;                        /* The track name is immediately determined by the track type */
+       
+  if (tk->track_type == 0) {
+    tk->handler_type = 0x76696465;     /* Handler type: vide */
+    cio_write(cio, tk->handler_type, 4);
+               
+    cio_write(cio, 0, 4);
+    cio_write(cio, 0, 4);
+    cio_write(cio, 0, 4);              /* Reserved */
+               
+    cio_write(cio, 0x76696465, 4);
+    cio_write(cio, 0x6F206d65, 4);
+    cio_write(cio, 0x64696120, 4);
+    cio_write(cio, 0x74726163, 4);
+    cio_write(cio, 0x6b00, 2); /* String: video media track */
+  } else if (tk->track_type == 1) {
+    tk->handler_type = 0x736F756E;     /* Handler type: soun */
+    cio_write(cio, tk->handler_type, 4);
+               
+    cio_write(cio, 0, 4);
+    cio_write(cio, 0, 4);
+    cio_write(cio, 0, 4);              /* Reserved */
+               
+    cio_write(cio, 0x536F756E, 4);
+    cio_write(cio, 0x6400, 2); /* String: Sound */
+  } else if (tk->track_type == 2) {
+    tk->handler_type = 0x68696E74;     /* Handler type: hint */
+    cio_write(cio, tk->handler_type, 4);
+               
+    cio_write(cio, 0, 4);
+    cio_write(cio, 0, 4);
+    cio_write(cio, 0, 4);              /* Reserved */
+               
+    cio_write(cio, 0x48696E74, 4);
+    cio_write(cio, 0, 2);              /* String: Hint */
+  }
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the HDLR box
+*
+* Handler reference box
+*
+*/
+int mj2_read_hdlr(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  int i;
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_HDLR != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected HDLR Marker\n");
+    return 1;
+  }
+       
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in HDLR box\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in HDLR box. Expected flag 0\n");
+    return 1;
+  }
+       
+  cio_skip(cio,4);                     /* Reserved */
+       
+  tk->handler_type = cio_read(cio, 4);
+  cio_skip(cio,12);                    /* Reserved */
+       
+  tk->name_size = box.length - 32;
+
+  tk->name = (char*) opj_malloc(tk->name_size * sizeof(char));
+  for (i = 0; i < tk->name_size; i++) {
+    tk->name[i] = cio_read(cio, 1);    /* Name */
+  }
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with HDLR Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the MDHD box
+*
+* Media Header Box
+*
+*/
+void mj2_write_mdhd(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+  unsigned int i;
+  time_t ltime;
+  unsigned int modification_time;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_MDHD, 4); /* MDHD       */
+       
+  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
+       
+  cio_write(cio, tk->creation_time, 4);        /* Creation Time */
+       
+  time(&ltime);                        /* Time since 1/1/70 */
+  modification_time = (unsigned int)ltime + 2082844800;        /* Seoonds between 1/1/04 and 1/1/70 */
+       
+  cio_write(cio, modification_time, 4);        /* Modification Time */
+       
+  cio_write(cio, tk->timescale, 4);    /* Timescale */
+       
+  tk->duration = 0;
+       
+  for (i = 0; i < tk->num_samples; i++)
+    tk->duration += tk->sample[i].sample_delta;
+       
+  cio_write(cio, tk->duration, 4);     /* Duration */
+       
+  cio_write(cio, tk->language, 2);     /* Language */
+       
+  cio_write(cio, 0, 2);                /* Predefined */
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the MDHD box
+*
+* Media Header Box
+*
+*/
+int mj2_read_mdhd(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (!(MJ2_MHDR == box.type || MJ2_MDHD == box.type)) {       // Kakadu writes MHDR instead of MDHD
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected MDHD Marker\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in MDHD box\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 3)) { /* Flags = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in MDHD box. Expected flag 0\n");
+    return 1;
+  }
+       
+       
+  tk->creation_time = cio_read(cio, 4);        /* Creation Time */
+       
+  tk->modification_time = cio_read(cio, 4);    /* Modification Time */
+       
+  tk->timescale = cio_read(cio, 4);    /* Timescale */
+       
+  tk->duration = cio_read(cio, 4);     /* Duration */
+       
+  tk->language = cio_read(cio, 2);     /* Language */
+       
+  cio_skip(cio,2);                     /* Predefined */
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with MDHD Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the MDIA box
+*
+* Media box
+*
+*/
+void mj2_write_mdia(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_MDIA, 4); /* MDIA       */
+       
+  mj2_write_mdhd(tk, cio);
+  mj2_write_hdlr(tk, cio);
+  mj2_write_minf(tk, cio);
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the MDIA box
+*
+* Media box
+*
+*/
+int mj2_read_mdia(mj2_tk_t * tk, opj_image_t * img, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_MDIA != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected MDIA Marker\n");
+    return 1;
+  }
+       
+  if (mj2_read_mdhd(tk, cio))
+    return 1;
+  if (mj2_read_hdlr(tk, cio))
+    return 1;
+  if (mj2_read_minf(tk, img, cio))
+    return 1;
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with MDIA Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the TKHD box
+*
+* Track Header box
+*
+*/
+void mj2_write_tkhd(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+  unsigned int i;
+  time_t ltime;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+       
+  cio_write(cio, MJ2_TKHD, 4); /* TKHD       */
+       
+  cio_write(cio, 3, 4);                /* Version=0, flags=3 */
+       
+  time(&ltime);                        /* Time since 1/1/70 */
+  tk->modification_time = (unsigned int)ltime + 2082844800;    /* Seoonds between 1/1/04 and 1/1/70 */
+       
+  cio_write(cio, tk->creation_time, 4);        /* Creation Time */
+       
+  cio_write(cio, tk->modification_time, 4);    /* Modification Time */
+       
+  cio_write(cio, tk->track_ID, 4);     /* Track ID */
+       
+  cio_write(cio, 0, 4);                /* Reserved */
+       
+  tk->duration = 0;
+       
+  for (i = 0; i < tk->num_samples; i++)
+    tk->duration += tk->sample[i].sample_delta;
+       
+  cio_write(cio, tk->duration, 4);     /* Duration */
+       
+  cio_write(cio, 0, 4);                /* Reserved */
+  cio_write(cio, 0, 4);                /* Reserved */
+       
+  cio_write(cio, tk->layer, 2);        /* Layer    */
+       
+  cio_write(cio, 0, 2);                /* Predefined */
+       
+  cio_write(cio, tk->volume, 2);       /* Volume       */
+       
+  cio_write(cio, 0, 2);                /* Reserved */
+       
+  cio_write(cio, tk->trans_matrix[0], 4);      /* Transformation matrix for track */
+  cio_write(cio, tk->trans_matrix[1], 4);
+  cio_write(cio, tk->trans_matrix[2], 4);
+  cio_write(cio, tk->trans_matrix[3], 4);
+  cio_write(cio, tk->trans_matrix[4], 4);
+  cio_write(cio, tk->trans_matrix[5], 4);
+  cio_write(cio, tk->trans_matrix[6], 4);
+  cio_write(cio, tk->trans_matrix[7], 4);
+  cio_write(cio, tk->trans_matrix[8], 4);
+       
+  cio_write(cio, tk->visual_w, 4);     /* Video Visual Width  */
+       
+  cio_write(cio, tk->visual_h, 4);     /* Video Visual Height */
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the TKHD box
+*
+* Track Header box
+*
+*/
+int mj2_read_tkhd(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  int flag;
+       
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+       
+  if (MJ2_TKHD != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected TKHD Marker\n");
+    return 1;
+  }
+       
+  if (0 != cio_read(cio, 1)) { /* Version = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in TKHD box\n");
+    return 1;
+  }
+       
+  flag = cio_read(cio, 3);
+       
+  if (!(flag == 1 || flag == 2 || flag == 3 || flag == 4)) {   /* Flags = 1,2,3 or 4 */
+    opj_event_msg(cio->cinfo, EVT_ERROR,
+                       "Error with flag in TKHD box: Expected flag 1,2,3 or 4\n");
+    return 1;
+  }
+       
+  tk->creation_time = cio_read(cio, 4);        /* Creation Time */
+       
+  tk->modification_time = cio_read(cio, 4);    /* Modification Time */
+       
+  tk->track_ID = cio_read(cio, 4);     /* Track ID */
+       
+  cio_skip(cio,4);                     /* Reserved */
+       
+  tk->duration = cio_read(cio, 4);     /* Duration */
+       
+  cio_skip(cio,8);                     /* Reserved */
+       
+  tk->layer = cio_read(cio, 2);        /* Layer    */
+       
+  cio_read(cio, 2);                    /* Predefined */
+       
+  tk->volume = cio_read(cio, 2);       /* Volume       */
+       
+  cio_skip(cio,2);                     /* Reserved */
+       
+  tk->trans_matrix[0] = cio_read(cio, 4);      /* Transformation matrix for track */
+  tk->trans_matrix[1] = cio_read(cio, 4);
+  tk->trans_matrix[2] = cio_read(cio, 4);
+  tk->trans_matrix[3] = cio_read(cio, 4);
+  tk->trans_matrix[4] = cio_read(cio, 4);
+  tk->trans_matrix[5] = cio_read(cio, 4);
+  tk->trans_matrix[6] = cio_read(cio, 4);
+  tk->trans_matrix[7] = cio_read(cio, 4);
+  tk->trans_matrix[8] = cio_read(cio, 4);
+       
+  tk->visual_w = cio_read(cio, 4);     /* Video Visual Width  */
+       
+  tk->visual_h = cio_read(cio, 4);     /* Video Visual Height */
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with TKHD Box size\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the TRAK box
+*
+* Track box
+*
+*/
+void mj2_write_trak(mj2_tk_t * tk, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+       
+  cio_write(cio, MJ2_TRAK, 4); /* TRAK       */
+       
+  mj2_write_tkhd(tk, cio);
+  mj2_write_mdia(tk, cio);
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the TRAK box
+*
+* Track box
+*
+*/
+int mj2_read_trak(mj2_tk_t * tk, opj_image_t * img, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_TRAK != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected TRAK Marker\n");
+    return 1;
+  }
+  if (mj2_read_tkhd(tk, cio))
+    return 1;
+  if (mj2_read_mdia(tk, img, cio))
+    return 1;
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with TRAK Box\n");
+    return 1;
+  }
+  return 0;
+}
+
+/*
+* Write the MVHD box
+*
+* Movie header Box
+*
+*/
+void mj2_write_mvhd(opj_mj2_t * movie, opj_cio_t *cio)
+{
+  int i;
+  mj2_box_t box;
+  unsigned j;
+  time_t ltime;
+  int max_tk_num = 0;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_MVHD, 4); /* MVHD       */
+       
+  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
+       
+  time(&ltime);                        /* Time since 1/1/70 */
+  movie->modification_time = (unsigned int)ltime + 2082844800; /* Seoonds between 1/1/04 and 1/1/70 */
+       
+  cio_write(cio, movie->creation_time, 4);     /* Creation Time */
+       
+  cio_write(cio, movie->modification_time, 4); /* Modification Time */
+       
+  cio_write(cio, movie->timescale, 4); /* Timescale */
+       
+  movie->duration = 0;
+       
+  for (i = 0; i < (movie->num_stk + movie->num_htk + movie->num_vtk); i++) {
+    mj2_tk_t *tk = &movie->tk[i];
+               
+    for (j = 0; j < tk->num_samples; j++) {
+      movie->duration += tk->sample[j].sample_delta;
+    }
+  }
+       
+  cio_write(cio, movie->duration, 4);
+       
+  cio_write(cio, movie->rate, 4);      /* Rate to play presentation    */
+       
+  cio_write(cio, movie->volume, 2);    /* Volume       */
+       
+  cio_write(cio, 0, 2);                /* Reserved */
+  cio_write(cio, 0, 4);                /* Reserved */
+  cio_write(cio, 0, 4);                /* Reserved */
+       
+  cio_write(cio, movie->trans_matrix[0], 4);   /* Transformation matrix for video */
+  cio_write(cio, movie->trans_matrix[1], 4);
+  cio_write(cio, movie->trans_matrix[2], 4);
+  cio_write(cio, movie->trans_matrix[3], 4);
+  cio_write(cio, movie->trans_matrix[4], 4);
+  cio_write(cio, movie->trans_matrix[5], 4);
+  cio_write(cio, movie->trans_matrix[6], 4);
+  cio_write(cio, movie->trans_matrix[7], 4);
+  cio_write(cio, movie->trans_matrix[8], 4);
+       
+  cio_write(cio, 0, 4);                /* Pre-defined */
+  cio_write(cio, 0, 4);                /* Pre-defined */
+  cio_write(cio, 0, 4);                /* Pre-defined */
+  cio_write(cio, 0, 4);                /* Pre-defined */
+  cio_write(cio, 0, 4);                /* Pre-defined */
+  cio_write(cio, 0, 4);                /* Pre-defined */
+       
+       
+  for (i = 0; i < movie->num_htk + movie->num_stk + movie->num_vtk; i++) {
+    if (max_tk_num < movie->tk[i].track_ID)
+      max_tk_num = movie->tk[i].track_ID;
+  }
+       
+  movie->next_tk_id = max_tk_num + 1;
+       
+  cio_write(cio, movie->next_tk_id, 4);        /* ID of Next track to be added */
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);
+}
+
+/*
+* Read the MVHD box
+*
+* Movie header Box
+*
+*/
+int mj2_read_mvhd(opj_mj2_t * movie, opj_cio_t *cio)
+{
+  mj2_box_t box;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_MVHD != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected MVHD Marker\n");
+    return 1;
+  }
+       
+       
+  if (0 != cio_read(cio, 4)) { /* Version = 0, flags = 0 */
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in MVHD box\n");
+  }
+       
+  movie->creation_time = cio_read(cio, 4);     /* Creation Time */
+       
+  movie->modification_time = cio_read(cio, 4); /* Modification Time */
+       
+  movie->timescale = cio_read(cio, 4); /* Timescale */
+       
+  movie->duration = cio_read(cio, 4);  /* Duration */
+       
+  movie->rate = cio_read(cio, 4);              /* Rate to play presentation    */
+       
+  movie->volume = cio_read(cio, 2);            /* Volume       */
+       
+  cio_skip(cio,10);                            /* Reserved */
+       
+  movie->trans_matrix[0] = cio_read(cio, 4);   /* Transformation matrix for video */
+  movie->trans_matrix[1] = cio_read(cio, 4);
+  movie->trans_matrix[2] = cio_read(cio, 4);
+  movie->trans_matrix[3] = cio_read(cio, 4);
+  movie->trans_matrix[4] = cio_read(cio, 4);
+  movie->trans_matrix[5] = cio_read(cio, 4);
+  movie->trans_matrix[6] = cio_read(cio, 4);
+  movie->trans_matrix[7] = cio_read(cio, 4);
+  movie->trans_matrix[8] = cio_read(cio, 4);
+       
+  cio_skip(cio,24);                    /* Pre-defined */
+       
+  movie->next_tk_id = cio_read(cio, 4);        /* ID of Next track to be added */
+       
+  if (cio_tell(cio) - box.init_pos != box.length) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with MVHD Box Size\n");
+    return 1;
+  }
+  return 0;
+}
+
+
+/*
+* Write the MOOV box
+*
+* Movie Box
+*
+*/
+void mj2_write_moov(opj_mj2_t * movie, opj_cio_t *cio)
+{
+  int i;
+  mj2_box_t box;
+       
+  box.init_pos = cio_tell(cio);
+  cio_skip(cio,4);
+  cio_write(cio, MJ2_MOOV, 4); /* MOOV       */
+       
+  mj2_write_mvhd(movie, cio);
+       
+  for (i = 0; i < (movie->num_stk + movie->num_htk + movie->num_vtk); i++) {
+    mj2_write_trak(&movie->tk[i], cio);
+  }
+       
+  box.length = cio_tell(cio) - box.init_pos;
+  cio_seek(cio, box.init_pos);
+  cio_write(cio, box.length, 4);       /* L          */
+  cio_seek(cio, box.init_pos + box.length);    
+}
+
+/*
+* Read the MOOV box
+*
+* Movie Box
+*
+*/
+int mj2_read_moov(opj_mj2_t * movie, opj_image_t * img, opj_cio_t *cio)
+{
+  unsigned int i;
+  mj2_box_t box;
+  mj2_box_t box2;
+       
+  mj2_read_boxhdr(&box, cio);
+  if (MJ2_MOOV != box.type) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected MOOV Marker\n");
+    return 1;
+  }
+       
+  if (mj2_read_mvhd(movie, cio))
+    return 1;
+
+  movie->tk = (mj2_tk_t*) opj_malloc((movie->next_tk_id - 1) * sizeof(mj2_tk_t));
+
+  for (i = 0; cio_tell(cio) - box.init_pos < box.length; i++) {
+               mj2_tk_t *tk = &movie->tk[i];
+               tk->cinfo = movie->cinfo;
+    mj2_read_boxhdr(&box2, cio);
+    if (box2.type == MJ2_TRAK) {
+      cio_seek(cio, box2.init_pos);
+      if (mj2_read_trak(tk, img, cio))
+                               return 1;
+                       
+      if (tk->track_type == 0) {
+                               movie->num_vtk++;
+      } else if (tk->track_type == 1) {
+                               movie->num_stk++;
+      } else if (tk->track_type == 2) {
+                               movie->num_htk++;
+      }
+    } else if (box2.type == MJ2_MVEX) {
+      cio_seek(cio, box2.init_pos);
+      cio_skip(cio,box2.length);
+      i--;
+    } else {
+      opj_event_msg(cio->cinfo, EVT_ERROR, "Error with MOOV Box: Expected TRAK or MVEX box\n");
+      return 1;
+    }
+  }
+  return 0;
+}
+
+int mj2_read_struct(FILE *file, opj_mj2_t *movie) {
+  mj2_box_t box;
+  opj_image_t img;
+  unsigned char * src;
+  int fsresult;
+  int foffset;
+       opj_cio_t *cio;
+       
+       /* open a byte stream for reading */    
+       src = (unsigned char*) opj_malloc(300 * sizeof(unsigned char)); 
+
+       /* Assuming that jp and ftyp markers size do
+     not exceed 300 bytes */
+  fread(src,300,1, file);  
+  
+  cio = opj_cio_open((opj_common_ptr)movie->cinfo, src, 300);
+  
+  if (mj2_read_jp(cio))
+    return 1;
+  if (mj2_read_ftyp(movie, cio))
+    return 1;
+       
+  fsresult = fseek(file,cio_tell(cio),SEEK_SET);
+  if( fsresult ) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read data after FTYP box\n" );
+    return 1;
+  }
+       
+  foffset = cio_tell(cio);
+  
+  box.type = 0;
+  
+  fread(src,30,1,file);
+  cio = opj_cio_open((opj_common_ptr)movie->cinfo, src, 300);
+  mj2_read_boxhdr(&box, cio);
+  
+  while(box.type != MJ2_MOOV) {
+    
+    switch(box.type)
+    {
+    case MJ2_MDAT:
+      fsresult = fseek(file,foffset+box.length,SEEK_SET);
+      if( fsresult ) {
+                               opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read MDAT box\n" );
+                               return 1;
+      }
+      foffset += box.length;
+      break;
+      
+    case MJ2_MOOF:
+      fsresult = fseek(file,foffset+box.length,SEEK_SET);
+      if( fsresult ) {
+                               opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read MOOF box\n" );
+                               return 1;
+      }
+      foffset += box.length;
+      break;      
+    case MJ2_FREE:
+      fsresult = fseek(file,foffset+box.length,SEEK_SET);
+      if( fsresult ) {
+                               opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read FREE box\n" );
+                               return 1;
+      }
+      foffset += box.length;
+      break;      
+    case MJ2_SKIP:
+      fsresult = fseek(file,foffset+box.length,SEEK_SET);
+      if( fsresult ) {
+                               opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read SKIP box\n" );
+                               return 1;
+      }
+      foffset += box.length;
+      break;      
+    default:
+      opj_event_msg(cio->cinfo, EVT_ERROR, "Unknown box in MJ2 stream\n");
+      fsresult = fseek(file,foffset+box.length,SEEK_SET);
+      if( fsresult ) {
+                               opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read end of unknown box\n"); 
+                               return 1;
+      }      
+      foffset += box.length;
+      break;
+    }
+    fsresult = fread(src,8,1,file);
+    if (fsresult != 1) {
+      opj_event_msg(cio->cinfo, EVT_ERROR, "MOOV box not found in file\n"); 
+      return 1;
+    }
+               cio = opj_cio_open((opj_common_ptr)movie->cinfo, src, 8);               
+    mj2_read_boxhdr(&box, cio);
+  }    
+
+  fseek(file,foffset,SEEK_SET);
+  src = (unsigned char*)opj_realloc(src,box.length);
+  fsresult = fread(src,box.length,1,file);
+  if (fsresult != 1) {
+    opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read MOOV box\n"); 
+    return 1;
+  }
+       
+       cio = opj_cio_open((opj_common_ptr)movie->cinfo, src, box.length);
+  
+  if (mj2_read_moov(movie, &img, cio))
+    return 1;
+
+  opj_free(src);
+  return 0;
+}
+
+/* ----------------------------------------------------------------------- */
+/* MJ2 decoder interface                                                                                                                                            */
+/* ----------------------------------------------------------------------- */
+
+opj_dinfo_t* mj2_create_decompress() {
+       opj_mj2_t* mj2;
+       opj_dinfo_t *dinfo = (opj_dinfo_t*) opj_calloc(1, sizeof(opj_dinfo_t));
+       if(!dinfo) return NULL;
+
+       dinfo->is_decompressor = true;  
+
+       mj2 = (opj_mj2_t*) opj_calloc(1, sizeof(opj_mj2_t));
+       dinfo->mj2_handle = mj2;
+       if(mj2) {
+               mj2->cinfo = (opj_common_ptr)dinfo;
+       }
+       mj2->j2k = j2k_create_decompress((opj_common_ptr)dinfo);
+       dinfo->j2k_handle = mj2->j2k;
+
+       return dinfo;
+}
+
+void mj2_setup_decoder(opj_mj2_t *movie, mj2_dparameters_t *mj2_parameters) {
+       movie->num_vtk=0;
+  movie->num_stk=0;
+  movie->num_htk=0;    
+
+       /* setup the J2K decoder parameters */
+       j2k_setup_decoder((opj_j2k_t*)movie->cinfo->j2k_handle, 
+               &mj2_parameters->j2k_parameters);
+
+}
+
+void mj2_destroy_decompress(opj_mj2_t *movie) {
+       if(movie) {
+               int i;
+               mj2_tk_t *tk=NULL;
+
+               if (movie->cinfo->j2k_handle) 
+                       j2k_destroy_compress(movie->j2k);
+               
+               if (movie->num_cl != 0)
+                       opj_free(movie->cl);
+               
+               for (i = 0; i < movie->num_vtk + movie->num_stk + movie->num_htk; i++) {
+                       tk = &movie->tk[i];
+                       if (tk->name_size != 0)
+                               opj_free(tk->name);
+                       if (tk->track_type == 0)  {// Video track
+                               if (tk->jp2_struct.comps != 0)
+                                       opj_free(tk->jp2_struct.comps);
+                               if (tk->jp2_struct.cl != 0)
+                                       opj_free(tk->jp2_struct.cl);
+                               if (tk->num_jp2x != 0)
+                                       opj_free(tk->jp2xdata);
+                               
+                       }
+                       if (tk->num_url != 0)
+                               opj_free(tk->url);
+                       if (tk->num_urn != 0)
+                               opj_free(tk->urn);
+                       if (tk->num_br != 0)
+                               opj_free(tk->br);
+                       if (tk->num_tts != 0)
+                               opj_free(tk->tts);
+                       if (tk->num_chunks != 0)
+                               opj_free(tk->chunk);
+                       if (tk->num_samplestochunk != 0)
+                               opj_free(tk->sampletochunk);
+                       if (tk->num_samples != 0)
+                               opj_free(tk->sample);
+               }
+               
+               opj_free(movie->tk);
+       }       
+       opj_free(movie);
+}
+
+/* ----------------------------------------------------------------------- */
+/* MJ2 encoder interface                                                                                                                                            */
+/* ----------------------------------------------------------------------- */
+
+
+opj_cinfo_t* mj2_create_compress() {
+       opj_mj2_t* mj2;
+       opj_cinfo_t *cinfo = (opj_cinfo_t*) opj_calloc(1, sizeof(opj_cinfo_t));
+       if(!cinfo) return NULL;
+
+       mj2 = (opj_mj2_t*) opj_calloc(1, sizeof(opj_mj2_t));
+       cinfo->mj2_handle = mj2;
+       if(mj2) {
+               mj2->cinfo = (opj_common_ptr)cinfo;
+       }
+
+       mj2->j2k = j2k_create_compress(mj2->cinfo);
+       cinfo->j2k_handle = mj2->j2k;
+
+       return cinfo;
+}
+
+void mj2_setup_encoder(opj_mj2_t *movie, mj2_cparameters_t *parameters) {
+       if(movie && parameters) {
+               opj_jp2_t *jp2_struct;
+                       
+               movie->num_htk = 0;       // No hint tracks
+               movie->num_stk = 0;       // No sound tracks
+               movie->num_vtk = 1;       // One video track  
+
+               movie->brand = MJ2_MJ2;  // One brand: MJ2
+               movie->num_cl = 2;        // Two compatible brands: MJ2 and MJ2S
+               movie->cl = (unsigned int*) opj_malloc(movie->num_cl * sizeof(unsigned int));
+               movie->cl[0] = MJ2_MJ2;
+               movie->cl[1] = MJ2_MJ2S;
+               movie->minversion = 0;    // Minimum version: 0         
+
+               movie->tk = (mj2_tk_t*) opj_malloc(sizeof(mj2_tk_t)); //Memory allocation for the video track
+               movie->tk[0].track_ID = 1;        // Track ID = 1 
+               movie->tk[0].track_type = 0;      // Video track
+               movie->tk[0].Dim[0] = parameters->Dim[0];
+               movie->tk[0].Dim[1] = parameters->Dim[1];
+               movie->tk[0].w = parameters->w;
+               movie->tk[0].h = parameters->h;
+               movie->tk[0].CbCr_subsampling_dx = parameters->CbCr_subsampling_dx;
+               movie->tk[0].CbCr_subsampling_dy = parameters->CbCr_subsampling_dy;
+               movie->tk[0].sample_rate = parameters->frame_rate;
+               movie->tk[0].name_size = 0;
+               movie->tk[0].chunk = (mj2_chunk_t*) opj_malloc(sizeof(mj2_chunk_t));  
+               movie->tk[0].sample = (mj2_sample_t*) opj_malloc(sizeof(mj2_sample_t));
+               movie->tk[0].depth = parameters->prec;
+
+               jp2_struct = &movie->tk[0].jp2_struct;
+               jp2_struct->numcomps = parameters->numcomps;    // NC           
+               jp2_struct->comps = (opj_jp2_comps_t*) opj_malloc(jp2_struct->numcomps * sizeof(opj_jp2_comps_t));
+               jp2_struct->precedence = 0;   /* PRECEDENCE*/
+               jp2_struct->approx = 0;   /* APPROX*/           
+               jp2_struct->brand = JP2_JP2;    /* BR         */
+               jp2_struct->minversion = 0;     /* MinV       */
+               jp2_struct->numcl = 1;
+               jp2_struct->cl = (unsigned int*) opj_malloc(jp2_struct->numcl * sizeof(unsigned int));
+               jp2_struct->cl[0] = JP2_JP2;    /* CL0 : JP2  */                
+               jp2_struct->C = 7;      /* C : Always 7*/
+               jp2_struct->UnkC = 0;      /* UnkC, colorspace specified in colr box*/
+               jp2_struct->IPR = 0;      /* IPR, no intellectual property*/                                            
+               jp2_struct->w = parameters->w;
+               jp2_struct->h = parameters->h;
+               jp2_struct->bpc = 7;  
+               jp2_struct->meth = parameters->meth;
+               jp2_struct->enumcs = parameters->enumcs;
+  }
+}
+
+void mj2_destroy_compress(opj_mj2_t *movie) {
+       if(movie) {
+               int i;
+               mj2_tk_t *tk=NULL;
+
+               if (movie->cinfo->j2k_handle) {
+                       j2k_destroy_compress(movie->j2k);
+               }
+               
+               if (movie->num_cl != 0)
+                       opj_free(movie->cl);
+               
+               for (i = 0; i < movie->num_vtk + movie->num_stk + movie->num_htk; i++) {
+                       tk = &movie->tk[i];
+                       if (tk->name_size != 0)
+                               opj_free(tk->name);
+                       if (tk->track_type == 0)  {// Video track
+                               if (tk->jp2_struct.comps != 0)
+                                       opj_free(tk->jp2_struct.comps);
+                               if (tk->jp2_struct.cl != 0)
+                                       opj_free(tk->jp2_struct.cl);
+                               if (tk->num_jp2x != 0)
+                                       opj_free(tk->jp2xdata);
+                               
+                       }
+                       if (tk->num_url != 0)
+                               opj_free(tk->url);
+                       if (tk->num_urn != 0)
+                               opj_free(tk->urn);
+                       if (tk->num_br != 0)
+                               opj_free(tk->br);
+                       if (tk->num_tts != 0)
+                               opj_free(tk->tts);
+                       if (tk->num_chunks != 0)
+                               opj_free(tk->chunk);
+                       if (tk->num_samplestochunk != 0)
+                               opj_free(tk->sampletochunk);
+                       if (tk->num_samples != 0)
+                               opj_free(tk->sample);
+               }
+               
+               opj_free(movie->tk);
+       }       
+       opj_free(movie);
+}
diff --git a/applications/mj2/mj2.h b/applications/mj2/mj2.h
new file mode 100644 (file)
index 0000000..0ddb6b8
--- /dev/null
@@ -0,0 +1,393 @@
+/*
+* Copyright (c) 2003-2004, Fran�ois-Olivier Devaux
+* Copyright (c) 2003-2004,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+* All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __MJ2_H
+#define __MJ2_H
+/**
+@file mj2.h
+@brief The Motion JPEG 2000 file format Reader/Writer (MJ22)
+
+*/
+
+/** @defgroup MJ2 MJ2 - Motion JPEG 2000 file format reader/writer */
+/*@{*/
+
+#define MJ2_JP    0x6a502020
+#define MJ2_FTYP  0x66747970
+#define MJ2_MJ2   0x6d6a7032
+#define MJ2_MJ2S  0x6d6a3273
+#define MJ2_MDAT  0x6d646174
+#define MJ2_MOOV  0x6d6f6f76
+#define MJ2_MVHD  0x6d766864
+#define MJ2_TRAK  0x7472616b
+#define MJ2_TKHD  0x746b6864
+#define MJ2_MDIA  0x6d646961
+#define MJ2_MDHD  0x6d646864
+#define MJ2_MHDR  0x6d686472
+#define MJ2_HDLR  0x68646C72
+#define MJ2_MINF  0x6d696e66
+#define MJ2_VMHD  0x766d6864
+#define MJ2_SMHD  0x736d6864
+#define MJ2_HMHD  0x686d6864
+#define MJ2_DINF  0x64696e66
+#define MJ2_DREF  0x64726566
+#define MJ2_URL   0x75726c20
+#define MJ2_URN   0x75726e20
+#define MJ2_STBL  0x7374626c
+#define MJ2_STSD  0x73747364
+#define MJ2_STTS  0x73747473
+#define MJ2_STSC  0x73747363
+#define MJ2_STSZ  0x7374737a
+#define MJ2_STCO  0x7374636f
+#define MJ2_MOOF  0x6d6f6f66
+#define MJ2_FREE  0x66726565
+#define MJ2_SKIP  0x736b6970
+#define MJ2_JP2C  0x6a703263
+#define MJ2_FIEL  0x6669656c
+#define MJ2_JP2P  0x6a703270
+#define MJ2_JP2X  0x6a703278
+#define MJ2_JSUB  0x6a737562
+#define MJ2_ORFO  0x6f72666f
+#define MJ2_MVEX  0x6d766578
+#define MJ2_JP2   0x6a703220
+#define MJ2_J2P0  0x4a325030
+
+/**
+Decompressed format used in parameters
+YUV = 0
+*/
+#define YUV_DFMT 1 
+
+/**
+Compressed format used in parameters
+MJ2 = 0
+*/
+#define MJ2_CFMT 2
+
+
+/* ----------------------------------------------------------------------- */
+
+/**
+Time To Sample
+*/
+typedef struct mj2_tts {
+  int sample_count;
+  int sample_delta;
+} mj2_tts_t;
+
+/**
+Chunk
+*/
+typedef struct mj2_chunk {             
+  int num_samples;
+  int sample_descr_idx;
+  int offset;
+} mj2_chunk_t;
+
+/**
+Sample to chunk
+*/
+typedef struct mj2_sampletochunk {             
+  int first_chunk;
+  int samples_per_chunk;
+  int sample_descr_idx;
+} mj2_sampletochunk_t;
+
+/**
+Sample
+*/
+typedef struct mj2_sample {            
+  unsigned int sample_size;
+  unsigned int offset;
+  unsigned int sample_delta;
+} mj2_sample_t;
+
+/**
+URL
+*/
+typedef struct mj2_url {
+  int location[4];
+} mj2_url_t;
+
+/**
+URN
+*/
+typedef struct mj2_urn {               
+  int name[2];
+  int location[4];
+} mj2_urn_t;
+
+/**
+Video Track Parameters
+*/
+typedef struct mj2_tk {
+       /** codec context */
+       opj_common_ptr cinfo;
+  int track_ID;
+  int track_type;
+  unsigned int creation_time;
+  unsigned int modification_time;
+  int duration;
+  int timescale;
+  int layer;
+  int volume;
+  int language;
+  int balance;
+  int maxPDUsize;
+  int avgPDUsize;
+  int maxbitrate;
+  int avgbitrate;
+  int slidingavgbitrate;
+  int graphicsmode;
+  int opcolor[3];
+  int num_url;
+  mj2_url_t *url;
+  int num_urn;
+  mj2_urn_t *urn;
+  int Dim[2];
+  int w;
+  int h;
+  int visual_w;
+  int visual_h;
+  int CbCr_subsampling_dx;
+  int CbCr_subsampling_dy;
+  int sample_rate;
+  int sample_description;
+  int horizresolution;
+  int vertresolution;
+  int compressorname[8];
+  int depth;
+  unsigned char fieldcount;
+  unsigned char fieldorder;
+  unsigned char or_fieldcount;
+  unsigned char or_fieldorder;
+  int num_br;
+  unsigned int *br;
+  unsigned char num_jp2x;
+  unsigned char *jp2xdata;
+  unsigned char hsub;
+  unsigned char vsub;
+  unsigned char hoff;
+  unsigned char voff;
+  int trans_matrix[9];
+       /** Number of samples */
+  unsigned int num_samples;    
+  int transorm;
+  int handler_type;
+  int name_size;
+  unsigned char same_sample_size;
+  int num_tts;
+       /** Time to sample    */
+  mj2_tts_t *tts;              
+  unsigned int num_chunks;
+  mj2_chunk_t *chunk;
+  int num_samplestochunk;
+  mj2_sampletochunk_t *sampletochunk;
+  char *name;
+  opj_jp2_t jp2_struct;
+       /** Sample parameters */
+  mj2_sample_t *sample;                
+} mj2_tk_t;                    
+
+/**
+MJ2 box
+*/
+typedef struct mj2_box {
+  int length;
+  int type;
+  int init_pos;
+} mj2_box_t;
+
+/**
+MJ2 Movie
+*/
+typedef struct opj_mj2 {               
+       /** codec context */
+       opj_common_ptr cinfo;
+       /** handle to the J2K codec  */
+       opj_j2k_t *j2k;
+  unsigned int brand;
+  unsigned int minversion;
+  int num_cl;
+  unsigned int *cl;
+  unsigned int creation_time;
+  unsigned int modification_time;
+  int timescale;
+  unsigned int duration;
+  int rate;
+  int num_vtk;
+  int num_stk;
+  int num_htk;
+  int volume;
+  int trans_matrix[9];
+  int next_tk_id;
+       /** Track Parameters  */
+  mj2_tk_t *tk;                        
+} opj_mj2_t;
+
+/**
+Decompression parameters
+*/
+typedef struct mj2_dparameters {
+       /**@name command line encoder parameters (not used inside the library) */
+       /*@{*/
+       /** input file name */
+       char infile[OPJ_PATH_LEN];
+       /** output file name */
+       char outfile[OPJ_PATH_LEN];     
+       /** J2K decompression parameters */
+       opj_dparameters_t j2k_parameters;       
+} mj2_dparameters_t;
+
+/**
+Compression parameters
+*/
+typedef struct mj2_cparameters {
+       /**@name command line encoder parameters (not used inside the library) */
+       /*@{*/
+       /** J2K compression parameters */
+       opj_cparameters_t j2k_parameters;       
+       /** input file name */
+       char infile[OPJ_PATH_LEN];
+       /** output file name */
+       char outfile[OPJ_PATH_LEN];     
+       /** input file format 0:MJ2 */
+       int decod_format;
+       /** output file format 0:YUV */
+       int cod_format;
+       /** Portion of the image coded */
+       int Dim[2];
+       /** YUV Frame width */
+       int w;
+       /** YUV Frame height */
+       int h;
+       /*   Sample rate of YUV 4:4:4, 4:2:2 or 4:2:0 */
+       int CbCr_subsampling_dx;        
+       /*   Sample rate of YUV 4:4:4, 4:2:2 or 4:2:0 */
+  int CbCr_subsampling_dy;     
+       /*   Video Frame Rate  */
+  int frame_rate;              
+       /*   In YUV files, numcomps always considered as 3 */
+  int numcomps;                        
+       /*   In YUV files, precision always considered as 8 */
+  int prec;            
+  unsigned int meth;
+  unsigned int enumcs;
+} mj2_cparameters_t;
+
+
+/** @name Exported functions */
+/*@{*/
+/* ----------------------------------------------------------------------- */
+/**
+Write the JP box 
+*/
+void mj2_write_jp(opj_cio_t *cio);
+/**
+Write the FTYP box
+@param movie MJ2 movie
+@param cio Output buffer stream
+*/
+void mj2_write_ftyp(opj_mj2_t *movie, opj_cio_t *cio);
+/**
+Creates an MJ2 decompression structure
+@return Returns a handle to a MJ2 decompressor if successful, returns NULL otherwise
+*/
+opj_dinfo_t* mj2_create_decompress();
+/**
+Destroy a MJ2 decompressor handle
+@param movie MJ2 decompressor handle to destroy
+*/
+void mj2_destroy_decompress(opj_mj2_t *movie);
+/**
+Setup the decoder decoding parameters using user parameters.
+Decoding parameters are returned in mj2->j2k->cp. 
+@param movie MJ2 decompressor handle
+@param parameters decompression parameters
+*/
+void mj2_setup_decoder(opj_mj2_t *movie, mj2_dparameters_t *mj2_parameters);
+/**
+Decode an image from a JPEG-2000 file stream
+@param movie MJ2 decompressor handle
+@param cio Input buffer stream
+@return Returns a decoded image if successful, returns NULL otherwise
+*/
+opj_image_t* mj2_decode(opj_mj2_t *movie, opj_cio_t *cio);
+/**
+Creates a MJ2 compression structure
+@return Returns a handle to a MJ2 compressor if successful, returns NULL otherwise
+*/
+opj_cinfo_t* mj2_create_compress();
+/**
+Destroy a MJ2 compressor handle
+@param movie MJ2 compressor handle to destroy
+*/
+void mj2_destroy_compress(opj_mj2_t *movie);
+/**
+Setup the encoder parameters using the current image and using user parameters. 
+Coding parameters are returned in mj2->j2k->cp. 
+@param movie MJ2 compressor handle
+@param parameters compression parameters
+*/
+void mj2_setup_encoder(opj_mj2_t *movie, mj2_cparameters_t *parameters);
+/**
+Encode an image into a JPEG-2000 file stream
+@param movie MJ2 compressor handle
+@param cio Output buffer stream
+@param image Image to encode
+@param index Name of the index file if required, NULL otherwise
+@return Returns true if successful, returns false otherwise
+*/
+bool mj2_encode(opj_mj2_t *movie, opj_cio_t *cio, opj_image_t *image, char *index);
+
+/**
+Init a Standard MJ2 movie
+@param movie MJ2 Movie
+@return Returns 0 if successful, returns 1 otherwise
+*/
+int mj2_init_stdmovie(opj_mj2_t *movie);
+/**
+Read the structure of an MJ2 file
+@param File MJ2 input File
+@param movie J2 movie structure 
+@return Returns 0 if successful, returns 1 otherwise
+*/
+int mj2_read_struct(FILE *file, opj_mj2_t *mj2);
+/**
+Write the the MOOV box to an output buffer stream
+@param movie MJ2 movie structure 
+@param cio Output buffer stream
+*/
+void mj2_write_moov(opj_mj2_t *movie, opj_cio_t *cio);
+
+
+/* ----------------------------------------------------------------------- */
+/*@}*/
+
+/*@}*/
+
+#endif /* __MJ2_H */
diff --git a/applications/mj2/mj2_convert.c b/applications/mj2/mj2_convert.c
new file mode 100644 (file)
index 0000000..3e6c122
--- /dev/null
@@ -0,0 +1,374 @@
+/*
+* Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+* Copyright (c) 2002-2007, Professor Benoit Macq
+* Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+* 1. Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+* 2. Redistributions in binary form must reproduce the above copyright
+*    notice, this list of conditions and the following disclaimer in the
+*    documentation and/or other materials provided with the distribution.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+* POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include "../libopenjpeg/opj_includes.h"
+#include "mj2.h"
+
+/*  -----------------------          */
+/*                                   */
+/*                                   */
+/*  Count the number of frames       */
+/*  in a YUV file                    */
+/*                                   */
+/*  -----------------------          */
+
+int yuv_num_frames(mj2_tk_t * tk, char *infile)
+{
+  int numimages, frame_size, prec_size;
+  long end_of_f;
+       FILE *f;
+
+  f = fopen(infile,"rb");
+  if (!f) {  
+    fprintf(stderr, "failed to open %s for reading\n",infile);
+    return -1;
+  }
+       prec_size = (tk->depth + 7)/8;/* bytes of precision */
+
+  frame_size = (int) (tk->w * tk->h * (1.0 + (double) 2 / (double) (tk->CbCr_subsampling_dx * tk->CbCr_subsampling_dy)));      /* Calculate frame size */
+       frame_size *= prec_size; 
+       
+  fseek(f, 0, SEEK_END);
+  end_of_f = ftell(f);         /* Calculate file size */
+       
+  if (end_of_f < frame_size) {
+    fprintf(stderr,
+                       "YUV does not contains any frame of %d x %d size\n", tk->w,
+                       tk->h);
+    return -1;
+  }
+       
+  numimages = end_of_f / frame_size;   /* Calculate number of images */
+       fclose(f);
+
+  return numimages;
+}
+
+//  -----------------------
+//
+//
+//  YUV to IMAGE
+//
+//  -----------------------
+
+opj_image_t *mj2_image_create(mj2_tk_t * tk, opj_cparameters_t *parameters)
+{
+       opj_image_cmptparm_t cmptparm[3];
+       opj_image_t * img;
+       int i;
+       int numcomps = 3;
+       int subsampling_dx = parameters->subsampling_dx;
+       int subsampling_dy = parameters->subsampling_dy;
+
+       /* initialize image components */
+       memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
+       for(i = 0; i < numcomps; i++) {
+               cmptparm[i].prec = tk->depth;
+               cmptparm[i].bpp = tk->depth;
+               cmptparm[i].sgnd = 0;           
+               cmptparm[i].dx = i ? subsampling_dx * tk->CbCr_subsampling_dx : subsampling_dx;
+               cmptparm[i].dy = i ? subsampling_dy * tk->CbCr_subsampling_dy : subsampling_dy;
+               cmptparm[i].w = tk->w;
+               cmptparm[i].h = tk->h;
+       }
+       /* create the image */
+       img = opj_image_create(numcomps, cmptparm, CLRSPC_SRGB);
+       return img;
+}
+
+char yuvtoimage(mj2_tk_t * tk, opj_image_t * img, int frame_num, opj_cparameters_t *parameters, char* infile)
+{
+  int i, compno;
+  int offset, size, max, prec_bytes, is_16, v;
+  long end_of_f, position;
+       int numcomps = 3;
+       int subsampling_dx = parameters->subsampling_dx;
+       int subsampling_dy = parameters->subsampling_dy;
+       FILE *yuvfile;
+       int *data;
+       unsigned char uc;
+
+  yuvfile = fopen(infile,"rb");
+  if (!yuvfile) {  
+    fprintf(stderr, "failed to open %s for readings\n",parameters->infile);
+    return 1;
+  }
+       is_16 = (tk->depth > 8);
+       prec_bytes = (is_16?2:1);
+
+  offset = (int) ((double) (frame_num * tk->w * tk->h) * (1.0 +
+               1.0 * (double) 2 / (double) (tk->CbCr_subsampling_dx * tk->CbCr_subsampling_dy)));
+  offset *= prec_bytes;
+
+  fseek(yuvfile, 0, SEEK_END);
+  end_of_f = ftell(yuvfile);
+  fseek(yuvfile, sizeof(unsigned char) * offset, SEEK_SET);
+  position = ftell(yuvfile);
+  if (position >= end_of_f) {
+    fprintf(stderr, "Cannot reach frame number %d in yuv file !!\n",
+                       frame_num);
+               fclose(yuvfile);
+    return 1;
+  }
+       
+  img->x0 = tk->Dim[0];
+  img->y0 = tk->Dim[1];
+  img->x1 = !tk->Dim[0] ? (tk->w - 1) * subsampling_dx + 1 : tk->Dim[0] +
+    (tk->w - 1) * subsampling_dx + 1;
+  img->y1 = !tk->Dim[1] ? (tk->h - 1) * subsampling_dy + 1 : tk->Dim[1] +
+    (tk->h - 1) * subsampling_dy + 1;
+
+       size = tk->w * tk->h * prec_bytes;
+       
+       for(compno = 0; compno < numcomps; compno++) 
+   {
+       max = size/(img->comps[compno].dx * img->comps[compno].dy);
+       data = img->comps[compno].data;
+
+       for (i = 0; i < max && !feof(yuvfile); i++)
+  {
+       v = 0;
+       fread(&uc, 1, 1, yuvfile);
+       v = uc;
+
+       if(is_16)
+ {
+       fread(&uc, 1, 1, yuvfile);
+       v |= (uc<<8);
+ }
+       *data++ = v;
+  }
+   }
+       fclose(yuvfile);
+       
+  return 0;
+}
+
+
+
+//  -----------------------
+//
+//
+//  IMAGE to YUV
+//
+//  -----------------------
+
+
+bool imagetoyuv(opj_image_t * img, char *outfile)
+{
+  FILE *f;
+  int *data;
+  int i, v, is_16, prec_bytes;
+  unsigned char buf[2];
+
+  if (img->numcomps == 3) {
+    if (img->comps[0].dx != img->comps[1].dx / 2
+      || img->comps[1].dx != img->comps[2].dx) {
+      fprintf(stderr,
+                               "Error with the input image components size: cannot create yuv file)\n");
+      return false;
+    }
+  } else if (!(img->numcomps == 1)) {
+    fprintf(stderr,
+      "Error with the number of image components(must be one or three)\n");
+    return false;
+  }
+  
+  f = fopen(outfile, "a+b");
+  if (!f) {
+    fprintf(stderr, "failed to open %s for writing\n", outfile);
+    return false;
+  }
+  is_16 = (img->comps[0].prec > 8);
+  prec_bytes = (is_16?2:1);
+  data = img->comps[0].data;
+  
+  for (i = 0; i < (img->comps[0].w * img->comps[0].h); i++) {
+    v = *data++;
+    buf[0] = (unsigned char)v;
+
+       if(is_16) buf[1] = (unsigned char)(v>>8);
+
+    fwrite(buf, 1, prec_bytes, f);
+  }
+  
+  
+  if (img->numcomps == 3) {
+       data = img->comps[1].data;
+
+    for (i = 0; i < (img->comps[1].w * img->comps[1].h); i++) {
+      v = *data++;
+      buf[0] = (unsigned char)v;
+
+      if(is_16) buf[1] = (unsigned char)(v>>8);
+
+      fwrite(buf, 1, prec_bytes, f);
+    }
+    data = img->comps[2].data;
+    
+    for (i = 0; i < (img->comps[2].w * img->comps[2].h); i++) {
+      v = *data++;
+      buf[0] = (unsigned char)v;
+
+      if(is_16) buf[1] = (unsigned char)(v>>8);
+
+      fwrite(buf, 1, prec_bytes, f);
+    }
+  } else if (img->numcomps == 1) {
+/* fake CbCr values */
+       if(is_16) 
+  { 
+       buf[0] = 255;
+       if(img->comps[0].prec == 10) buf[1] = 1;
+       else
+       if(img->comps[0].prec == 12) buf[1] = 3;
+       else
+        buf[1] = 125;
+  } 
+       else buf[0] = 125;
+
+    for (i = 0; i < (img->comps[0].w * img->comps[0].h * 0.25); i++) {
+      fwrite(buf, 1, prec_bytes, f);
+    }
+    
+    
+    for (i = 0; i < (img->comps[0].w * img->comps[0].h * 0.25); i++) {
+      fwrite(buf, 1, prec_bytes, f);
+    }
+  }  
+  fclose(f);
+  return true;
+}
+
+//  -----------------------
+//
+//
+//  IMAGE to BMP
+//
+//  -----------------------
+
+int imagetobmp(opj_image_t * img, char *outfile) {
+  int w,wr,h,hr,i,pad;
+  FILE *f;
+  
+  if (img->numcomps == 3 && img->comps[0].dx == img->comps[1].dx
+    && img->comps[1].dx == img->comps[2].dx
+    && img->comps[0].dy == img->comps[1].dy
+    && img->comps[1].dy == img->comps[2].dy
+    && img->comps[0].prec == img->comps[1].prec
+    && img->comps[1].prec == img->comps[2].prec) {
+    /* -->> -->> -->> -->>
+    
+      24 bits color
+      
+    <<-- <<-- <<-- <<-- */
+    
+    f = fopen(outfile, "wb");
+    if (!f) {
+      fprintf(stderr, "failed to open %s for writing\n", outfile);
+      return 1;
+    }   
+    
+    w = img->comps[0].w;
+    wr = int_ceildivpow2(img->comps[0].w, img->comps[0].factor);
+    
+    h = img->comps[0].h;
+    hr = int_ceildivpow2(img->comps[0].h, img->comps[0].factor);
+    
+    fprintf(f, "BM");
+    
+    /* FILE HEADER */
+    /* ------------- */
+    fprintf(f, "%c%c%c%c",
+      (unsigned char) (hr * wr * 3 + 3 * hr * (wr % 2) +
+      54) & 0xff,
+      (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2) + 54)
+      >> 8) & 0xff,
+      (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2) + 54)
+      >> 16) & 0xff,
+      (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2) + 54)
+      >> 24) & 0xff);
+    fprintf(f, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff,
+      ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
+    fprintf(f, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,
+      ((54) >> 16) & 0xff, ((54) >> 24) & 0xff);
+    
+    /* INFO HEADER   */
+    /* ------------- */
+    fprintf(f, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,
+      ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
+    fprintf(f, "%c%c%c%c", (unsigned char) ((wr) & 0xff),
+      (unsigned char) ((wr) >> 8) & 0xff,
+      (unsigned char) ((wr) >> 16) & 0xff,
+      (unsigned char) ((wr) >> 24) & 0xff);
+    fprintf(f, "%c%c%c%c", (unsigned char) ((hr) & 0xff),
+      (unsigned char) ((hr) >> 8) & 0xff,
+      (unsigned char) ((hr) >> 16) & 0xff,
+      (unsigned char) ((hr) >> 24) & 0xff);
+    fprintf(f, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
+    fprintf(f, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff);
+    fprintf(f, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff,
+      ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
+    fprintf(f, "%c%c%c%c",
+      (unsigned char) (3 * hr * wr +
+      3 * hr * (wr % 2)) & 0xff,
+      (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2)) >>
+      8) & 0xff,
+      (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2)) >>
+      16) & 0xff,
+      (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2)) >>
+      24) & 0xff);
+    fprintf(f, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff,
+      ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
+    fprintf(f, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff,
+      ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
+    fprintf(f, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff,
+      ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
+    fprintf(f, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff,
+      ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
+    
+    for (i = 0; i < wr * hr; i++) {
+      unsigned char R, G, B;
+      /* a modifier */
+      // R = img->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
+      R = img->comps[0].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
+      // G = img->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
+      G = img->comps[1].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
+      // B = img->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
+      B = img->comps[2].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
+      fprintf(f, "%c%c%c", B, G, R);
+      
+      if ((i + 1) % wr == 0) {
+                               for (pad = (3 * wr) % 4 ? 4 - (3 * wr) % 4 : 0; pad > 0; pad--) /* ADD */
+                                       fprintf(f, "%c", 0);
+      }
+    }
+    fclose(f);
+  }
+  return 0;
+}
diff --git a/applications/mj2/mj2_convert.h b/applications/mj2/mj2_convert.h
new file mode 100644 (file)
index 0000000..78e6c47
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2003-2004, Fran�ois-Olivier Devaux
+* Copyright (c) 2002-2004,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+* 1. Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+* 2. Redistributions in binary form must reproduce the above copyright
+*    notice, this list of conditions and the following disclaimer in the
+*    documentation and/or other materials provided with the distribution.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+* POSSIBILITY OF SUCH DAMAGE.
+*/
+
+
+#include "mj2.h"
+
+#ifndef __MJ2_CONVERT_H
+#define __MJ2_CONVERT_H
+
+int imagetoyuv(opj_image_t * img, char *outfile);
+
+int imagetobmp(opj_image_t * img, char *outfile);
+
+opj_image_t *mj2_image_create(mj2_tk_t * tk, opj_cparameters_t *parameters);
+
+char yuvtoimage(mj2_tk_t * tk, opj_image_t * img, int frame_num, opj_cparameters_t *parameters, char* infile);
+
+int yuv_num_frames(mj2_tk_t * tk, char *infile);
+
+
+#endif
diff --git a/applications/mj2/mj2_to_frames.c b/applications/mj2/mj2_to_frames.c
new file mode 100644 (file)
index 0000000..156a101
--- /dev/null
@@ -0,0 +1,251 @@
+/*
+* Copyright (c) 2003-2004, Fran�ois-Olivier Devaux
+* Copyright (c) 2002-2004,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+* 1. Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+* 2. Redistributions in binary form must reproduce the above copyright
+*    notice, this list of conditions and the following disclaimer in the
+*    documentation and/or other materials provided with the distribution.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+* POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "opj_config.h"
+#include "openjpeg.h"
+#include "../libopenjpeg/j2k_lib.h"
+#include "../libopenjpeg/j2k.h"
+#include "../libopenjpeg/jp2.h"
+#include "mj2.h"
+#include "mj2_convert.h"
+
+#ifdef HAVE_LIBLCMS2
+#include <lcms2.h>
+#endif
+#ifdef HAVE_LIBLCMS1
+#include <lcms.h>
+#endif
+#include "color.h"
+/* -------------------------------------------------------------------------- */
+
+/**
+sample error callback expecting a FILE* client object
+*/
+void error_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[ERROR] %s", msg);
+}
+/**
+sample warning callback expecting a FILE* client object
+*/
+void warning_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[WARNING] %s", msg);
+}
+/**
+sample debug callback expecting a FILE* client object
+*/
+void info_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[INFO] %s", msg);
+}
+
+/* -------------------------------------------------------------------------- */
+
+
+int main(int argc, char *argv[]) {
+       mj2_dparameters_t mj2_parameters;                       /* decompression parameters */
+       opj_dinfo_t* dinfo; 
+       opj_event_mgr_t event_mgr;              /* event manager */     
+       opj_cio_t *cio = NULL;
+  unsigned int tnum, snum;
+  opj_mj2_t *movie;
+  mj2_tk_t *track;
+  mj2_sample_t *sample;
+  unsigned char* frame_codestream;
+  FILE *file, *outfile;
+  char outfilename[50];
+  opj_image_t *img = NULL;
+       unsigned int max_codstrm_size = 0;
+       double total_time = 0;
+       unsigned int numframes = 0;
+                       
+  if (argc != 3) {
+    printf("Usage: %s inputfile.mj2 outputfile.yuv\n",argv[0]); 
+    return 1;
+  }
+  
+  file = fopen(argv[1], "rb");
+  
+  if (!file) {
+    fprintf(stderr, "failed to open %s for reading\n", argv[1]);
+    return 1;
+  }
+       
+  // Checking output file
+  outfile = fopen(argv[2], "w");
+  if (!file) {
+    fprintf(stderr, "failed to open %s for writing\n", argv[2]);
+    return 1;
+  }
+  fclose(outfile);
+       
+       /*
+       configure the event callbacks (not required)
+       setting of each callback is optionnal
+       */
+       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
+       event_mgr.error_handler = error_callback;
+       event_mgr.warning_handler = warning_callback;
+       event_mgr.info_handler = NULL;
+       
+       /* get a MJ2 decompressor handle */
+       dinfo = mj2_create_decompress();
+       movie = (opj_mj2_t*)dinfo->mj2_handle;
+       
+       /* catch events using our callbacks and give a local context */
+       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);           
+
+       memset(&mj2_parameters, 0, sizeof(mj2_dparameters_t));
+       /* set J2K decoding parameters to default values */
+       opj_set_default_decoder_parameters(&mj2_parameters.j2k_parameters);
+       
+       /* setup the decoder decoding parameters using user parameters */
+       mj2_setup_decoder(movie, &mj2_parameters);
+                       
+  if (mj2_read_struct(file, movie)) // Creating the movie structure
+    return 1;  
+       
+  // Decode first video track 
+       for (tnum=0; tnum < (unsigned int)(movie->num_htk + movie->num_stk + movie->num_vtk); tnum++) {
+               if (movie->tk[tnum].track_type == 0) 
+                       break;
+       }
+       
+       if (movie->tk[tnum].track_type != 0) {
+               printf("Error. Movie does not contain any video track\n");
+               return 1;
+       }
+       
+  track = &movie->tk[tnum];
+       
+  // Output info on first video tracl
+  fprintf(stdout,"The first video track contains %d frames.\nWidth: %d, Height: %d \n\n",
+    track->num_samples, track->w, track->h);
+       
+       max_codstrm_size = track->sample[0].sample_size-8;
+       frame_codestream = (unsigned char*) malloc(max_codstrm_size * sizeof(unsigned char)); 
+
+       numframes = track->num_samples;
+       
+  for (snum=0; snum < numframes; snum++)
+  {
+               double init_time = opj_clock();
+               double elapsed_time;
+
+    sample = &track->sample[snum];
+               if (sample->sample_size-8 > max_codstrm_size) {
+                       max_codstrm_size =  sample->sample_size-8;
+                       if ((frame_codestream = (unsigned char*)
+                               realloc(frame_codestream, max_codstrm_size)) == NULL) {
+                               printf("Error reallocation memory\n");
+                               return 1;
+                       };              
+               }
+    fseek(file,sample->offset+8,SEEK_SET);
+    fread(frame_codestream, sample->sample_size-8, 1, file);  // Assuming that jp and ftyp markers size do
+               
+               /* open a byte stream */
+               cio = opj_cio_open((opj_common_ptr)dinfo, frame_codestream, sample->sample_size-8);
+               
+               img = opj_decode(dinfo, cio); // Decode J2K to image
+
+#ifdef WANT_SYCC_TO_RGB
+       if(img->color_space == CLRSPC_SYCC)
+  {
+       color_sycc_to_rgb(img);
+  }
+#endif
+
+       if(img->icc_profile_buf)
+  {
+#if defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2)
+       color_apply_icc_profile(img);
+#endif
+
+       free(img->icc_profile_buf);
+       img->icc_profile_buf = NULL; img->icc_profile_len = 0;
+  }
+
+    if (((img->numcomps == 3) && (img->comps[0].dx == img->comps[1].dx / 2) 
+      && (img->comps[0].dx == img->comps[2].dx / 2 ) && (img->comps[0].dx == 1)) 
+      || (img->numcomps == 1)) {
+      
+      if (!imagetoyuv(img, argv[2]))   // Convert image to YUV
+                               return 1;
+    }
+    else if ((img->numcomps == 3) && 
+      (img->comps[0].dx == 1) && (img->comps[1].dx == 1)&&
+      (img->comps[2].dx == 1))// If YUV 4:4:4 input --> to bmp
+    {
+      fprintf(stdout,"The frames will be output in a bmp format (output_1.bmp, ...)\n");
+      sprintf(outfilename,"output_%d.bmp",snum);
+      if (imagetobmp(img, outfilename))        // Convert image to BMP
+                               return 1;
+      
+    }
+    else {
+      fprintf(stdout,"Image component dimensions are unknown. Unable to output image\n");
+      fprintf(stdout,"The frames will be output in a j2k file (output_1.j2k, ...)\n");
+                       
+      sprintf(outfilename,"output_%d.j2k",snum);
+      outfile = fopen(outfilename, "wb");
+      if (!outfile) {
+                               fprintf(stderr, "failed to open %s for writing\n",outfilename);
+                               return 1;
+      }
+      fwrite(frame_codestream,sample->sample_size-8,1,outfile);
+      fclose(outfile);
+    }
+               /* close the byte stream */
+               opj_cio_close(cio);     
+               /* free image data structure */
+               opj_image_destroy(img);
+               elapsed_time = opj_clock()-init_time;
+               fprintf(stderr, "Frame number %d/%d decoded in %.2f mseconds\n", snum + 1, numframes, elapsed_time*1000);
+               total_time += elapsed_time;
+
+  }
+       
+       free(frame_codestream); 
+  fclose(file);        
+
+       /* free remaining structures */
+       if(dinfo) {
+               mj2_destroy_decompress((opj_mj2_t*)dinfo->mj2_handle);
+       }
+       free(dinfo);
+       
+       fprintf(stdout, "%d frame(s) correctly decompressed\n", snum);
+       fprintf(stdout,"Total decoding time: %.2f seconds (%.1f fps)\n", total_time, (float)numframes/total_time);
+               
+  return 0;
+}
diff --git a/applications/mj2/mj2_to_metadata.c b/applications/mj2/mj2_to_metadata.c
new file mode 100644 (file)
index 0000000..90be620
--- /dev/null
@@ -0,0 +1,312 @@
+/* mj2_to_metadata.c */
+/* Dump MJ2, JP2 metadata (partial so far) to xml file */
+/* Contributed to Open JPEG by Glenn Pearson, contract software developer, U.S. National Library of Medicine.
+
+The base code in this file was developed by the author as part of a video archiving
+project for the U.S. National Library of Medicine, Bethesda, MD. 
+It is the policy of NLM (and U.S. government) to not assert copyright.
+
+A non-exclusive copy of this code has been contributed to the Open JPEG project.
+Except for copyright, inclusion of the code within Open JPEG for distribution and use
+can be bound by the Open JPEG open-source license and disclaimer, expressed elsewhere.
+*/
+
+#include "../libopenjpeg/opj_includes.h"
+#include "mj2.h"
+
+#include "mj2_to_metadata.h"
+#include <string.h>
+#include "getopt.h"
+
+/* -------------------------------------------------------------------------- */
+
+/**
+sample error callback expecting a FILE* client object
+*/
+void error_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[ERROR] %s", msg);
+}
+/**
+sample warning callback expecting a FILE* client object
+*/
+void warning_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[WARNING] %s", msg);
+}
+/**
+sample debug callback expecting a FILE* client object
+*/
+void info_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[INFO] %s", msg);
+}
+
+/* -------------------------------------------------------------------------- */
+
+
+
+/* ------------- */
+
+void help_display()
+{
+  /*             "1234567890123456789012345678901234567890123456789012345678901234567890123456789" */
+  fprintf(stdout,"                Help for the 'mj2_to_metadata' Program\n");
+  fprintf(stdout,"                ======================================\n");
+  fprintf(stdout,"The -h option displays this information on screen.\n\n");
+  
+  fprintf(stdout,"mj2_to_metadata generates an XML file from a Motion JPEG 2000 file.\n");
+  fprintf(stdout,"The generated XML shows the structural, but not (yet) curatorial,\n");
+  fprintf(stdout,"metadata from the movie header and from the JPEG 2000 image and tile\n");
+  fprintf(stdout,"headers of a sample frame.  Excluded: low-level packed-bits image data.\n\n");
+
+  fprintf(stdout,"By Default\n");
+  fprintf(stdout,"----------\n");
+  fprintf(stdout,"The metadata includes the jp2 image and tile headers of the first frame.\n");
+  fprintf(stdout,"\n");
+  fprintf(stdout,"Metadata values are shown in 'raw' form (e.g., hexidecimal) as stored in the\n");
+  fprintf(stdout,"file, and, if apt, in a 'derived' form that is more quickly grasped.\n");
+  fprintf(stdout,"\n");
+  fprintf(stdout,"Notes explaining the XML are embedded as terse comments.  These include\n");
+  fprintf(stdout,"   meaning of non-obvious tag abbreviations;\n");
+  fprintf(stdout,"   range and precision of valid values;\n");
+  fprintf(stdout,"   interpretations of values, such as enumerations; and\n");
+  fprintf(stdout,"   current implementation limitations.\n");
+  fprintf(stdout,"\n");
+  fprintf(stdout,"The sample-size and chunk-offset tables, each with 1 row per frame, are not reported.\n");
+  fprintf(stdout,"\n");
+  fprintf(stdout,"The file is self-contained and no verification (e.g., against a DTD) is requested.\n");
+  fprintf(stdout,"\n");
+  fprintf(stdout,"Required Parameters (except with -h)\n");
+  fprintf(stdout,"------------------------------------\n");
+  fprintf(stdout,"[Caution: file strings that contain spaces should be wrapped with quotes.]\n");
+  fprintf(stdout,"-i input.mj2  : where 'input' is any source file name or path.\n");
+  fprintf(stdout,"                MJ2 files created with 'frames_to_mj2' are supported so far.\n");
+  fprintf(stdout,"                These are silent, single-track, 'MJ2 Simple Profile' videos.\n");
+  fprintf(stdout,"-o output.xml : where 'output' is any destination file name or path.\n");
+  fprintf(stdout,"\n");
+  fprintf(stdout,"Optional Parameters\n");
+  fprintf(stdout,"-------------------\n");
+  fprintf(stdout,"-h            : Display this help information.\n");
+  fprintf(stdout,"-n            : Suppress all mj2_to_metadata notes.\n");
+  fprintf(stdout,"-t            : Include sample-size and chunk-offset tables.\n");
+  fprintf(stdout,"-f n          : where n > 0.  Include jp2 header info for frame n [default=1].\n");
+  fprintf(stdout,"-f 0          : No jp2 header info.\n");
+  fprintf(stdout,"-r            : Suppress all 'raw' data for which a 'derived' form exists.\n");
+  fprintf(stdout,"-d            : Suppress all 'derived' data.\n");
+  fprintf(stdout,"                (If both -r and -d given, -r will be ignored.)\n");
+  fprintf(stdout,"-v string     : Verify against the DTD file located by the string.\n");
+  fprintf(stdout,"                Prepend quoted 'string' with either SYSTEM or PUBLIC keyword.\n");
+  fprintf(stdout,"                Thus, for the distributed DTD placed in the same directory as\n");
+  fprintf(stdout,"                the output file: -v \"SYSTEM mj2_to_metadata.dtd\"\n");
+  fprintf(stdout,"                \"PUBLIC\" is used with an access protocol (e.g., http:) + URL.\n");
+  /* More to come */
+  fprintf(stdout,"\n");
+  /*             "1234567890123456789012345678901234567890123456789012345678901234567890123456789" */
+}
+
+/* ------------- */
+
+int main(int argc, char *argv[]) {
+
+       opj_dinfo_t* dinfo; 
+       opj_event_mgr_t event_mgr;              /* event manager */
+
+  FILE *file, *xmlout;
+/*  char xmloutname[50]; */
+  opj_mj2_t *movie;
+
+  char* infile = 0;
+  char* outfile = 0;
+  char* s, S1, S2, S3;
+  int len;
+  unsigned int sampleframe = 1; /* First frame */
+  char* stringDTD = NULL;
+  BOOL notes = TRUE;
+  BOOL sampletables = FALSE;
+  BOOL raw = TRUE;
+  BOOL derived = TRUE;
+       mj2_dparameters_t parameters;
+
+  while (TRUE) {
+       /* ':' after letter means it takes an argument */
+    int c = getopt(argc, argv, "i:o:f:v:hntrd");
+       /* FUTURE:  Reserve 'p' for pruning file (which will probably make -t redundant) */
+    if (c == -1)
+      break;
+    switch (c) {
+    case 'i':                  /* IN file */
+      infile = optarg;
+      s = optarg;
+      while (*s) { s++; } /* Run to filename end */
+      s--;
+      S3 = *s;
+      s--;
+      S2 = *s;
+      s--;
+      S1 = *s;
+      
+      if ((S1 == 'm' && S2 == 'j' && S3 == '2')
+      || (S1 == 'M' && S2 == 'J' && S3 == '2')) {
+       break;
+      }
+      fprintf(stderr, "Input file name must have .mj2 extension, not .%c%c%c.\n", S1, S2, S3);
+      return 1;
+
+      /* ----------------------------------------------------- */
+    case 'o':                  /* OUT file */
+      outfile = optarg;
+      while (*outfile) { outfile++; } /* Run to filename end */
+      outfile--;
+      S3 = *outfile;
+      outfile--;
+      S2 = *outfile;
+      outfile--;
+      S1 = *outfile;
+      
+      outfile = optarg;
+      
+      if ((S1 == 'x' && S2 == 'm' && S3 == 'l')
+         || (S1 == 'X' && S2 == 'M' && S3 == 'L'))
+        break;
+    
+      fprintf(stderr,
+         "Output file name must have .xml extension, not .%c%c%c\n", S1, S2, S3);
+         return 1;
+
+      /* ----------------------------------------------------- */
+    case 'f':                  /* Choose sample frame.  0 = none */
+      sscanf(optarg, "%u", &sampleframe);
+      break;
+
+      /* ----------------------------------------------------- */
+    case 'v':                  /* Verification by DTD. */
+      stringDTD = optarg;
+         /* We will not insist upon last 3 chars being "dtd", since non-file
+         access protocol may be used. */
+         if(strchr(stringDTD,'"') != NULL) {
+        fprintf(stderr, "-D's string must not contain any embedded double-quote characters.\n");
+           return 1;
+         }
+
+      if (strncmp(stringDTD,"PUBLIC ",7) == 0 || strncmp(stringDTD,"SYSTEM ",7) == 0)
+        break;
+    
+      fprintf(stderr, "-D's string must start with \"PUBLIC \" or \"SYSTEM \"\n");
+         return 1;
+
+    /* ----------------------------------------------------- */
+    case 'n':                  /* Suppress comments */
+      notes = FALSE;
+      break;
+
+    /* ----------------------------------------------------- */
+    case 't':                  /* Show sample size and chunk offset tables */
+      sampletables = TRUE;
+      break;
+
+    /* ----------------------------------------------------- */
+    case 'h':                  /* Display an help description */
+      help_display();
+      return 0;
+
+    /* ----------------------------------------------------- */
+    case 'r':                  /* Suppress raw data */
+      raw = FALSE;
+      break;
+
+    /* ----------------------------------------------------- */
+    case 'd':                  /* Suppress derived data */
+      derived = FALSE;
+      break;
+
+   /* ----------------------------------------------------- */
+    default:
+      return 1;
+    } /* switch */
+  } /* while */
+
+  if(!raw && !derived)
+         raw = TRUE; /* At least one of 'raw' and 'derived' must be true */
+
+    /* Error messages */
+  /* -------------- */
+  if (!infile || !outfile) {
+    fprintf(stderr,"Correct usage: mj2_to_metadata -i mj2-file -o xml-file (plus options)\n");
+    return 1;
+  }
+
+/* was:
+  if (argc != 3) {
+    printf("Bad syntax: Usage: MJ2_to_metadata inputfile.mj2 outputfile.xml\n"); 
+    printf("Example: MJ2_to_metadata foreman.mj2 foreman.xml\n");
+    return 1;
+  }
+*/
+  len = strlen(infile);
+  if(infile[0] == ' ')
+  {
+    infile++; /* There may be a leading blank if user put space after -i */
+  }
+  
+  file = fopen(infile, "rb"); /* was: argv[1] */
+  
+  if (!file) {
+    fprintf(stderr, "Failed to open %s for reading.\n", infile); /* was: argv[1] */
+    return 1;
+  }
+
+  len = strlen(outfile);
+  if(outfile[0] == ' ')
+  {
+    outfile++; /* There may be a leading blank if user put space after -o */
+  }
+
+  // Checking output file
+  xmlout = fopen(outfile, "w"); /* was: argv[2] */
+  if (!xmlout) {
+    fprintf(stderr, "Failed to open %s for writing.\n", outfile); /* was: argv[2] */
+    return 1;
+  }
+  // Leave it open
+
+       /*
+       configure the event callbacks (not required)
+       setting of each callback is optionnal
+       */
+       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
+       event_mgr.error_handler = error_callback;
+       event_mgr.warning_handler = warning_callback;
+       event_mgr.info_handler = info_callback;
+
+       /* get a MJ2 decompressor handle */
+       dinfo = mj2_create_decompress();
+
+       /* catch events using our callbacks and give a local context */
+       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);           
+
+       /* setup the decoder decoding parameters using user parameters */
+       movie = (opj_mj2_t*) dinfo->mj2_handle;
+       mj2_setup_decoder(dinfo->mj2_handle, &parameters);
+
+  if (mj2_read_struct(file, movie)) // Creating the movie structure
+  {
+    fclose(xmlout);
+    return 1;
+  }
+
+  xml_write_init(notes, sampletables, raw, derived);
+  xml_write_struct(file, xmlout, movie, sampleframe, stringDTD, &event_mgr);
+  fclose(xmlout);
+
+       fprintf(stderr,"Metadata correctly extracted to XML file \n");; 
+
+       /* free remaining structures */
+       if(dinfo) {
+               mj2_destroy_decompress((opj_mj2_t*)dinfo->mj2_handle);
+       }
+
+  return 0;
+}
+
+
diff --git a/applications/mj2/mj2_to_metadata.dtd b/applications/mj2/mj2_to_metadata.dtd
new file mode 100644 (file)
index 0000000..249de1a
--- /dev/null
@@ -0,0 +1,425 @@
+<!--
+Preliminary DTD for Open JPEG "mj2_to_metadata" function.
+Last revised: April 20, 2005
+Author:  Glenn Pearson, at U.S. National Library of Medicine.
+See mj2_to_metadata.c regarding copyright, license, disclaimer status.
+
+While the vocabulary of this DTD is based on the relevant portions of the
+ISO/IEC JPEG 200 standard, the detailed representation is the author's own.
+It is neither an ISO/IEC nor NLM official or consensus representation.
+Furthermore, it deviates from a pure representation of the ISO/IEC standard
+in these aspects:
+
+  - it is incomplete in a number of ways (which to some extent may be
+    addressed over time);
+  - it has extensions for "derived" data and "statistics";
+  - it is more flexible.  That is, some elements are marked as optional
+    not because they are optional in an MJ2 file, but because reporting
+    of them is optional based on current or projected mj2_to_metadata
+    command-line flags.
+-->
+<!ELEMENT MJ2_File (JP2?, FileType?, MovieBox?)>
+<!ELEMENT JP2 EMPTY>
+<!ATTLIST JP2 BoxType CDATA #FIXED "jP[space][space]">
+<!ATTLIST JP2 Signature CDATA #FIXED "0x0d0a870a">
+<!ELEMENT FileType (Brand, MinorVersion, CompatibilityList)>
+<!ATTLIST FileType BoxType CDATA #FIXED "ftyp">
+<!ELEMENT Brand (#PCDATA)> <!-- 4 characters max -->
+<!ELEMENT MinorVersion (#PCDATA)> <!-- 4 chararcters max -->
+<!ELEMENT CompatibilityList (CompatibleBrand)*>
+<!ATTLIST CompatibilityList Count CDATA #REQUIRED>  <!-- Count >= 0 -->
+<!ELEMENT CompatibleBrand (#PCDATA)> <!-- 4 characters max -->
+<!ELEMENT MovieBox (MovieHeader, Statistics?, Track*)>
+<!ATTLIST MovieBox BoxType CDATA #FIXED "moov">
+<!ELEMENT MovieHeader (CreationTime, ModificationTime, Timescale, Rate, Duration, Volume, TransformationMatrix)>
+<!ATTLIST MovieHeader BoxType CDATA #FIXED "mvhd">
+<!ELEMENT CreationTime (InSeconds?,AsLocalTime?)>
+<!ELEMENT InSeconds (#PCDATA)>
+<!ELEMENT AsLocalTime (#PCDATA)>
+<!ELEMENT ModificationTime (InSeconds?,AsLocalTime?)>
+<!ELEMENT Timescale (#PCDATA)> <!-- Timescale defines time units in one second -->
+<!ELEMENT Rate (AsHex | (AsHex, AsDecimal) | AsDecimal)>  <!-- Decimal is Approximation; Optional on input. -->
+<!ELEMENT AsHex (#PCDATA)>
+<!ELEMENT AsDecimal (#PCDATA)> 
+<!ELEMENT Duration (InTimeUnits | (InTimeUnits, InSeconds) | InSeconds)>  <!-- InSeconds Optional on input. -->
+<!ELEMENT InTimeUnits (#PCDATA)>
+<!ELEMENT Volume (AsHex | (AsHex, AsDecimal) | AsDecimal)>   <!-- hex default = 0x0100 -->
+<!-- Fixed 8.8 value of audio volume.  Full, normal value is 1.0 (0x0100) -->
+<!ELEMENT TransformationMatrix (TMa,TMb,TMu,TMc,TMd,TMv,TMx,TMy,TMw)> <!-- for video -->
+<!-- 3 x 3 Video Transformation Matrix {a,b,u,c,d,v,x,y,w}.  Required: u=0, v=0, w=1 -->
+<!-- Maps decompressed point (p,q) to rendered point (ap + cq + x, bp + dq + y) -->
+<!-- Stored as Fixed Point Hex: all are 16.16, except u,v,w are 2.30 -->
+<!-- Unity = 0x00010000,0,0,0,0x00010000,0,0,0,0x40000000 -->
+<!ELEMENT TMa (#PCDATA)>    
+<!ELEMENT TMb (#PCDATA)>  
+<!ELEMENT TMu (#PCDATA)> <!--Always "0x00000000" -->
+<!ELEMENT TMc (#PCDATA)>
+<!ELEMENT TMd (#PCDATA)>
+<!ELEMENT TMv (#PCDATA)> <!--Always "0x00000000" -->
+<!ELEMENT TMx (#PCDATA)>
+<!ELEMENT TMy (#PCDATA)>
+<!ELEMENT TMw (#PCDATA)> <!--Always "0x40000000" -->
+
+<!ELEMENT Statistics (TracksFound)>
+<!ELEMENT TracksFound (Video,Audio,Hint)>
+<!ELEMENT Video (#PCDATA)>
+<!ELEMENT Audio (#PCDATA)>
+<!ELEMENT Hint (#PCDATA)>
+
+<!-- For now, output info on at most one video track -->
+
+
+<!ELEMENT Track (TrackHeader, TrackReferenceContainer?, EditListContainer?, Media, JP2_Frame?)>  <!-- JP2_Frame is mj2_to_metadata extension -->
+<!ATTLIST Track BoxType CDATA #FIXED "trak">
+<!ATTLIST Track Instance CDATA #REQUIRED>
+<!ELEMENT TrackHeader (TrackID, TrackLayer?, Volume?, TransformationMatrix?, Width?, Height?)>
+<!ATTLIST TrackHeader BoxType CDATA #FIXED "tkhd">
+<!-- Not shown here: CreationTime, ModificationTime, Duration. -->
+<!-- These 3 fields are reported under MediaHeader below.   When reading these 3, -->
+<!-- m2j_to_metadata currently doesn't distinguish between TrackHeader and MediaHeader source. -->
+<!-- If both found, value read from MediaHeader is used. -->
+<!ELEMENT TrackID (#PCDATA)>
+<!ELEMENT TrackLayer (#PCDATA)>  <!-- front-to-back ordering of video tracks. 0 = normal, -1 is closer, etc. -->
+<!-- "Volume" element described above; here it is for particular audio track.  Full, normal (default = 0x0100) -->
+<!-- "TransformationMatrix" element described above; matrix here is applied before MovieHeader one. -->
+<!ELEMENT Width (AsHex | (AsHex, AsDecimal) | AsDecimal)>
+<!ELEMENT Height (AsHex | (AsHex, AsDecimal) | AsDecimal)>
+<!-- AsHex, AsDecimal already defined above -->
+ <!-- Width and Height are for the presentation; frames will be scaled to this -->
+<!-- /TrackHeader -->
+<!ELEMENT TrackReferenceContainer ANY>  <!-- TO DO: TrackReferenceContainer 'tref'  just used in hint track -->
+<!ELEMENT EditListContainer ANY>  <!-- TO DO: EditListContainer 'edts', contains EditList 'elst' with media-time, segment-duration, media-rate -->
+<!ELEMENT Media (MediaHeader, HandlerReference,MediaInfoContainer)>
+<!ATTLIST Media BoxType CDATA #FIXED "mdia">
+<!ELEMENT MediaHeader (CreationTime,ModificationTime,Timescale,Duration,Language)>
+<!ATTLIST MediaHeader BoxType CDATA #FIXED "mdhd">
+<!-- Elements already defined above: CreationTime, ModificationTime, Timescale, Duration -->
+<!ELEMENT Language (#PCDATA)> <!-- 3 chars max.  There's an enumeration available -->
+<!ELEMENT HandlerReference (HandlerType)>
+<!ATTLIST HandlerReference BoxType CDATA #FIXED "hdlr">
+<!ELEMENT HandlerType (#PCDATA)>
+<!ATTLIST HandlerType Code ( vide | soun | hint ) "vide">
+
+<!-- make the media headers multiple? -->
+<!ELEMENT MediaInfoContainer ((VideoMediaHeader | SoundMediaHeader | HintMediaHeader), DataInfo, SampleTable)>
+<!ATTLIST MediaInfoContainer BoxType CDATA #FIXED "minf">
+<!ELEMENT VideoMediaHeader (GraphicsMode, Opcolor)>
+<!ATTLIST VideoMediaHeader BoxType CDATA #FIXED "vmhd">
+<!ELEMENT GraphicsMode (#PCDATA)>
+          <!-- Enumerated values of graphics mode: -->
+          <!--  0x00 = copy (over existing image); -->
+          <!--  0x24 = transparent; 'blue-screen' this image using opcolor; -->
+          <!--  0x100 = alpha; alpha-blend this image -->
+          <!--  0x101 = whitealpha; alpha-blend this image, which has been blended with white; -->
+          <!--  0x102 = blackalpha; alpha-blend this image, which has been blended with black. -->
+<!ELEMENT Opcolor (Red,Green,Blue)>
+<!ELEMENT Red (#PCDATA)>
+<!ELEMENT Green (#PCDATA)>
+<!ELEMENT Blue (#PCDATA)>
+<!ELEMENT SoundMediaHeader (Balance)>
+<!ATTLIST SoundMediaHeader BoxType CDATA #FIXED "smhd">
+<!ELEMENT Balance (#PCDATA)>
+          <!-- Fixed Point 8.8, fixes mono track in stereo space. -->
+          <!-- 0.0 = center, -1.0 = full left, 1.0 = full right -->
+<!ELEMENT HintMediaHeader (MaxPDU_Size, AvgPDU_Size, MaxBitRate, AvgBitRate, SlidingAvgBitRate)>
+<!ATTLIST HintMediaHeader BoxType CDATA #FIXED "hmhd">
+<!ELEMENT MaxPDU_Size (#PCDATA)>
+          <!-- Size in bytes of largest PDU in this hint stream. -->
+<!ELEMENT AvgPDU_Size (#PCDATA)>
+           <!-- Average size in bytes of a PDU over the entire presentation. -->
+<!ELEMENT MaxBitRate (#PCDATA)>
+          <!-- Maximum rate in bits per second over any window of 1 second. -->
+<!ELEMENT AvgBitRate (#PCDATA)>
+          <!-- Averate rate in bits per second over the entire presentation. -->
+<!ELEMENT SlidingAvgBit (#PCDATA)>
+          <!-- Maximum rate in bits per second over any window of one minute. -->
+<!ELEMENT DataInfo (DataReference)>
+<!ATTLIST DataInfo BoxType CDATA #FIXED "dinf">
+<!ELEMENT DataReference (DataEntryUrlBox | DataEntryUrnBox )*>
+<!ATTLIST DataReference BoxType CDATA #FIXED "dref">
+<!ATTLIST DataReference URL_Count CDATA #REQUIRED>
+<!ATTLIST DataReference URN_Count CDATA #REQUIRED> <!-- table w. flags, URLs, URNs -->
+<!--  // Data structure does not distinguish between single URL, single URN, or DREF table or URLs & URNs.
+  // We could infer those, but for now just present everything as a DREF table.
+-->
+              <!-- No entries here mean that file is self-contained, as required by Simple Profile. -->
+
+<!ELEMENT DataEntryUrlBox (Location)>
+<!ATTLIST DataEntryUrlBox BoxType CDATA #FIXED "url[space]"> <!-- table w. flags, URLs, URNs -->
+            <!-- Only the first 16 bytes of URL location are recorded in mj2_to_metadata data structure. -->
+<!ELEMENT DataEntryUrnBox (Name, Location?)>
+<!ATTLIST DataEntryUrnBox BoxType CDATA #FIXED "urn[space]\">
+            <!-- Only the first 16 bytes each of URN name and optional location are recorded in mj2_to_metadata data structure. -->
+
+<!ELEMENT SampleTable (VisualSampleEntry,TimeToSample,SampleToChunk,SampleSize,ChunkOffset)>  <!-- structure doesn't do non-visual sample entry yet -->
+<!ATTLIST SampleTable BoxType CDATA #FIXED "stbl">  <!-- to add: entry count -->
+            <!-- Next are instances of generic SampleDescription BoxType=\"stsd\" -->
+    <!-- There could be multiple instances of this, but "entry_count" is just a local at read-time.
+       And it's used wrong, too, as count of just visual type, when it's really all 3 types.
+       This is referred to as "smj2" within mj2.c -->
+<!ELEMENT VisualSampleEntry (WidthAsInteger, HeightAsInteger, HorizontalRes, VerticalRes, CompressorName, Depth, JP2Header?, FieldCoding?, MJP2_Profile?, MJP2_Prefix?, MJP2_SubSampling?, MJP2_OriginalFormat?)>
+<!ATTLIST VisualSampleEntry BoxType CDATA #FIXED "mjp2">
+          <!-- If multiple instances of this, only first is shown here. -->
+<!ELEMENT WidthAsInteger (#PCDATA)>
+<!ELEMENT HeightAsInteger (#PCDATA)>
+<!ELEMENT HorizontalRes (AsHex | (AsHex, AsDecimal) | AsDecimal)>
+<!ELEMENT VerticalRes (AsHex | (AsHex, AsDecimal) | AsDecimal)>
+<!-- Typical value for both resolution is 72 (0x00480000) -->
+<!ELEMENT CompressorName (#PCDATA)>
+          <!-- Compressor name for debugging.  Standard restricts max length to 31 bytes. -->
+          <!-- Usually blank or \"Motion JPEG2000\" -->
+<!ELEMENT Depth (#PCDATA)>
+          <!-- Depth is: -->
+          <!--   0x20: alpha channels present (color or grayscale) -->
+          <!--   0x28: grayscale without alpha -->
+          <!--   0x18: color without alpha -->
+
+<!-- TODO somewhere: tk->jp2_struct.numcomps -->
+<!ELEMENT JP2Header (ImageHeader, ColourSpecification)>
+<!ATTLIST JP2Header BoxType CDATA #FIXED "jp2h">
+<!ELEMENT ImageHeader (HEIGHT, WIDTH, NC, BPC, C, UnkC, IPR)>
+<!ATTLIST ImageHeader BoxType CDATA #FIXED "ihdr">
+<!ELEMENT HEIGHT (#PCDATA)>  <!-- If 2 fields/frame, total deinterlaced height -->
+<!ELEMENT WIDTH (#PCDATA)>
+<!ELEMENT NC (#PCDATA)>  <!-- number of components -->
+<!ELEMENT BPC (AsHex | (AsHex,BitsPerPixel,Signed) | (BitsPerPixel,Signed))>
+<!ELEMENT BitsPerPixel (#PCDATA)>
+<!ELEMENT Signed (#PCDATA)>
+<!ELEMENT C (#PCDATA)>  <!-- Compression type.  Only "7" defined -->
+<!ELEMENT UnkC (#PCDATA)>  <!-- Colourspace Unknown. 1 = unknown, 0 = known -->
+<!ELEMENT IPR (#PCDATA)>  <!-- 1 = frame has Intellectual Prop. box; otherwise 0 -->
+<!ELEMENT ColourSpecification (METH, PREC, APPROX, EnumCS)>
+<!ATTLIST ColourSpecification BoxType CDATA #FIXED "colr">
+<!ELEMENT METH (#PCDATA)>  <!-- 1 = EnumCS field; 2 = PROFILE field (not yet generated) -->
+<!ELEMENT PREC (#PCDATA)> <!-- precedence must be 0 so far -->
+<!ELEMENT APPROX (#PCDATA)>  <!-- colourspace approximation must be 0 so far -->
+<!ELEMENT EnumCS (#PCDATA)> <!-- Valid enumerated MJ2 colourspaces: 16 (sRGB), 17 (grey sRGB), 18 (YCC) -->
+
+<!-- Following subboxes are optional -->
+<!ELEMENT FieldCoding (FieldCount, FieldOrder)>
+<!ATTLIST FieldCoding BoxType CDATA #FIXED "fiel">
+<!ELEMENT FieldCount (#PCDATA)>
+            <!-- Must be either 1 or 2 -->
+<!ELEMENT FieldOrder (#PCDATA)>
+            <!-- When FieldCount=2, FieldOrder means: -->
+            <!--   0: Field coding unknown -->
+            <!--   1: Field with topmost line is stored first in sample; fields are in temporal order -->
+            <!--   6: Field with topmost line is stored second in sample; fields are in temporal order -->
+            <!-- Defaults: FieldCount=1, FieldOrder=0 if FieldCoding box not present -->
+            <!-- Current implementation doesn't retain whether box was actually present. -->
+
+<!ELEMENT MJP2_Profile (CompatibleBrand*)>
+<!ATTLIST MJP2_Profile BoxType CDATA #FIXED "jp2p">
+<!ATTLIST MJP2_Profile Count CDATA #REQUIRED>
+
+<!ELEMENT MJP2_Prefix (Data*)>
+<!ATTLIST MJP2_Prefix BoxType CDATA #FIXED "jp2x">
+<!ATTLIST MJP2_Prefix Count CDATA #REQUIRED>
+<!-- We'll probably need better formatting than this  -->
+<!ELEMENT Data (#PCDATA)>    <!-- Multiple. Each entry is single byte -->
+
+<!ELEMENT MJP2_SubSampling (HorizontalSub, VerticalSub, HorizontalOffset, VerticalOffset)>
+<!ATTLIST MJP2_SubSampling BoxType CDATA #FIXED "jsub">
+<!-- These values are all 1 byte -->
+            <!-- Typical subsample value is 2 for 4:2:0 -->
+<!ELEMENT HorizontalSub (#PCDATA)>
+<!ELEMENT VerticalSub (#PCDATA)>
+<!ELEMENT HorizontalOffset (#PCDATA)>
+<!ELEMENT VerticalOffset (#PCDATA)>
+
+<!ELEMENT MJP2_OriginalFormat (OriginalFieldCount, OriginalFieldOrder)>
+<!ATTLIST MJP2_OriginalFormat BoxType CDATA #FIXED "orfo"> <!-- Part III Appx. 2 -->
+<!ELEMENT OriginalFieldCount (#PCDATA)>
+            <!-- In original material before encoding.  Must be either 1 or 2 -->
+<!ELEMENT OriginalFieldOrder (#PCDATA)>
+            <!-- When FieldCount=2, FieldOrder means: -->
+            <!--   0: Field coding unknown -->
+            <!--   11: Topmost line came from the earlier field; -->
+            <!--   16:  Topmost line came form the later field. -->
+            <!-- Defaults: FieldCount=1, FieldOrder=0 if FieldCoding box not present -->
+            <!-- Current implementation doesn't retain whether box was actually present. -->
+
+
+            <!-- mj2_to_metadata's data structure doesn't record Audio and Hint sample data currently. -->
+
+<!-- Within SampleTable: -->
+<!ELEMENT TimeToSample (SampleStatistics, SampleEntries)>
+<!ATTLIST TimeToSample BoxType CDATA #FIXED "stts">  
+<!ELEMENT SampleStatistics (TotalSamples)>  <!-- Not part of standard -->  
+<!ELEMENT TotalSamples (#PCDATA)>
+                <!-- For video, gives the total frames in the track, by summing all entries in the Sample Table -->
+
+<!ELEMENT SampleEntries (Table*)>
+<!ATTLIST SampleEntries EntryCount CDATA #REQUIRED>
+<!ELEMENT Table EMPTY> <!-- Multiple.  Attributes have values -->
+<!ATTLIST Table Entry CDATA #REQUIRED>
+<!ATTLIST Table SampleCount CDATA #REQUIRED>
+<!ATTLIST Table SampleDelta CDATA #REQUIRED>
+
+<!-- Within SampleTable: -->
+<!ELEMENT SampleToChunk (FirstChunk,SamplesPerChunk,SampleDescrIndex)>
+<!ATTLIST SampleToChunk BoxType CDATA #FIXED "stsc">
+<!ATTLIST SampleToChunk Count CDATA #REQUIRED>
+<!ELEMENT FirstChunk (#PCDATA)>
+<!ELEMENT SamplesPerChunk (#PCDATA)>
+<!ELEMENT SampleDescrIndex (#PCDATA)>
+<!ELEMENT SampleSize (Sample_Size,Sample_Count,EntrySize*)>
+<!ATTLIST SampleSize BoxType CDATA #FIXED "stsz">
+<!ELEMENT Sample_Size (#PCDATA)>
+<!ELEMENT Sample_Count (#PCDATA)>
+<!ELEMENT EntrySize (#PCDATA)>  <!-- appears multiply, but only with mj2_to_metadata option -t -->
+<!ATTLIST EntrySize Num CDATA #REQUIRED>
+<!ELEMENT ChunkOffset (EntryCount, Chunk_Offset*)>
+<!ATTLIST ChunkOffset BoxType CDATA #FIXED "stco">
+<!ELEMENT EntryCount (#PCDATA)>
+<!ELEMENT Chunk_Offset (#PCDATA)>  <!-- appears multiply, but only with mj2_to_metadata option -t -->
+<!ATTLIST Chunk_Offset Num CDATA #REQUIRED>
+<!-- </SampleTable> </MediaInfoContainer> </Media> -->
+
+<!-- TO DO: optional UserData 'udat', can contain multiple Copyright 'cprt' -->
+
+
+<!-- Optional, and only for Visual Track: given individual frame -->
+<!ELEMENT JP2_Frame (MainHeader, TilePartHeaders)>
+<!ATTLIST JP2_Frame Num CDATA #REQUIRED>
+<!ELEMENT MainHeader (StartOfCodestream,ImageAndFileSize,CodingStyleDefault,QuantizationDefault,QuantizationComponent*,RegionOfInterest?,ProgressionOrderChange*)>
+<!ELEMENT StartOfCodestream EMPTY>
+<!ATTLIST StartOfCodestream Marker CDATA #FIXED "SOC">
+<!ELEMENT ImageAndFileSize (Xsiz,Ysiz,XOsiz,YOsiz,XTsiz,YTsiz,XTOsiz,YTOsiz,Csiz,Component+)>
+<!ATTLIST ImageAndFileSize Marker CDATA #FIXED "SIZ">
+<!ELEMENT Xsiz (#PCDATA)>
+<!ELEMENT Ysiz (#PCDATA)>  <!-- Xsiz, Ysiz is the size of the reference grid. -->
+<!ELEMENT XOsiz (#PCDATA)>
+<!ELEMENT YOsiz (#PCDATA)>  <!-- XOsiz, YOsiz are offsets from grid origin to image origin. -->
+<!ELEMENT XTsiz (#PCDATA)>
+<!ELEMENT YTsiz (#PCDATA)>  <!-- XTsiz, YTsiz is the size of one tile with respect to the grid. -->
+<!ELEMENT XTOsiz (#PCDATA)>
+<!ELEMENT YTOsiz (#PCDATA)> <!-- XTOsiz, YTOsiz are offsets from grid origin to first tile origin. -->
+<!ELEMENT Csiz (#PCDATA)>  <!-- Csiz is the number of components in the image. -->
+<!-- For image components next -->
+<!ELEMENT Component (Ssiz,XRsiz,YRsiz,WidthOfData,HeightOfData)>
+<!ATTLIST Component Num CDATA #REQUIRED>
+<!ELEMENT Ssiz (AsHex | (AsHex,Signed,PrecisionInBits) | (Signed,PrecisionInBits))>
+<!-- Signed already defined -->
+<!ELEMENT PrecisionInBits (#PCDATA)>  <!--   Bits per pixel (bpp) or pixel depth. -->
+<!ELEMENT XRsiz (#PCDATA)>
+<!ELEMENT YRsiz (#PCDATA)> <!-- XRsiz, YRsiz denote pixel-sample-spacing on the grid, per Part I Annex B. -->
+<!ELEMENT WidthOfData (#PCDATA)>
+<!ELEMENT HeightOfData (#PCDATA)>  <!-- WidthOfData and HeightOfData are calculated values, e.g.: w = roundup((Xsiz - XOsiz)/ XRsiz) -->
+<!-- -->
+<!ELEMENT CodingStyleDefault (Scod,SGcod,SPcod)>
+<!ATTLIST CodingStyleDefault Marker CDATA #FIXED "COD">
+<!ELEMENT Scod (#PCDATA)>
+          <!-- For Scod, specific bits mean (where bit 0 is lowest or rightmost): -->
+          <!-- bit 0: Defines entropy coder precincts -->
+          <!--        0 = (PPx=15, PPy=15); 1 = precincts defined below. -->
+          <!-- bit 1: 1 = SOP marker may be used; 0 = not. -->
+          <!-- bit 2: 1 = EPH marker may be used; 0 = not. -->
+<!ELEMENT SGcod (ProgressionOrder,NumberOfLayers,MultipleComponentTransformation)>
+<!ELEMENT ProgressionOrder (#PCDATA)>
+            <!-- Defined Progression Order Values are: -->
+            <!-- 0 = LRCP; 1 = RLCP; 2 = RPCL; 3 = PCRL; 4 = CPRL -->
+            <!-- where L = "layer", R = "resolution level", C = "component", P = "position". -->
+<!ELEMENT NumberOfLayers (#PCDATA)>
+<!ELEMENT MultipleComponentTransformation (#PCDATA)>
+            <!-- For MCT, 0 = none, 1 = transform first 3 components for efficiency, per Part I Annex G -->
+<!ELEMENT SPcod (NumberOfDecompositionLevels,CodeblockWidth,CodeblockHeight,CodeblockStyle,Transformation)>
+<!ELEMENT NumberOfDecompositionLevels (#PCDATA)>
+<!ELEMENT CodeblockWidth (#PCDATA)>   <!-- CBW and CBH are non-negative, and summed cannot exceed 8 -->
+<!ELEMENT CodeblockHeight (#PCDATA)>  <!-- Codeblock dimension is 2^(value + 2) -->
+<!ELEMENT CodeblockStyle (#PCDATA)>
+            <!-- For CodeblockStyle, bits mean (with value 1=feature on, 0=off): -->
+            <!-- bit 0: Selective arithmetic coding bypass. -->
+            <!-- bit 1: Reset context probabilities on coding pass boundaries. -->
+            <!-- bit 2: Termination on each coding pass. -->
+            <!-- bit 3: Vertically causal context. -->
+            <!-- bit 4: Predictable termination. -->
+            <!-- bit 5: Segmentation symbols are used. -->
+<!ELEMENT Transformation (#PCDATA)> <!-- For Transformation, 0="9-7 irreversible filter", 1="5-3 reversible filter" -->
+        <!-- mj2_to_metadata implementation always reports component[0] as using default COD, -->
+        <!-- and any other component, with main-header style values different from [0], as COC. -->
+<!ELEMENT QuantizationDefault (Sqcd,SPqcd)>
+<!ATTLIST QuantizationDefault Marker CDATA #FIXED "QCD">
+<!ELEMENT Sqcd (AsHex | (AsHex,QuantizationStyle,NumberOfGuardBits) | (QuantizationStyle,NumberOfGuardBits))>
+<!ELEMENT QuantizationStyle (#PCDATA)>  <!-- Default quantization style for all components. -->
+            <!-- Quantization style (in Sqcd's low 5 bits) may be: -->
+            <!--   0 = No quantization. SPqcd size = 8 bits-->
+            <!--   1 = Scalar derived (values signaled for N(L)LL subband only). Use Eq. E.5. SPqcd size = 16. -->
+            <!--   2 = Scalar expounded (values signaled for each subband). SPqcd size = 16. -->
+<!ELEMENT NumberOfGuardBits (#PCDATA)>  <!-- 0-7 guard bits allowed (stored in Sqcd's high 3 bits) -->
+<!ELEMENT SPqcd (ReversibleStepSizeValue | QuantizationStepSizeValues )>  <!-- TO DO: Irreversible choices -->
+<!ELEMENT ReversibleStepSizeValue (DynamicRangeExponent+)>
+            <!-- Current mj2_to_metadata implementation dumps entire internal table, -->
+            <!-- until an exponent with zero value is reached. -->
+            <!-- Exponent epsilon(b) of reversible dynamic range. -->
+            <!-- Hex value is as stored, in high-order 5 bits. -->
+<!ELEMENT DynamicRangeExponent (AsHex | (AsHex, AsDecimal) | AsDecimal)>
+<!ATTLIST DynamicRangeExponent Subband CDATA #REQUIRED>
+<!ELEMENT QuantizationStepSizeValues (QuantizationValues+, CalculatedExponent*)>  <!-- Calculated exponents iff only subband 0 reported -->
+<!ELEMENT QuantizationValues (AsHex | (AsHex,Exponent,Mantissa) | (Exponent,Mantissa))>
+<!ATTLIST QuantizationValues Subband CDATA #REQUIRED>
+<!ELEMENT Exponent (#PCDATA)>
+<!ELEMENT Mantissa (#PCDATA)>
+<!ELEMENT CalculatedExponent (#PCDATA)>
+<!ATTLIST CalculatedExponent Subband CDATA #REQUIRED>
+<!-- /QuantizationDefault -->
+        <!-- mj2_to_metadata implementation always reports component[0] as using default QCD, -->
+        <!-- and any other component, with main-header quantization values different from [0], as QCC. -->
+<!ELEMENT QuantizationComponent (Sqcc,SPqcc)>
+<!ATTLIST QuantizationComponent Marker CDATA #FIXED "QCC">
+<!ATTLIST QuantizationComponent Component CDATA #REQUIRED>
+<!ELEMENT Sqcc (AsHex | (AsHex,QuantizationStyle,NumberOfGuardBits) | (QuantizationStyle,NumberOfGuardBits))>
+<!ELEMENT SPqcc (ReversibleStepSizeValue | QuantizationStepSizeValues )>  <!-- TO DO: Irreversible choices -->
+<!-- /QuantizationComponent -->
+<!-- Don't know if MJ2 files can have regions of interest.  Assume yes -->
+<!ELEMENT RegionOfInterest (Srgn,Crgn,Sprgn)> <!-- Optional in main header, at most 1 per component -->
+<!ATTLIST RegionOfInterest Marker CDATA #FIXED "RGN">
+<!ELEMENT Srgn (#PCDATA)>  <!-- ROI style.  Only style=0 defined: Implicit ROI (max. shift) -->
+<!ELEMENT Crgn (#PCDATA)>  <!-- Zero-based component number. -->
+<!ELEMENT SPrgn (#PCDATA)> <!-- Implicit ROI shift, i.e., binary shifting of ROI coefficients above background. -->
+<!-- </RegionOfInterest> -->
+<!ELEMENT ProgressionOrderChange (Progression+)> <!-- Optional in main header, at most 1 per component (but impl allows more?) -->
+<!ATTLIST ProgressionOrderChange Marker CDATA #REQUIRED>
+<!ELEMENT Progression (RSpoc,CSpoc,LYEpoc,REpoc,CEpoc,Ppoc)>
+<!ATTLIST Progression Num CDATA #REQUIRED>
+<!ELEMENT RSpoc (#PCDATA)> <!-- Resolution level index (inclusive) for progression start. Range: 0 to 33 -->
+<!ELEMENT CSpoc (#PCDATA)> <!-- Component index (inclusive) for progression start. -->
+<!ELEMENT LYEpoc (#PCDATA)> <!-- Layer index (exclusive) for progression end. -->
+<!ELEMENT REpoc (#PCDATA)> <!-- Resolution level index (exclusive) for progression end. Range: RSpoc to 33 -->
+<!ELEMENT CEpoc (#PCDATA)> <!-- Component index (exclusive) for progression end.  Minimum: CSpoc -->
+<!ELEMENT Ppoc (#PCDATA)> <!-- Defined Progression Order Values are: -->
+                          <!-- 0 = LRCP; 1 = RLCP; 2 = RPCL; 3 = PCRL; 4 = CPRL -->
+                          <!-- where L = "layer", R = "resolution level", C = "component", P = "position". -->
+<!-- </Progression>, </ProgressionOrderChange -->
+<!-- /MainHeader -->
+<!ELEMENT TilePartHeaders (TilePartHeader+)>
+<!ATTLIST TilePartHeaders Count CDATA #REQUIRED>
+<!ELEMENT TilePartHeader (StartOfTilePart,CodingStyleDefault,QuantizationDefault,QuantizationComponent*,RegionOfInterest?,ProgressionOrderChange*,StartOfData)>
+<!ATTLIST TilePartHeader Num CDATA #REQUIRED>
+<!ATTLIST TilePartHeader ID CDATA #REQUIRED>
+<!ELEMENT StartOfTilePart EMPTY>
+<!ATTLIST StartOfTilePart Marker CDATA #FIXED "SOT">
+<!-- CodingStyleDefault, QuantizationDefault, QuantizationComponent already defined -->
+        <!-- mj2_to_metadata implementation always reports component[0] as using default QCD, -->
+        <!-- and any other component, with tile-part-header quantization values different from [0], as QCC. -->
+<!ELEMENT StartOfData EMPTY> <!-- always empty for now -->
+<!ATTLIST StartOfData Marker CDATA #FIXED "SOD">
+          <!-- Tile-part bitstream, not shown, follows tile-part header and SOD marker. -->
+<!-- /TilePartHeader, /TilePartHeaders, /JP2_Frame -->
+<!-- </Track> -->
+
+<!-- to come:
+  <MovieExtends mvek> // possibly not in Simple Profile
+  <UserDataBox udat> contains <CopyrightBox cprt>
+  -->
+<!-- /MovieBox -->
+<!-- To come:
+  <mdat>
+  <moof>  // probably not in Simple Profile
+  <free>
+  <skip>
+  -->
+<!-- </MJ2_File> -->
\ No newline at end of file
diff --git a/applications/mj2/mj2_to_metadata.h b/applications/mj2/mj2_to_metadata.h
new file mode 100644 (file)
index 0000000..f4c3491
--- /dev/null
@@ -0,0 +1,9 @@
+/* mj2_to_metadata.h */
+/* Dump MJ2, JP2 metadata (partial so far) to xml file */
+/* Contributed to Open JPEG by Glenn Pearson, U.S. National Library of Medicine */
+
+#define BOOL int
+#define FALSE 0
+#define TRUE 1
+
+#include "meta_out.h"
diff --git a/applications/mj2/mj2_to_metadata.sln b/applications/mj2/mj2_to_metadata.sln
new file mode 100644 (file)
index 0000000..32b926d
--- /dev/null
@@ -0,0 +1,29 @@
+\r
+Microsoft Visual Studio Solution File, Format Version 9.00\r
+# Visual Studio 2005\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mj2_to_metadata", "mj2_to_metadata.vcproj", "{69BE42AB-E7CE-4DA1-BBD2-39FEA2C91E0B}"\r
+       ProjectSection(ProjectDependencies) = postProject\r
+               {0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD} = {0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD}\r
+       EndProjectSection\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibOpenJPEG", "..\LibOpenJPEG.vcproj", "{0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD}"\r
+EndProject\r
+Global\r
+       GlobalSection(SolutionConfigurationPlatforms) = preSolution\r
+               Debug|Win32 = Debug|Win32\r
+               Release|Win32 = Release|Win32\r
+       EndGlobalSection\r
+       GlobalSection(ProjectConfigurationPlatforms) = postSolution\r
+               {69BE42AB-E7CE-4DA1-BBD2-39FEA2C91E0B}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {69BE42AB-E7CE-4DA1-BBD2-39FEA2C91E0B}.Debug|Win32.Build.0 = Debug|Win32\r
+               {69BE42AB-E7CE-4DA1-BBD2-39FEA2C91E0B}.Release|Win32.ActiveCfg = Release|Win32\r
+               {69BE42AB-E7CE-4DA1-BBD2-39FEA2C91E0B}.Release|Win32.Build.0 = Release|Win32\r
+               {0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD}.Debug|Win32.Build.0 = Debug|Win32\r
+               {0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD}.Release|Win32.ActiveCfg = Release|Win32\r
+               {0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD}.Release|Win32.Build.0 = Release|Win32\r
+       EndGlobalSection\r
+       GlobalSection(SolutionProperties) = preSolution\r
+               HideSolutionNode = FALSE\r
+       EndGlobalSection\r
+EndGlobal\r
diff --git a/applications/mj2/mj2_to_metadata.vcproj b/applications/mj2/mj2_to_metadata.vcproj
new file mode 100644 (file)
index 0000000..4207365
--- /dev/null
@@ -0,0 +1,349 @@
+<?xml version="1.0" encoding="Windows-1252"?>\r
+<VisualStudioProject\r
+       ProjectType="Visual C++"\r
+       Version="8,00"\r
+       Name="mj2_to_metadata"\r
+       ProjectGUID="{69BE42AB-E7CE-4DA1-BBD2-39FEA2C91E0B}"\r
+       >\r
+       <Platforms>\r
+               <Platform\r
+                       Name="Win32"\r
+               />\r
+       </Platforms>\r
+       <ToolFiles>\r
+       </ToolFiles>\r
+       <Configurations>\r
+               <Configuration\r
+                       Name="Debug|Win32"\r
+                       OutputDirectory=".\mj2_to_metadata___Win32_Debug0"\r
+                       IntermediateDirectory=".\mj2_to_metadata___Win32_Debug0"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TypeLibraryName=".\mj2_to_metadata___Win32_Debug0/mj2_to_metadata.tlb"\r
+                               HeaderFileName=""\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="0"\r
+                               AdditionalIncludeDirectories="../libopenjpeg"\r
+                               PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;OPJ_STATIC;_CRT_SECURE_NO_DEPRECATE"\r
+                               MinimalRebuild="true"\r
+                               BasicRuntimeChecks="3"\r
+                               RuntimeLibrary="1"\r
+                               PrecompiledHeaderFile=".\mj2_to_metadata___Win32_Debug0/mj2_to_metadata.pch"\r
+                               AssemblerListingLocation=".\mj2_to_metadata___Win32_Debug0/"\r
+                               ObjectFile=".\mj2_to_metadata___Win32_Debug0/"\r
+                               ProgramDataBaseFileName=".\mj2_to_metadata___Win32_Debug0/"\r
+                               BrowseInformation="1"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                               DebugInformationFormat="4"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               PreprocessorDefinitions="_DEBUG"\r
+                               Culture="2057"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               OutputFile=".\mj2_to_metadata___Win32_Debug0/mj2_to_metadata.exe"\r
+                               LinkIncremental="2"\r
+                               SuppressStartupBanner="true"\r
+                               IgnoreDefaultLibraryNames="LIBCMT"\r
+                               GenerateDebugInformation="true"\r
+                               ProgramDatabaseFile=".\mj2_to_metadata___Win32_Debug0/mj2_to_metadata.pdb"\r
+                               SubSystem="1"\r
+                               TargetMachine="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                               SuppressStartupBanner="true"\r
+                               OutputFile=".\mj2_to_metadata___Win32_Debug0/mj2_to_metadata.bsc"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+               <Configuration\r
+                       Name="Release|Win32"\r
+                       OutputDirectory=".\Release"\r
+                       IntermediateDirectory=".\Release"\r
+                       ConfigurationType="1"\r
+                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"\r
+                       UseOfMFC="0"\r
+                       ATLMinimizesCRunTimeLibraryUsage="false"\r
+                       CharacterSet="2"\r
+                       >\r
+                       <Tool\r
+                               Name="VCPreBuildEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCCustomBuildTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXMLDataGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebServiceProxyGeneratorTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCMIDLTool"\r
+                               TypeLibraryName=".\Release/mj2_to_metadata.tlb"\r
+                               HeaderFileName=""\r
+                       />\r
+                       <Tool\r
+                               Name="VCCLCompilerTool"\r
+                               Optimization="2"\r
+                               InlineFunctionExpansion="1"\r
+                               AdditionalIncludeDirectories="../libopenjpeg"\r
+                               PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;OPJ_STATIC;_CRT_SECURE_NO_DEPRECATE"\r
+                               StringPooling="true"\r
+                               RuntimeLibrary="0"\r
+                               EnableFunctionLevelLinking="true"\r
+                               PrecompiledHeaderFile=".\Release/mj2_to_metadata.pch"\r
+                               AssemblerListingLocation=".\Release/"\r
+                               ObjectFile=".\Release/"\r
+                               ProgramDataBaseFileName=".\Release/"\r
+                               WarningLevel="3"\r
+                               SuppressStartupBanner="true"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManagedResourceCompilerTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCResourceCompilerTool"\r
+                               PreprocessorDefinitions="NDEBUG"\r
+                               Culture="2057"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPreLinkEventTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCLinkerTool"\r
+                               OutputFile=".\Release/mj2_to_metadata.exe"\r
+                               LinkIncremental="1"\r
+                               SuppressStartupBanner="true"\r
+                               IgnoreDefaultLibraryNames="libcmtd"\r
+                               ProgramDatabaseFile=".\Release/mj2_to_metadata.pdb"\r
+                               SubSystem="1"\r
+                               TargetMachine="1"\r
+                       />\r
+                       <Tool\r
+                               Name="VCALinkTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCManifestTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCXDCMakeTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCBscMakeTool"\r
+                               SuppressStartupBanner="true"\r
+                               OutputFile=".\Release/mj2_to_metadata.bsc"\r
+                       />\r
+                       <Tool\r
+                               Name="VCFxCopTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCAppVerifierTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCWebDeploymentTool"\r
+                       />\r
+                       <Tool\r
+                               Name="VCPostBuildEventTool"\r
+                       />\r
+               </Configuration>\r
+       </Configurations>\r
+       <References>\r
+       </References>\r
+       <Files>\r
+               <Filter\r
+                       Name="MJ2"\r
+                       >\r
+                       <Filter\r
+                               Name="MJ2 Header Files"\r
+                               >\r
+                               <File\r
+                                       RelativePath="compat\getopt.h"\r
+                                       >\r
+                               </File>\r
+                               <File\r
+                                       RelativePath="meta_out.h"\r
+                                       >\r
+                               </File>\r
+                               <File\r
+                                       RelativePath="mj2.h"\r
+                                       >\r
+                               </File>\r
+                               <File\r
+                                       RelativePath="mj2_convert.h"\r
+                                       >\r
+                               </File>\r
+                               <File\r
+                                       RelativePath="mj2_to_metadata.h"\r
+                                       >\r
+                               </File>\r
+                       </Filter>\r
+                       <Filter\r
+                               Name="MJ2 Source Files"\r
+                               >\r
+                               <File\r
+                                       RelativePath="compat\getopt.c"\r
+                                       >\r
+                                       <FileConfiguration\r
+                                               Name="Debug|Win32"\r
+                                               >\r
+                                               <Tool\r
+                                                       Name="VCCLCompilerTool"\r
+                                                       AdditionalIncludeDirectories=""\r
+                                                       PreprocessorDefinitions=""\r
+                                               />\r
+                                       </FileConfiguration>\r
+                                       <FileConfiguration\r
+                                               Name="Release|Win32"\r
+                                               >\r
+                                               <Tool\r
+                                                       Name="VCCLCompilerTool"\r
+                                                       AdditionalIncludeDirectories=""\r
+                                                       PreprocessorDefinitions=""\r
+                                               />\r
+                                       </FileConfiguration>\r
+                               </File>\r
+                               <File\r
+                                       RelativePath="meta_out.c"\r
+                                       >\r
+                                       <FileConfiguration\r
+                                               Name="Debug|Win32"\r
+                                               >\r
+                                               <Tool\r
+                                                       Name="VCCLCompilerTool"\r
+                                                       AdditionalIncludeDirectories=""\r
+                                                       PreprocessorDefinitions=""\r
+                                               />\r
+                                       </FileConfiguration>\r
+                                       <FileConfiguration\r
+                                               Name="Release|Win32"\r
+                                               >\r
+                                               <Tool\r
+                                                       Name="VCCLCompilerTool"\r
+                                                       AdditionalIncludeDirectories=""\r
+                                                       PreprocessorDefinitions=""\r
+                                               />\r
+                                       </FileConfiguration>\r
+                               </File>\r
+                               <File\r
+                                       RelativePath="mj2.c"\r
+                                       >\r
+                                       <FileConfiguration\r
+                                               Name="Debug|Win32"\r
+                                               >\r
+                                               <Tool\r
+                                                       Name="VCCLCompilerTool"\r
+                                                       AdditionalIncludeDirectories=""\r
+                                                       PreprocessorDefinitions=""\r
+                                               />\r
+                                       </FileConfiguration>\r
+                                       <FileConfiguration\r
+                                               Name="Release|Win32"\r
+                                               >\r
+                                               <Tool\r
+                                                       Name="VCCLCompilerTool"\r
+                                                       AdditionalIncludeDirectories=""\r
+                                                       PreprocessorDefinitions=""\r
+                                               />\r
+                                       </FileConfiguration>\r
+                               </File>\r
+                               <File\r
+                                       RelativePath="mj2_convert.c"\r
+                                       >\r
+                                       <FileConfiguration\r
+                                               Name="Debug|Win32"\r
+                                               >\r
+                                               <Tool\r
+                                                       Name="VCCLCompilerTool"\r
+                                                       AdditionalIncludeDirectories=""\r
+                                                       PreprocessorDefinitions=""\r
+                                               />\r
+                                       </FileConfiguration>\r
+                                       <FileConfiguration\r
+                                               Name="Release|Win32"\r
+                                               >\r
+                                               <Tool\r
+                                                       Name="VCCLCompilerTool"\r
+                                                       AdditionalIncludeDirectories=""\r
+                                                       PreprocessorDefinitions=""\r
+                                               />\r
+                                       </FileConfiguration>\r
+                               </File>\r
+                               <File\r
+                                       RelativePath="mj2_to_metadata.c"\r
+                                       >\r
+                                       <FileConfiguration\r
+                                               Name="Debug|Win32"\r
+                                               >\r
+                                               <Tool\r
+                                                       Name="VCCLCompilerTool"\r
+                                                       AdditionalIncludeDirectories=""\r
+                                                       PreprocessorDefinitions=""\r
+                                               />\r
+                                       </FileConfiguration>\r
+                                       <FileConfiguration\r
+                                               Name="Release|Win32"\r
+                                               >\r
+                                               <Tool\r
+                                                       Name="VCCLCompilerTool"\r
+                                                       AdditionalIncludeDirectories=""\r
+                                                       PreprocessorDefinitions=""\r
+                                               />\r
+                                       </FileConfiguration>\r
+                               </File>\r
+                       </Filter>\r
+               </Filter>\r
+       </Files>\r
+       <Globals>\r
+       </Globals>\r
+</VisualStudioProject>\r
diff --git a/applications/mj2/mj2_to_metadata_Notes.doc b/applications/mj2/mj2_to_metadata_Notes.doc
new file mode 100644 (file)
index 0000000..05ccec2
Binary files /dev/null and b/applications/mj2/mj2_to_metadata_Notes.doc differ
diff --git a/applications/mj2/readme.txt b/applications/mj2/readme.txt
new file mode 100644 (file)
index 0000000..9419d2a
--- /dev/null
@@ -0,0 +1,3 @@
+Attention : the motion jpeg 2000 files currently only work with OpenJPEG v0.97 that you can find here : 
+
+http://www.openjpeg.org/openjpeg_v097.tar.gz
\ No newline at end of file
diff --git a/applications/mj2/wrap_j2k_in_mj2.c b/applications/mj2/wrap_j2k_in_mj2.c
new file mode 100644 (file)
index 0000000..7766dd3
--- /dev/null
@@ -0,0 +1,516 @@
+/*
+ * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2007, Professor Benoit Macq
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux 
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "openjpeg.h"
+#include "../libopenjpeg/j2k.h"
+#include "../libopenjpeg/jp2.h"
+#include "../libopenjpeg/cio.h"
+#include "mj2.h"
+
+static int int_ceildiv(int a, int b) {
+       return (a + b - 1) / b;
+}
+
+/**
+Size of memory first allocated for MOOV box
+*/
+#define TEMP_BUF 10000 
+
+#define ENUMCS_GRAY 16
+#define ENUMCS_SRGB 17
+#define ENUMCS_SYCC 18
+
+#define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51"
+
+/* -------------------------------------------------------------------------- */
+
+static int test_image(const char *fname, mj2_cparameters_t *cp)
+{
+       FILE *reader;
+       opj_image_t *image;
+       unsigned char *src;
+       opj_dinfo_t *dinfo;
+       opj_cio_t *cio;
+       opj_dparameters_t dparameters;
+       int success;
+       long src_len;
+
+       success = 0;
+
+       if((reader = fopen(fname, "rb")) == NULL) return success;
+
+       fseek(reader, 0, SEEK_END);
+       src_len = ftell(reader);
+       fseek(reader, 0, SEEK_SET);
+       src = (unsigned char*) malloc(src_len);
+       fread(src, 1, src_len, reader);
+       fclose(reader);
+
+       if(memcmp(src, J2K_CODESTREAM_MAGIC, 4) != 0)
+   {
+       free(src); return success;
+   }
+       memset(&dparameters, 0, sizeof(opj_dparameters_t));
+
+       opj_set_default_decoder_parameters(&dparameters);
+
+       dinfo = opj_create_decompress(CODEC_J2K);
+
+       opj_setup_decoder(dinfo, &dparameters);
+
+       cio = opj_cio_open((opj_common_ptr)dinfo, src, src_len);
+
+       image = opj_decode(dinfo, cio);
+
+       free(src); cio->buffer = NULL;
+       opj_cio_close(cio);
+
+       if(image == NULL) goto fin;
+
+       cp->numcomps = image->numcomps;
+       cp->w = image->comps[0].w;
+       cp->h = image->comps[0].h;
+       cp->prec = image->comps[0].prec;
+
+       if(image->numcomps > 2 )
+   {
+       if((image->comps[0].dx == 1)
+       && (image->comps[1].dx == 2)
+       && (image->comps[2].dx == 2)
+       && (image->comps[0].dy == 1)
+       && (image->comps[1].dy == 2)
+       && (image->comps[2].dy == 2))// horizontal and vertical
+  {
+//   Y420
+       cp->enumcs = ENUMCS_SYCC;
+       cp->CbCr_subsampling_dx = 2;
+       cp->CbCr_subsampling_dy = 2;
+  }
+       else
+       if((image->comps[0].dx == 1)
+       && (image->comps[1].dx == 2)
+       && (image->comps[2].dx == 2)
+       && (image->comps[0].dy == 1)
+       && (image->comps[1].dy == 1)
+       && (image->comps[2].dy == 1))// horizontal only
+  {
+//   Y422
+       cp->enumcs = ENUMCS_SYCC;
+       cp->CbCr_subsampling_dx = 2;
+       cp->CbCr_subsampling_dy = 1;
+  }
+       else
+       if((image->comps[0].dx == 1)
+       && (image->comps[1].dx == 1)
+       && (image->comps[2].dx == 1)
+       && (image->comps[0].dy == 1)
+       && (image->comps[1].dy == 1)
+       && (image->comps[2].dy == 1))
+  {
+//   Y444 or RGB
+
+       if(image->color_space ==  CLRSPC_SRGB)
+ {
+       cp->enumcs = ENUMCS_SRGB;
+
+//    cp->CbCr_subsampling_dx = 0;
+//    cp->CbCr_subsampling_dy = 0;
+ }
+       else
+ {
+       cp->enumcs = ENUMCS_SYCC;
+
+       cp->CbCr_subsampling_dx = 1;
+       cp->CbCr_subsampling_dy = 1;
+ }
+  }
+       else
+  {
+       goto fin;
+  }
+   }
+       else
+   {
+       cp->enumcs = ENUMCS_GRAY;
+//  cp->CbCr_subsampling_dx = 0;
+//  cp->CbCr_subsampling_dy = 0;
+   }
+       if(image->icc_profile_buf)
+   {
+       cp->meth = 2;
+       free(image->icc_profile_buf); image->icc_profile_buf = NULL;
+   }
+       else cp->meth = 1;
+
+       success = 1;
+fin:
+       if(dinfo)
+        opj_destroy_decompress(dinfo);
+
+       if(image)
+        opj_image_destroy(image);
+
+       return success;
+}
+
+/**
+sample error callback expecting a FILE* client object
+*/
+void error_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[ERROR] %s", msg);
+}
+/**
+sample warning callback expecting a FILE* client object
+*/
+void warning_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[WARNING] %s", msg);
+}
+/**
+sample debug callback expecting a FILE* client object
+*/
+void info_callback(const char *msg, void *client_data) {
+       FILE *stream = (FILE*)client_data;
+       fprintf(stream, "[INFO] %s", msg);
+}
+
+/* -------------------------------------------------------------------------- */
+
+
+
+static void read_siz_marker(FILE *file, opj_image_t *image)
+{
+  int len,i;
+  char buf, buf2[2];
+  unsigned char *siz_buffer;
+       opj_cio_t *cio;
+  
+  fseek(file, 0, SEEK_SET);
+  do {
+    fread(&buf,1,1, file);
+    if (buf==(char)0xff)
+      fread(&buf,1,1, file);
+  }
+  while (!(buf==(char)0x51));
+  
+  fread(buf2,2,1,file);                /* Lsiz                */
+  len = ((buf2[0])<<8) + buf2[1];
+  
+  siz_buffer = (unsigned char*) malloc(len * sizeof(unsigned char));
+  fread(siz_buffer,len, 1, file);
+       cio = opj_cio_open(NULL, siz_buffer, len);
+  
+  cio_read(cio, 2);                    /* Rsiz (capabilities) */
+  image->x1 = cio_read(cio, 4);        /* Xsiz                */
+  image->y1 = cio_read(cio, 4);        /* Ysiz                */
+  image->x0 = cio_read(cio, 4);        /* X0siz               */
+  image->y0 = cio_read(cio, 4);        /* Y0siz               */
+  cio_skip(cio, 16);                   /* XTsiz, YTsiz, XT0siz, YT0siz        */
+  
+  image->numcomps = cio_read(cio,2);   /* Csiz                */
+  image->comps =
+    (opj_image_comp_t *) malloc(image->numcomps * sizeof(opj_image_comp_t));
+       
+  for (i = 0; i < image->numcomps; i++) {
+    int tmp;
+    tmp = cio_read(cio,1);             /* Ssiz_i          */
+    image->comps[i].prec = (tmp & 0x7f) + 1;
+    image->comps[i].sgnd = tmp >> 7;
+    image->comps[i].dx = cio_read(cio,1);      /* XRsiz_i         */
+    image->comps[i].dy = cio_read(cio,1);      /* YRsiz_i         */
+    image->comps[i].resno_decoded = 0; /* number of resolution decoded */
+    image->comps[i].factor = 0;        /* reducing factor by component */
+  }
+  fseek(file, 0, SEEK_SET);
+       opj_cio_close(cio);
+  free(siz_buffer);
+}
+
+static void setparams(opj_mj2_t *movie, opj_image_t *image) {
+  int i, depth_0, depth, sign;
+  
+  movie->tk[0].w = int_ceildiv(image->x1 - image->x0, image->comps[0].dx);
+  movie->tk[0].h = int_ceildiv(image->y1 - image->y0, image->comps[0].dy);
+  mj2_init_stdmovie(movie);
+  
+  movie->tk[0].depth = image->comps[0].prec;
+       
+  if (image->numcomps==3) {
+    if ((image->comps[0].dx == 1) 
+       && (image->comps[1].dx == 1) 
+       && (image->comps[2].dx == 1)) 
+      movie->tk[0].CbCr_subsampling_dx = 1;
+    else 
+       if ((image->comps[0].dx == 1) 
+       && (image->comps[1].dx == 2) 
+       && (image->comps[2].dx == 2))
+      movie->tk[0].CbCr_subsampling_dx = 2;
+    else
+      fprintf(stderr,"Image component sizes are incoherent\n");
+    
+    if ((image->comps[0].dy == 1) 
+       && (image->comps[1].dy == 1) 
+       && (image->comps[2].dy == 1)) 
+      movie->tk[0].CbCr_subsampling_dy = 1;
+    else 
+       if ((image->comps[0].dy == 1) 
+       && (image->comps[1].dy == 2) 
+       && (image->comps[2].dy == 2))
+      movie->tk[0].CbCr_subsampling_dy = 2;
+    else
+      fprintf(stderr,"Image component sizes are incoherent\n");
+  }
+  
+  movie->tk[0].sample_rate = 25;
+  
+  movie->tk[0].jp2_struct.numcomps = image->numcomps;  // NC  
+       
+       /* Init Standard jp2 structure */
+       
+       movie->tk[0].jp2_struct.comps =
+    (opj_jp2_comps_t *) malloc(movie->tk[0].jp2_struct.numcomps * sizeof(opj_jp2_comps_t));
+  movie->tk[0].jp2_struct.precedence = 0;   /* PRECEDENCE*/
+  movie->tk[0].jp2_struct.approx = 0;   /* APPROX*/
+  movie->tk[0].jp2_struct.brand = JP2_JP2;     /* BR         */
+  movie->tk[0].jp2_struct.minversion = 0;      /* MinV       */
+  movie->tk[0].jp2_struct.numcl = 1;
+  movie->tk[0].jp2_struct.cl = (unsigned int *) malloc(movie->tk[0].jp2_struct.numcl * sizeof(int));
+  movie->tk[0].jp2_struct.cl[0] = JP2_JP2;     /* CL0 : JP2  */
+  movie->tk[0].jp2_struct.C = 7;      /* C : Always 7*/
+  movie->tk[0].jp2_struct.UnkC = 0;      /* UnkC, colorspace specified in colr box*/
+  movie->tk[0].jp2_struct.IPR = 0;      /* IPR, no intellectual property*/
+  movie->tk[0].jp2_struct.w = int_ceildiv(image->x1 - image->x0, image->comps[0].dx);
+  movie->tk[0].jp2_struct.h = int_ceildiv(image->y1 - image->y0, image->comps[0].dy);
+  
+  depth_0 = image->comps[0].prec - 1;
+  sign = image->comps[0].sgnd;
+  movie->tk[0].jp2_struct.bpc = depth_0 + (sign << 7);
+  
+  for (i = 1; i < image->numcomps; i++) {
+    depth = image->comps[i].prec - 1;
+    sign = image->comps[i].sgnd;
+    if (depth_0 != depth)
+      movie->tk[0].jp2_struct.bpc = 255;
+  }
+  
+  for (i = 0; i < image->numcomps; i++)
+    movie->tk[0].jp2_struct.comps[i].bpcc =
+    image->comps[i].prec - 1 + (image->comps[i].sgnd << 7);
+  
+  if ((image->numcomps == 1 || image->numcomps == 3)
+    && (movie->tk[0].jp2_struct.bpc != 255))
+    movie->tk[0].jp2_struct.meth = 1;
+  else
+    movie->tk[0].jp2_struct.meth = 2;
+       
+    if (image->numcomps == 1)
+     movie->tk[0].jp2_struct.enumcs = 17;  // Grayscale
+  
+    else   
+       if ((image->comps[0].dx == 1) 
+       && (image->comps[1].dx == 1) 
+       && (image->comps[2].dx == 1) 
+    && (image->comps[0].dy == 1) 
+       && (image->comps[1].dy == 1) 
+       && (image->comps[2].dy == 1)) 
+     movie->tk[0].jp2_struct.enumcs = 16;    // RGB
+  
+    else   
+       if ((image->comps[0].dx == 1) 
+       && (image->comps[1].dx == 2) 
+       && (image->comps[2].dx == 2) 
+    && (image->comps[0].dy == 1) 
+       && (image->comps[1].dy == 2) 
+       && (image->comps[2].dy == 2)) 
+     movie->tk[0].jp2_struct.enumcs = 18;  // YUV
+  
+  else
+    movie->tk[0].jp2_struct.enumcs = 0;        // Unkown profile */
+}
+
+int main(int argc, char *argv[]) {
+       opj_cinfo_t* cinfo; 
+       opj_event_mgr_t event_mgr;              /* event manager */  
+  unsigned int snum;
+  opj_mj2_t *movie;
+  mj2_sample_t *sample;
+  unsigned char* frame_codestream;
+  FILE *mj2file, *j2kfile;
+  char *j2kfilename;
+  unsigned char *buf;
+  int offset, mdat_initpos;
+  opj_image_t img;
+       opj_cio_t *cio;
+       mj2_cparameters_t parameters;
+       
+  if (argc != 3) {
+    printf("Usage: %s source_location mj2_filename\n",argv[0]);
+    printf("Example: %s input/input output.mj2\n",argv[0]);
+    return 1;
+  }
+  
+  mj2file = fopen(argv[2], "wb");
+  
+  if (!mj2file) {
+    fprintf(stderr, "failed to open %s for writing\n", argv[2]);
+    return 1;
+  }
+       memset(&img, 0, sizeof(opj_image_t));
+       /*
+       configure the event callbacks (not required)
+       setting of each callback is optionnal
+       */
+       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
+       event_mgr.error_handler = error_callback;
+       event_mgr.warning_handler = warning_callback;
+       event_mgr.info_handler = info_callback;
+
+       /* get a MJ2 decompressor handle */
+       cinfo = mj2_create_compress();
+
+       /* catch events using our callbacks and give a local context */
+       opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);   
+       
+       /* setup the decoder encoding parameters using user parameters */
+       memset(&parameters, 0, sizeof(mj2_cparameters_t));
+       movie = (opj_mj2_t*) cinfo->mj2_handle;
+
+       j2kfilename = (char*)malloc(strlen(argv[1]) + 12);/* max. '%6d' */
+       sprintf(j2kfilename, "%s_00001.j2k",argv[1]);
+
+       if(test_image(j2kfilename, &parameters) == 0) goto fin;
+
+       parameters.frame_rate = 25; /* DEFAULT */
+
+       mj2_setup_encoder(movie, &parameters);
+
+  
+       /* Writing JP, FTYP and MDAT boxes 
+       Assuming that the JP and FTYP boxes won't be longer than 300 bytes */
+       
+  buf = (unsigned char*) malloc (300 * sizeof(unsigned char)); 
+  cio = opj_cio_open(movie->cinfo, buf, 300);
+  mj2_write_jp(cio);
+  mj2_write_ftyp(movie, cio);
+  mdat_initpos = cio_tell(cio);
+  cio_skip(cio, 4);
+  cio_write(cio,MJ2_MDAT, 4);  
+  fwrite(buf,cio_tell(cio),1,mj2file);
+  free(buf);
+       
+  // Insert each j2k codestream in a JP2C box  
+  snum=0;
+  offset = 0;  
+  while(1)
+  {
+    sample = &movie->tk[0].sample[snum];
+    sprintf(j2kfilename,"%s_%05d.j2k",argv[1],snum);
+    j2kfile = fopen(j2kfilename, "rb");
+    if (!j2kfile) {
+      if (snum==0) {  // Could not open a single codestream
+                               fprintf(stderr, "failed to open %s for reading\n",j2kfilename);
+                               return 1;
+      }
+      else {         // Tried to open a inexistant codestream
+                               fprintf(stdout,"%d frames are being added to the MJ2 file\n",snum);
+                               break;
+      }
+    }
+
+    // Calculating offset for samples and chunks
+    offset += cio_tell(cio);     
+    sample->offset = offset;
+    movie->tk[0].chunk[snum].offset = offset;  // There will be one sample per chunk
+    
+    // Calculating sample size
+    fseek(j2kfile,0,SEEK_END); 
+    sample->sample_size = ftell(j2kfile) + 8; // Sample size is codestream + JP2C box header
+    fseek(j2kfile,0,SEEK_SET);
+    
+    // Reading siz marker of j2k image for the first codestream
+    if (snum==0)             
+      read_siz_marker(j2kfile, &img);
+    
+    // Writing JP2C box header                     
+    frame_codestream = (unsigned char*) malloc (sample->sample_size+8); 
+               cio = opj_cio_open(movie->cinfo, frame_codestream, sample->sample_size);    
+    cio_write(cio,sample->sample_size, 4);  // Sample size
+    cio_write(cio,JP2_JP2C, 4);        // JP2C
+    
+    // Writing codestream from J2K file to MJ2 file
+    fread(frame_codestream+8,sample->sample_size-8,1,j2kfile);
+    fwrite(frame_codestream,sample->sample_size,1,mj2file);
+    cio_skip(cio, sample->sample_size-8);
+    
+    // Ending loop
+    fclose(j2kfile);
+    snum++;
+    movie->tk[0].sample = (mj2_sample_t*)
+               realloc(movie->tk[0].sample, (snum+1) * sizeof(mj2_sample_t));
+    movie->tk[0].chunk = (mj2_chunk_t*)
+               realloc(movie->tk[0].chunk, (snum+1) * sizeof(mj2_chunk_t));
+    free(frame_codestream);
+  }
+  
+  // Writing the MDAT box length in header
+  offset += cio_tell(cio);
+  buf = (unsigned char*) malloc (4 * sizeof(unsigned char));
+       cio = opj_cio_open(movie->cinfo, buf, 4);
+  cio_write(cio,offset-mdat_initpos,4); 
+  fseek(mj2file,(long)mdat_initpos,SEEK_SET);
+  fwrite(buf,4,1,mj2file);
+  fseek(mj2file,0,SEEK_END);
+  free(buf);
+       
+  // Setting movie parameters
+  movie->tk[0].num_samples=snum;
+  movie->tk[0].num_chunks=snum;
+  setparams(movie, &img);
+       
+  // Writing MOOV box 
+       buf = (unsigned char*) malloc ((TEMP_BUF+snum*20) * sizeof(unsigned char));
+       cio = opj_cio_open(movie->cinfo, buf, (TEMP_BUF+snum*20));
+       mj2_write_moov(movie, cio);
+  fwrite(buf,cio_tell(cio),1,mj2file);
+       
+  // Ending program
+  free(img.comps);
+  opj_cio_close(cio);
+
+fin:
+  fclose(mj2file);
+  mj2_destroy_compress(movie);
+  free(j2kfilename);
+
+  return 0;
+}
diff --git a/codec/CMakeLists.txt b/codec/CMakeLists.txt
deleted file mode 100644 (file)
index 791d13b..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-  # Build the demo app, small examples
-
-# First thing define the common source:
-SET(common_SRCS
-  convert.c
-  index.c
-  ${OPENJPEG_SOURCE_DIR}/common/color.c
-)
-
-# If not getopt was found then add it to the lib:
-IF(DONT_HAVE_GETOPT)
-  SET(common_SRCS
-    ${common_SRCS}
-    ${OPENJPEG_SOURCE_DIR}/common/getopt.c
-  )
-ENDIF(DONT_HAVE_GETOPT)
-
-# Headers file are located here:
-INCLUDE_DIRECTORIES(
-  ${OPENJPEG_SOURCE_DIR}/libopenjpeg
-  ${LCMS_INCLUDE_DIRNAME}
-  ${OPENJPEG_SOURCE_DIR}/common
-  ${Z_INCLUDE_DIRNAME}
-  ${PNG_INCLUDE_DIRNAME}
-  ${TIFF_INCLUDE_DIRNAME}
-  )
-
-IF(WIN32)
-  IF(BUILD_SHARED_LIBS)
-    ADD_DEFINITIONS(-DOPJ_EXPORTS)
-  ELSE(BUILD_SHARED_LIBS)
-    ADD_DEFINITIONS(-DOPJ_STATIC)
-  ENDIF(BUILD_SHARED_LIBS)
-ENDIF(WIN32)
-
-# Loop over all executables:
-FOREACH(exe j2k_to_image image_to_j2k j2k_dump)
-  ADD_EXECUTABLE(${exe} ${exe}.c ${common_SRCS})
-  TARGET_LINK_LIBRARIES(${exe} ${OPENJPEG_LIBRARY_NAME} 
-       ${LCMS_LIBNAME} ${Z_LIBNAME} ${PNG_LIBNAME} ${TIFF_LIBNAME})
-
-  ADD_TEST(${exe} ${EXECUTABLE_OUTPUT_PATH}/${exe})
-  # calling those exe without option will make them fail always:
-  SET_TESTS_PROPERTIES(${exe} PROPERTIES WILL_FAIL TRUE)
-  # On unix you need to link to the math library:
-  IF(UNIX)
-    TARGET_LINK_LIBRARIES(${exe} m)
-  ENDIF(UNIX)
-  # Install exe
-  INSTALL(TARGETS ${exe}
-    EXPORT OpenJPEGTargets
-    DESTINATION ${OPENJPEG_INSTALL_BIN_DIR} COMPONENT Applications
-  )
-ENDFOREACH(exe)
-
-# Install man pages
-INSTALL(
-  FILES       ../doc/man/man1/image_to_j2k.1
-              ../doc/man/man1/j2k_dump.1
-              ../doc/man/man1/j2k_to_image.1
-  DESTINATION ${OPENJPEG_INSTALL_MAN_DIR}/man1)
-#
-
-if(BUILD_TESTING)
-# Do testing here, once we know the examples are being built:
-FILE(GLOB_RECURSE OPENJPEG_DATA_IMAGES_GLOB
-  "${JPEG2000_CONFORMANCE_DATA_ROOT}/*.j2k"
-  "${JPEG2000_CONFORMANCE_DATA_ROOT}/*.j2c"
-  "${JPEG2000_CONFORMANCE_DATA_ROOT}/*.jp2"
-  )
-
-foreach(filename ${OPENJPEG_DATA_IMAGES_GLOB})
-  get_filename_component(filename_temp ${filename} NAME)
-  get_filename_component(filename_ext ${filename} EXT)
-  execute_process(COMMAND ${EXECUTABLE_OUTPUT_PATH}/j2k_dump -i ${filename}
-    OUTPUT_VARIABLE dump_success
-    OUTPUT_FILE ${CMAKE_CURRENT_BINARY_DIR}/${filename_temp}.dump
-    ERROR_QUIET
-  )
-  if(dump_success)
-  file(READ ${CMAKE_CURRENT_BINARY_DIR}/${filename_temp}.dump numcomp_file)
-  string(REGEX REPLACE ".*numcomps=([0-9]+).*" "\\1"
-    numcomps "${numcomp_file}")
-  #message( "found:${output_variable} for ${filename_temp}" )
-  endif()
-  ADD_TEST(dump-${filename_temp} ${EXECUTABLE_OUTPUT_PATH}/j2k_dump -i ${filename})
-  foreach(codec_type ppm pgx bmp tif raw tga png)
-    ADD_TEST(j2i-${filename_temp}-${codec_type} ${EXECUTABLE_OUTPUT_PATH}/j2k_to_image -i ${filename} -o ${filename_temp}.${codec_type})
-  endforeach(codec_type)
-  foreach(codec_type ppm bmp tif tga png)
-    ADD_TEST(i2j-${filename_temp}-${codec_type} ${EXECUTABLE_OUTPUT_PATH}/image_to_j2k -i ${filename_temp}.${codec_type} -o ${filename_temp}.${codec_type}${filename_ext})
-    #if(UNIX)
-    #  ADD_TEST(cmp-${filename_temp}-${codec_type} cmp ${filename} ${filename_temp}.${codec_type}${filename_ext})
-    #endif(UNIX)
-  endforeach(codec_type)
-endforeach(filename)
-endif(BUILD_TESTING)
diff --git a/codec/Makefile.am b/codec/Makefile.am
deleted file mode 100644 (file)
index 14e5160..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-MAINTAINERCLEANFILES = Makefile.in
-
-bin_PROGRAMS = j2k_to_image image_to_j2k j2k_dump
-
-j2k_to_image_CPPFLAGS = \
--I. \
--I$(top_srcdir)/codec \
--I$(top_builddir)/codec \
--I$(top_srcdir)/common \
--I$(top_builddir)/common \
--I$(top_srcdir)/libopenjpeg \
--I$(top_builddir)/libopenjpeg \
-@PNG_CFLAGS@ \
-@TIFF_CFLAGS@ \
-@LCMS1_CFLAGS@ \
-@LCMS2_CFLAGS@
-j2k_to_image_CFLAGS = 
-j2k_to_image_LDADD = $(top_builddir)/libopenjpeg/libopenjpeg.la @LCMS1_LIBS@ @LCMS2_LIBS@ @TIFF_LIBS@ @PNG_LIBS@ -lm
-j2k_to_image_SOURCES = \
-../common/color.c \
-../common/getopt.c \
-convert.c \
-index.c \
-j2k_to_image.c \
-../common/color.h
-
-image_to_j2k_CPPFLAGS = \
--I. \
--I$(top_srcdir)/codec \
--I$(top_builddir)/codec \
--I$(top_srcdir)/common \
--I$(top_builddir)/common \
--I$(top_srcdir)/libopenjpeg \
--I$(top_builddir)/libopenjpeg \
-@PNG_CFLAGS@ \
-@TIFF_CFLAGS@
-image_to_j2k_CFLAGS = 
-image_to_j2k_LDADD = $(top_builddir)/libopenjpeg/libopenjpeg.la @TIFF_LIBS@ @PNG_LIBS@ -lm
-image_to_j2k_SOURCES = \
-../common/getopt.c \
-convert.c \
-index.c \
-image_to_j2k.c \
-convert.h \
-../common/format_defs.h \
-index.h
-
-j2k_dump_CPPFLAGS = \
--I. \
--I$(top_srcdir)/codec \
--I$(top_builddir)/codec \
--I$(top_srcdir)/common \
--I$(top_builddir)/common \
--I$(top_srcdir)/libopenjpeg \
--I$(top_builddir)/libopenjpeg
-j2k_dump_CFLAGS = 
-j2k_dump_LDADD = $(top_builddir)/libopenjpeg/libopenjpeg.la -lm
-j2k_dump_SOURCES = \
-../common/getopt.c \
-index.c \
-j2k_dump.c \
-../common/getopt.h \
-index.h
-
-EXTRA_DIST = \
-CMakeLists.txt \
-windirent.h
-
-install-data-hook:
-       @echo -e " (B)\t$(bindir)/j2k_to_image$(EXEEXT)" >> $(top_builddir)/report.txt
-       @echo -e " (B)\t$(bindir)/image_to_j2k$(EXEEXT)" >> $(top_builddir)/report.txt
-       @echo -e " (B)\t$(bindir)/j2k_dump$(EXEEXT)" >> $(top_builddir)/report.txt
diff --git a/codec/Makefile.nix b/codec/Makefile.nix
deleted file mode 100644 (file)
index 183e905..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-#codec Makefile
-include ../config.nix
-
-CFLAGS = -Wall
-
-INSTALL_BIN = $(prefix)/bin
-
-INCLUDE = -I.. -I. -I../libopenjpeg -I../common
-USERLIBS = -lm
-
-ifeq ($(WITH_TIFF),yes)
-INCLUDE += $(TIFF_INCLUDE)
-USERLIBS += $(TIFF_LIB)
-endif
-
-ifeq ($(WITH_PNG),yes)
-INCLUDE += $(PNG_INCLUDE)
-USERLIBS += $(PNG_LIB)
-endif
-
-ifeq ($(WITH_LCMS2),yes)
-INCLUDE += $(LCMS2_INCLUDE)
-USERLIBS += $(LCMS2_LIB)
-endif
-
-ifeq ($(WITH_LCMS1),yes)
-INCLUDE += $(LCMS1_INCLUDE)
-USERLIBS += $(LCMS1_LIB)
-endif
-
-CFLAGS += $(INCLUDE) -lstdc++ # -g -p -pg
-
-all: j2k_to_image image_to_j2k j2k_dump
-       install -d ../bin
-       install j2k_to_image image_to_j2k j2k_dump ../bin
-
-ifeq ($(ENABLE_SHARED),yes)
-ELIB = ../libopenjpeg.so.$(MAJOR).$(MINOR).$(BUILD)
-else
-ELIB = ../libopenjpeg.a
-endif
-
-j2k_to_image: j2k_to_image.c $(ELIB)
-       $(CC)  $(CFLAGS) ../common/getopt.c index.c convert.c \
-       ../common/color.c j2k_to_image.c \
-       -o j2k_to_image  $(ELIB) $(USERLIBS)
-
-image_to_j2k: image_to_j2k.c  $(ELIB)
-       $(CC) $(CFLAGS) ../common/getopt.c index.c convert.c image_to_j2k.c \
-       -o image_to_j2k  $(ELIB) $(USERLIBS)
-
-j2k_dump: j2k_dump.c  $(ELIB)
-       $(CC) $(CFLAGS) ../common/getopt.c index.c j2k_dump.c \
-       -o j2k_dump $(ELIB) $(USERLIBS)
-
-clean:
-       rm -f j2k_to_image image_to_j2k j2k_dump
-
-install: all
-       install -d $(DESTDIR)$(INSTALL_BIN)
-       install -m 755 -o root -g root j2k_to_image $(DESTDIR)$(INSTALL_BIN)
-       install -m 755 -o root -g root image_to_j2k $(DESTDIR)$(INSTALL_BIN)
-       install -m 755 -o root -g root j2k_dump $(DESTDIR)$(INSTALL_BIN)
-
-uninstall:
-       rm -f $(DESTDIR)$(INSTALL_BIN)/j2k_to_image
-       rm -f $(DESTDIR)$(INSTALL_BIN)/image_to_j2k
-       rm -f $(DESTDIR)$(INSTALL_BIN)/j2k_dump
diff --git a/codec/README b/codec/README
deleted file mode 100644 (file)
index 8004998..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-Simple codec compilation
-------------------------
-Once you've built the library, you might want to test it with a basic codec. To do this, go to the codec directory and either use the provided Makefile or use one of the following commands to build an encoder and decoder respectively:
-
-gcc index.c convert.c image_to_j2k.c -o image_to_j2k -lopenjpeg -I ../libopenjpeg/ -lm -ltiff
-gcc index.c convert.c j2k_to_image.c -o j2k_to_image -lopenjpeg -I ../libopenjpeg/ -lm -ltiff
-
-You should add '-L..' to those lines if you did not use the 'install' target when building the library.
\ No newline at end of file
diff --git a/codec/convert.c b/codec/convert.c
deleted file mode 100644 (file)
index 98d5435..0000000
+++ /dev/null
@@ -1,3193 +0,0 @@
-/*
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
- * Copyright (c) 2002-2007, Professor Benoit Macq
- * Copyright (c) 2001-2003, David Janssens
- * Copyright (c) 2002-2003, Yannick Verschueren
- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
- * Copyright (c) 2005, Herve Drolon, FreeImage Team
- * Copyright (c) 2006-2007, Parvatha Elangovan
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-#include "opj_config.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-
-#ifdef HAVE_LIBTIFF
-#include <tiffio.h>
-#endif /* HAVE_LIBTIFF */
-
-#ifdef HAVE_LIBPNG
-#include <zlib.h>
-#include <png.h>
-#endif /* HAVE_LIBPNG */
-
-#include "../libopenjpeg/openjpeg.h"
-#include "convert.h"
-
-/*
- * Get logarithm of an integer and round downwards.
- *
- * log2(a)
- */
-static int int_floorlog2(int a) {
-       int l;
-       for (l = 0; a > 1; l++) {
-               a >>= 1;
-       }
-       return l;
-}
-
-/* -->> -->> -->> -->>
-
-  TGA IMAGE FORMAT
-
- <<-- <<-- <<-- <<-- */
-
-// TGA header definition.
-#pragma pack(push,1) // Pack structure byte aligned
-typedef struct tga_header
-{                           
-    unsigned char   id_length;              /* Image id field length    */
-    unsigned char   colour_map_type;        /* Colour map type          */
-    unsigned char   image_type;             /* Image type               */
-    /*
-    ** Colour map specification
-    */
-    unsigned short  colour_map_index;       /* First entry index        */
-    unsigned short  colour_map_length;      /* Colour map length        */
-    unsigned char   colour_map_entry_size;  /* Colour map entry size    */
-    /*
-    ** Image specification
-    */
-    unsigned short  x_origin;               /* x origin of image        */
-    unsigned short  y_origin;               /* u origin of image        */
-    unsigned short  image_width;            /* Image width              */
-    unsigned short  image_height;           /* Image height             */
-    unsigned char   pixel_depth;            /* Pixel depth              */
-    unsigned char   image_desc;             /* Image descriptor         */
-} tga_header;
-#pragma pack(pop) // Return to normal structure packing alignment.
-
-int tga_readheader(FILE *fp, unsigned int *bits_per_pixel, 
-       unsigned int *width, unsigned int *height, int *flip_image)
-{
-       int palette_size;
-       tga_header tga ;
-
-       if (!bits_per_pixel || !width || !height || !flip_image)
-               return 0;
-       
-       // Read TGA header
-       fread((unsigned char*)&tga, sizeof(tga_header), 1, fp);
-
-       *bits_per_pixel = tga.pixel_depth;
-       
-       *width  = tga.image_width;
-       *height = tga.image_height ;
-
-       // Ignore tga identifier, if present ...
-       if (tga.id_length)
-       {
-               unsigned char *id = (unsigned char *) malloc(tga.id_length);
-               fread(id, tga.id_length, 1, fp);
-               free(id);  
-       }
-
-       // Test for compressed formats ... not yet supported ...
-       // Note :-  9 - RLE encoded palettized.
-       //                 10 - RLE encoded RGB.
-       if (tga.image_type > 8)
-       {
-               fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
-               return 0 ;
-       }
-
-       *flip_image = !(tga.image_desc & 32);
-
-       // Palettized formats are not yet supported, skip over the palette, if present ... 
-       palette_size = tga.colour_map_length * (tga.colour_map_entry_size/8);
-       
-       if (palette_size>0)
-       {
-               fprintf(stderr, "File contains a palette - not yet supported.");
-               fseek(fp, palette_size, SEEK_CUR);
-       }
-       return 1;
-}
-
-int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height, 
-       bool flip_image)
-{
-       tga_header tga;
-
-       if (!bits_per_pixel || !width || !height)
-               return 0;
-
-       memset(&tga, 0, sizeof(tga_header));
-
-       tga.pixel_depth = bits_per_pixel;
-       tga.image_width  = width;
-       tga.image_height = height;
-       tga.image_type = 2; // Uncompressed.
-       tga.image_desc = 8; // 8 bits per component.
-
-       if (flip_image)
-               tga.image_desc |= 32;
-
-       // Write TGA header
-       fwrite((unsigned char*)&tga, sizeof(tga_header), 1, fp);
-
-       return 1;
-}
-
-opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
-       FILE *f;
-       opj_image_t *image;
-       unsigned int image_width, image_height, pixel_bit_depth;
-       unsigned int x, y;
-       int flip_image=0;
-       opj_image_cmptparm_t cmptparm[4];       /* maximum 4 components */
-       int numcomps;
-       OPJ_COLOR_SPACE color_space;
-       bool mono ;
-       bool save_alpha;
-       int subsampling_dx, subsampling_dy;
-       int i;  
-
-       f = fopen(filename, "rb");
-       if (!f) {
-               fprintf(stderr, "Failed to open %s for reading !!\n", filename);
-               return 0;
-       }
-
-       if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image))
-               return NULL;
-
-       // We currently only support 24 & 32 bit tga's ...
-       if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32)))
-               return NULL;
-
-       /* initialize image components */   
-       memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
-
-       mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16);  // Mono with & without alpha.
-       save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); // Mono with alpha, or RGB with alpha
-
-       if (mono) {
-               color_space = CLRSPC_GRAY;
-               numcomps = save_alpha ? 2 : 1;
-       }       
-       else {
-               numcomps = save_alpha ? 4 : 3;
-               color_space = CLRSPC_SRGB;
-       }
-
-       subsampling_dx = parameters->subsampling_dx;
-       subsampling_dy = parameters->subsampling_dy;
-
-       for (i = 0; i < numcomps; i++) {
-               cmptparm[i].prec = 8;
-               cmptparm[i].bpp = 8;
-               cmptparm[i].sgnd = 0;
-               cmptparm[i].dx = subsampling_dx;
-               cmptparm[i].dy = subsampling_dy;
-               cmptparm[i].w = image_width;
-               cmptparm[i].h = image_height;
-       }
-
-       /* create the image */
-       image = opj_image_create(numcomps, &cmptparm[0], color_space);
-
-       if (!image)
-               return NULL;
-
-       /* set image offset and reference grid */
-       image->x0 = parameters->image_offset_x0;
-       image->y0 = parameters->image_offset_y0;
-       image->x1 =     !image->x0 ? (image_width - 1) * subsampling_dx + 1 : image->x0 + (image_width - 1) * subsampling_dx + 1;
-       image->y1 =     !image->y0 ? (image_height - 1) * subsampling_dy + 1 : image->y0 + (image_height - 1) * subsampling_dy + 1;
-
-       /* set image data */
-       for (y=0; y < image_height; y++) 
-       {
-               int index;
-
-               if (flip_image)
-                       index = (image_height-y-1)*image_width;
-               else
-                       index = y*image_width;
-
-               if (numcomps==3)
-               {
-                       for (x=0;x<image_width;x++) 
-                       {
-                               unsigned char r,g,b;
-                               fread(&b, 1, 1, f);
-                               fread(&g, 1, 1, f);
-                               fread(&r, 1, 1, f);
-
-                               image->comps[0].data[index]=r;
-                               image->comps[1].data[index]=g;
-                               image->comps[2].data[index]=b;
-                               index++;
-                       }
-               }
-               else if (numcomps==4)
-               {
-                       for (x=0;x<image_width;x++) 
-                       {
-                               unsigned char r,g,b,a;
-                               fread(&b, 1, 1, f);
-                               fread(&g, 1, 1, f);
-                               fread(&r, 1, 1, f);
-                               fread(&a, 1, 1, f);
-
-                               image->comps[0].data[index]=r;
-                               image->comps[1].data[index]=g;
-                               image->comps[2].data[index]=b;
-                               image->comps[3].data[index]=a;
-                               index++;
-                       }
-               }
-               else {
-                       fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
-               }
-       }       
-       return image;
-}
-
-int imagetotga(opj_image_t * image, const char *outfile) {
-       int width, height, bpp, x, y;
-       bool write_alpha;
-       int i;
-       unsigned int alpha_channel;
-       float r,g,b,a;
-       unsigned char value;
-       float scale;
-       FILE *fdest;
-
-       fdest = fopen(outfile, "wb");
-       if (!fdest) {
-               fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
-               return 1;
-       }
-
-       for (i = 0; i < image->numcomps-1; i++) {
-               if ((image->comps[0].dx != image->comps[i+1].dx) 
-                       ||(image->comps[0].dy != image->comps[i+1].dy) 
-                       ||(image->comps[0].prec != image->comps[i+1].prec))     {
-      fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.");
-      return 1;
-   }
-       }
-
-       width = image->comps[0].w;
-       height = image->comps[0].h; 
-
-       // Mono with alpha, or RGB with alpha.
-       write_alpha = (image->numcomps==2) || (image->numcomps==4);   
-
-       // Write TGA header 
-       bpp = write_alpha ? 32 : 24;
-       if (!tga_writeheader(fdest, bpp, width , height, true))
-               return 1;
-
-       alpha_channel = image->numcomps-1; 
-
-       scale = 255.0f / (float)((1<<image->comps[0].prec)-1);
-
-       for (y=0; y < height; y++) {
-               unsigned int index=y*width;
-
-               for (x=0; x < width; x++, index++)      {
-                       r = (float)(image->comps[0].data[index]);
-
-                       if (image->numcomps>2) {
-                               g = (float)(image->comps[1].data[index]);
-                               b = (float)(image->comps[2].data[index]);
-                       }
-                       else  {// Greyscale ...
-                               g = r;
-                               b = r;
-                       }
-
-                       // TGA format writes BGR ...
-                       value = (unsigned char)(b*scale);
-                       fwrite(&value,1,1,fdest);
-
-                       value = (unsigned char)(g*scale);
-                       fwrite(&value,1,1,fdest);
-
-                       value = (unsigned char)(r*scale);
-                       fwrite(&value,1,1,fdest);
-
-                       if (write_alpha) {
-                               a = (float)(image->comps[alpha_channel].data[index]);
-                               value = (unsigned char)(a*scale);
-                               fwrite(&value,1,1,fdest);
-                       }
-               }
-       }
-
-       return 0;
-}
-
-/* -->> -->> -->> -->>
-
-  BMP IMAGE FORMAT
-
- <<-- <<-- <<-- <<-- */
-
-/* WORD defines a two byte word */
-typedef unsigned short int WORD;
-
-/* DWORD defines a four byte word */
-typedef unsigned long int DWORD;
-
-typedef struct {
-  WORD bfType;                 /* 'BM' for Bitmap (19776) */
-  DWORD bfSize;                        /* Size of the file        */
-  WORD bfReserved1;            /* Reserved : 0            */
-  WORD bfReserved2;            /* Reserved : 0            */
-  DWORD bfOffBits;             /* Offset                  */
-} BITMAPFILEHEADER_t;
-
-typedef struct {
-  DWORD biSize;                        /* Size of the structure in bytes */
-  DWORD biWidth;               /* Width of the image in pixels */
-  DWORD biHeight;              /* Heigth of the image in pixels */
-  WORD biPlanes;               /* 1 */
-  WORD biBitCount;             /* Number of color bits by pixels */
-  DWORD biCompression;         /* Type of encoding 0: none 1: RLE8 2: RLE4 */
-  DWORD biSizeImage;           /* Size of the image in bytes */
-  DWORD biXpelsPerMeter;       /* Horizontal (X) resolution in pixels/meter */
-  DWORD biYpelsPerMeter;       /* Vertical (Y) resolution in pixels/meter */
-  DWORD biClrUsed;             /* Number of color used in the image (0: ALL) */
-  DWORD biClrImportant;                /* Number of important color (0: ALL) */
-} BITMAPINFOHEADER_t;
-
-opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters) {
-       int subsampling_dx = parameters->subsampling_dx;
-       int subsampling_dy = parameters->subsampling_dy;
-
-       int i, numcomps, w, h;
-       OPJ_COLOR_SPACE color_space;
-       opj_image_cmptparm_t cmptparm[3];       /* maximum of 3 components */
-       opj_image_t * image = NULL;
-
-       FILE *IN;
-       BITMAPFILEHEADER_t File_h;
-       BITMAPINFOHEADER_t Info_h;
-       unsigned char *RGB;
-       unsigned char *table_R, *table_G, *table_B;
-       unsigned int j, PAD = 0;
-
-       int x, y, index;
-       int gray_scale = 1, not_end_file = 1; 
-
-       unsigned int line = 0, col = 0;
-       unsigned char v, v2;
-       DWORD W, H;
-  
-       IN = fopen(filename, "rb");
-       if (!IN) {
-               fprintf(stderr, "Failed to open %s for reading !!\n", filename);
-               return 0;
-       }
-       
-       File_h.bfType = getc(IN);
-       File_h.bfType = (getc(IN) << 8) + File_h.bfType;
-       
-       if (File_h.bfType != 19778) {
-               fprintf(stderr,"Error, not a BMP file!\n");
-               return 0;
-       } else {
-               /* FILE HEADER */
-               /* ------------- */
-               File_h.bfSize = getc(IN);
-               File_h.bfSize = (getc(IN) << 8) + File_h.bfSize;
-               File_h.bfSize = (getc(IN) << 16) + File_h.bfSize;
-               File_h.bfSize = (getc(IN) << 24) + File_h.bfSize;
-
-               File_h.bfReserved1 = getc(IN);
-               File_h.bfReserved1 = (getc(IN) << 8) + File_h.bfReserved1;
-
-               File_h.bfReserved2 = getc(IN);
-               File_h.bfReserved2 = (getc(IN) << 8) + File_h.bfReserved2;
-
-               File_h.bfOffBits = getc(IN);
-               File_h.bfOffBits = (getc(IN) << 8) + File_h.bfOffBits;
-               File_h.bfOffBits = (getc(IN) << 16) + File_h.bfOffBits;
-               File_h.bfOffBits = (getc(IN) << 24) + File_h.bfOffBits;
-
-               /* INFO HEADER */
-               /* ------------- */
-
-               Info_h.biSize = getc(IN);
-               Info_h.biSize = (getc(IN) << 8) + Info_h.biSize;
-               Info_h.biSize = (getc(IN) << 16) + Info_h.biSize;
-               Info_h.biSize = (getc(IN) << 24) + Info_h.biSize;
-
-               Info_h.biWidth = getc(IN);
-               Info_h.biWidth = (getc(IN) << 8) + Info_h.biWidth;
-               Info_h.biWidth = (getc(IN) << 16) + Info_h.biWidth;
-               Info_h.biWidth = (getc(IN) << 24) + Info_h.biWidth;
-               w = Info_h.biWidth;
-
-               Info_h.biHeight = getc(IN);
-               Info_h.biHeight = (getc(IN) << 8) + Info_h.biHeight;
-               Info_h.biHeight = (getc(IN) << 16) + Info_h.biHeight;
-               Info_h.biHeight = (getc(IN) << 24) + Info_h.biHeight;
-               h = Info_h.biHeight;
-
-               Info_h.biPlanes = getc(IN);
-               Info_h.biPlanes = (getc(IN) << 8) + Info_h.biPlanes;
-
-               Info_h.biBitCount = getc(IN);
-               Info_h.biBitCount = (getc(IN) << 8) + Info_h.biBitCount;
-
-               Info_h.biCompression = getc(IN);
-               Info_h.biCompression = (getc(IN) << 8) + Info_h.biCompression;
-               Info_h.biCompression = (getc(IN) << 16) + Info_h.biCompression;
-               Info_h.biCompression = (getc(IN) << 24) + Info_h.biCompression;
-
-               Info_h.biSizeImage = getc(IN);
-               Info_h.biSizeImage = (getc(IN) << 8) + Info_h.biSizeImage;
-               Info_h.biSizeImage = (getc(IN) << 16) + Info_h.biSizeImage;
-               Info_h.biSizeImage = (getc(IN) << 24) + Info_h.biSizeImage;
-
-               Info_h.biXpelsPerMeter = getc(IN);
-               Info_h.biXpelsPerMeter = (getc(IN) << 8) + Info_h.biXpelsPerMeter;
-               Info_h.biXpelsPerMeter = (getc(IN) << 16) + Info_h.biXpelsPerMeter;
-               Info_h.biXpelsPerMeter = (getc(IN) << 24) + Info_h.biXpelsPerMeter;
-
-               Info_h.biYpelsPerMeter = getc(IN);
-               Info_h.biYpelsPerMeter = (getc(IN) << 8) + Info_h.biYpelsPerMeter;
-               Info_h.biYpelsPerMeter = (getc(IN) << 16) + Info_h.biYpelsPerMeter;
-               Info_h.biYpelsPerMeter = (getc(IN) << 24) + Info_h.biYpelsPerMeter;
-
-               Info_h.biClrUsed = getc(IN);
-               Info_h.biClrUsed = (getc(IN) << 8) + Info_h.biClrUsed;
-               Info_h.biClrUsed = (getc(IN) << 16) + Info_h.biClrUsed;
-               Info_h.biClrUsed = (getc(IN) << 24) + Info_h.biClrUsed;
-
-               Info_h.biClrImportant = getc(IN);
-               Info_h.biClrImportant = (getc(IN) << 8) + Info_h.biClrImportant;
-               Info_h.biClrImportant = (getc(IN) << 16) + Info_h.biClrImportant;
-               Info_h.biClrImportant = (getc(IN) << 24) + Info_h.biClrImportant;
-
-               /* Read the data and store them in the OUT file */
-    
-               if (Info_h.biBitCount == 24) {
-                       numcomps = 3;
-                       color_space = CLRSPC_SRGB;
-                       /* initialize image components */
-                       memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
-                       for(i = 0; i < numcomps; i++) {
-                               cmptparm[i].prec = 8;
-                               cmptparm[i].bpp = 8;
-                               cmptparm[i].sgnd = 0;
-                               cmptparm[i].dx = subsampling_dx;
-                               cmptparm[i].dy = subsampling_dy;
-                               cmptparm[i].w = w;
-                               cmptparm[i].h = h;
-                       }
-                       /* create the image */
-                       image = opj_image_create(numcomps, &cmptparm[0], color_space);
-                       if(!image) {
-                               fclose(IN);
-                               return NULL;
-                       }
-
-                       /* set image offset and reference grid */
-                       image->x0 = parameters->image_offset_x0;
-                       image->y0 = parameters->image_offset_y0;
-                       image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
-                       image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
-
-                       /* set image data */
-
-                       /* Place the cursor at the beginning of the image information */
-                       fseek(IN, 0, SEEK_SET);
-                       fseek(IN, File_h.bfOffBits, SEEK_SET);
-                       
-                       W = Info_h.biWidth;
-                       H = Info_h.biHeight;
-
-                       /* PAD = 4 - (3 * W) % 4; */
-                       /* PAD = (PAD == 4) ? 0 : PAD; */
-                       PAD = (3 * W) % 4 ? 4 - (3 * W) % 4 : 0;
-                       
-                       RGB = (unsigned char *) malloc((3 * W + PAD) * H * sizeof(unsigned char));
-                       
-                       fread(RGB, sizeof(unsigned char), (3 * W + PAD) * H, IN);
-                       
-                       index = 0;
-
-                       for(y = 0; y < (int)H; y++) {
-                               unsigned char *scanline = RGB + (3 * W + PAD) * (H - 1 - y);
-                               for(x = 0; x < (int)W; x++) {
-                                       unsigned char *pixel = &scanline[3 * x];
-                                       image->comps[0].data[index] = pixel[2]; /* R */
-                                       image->comps[1].data[index] = pixel[1]; /* G */
-                                       image->comps[2].data[index] = pixel[0]; /* B */
-                                       index++;
-                               }
-                       }
-
-                       free(RGB);
-
-               } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 0) {
-                       table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
-                       table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
-                       table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
-                       
-                       for (j = 0; j < Info_h.biClrUsed; j++) {
-                               table_B[j] = getc(IN);
-                               table_G[j] = getc(IN);
-                               table_R[j] = getc(IN);
-                               getc(IN);
-                               if (table_R[j] != table_G[j] && table_R[j] != table_B[j] && table_G[j] != table_B[j])
-                                       gray_scale = 0;
-                       }
-                       
-                       /* Place the cursor at the beginning of the image information */
-                       fseek(IN, 0, SEEK_SET);
-                       fseek(IN, File_h.bfOffBits, SEEK_SET);
-                       
-                       W = Info_h.biWidth;
-                       H = Info_h.biHeight;
-                       if (Info_h.biWidth % 2)
-                               W++;
-                       
-                       numcomps = gray_scale ? 1 : 3;
-                       color_space = gray_scale ? CLRSPC_GRAY : CLRSPC_SRGB;
-                       /* initialize image components */
-                       memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
-                       for(i = 0; i < numcomps; i++) {
-                               cmptparm[i].prec = 8;
-                               cmptparm[i].bpp = 8;
-                               cmptparm[i].sgnd = 0;
-                               cmptparm[i].dx = subsampling_dx;
-                               cmptparm[i].dy = subsampling_dy;
-                               cmptparm[i].w = w;
-                               cmptparm[i].h = h;
-                       }
-                       /* create the image */
-                       image = opj_image_create(numcomps, &cmptparm[0], color_space);
-                       if(!image) {
-                               fclose(IN);
-                               return NULL;
-                       }
-
-                       /* set image offset and reference grid */
-                       image->x0 = parameters->image_offset_x0;
-                       image->y0 = parameters->image_offset_y0;
-                       image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
-                       image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
-
-                       /* set image data */
-
-                       RGB = (unsigned char *) malloc(W * H * sizeof(unsigned char));
-                       
-                       fread(RGB, sizeof(unsigned char), W * H, IN);
-                       if (gray_scale) {
-                               index = 0;
-                               for (j = 0; j < W * H; j++) {
-                                       if ((j % W < W - 1 && Info_h.biWidth % 2) || !(Info_h.biWidth % 2)) {
-                                               image->comps[0].data[index] = table_R[RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)]];
-                                               index++;
-                                       }
-                               }
-
-                       } else {                
-                               index = 0;
-                               for (j = 0; j < W * H; j++) {
-                                       if ((j % W < W - 1 && Info_h.biWidth % 2) || !(Info_h.biWidth % 2)) {
-                                               unsigned char pixel_index = RGB[W * H - ((j) / (W) + 1) * W + (j) % (W)];
-                                               image->comps[0].data[index] = table_R[pixel_index];
-                                               image->comps[1].data[index] = table_G[pixel_index];
-                                               image->comps[2].data[index] = table_B[pixel_index];
-                                               index++;
-                                       }
-                               }
-                       }
-                       free(RGB);
-      free(table_R);
-      free(table_G);
-      free(table_B);
-               } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 1) {                               
-                       table_R = (unsigned char *) malloc(256 * sizeof(unsigned char));
-                       table_G = (unsigned char *) malloc(256 * sizeof(unsigned char));
-                       table_B = (unsigned char *) malloc(256 * sizeof(unsigned char));
-                       
-                       for (j = 0; j < Info_h.biClrUsed; j++) {
-                               table_B[j] = getc(IN);
-                               table_G[j] = getc(IN);
-                               table_R[j] = getc(IN);
-                               getc(IN);
-                               if (table_R[j] != table_G[j] && table_R[j] != table_B[j] && table_G[j] != table_B[j])
-                                       gray_scale = 0;
-                       }
-
-                       numcomps = gray_scale ? 1 : 3;
-                       color_space = gray_scale ? CLRSPC_GRAY : CLRSPC_SRGB;
-                       /* initialize image components */
-                       memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
-                       for(i = 0; i < numcomps; i++) {
-                               cmptparm[i].prec = 8;
-                               cmptparm[i].bpp = 8;
-                               cmptparm[i].sgnd = 0;
-                               cmptparm[i].dx = subsampling_dx;
-                               cmptparm[i].dy = subsampling_dy;
-                               cmptparm[i].w = w;
-                               cmptparm[i].h = h;
-                       }
-                       /* create the image */
-                       image = opj_image_create(numcomps, &cmptparm[0], color_space);
-                       if(!image) {
-                               fclose(IN);
-                               return NULL;
-                       }
-
-                       /* set image offset and reference grid */
-                       image->x0 = parameters->image_offset_x0;
-                       image->y0 = parameters->image_offset_y0;
-                       image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
-                       image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
-
-                       /* set image data */
-                       
-                       /* Place the cursor at the beginning of the image information */
-                       fseek(IN, 0, SEEK_SET);
-                       fseek(IN, File_h.bfOffBits, SEEK_SET);
-                       
-                       RGB = (unsigned char *) malloc(Info_h.biWidth * Info_h.biHeight * sizeof(unsigned char));
-            
-                       while (not_end_file) {
-                               v = getc(IN);
-                               if (v) {
-                                       v2 = getc(IN);
-                                       for (i = 0; i < (int) v; i++) {
-                                               RGB[line * Info_h.biWidth + col] = v2;
-                                               col++;
-                                       }
-                               } else {
-                                       v = getc(IN);
-                                       switch (v) {
-                                               case 0:
-                                                       col = 0;
-                                                       line++;
-                                                       break;
-                                               case 1:
-                                                       line++;
-                                                       not_end_file = 0;
-                                                       break;
-                                               case 2:
-                                                       fprintf(stderr,"No Delta supported\n");
-                                                       opj_image_destroy(image);
-                                                       fclose(IN);
-                                                       return NULL;
-                                               default:
-                                                       for (i = 0; i < v; i++) {
-                                                               v2 = getc(IN);
-                                                               RGB[line * Info_h.biWidth + col] = v2;
-                                                               col++;
-                                                       }
-                                                       if (v % 2)
-                                                               v2 = getc(IN);
-                                                       break;
-                                       }
-                               }
-                       }
-                       if (gray_scale) {
-                               index = 0;
-                               for (line = 0; line < Info_h.biHeight; line++) {
-                                       for (col = 0; col < Info_h.biWidth; col++) {
-                                               image->comps[0].data[index] = table_R[(int)RGB[(Info_h.biHeight - line - 1) * Info_h.biWidth + col]];
-                                               index++;
-                                       }
-                               }
-                       } else {
-                               index = 0;
-                               for (line = 0; line < Info_h.biHeight; line++) {
-                                       for (col = 0; col < Info_h.biWidth; col++) {
-                                               unsigned char pixel_index = (int)RGB[(Info_h.biHeight - line - 1) * Info_h.biWidth + col];
-                                               image->comps[0].data[index] = table_R[pixel_index];
-                                               image->comps[1].data[index] = table_G[pixel_index];
-                                               image->comps[2].data[index] = table_B[pixel_index];
-                                               index++;
-                                       }
-                               }
-                       }
-                       free(RGB);
-      free(table_R);
-      free(table_G);
-      free(table_B);
-       } else {
-               fprintf(stderr, 
-                       "Other system than 24 bits/pixels or 8 bits (no RLE coding) is not yet implemented [%d]\n", Info_h.biBitCount);
-       }
-       fclose(IN);
- }
- return image;
-}
-
-int imagetobmp(opj_image_t * image, const char *outfile) {
-       int w, h;
-       int i, pad;
-       FILE *fdest = NULL;
-       int adjustR, adjustG, adjustB;
-
-       if (image->numcomps == 3 && image->comps[0].dx == image->comps[1].dx
-               && image->comps[1].dx == image->comps[2].dx
-               && image->comps[0].dy == image->comps[1].dy
-               && image->comps[1].dy == image->comps[2].dy
-               && image->comps[0].prec == image->comps[1].prec
-               && image->comps[1].prec == image->comps[2].prec) {
-               
-               /* -->> -->> -->> -->>    
-               24 bits color       
-               <<-- <<-- <<-- <<-- */
-           
-               fdest = fopen(outfile, "wb");
-               if (!fdest) {
-                       fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
-                       return 1;
-               }
-           
-               w = image->comps[0].w;      
-               h = image->comps[0].h;
-           
-               fprintf(fdest, "BM");
-           
-               /* FILE HEADER */
-               /* ------------- */
-               fprintf(fdest, "%c%c%c%c",
-                       (unsigned char) (h * w * 3 + 3 * h * (w % 2) + 54) & 0xff,
-                       (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 8) & 0xff,
-                       (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 16) & 0xff,
-                       (unsigned char) ((h * w * 3 + 3 * h * (w % 2) + 54)     >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,((54) >> 16) & 0xff, ((54) >> 24) & 0xff);
-           
-               /* INFO HEADER   */
-               /* ------------- */
-               fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
-                       (unsigned char) ((w) >> 8) & 0xff,
-                       (unsigned char) ((w) >> 16) & 0xff,
-                       (unsigned char) ((w) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
-                       (unsigned char) ((h) >> 8) & 0xff,
-                       (unsigned char) ((h) >> 16) & 0xff,
-                       (unsigned char) ((h) >> 24) & 0xff);
-               fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
-               fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (unsigned char) (3 * h * w + 3 * h * (w % 2)) & 0xff,
-                       (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 8) & 0xff,
-                       (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 16) & 0xff,
-                       (unsigned char) ((h * w * 3 + 3 * h * (w % 2)) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
-           
-               if (image->comps[0].prec > 8) {
-                       adjustR = image->comps[0].prec - 8;
-                       printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
-               }
-               else 
-                       adjustR = 0;
-               if (image->comps[1].prec > 8) {
-                       adjustG = image->comps[1].prec - 8;
-                       printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
-               }
-               else 
-                       adjustG = 0;
-               if (image->comps[2].prec > 8) {
-                       adjustB = image->comps[2].prec - 8;
-                       printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec);
-               }
-               else 
-                       adjustB = 0;
-
-               for (i = 0; i < w * h; i++) {
-                       unsigned char rc, gc, bc;
-                       int r, g, b;
-                                                       
-                       r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
-                       r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
-                       r = ((r >> adjustR)+((r >> (adjustR-1))%2));
-                       if(r > 255) r = 255; else if(r < 0) r = 0;
-                       rc = (unsigned char)r;
-
-                       g = image->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
-                       g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
-                       g = ((g >> adjustG)+((g >> (adjustG-1))%2));
-                       if(g > 255) g = 255; else if(g < 0) g = 0;
-                       gc = (unsigned char)g;
-
-                       b = image->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
-                       b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
-                       b = ((b >> adjustB)+((b >> (adjustB-1))%2));
-                       if(b > 255) b = 255; else if(b < 0) b = 0;
-                       bc = (unsigned char)b;
-
-                       fprintf(fdest, "%c%c%c", bc, gc, rc);
-                       
-                       if ((i + 1) % w == 0) {
-                               for (pad = (3 * w) % 4 ? 4 - (3 * w) % 4 : 0; pad > 0; pad--)   /* ADD */
-                                       fprintf(fdest, "%c", 0);
-                       }
-               }
-               fclose(fdest);
-       } else {                        /* Gray-scale */
-
-               /* -->> -->> -->> -->>
-               8 bits non code (Gray scale)
-               <<-- <<-- <<-- <<-- */
-
-               fdest = fopen(outfile, "wb");
-               w = image->comps[0].w;      
-               h = image->comps[0].h;
-           
-               fprintf(fdest, "BM");
-           
-               /* FILE HEADER */
-               /* ------------- */
-               fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + 54 + 1024 + h * (w % 2)) & 0xff,
-                       (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 8) & 0xff,
-                       (unsigned char) ((h * w + 54 + 1024 + h * (w % 2)) >> 16) & 0xff,
-                       (unsigned char) ((h * w + 54 + 1024 + w * (w % 2)) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff, 
-                       ((54 + 1024) >> 16) & 0xff,
-                       ((54 + 1024) >> 24) & 0xff);
-           
-               /* INFO HEADER */
-               /* ------------- */
-               fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,     ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (unsigned char) ((w) & 0xff),
-                       (unsigned char) ((w) >> 8) & 0xff,
-                       (unsigned char) ((w) >> 16) & 0xff,
-                       (unsigned char) ((w) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (unsigned char) ((h) & 0xff),
-                       (unsigned char) ((h) >> 8) & 0xff,
-                       (unsigned char) ((h) >> 16) & 0xff,
-                       (unsigned char) ((h) >> 24) & 0xff);
-               fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
-               fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (unsigned char) (h * w + h * (w % 2)) & 0xff,
-                       (unsigned char) ((h * w + h * (w % 2)) >> 8) &  0xff,
-                       (unsigned char) ((h * w + h * (w % 2)) >> 16) & 0xff,
-                       (unsigned char) ((h * w + h * (w % 2)) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
-               fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
-
-               if (image->comps[0].prec > 8) {
-                       adjustR = image->comps[0].prec - 8;
-                       printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
-               }else 
-                       adjustR = 0;
-
-               for (i = 0; i < 256; i++) {
-                       fprintf(fdest, "%c%c%c%c", i, i, i, 0);
-               }
-
-               for (i = 0; i < w * h; i++) {
-                       unsigned char rc;
-                       int r;
-                       
-                       r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
-                       r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
-                       r = ((r >> adjustR)+((r >> (adjustR-1))%2));
-                       if(r > 255) r = 255; else if(r < 0) r = 0;
-
-                       fprintf(fdest, "%c", (unsigned char)r);
-
-                       if ((i + 1) % w == 0) {
-                               for (pad = w % 4 ? 4 - w % 4 : 0; pad > 0; pad--)       /* ADD */
-                                       fprintf(fdest, "%c", 0);
-                       }
-               }
-               fclose(fdest);
-       }
-
-       return 0;
-}
-
-/* -->> -->> -->> -->>
-
-PGX IMAGE FORMAT
-
-<<-- <<-- <<-- <<-- */
-
-
-unsigned char readuchar(FILE * f)
-{
-  unsigned char c1;
-  fread(&c1, 1, 1, f);
-  return c1;
-}
-
-unsigned short readushort(FILE * f, int bigendian)
-{
-  unsigned char c1, c2;
-  fread(&c1, 1, 1, f);
-  fread(&c2, 1, 1, f);
-  if (bigendian)
-    return (c1 << 8) + c2;
-  else
-    return (c2 << 8) + c1;
-}
-
-unsigned int readuint(FILE * f, int bigendian)
-{
-  unsigned char c1, c2, c3, c4;
-  fread(&c1, 1, 1, f);
-  fread(&c2, 1, 1, f);
-  fread(&c3, 1, 1, f);
-  fread(&c4, 1, 1, f);
-  if (bigendian)
-    return (c1 << 24) + (c2 << 16) + (c3 << 8) + c4;
-  else
-    return (c4 << 24) + (c3 << 16) + (c2 << 8) + c1;
-}
-
-opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
-       FILE *f = NULL;
-       int w, h, prec;
-       int i, numcomps, max;
-       OPJ_COLOR_SPACE color_space;
-       opj_image_cmptparm_t cmptparm;  /* maximum of 1 component  */
-       opj_image_t * image = NULL;
-
-       char endian1,endian2,sign;
-       char signtmp[32];
-
-       char temp[32];
-       int bigendian;
-       opj_image_comp_t *comp = NULL;
-
-       numcomps = 1;
-       color_space = CLRSPC_GRAY;
-
-       memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
-
-       max = 0;
-
-       f = fopen(filename, "rb");
-       if (!f) {
-         fprintf(stderr, "Failed to open %s for reading !\n", filename);
-         return NULL;
-       }
-
-       fseek(f, 0, SEEK_SET);
-       fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d",temp,&endian1,&endian2,signtmp,&prec,temp,&w,temp,&h);
-       
-       i=0;
-       sign='+';               
-       while (signtmp[i]!='\0') {
-               if (signtmp[i]=='-') sign='-';
-               i++;
-       }
-       
-       fgetc(f);
-       if (endian1=='M' && endian2=='L') {
-               bigendian = 1;
-       } else if (endian2=='M' && endian1=='L') {
-               bigendian = 0;
-       } else {
-               fprintf(stderr, "Bad pgx header, please check input file\n");
-               return NULL;
-       }
-
-       /* initialize image component */
-
-       cmptparm.x0 = parameters->image_offset_x0;
-       cmptparm.y0 = parameters->image_offset_y0;
-       cmptparm.w = !cmptparm.x0 ? (w - 1) * parameters->subsampling_dx + 1 : cmptparm.x0 + (w - 1) * parameters->subsampling_dx + 1;
-       cmptparm.h = !cmptparm.y0 ? (h - 1) * parameters->subsampling_dy + 1 : cmptparm.y0 + (h - 1) * parameters->subsampling_dy + 1;
-       
-       if (sign == '-') {
-               cmptparm.sgnd = 1;
-       } else {
-               cmptparm.sgnd = 0;
-       }
-       cmptparm.prec = prec;
-       cmptparm.bpp = prec;
-       cmptparm.dx = parameters->subsampling_dx;
-       cmptparm.dy = parameters->subsampling_dy;
-       
-       /* create the image */
-       image = opj_image_create(numcomps, &cmptparm, color_space);
-       if(!image) {
-               fclose(f);
-               return NULL;
-       }
-       /* set image offset and reference grid */
-       image->x0 = cmptparm.x0;
-       image->y0 = cmptparm.x0;
-       image->x1 = cmptparm.w;
-       image->y1 = cmptparm.h;
-
-       /* set image data */
-
-       comp = &image->comps[0];
-
-       for (i = 0; i < w * h; i++) {
-               int v;
-               if (comp->prec <= 8) {
-                       if (!comp->sgnd) {
-                               v = readuchar(f);
-                       } else {
-                               v = (char) readuchar(f);
-                       }
-               } else if (comp->prec <= 16) {
-                       if (!comp->sgnd) {
-                               v = readushort(f, bigendian);
-                       } else {
-                               v = (short) readushort(f, bigendian);
-                       }
-               } else {
-                       if (!comp->sgnd) {
-                               v = readuint(f, bigendian);
-                       } else {
-                               v = (int) readuint(f, bigendian);
-                       }
-               }
-               if (v > max)
-                       max = v;
-               comp->data[i] = v;
-       }
-       fclose(f);
-       comp->bpp = int_floorlog2(max) + 1;
-
-       return image;
-}
-
-int imagetopgx(opj_image_t * image, const char *outfile) {
-       int w, h;
-       int i, j, compno;
-       FILE *fdest = NULL;
-
-       for (compno = 0; compno < image->numcomps; compno++) {
-               opj_image_comp_t *comp = &image->comps[compno];
-               char bname[256]; /* buffer for name */
-    char *name = bname; /* pointer */
-    int nbytes = 0;
-    const size_t olen = strlen(outfile);
-    const size_t dotpos = olen - 4;
-    const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
-    if( outfile[dotpos] != '.' ) {
-      /* `pgx` was recognized but there is no dot at expected position */
-      fprintf(stderr, "ERROR -> Impossible happen." );
-      return 1;
-      }
-    if( total > 256 ) {
-      name = (char*)malloc(total+1);
-      }
-    strncpy(name, outfile, dotpos);
-               if (image->numcomps > 1) {
-                       sprintf(name+dotpos, "-%d.pgx", compno);
-               } else {
-                       strcpy(name+dotpos, ".pgx");
-               }
-               fdest = fopen(name, "wb");
-               if (!fdest) {
-                       fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
-                       return 1;
-               }
-    /* dont need name anymore */
-    if( total > 256 ) {
-      free(name);
-      }
-
-               w = image->comps[compno].w;
-               h = image->comps[compno].h;
-           
-               fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec, w, h);
-               if (comp->prec <= 8) {
-                       nbytes = 1;
-               } else if (comp->prec <= 16) {
-                       nbytes = 2;
-               } else {
-                       nbytes = 4;
-               }
-               for (i = 0; i < w * h; i++) {
-                       int v = image->comps[compno].data[i];
-                       for (j = nbytes - 1; j >= 0; j--) {
-                               char byte = (char) (v >> (j * 8));
-                               fwrite(&byte, 1, 1, fdest);
-                       }
-               }
-               fclose(fdest);
-       }
-
-       return 0;
-}
-
-/* -->> -->> -->> -->>
-
-PNM IMAGE FORMAT
-
-<<-- <<-- <<-- <<-- */
-
-struct pnm_header
-{
-    int width, height, maxval, depth, format;
-    char rgb, rgba, gray, graya, bw;
-    char ok;
-};
-
-static char *skip_white(char *s)
-{
-    while(*s)
-   {
-    if(*s == '\n' || *s == '\r') return NULL;
-    if(isspace(*s)) { ++s; continue; }
-    return s;
-   }
-    return NULL;
-}
-
-static char *skip_int(char *start, int *out_n)
-{
-    char *s;
-    char c;
-
-    *out_n = 0; s = start;
-
-    s = skip_white(start);
-    if(s == NULL) return NULL;
-    start = s;
-
-    while(*s)
-   {
-    if( !isdigit(*s)) break;
-    ++s;
-   }
-    c = *s; *s = 0; *out_n = atoi(start); *s = c;
-    return s;
-}
-
-static char *skip_idf(char *start, char out_idf[256])
-{
-    char *s;
-    char c;
-
-    s = skip_white(start);
-    if(s == NULL) return NULL;
-    start = s;
-
-    while(*s)
-   {
-    if(isalpha(*s) || *s == '_') { ++s; continue; }
-    break;
-   }
-    c = *s; *s = 0; strncpy(out_idf, start, 255); *s = c;
-    return s;
-}
-
-static void read_pnm_header(FILE *reader, struct pnm_header *ph)
-{
-    char *s;
-    int format, have_wh, end, ttype;
-    char idf[256], type[256];
-    char line[256];
-
-    fgets(line, 250, reader);
-
-    if(line[0] != 'P')
-   {
-    fprintf(stderr,"read_pnm_header:PNM:magic P missing\n"); return;
-   }
-    format = atoi(line + 1);
-    if(format < 1 || format > 7)
-   {
-    fprintf(stderr,"read_pnm_header:magic format %d invalid\n", format);
-    return;
-   }
-    ph->format = format;
-    ttype = end = have_wh = 0;
-
-    while(fgets(line, 250, reader))
-   {
-    if(*line == '#') continue;
-
-    s = line;
-
-    if(format == 7)
-  {
-    s = skip_idf(s, idf);
-
-    if(s == NULL || *s == 0) return;
-
-    if(strcmp(idf, "ENDHDR") == 0)
- {
-    end = 1; break;
- }
-    if(strcmp(idf, "WIDTH") == 0)
- {
-    s = skip_int(s, &ph->width);
-    if(s == NULL || *s == 0) return;
-
-    continue;
- }
-    if(strcmp(idf, "HEIGHT") == 0)
- {
-    s = skip_int(s, &ph->height);
-    if(s == NULL || *s == 0) return;
-
-    continue;
- }
-    if(strcmp(idf, "DEPTH") == 0)
- {
-    s = skip_int(s, &ph->depth);
-    if(s == NULL || *s == 0) return;
-
-    continue;
- }
-    if(strcmp(idf, "MAXVAL") == 0)
- {
-    s = skip_int(s, &ph->maxval);
-    if(s == NULL || *s == 0) return;
-
-    continue;
- }
-    if(strcmp(idf, "TUPLTYPE") == 0)
- {
-    s = skip_idf(s, type);
-    if(s == NULL || *s == 0) return;
-
-        if(strcmp(type, "BLACKANDWHITE") == 0)
-       {
-        ph->bw = 1; ttype = 1; continue;
-       }
-        if(strcmp(type, "GRAYSCALE") == 0)
-       {
-        ph->gray = 1; ttype = 1; continue;
-       }
-        if(strcmp(type, "GRAYSCALE_ALPHA") == 0)
-       {
-        ph->graya = 1; ttype = 1; continue;
-       }
-        if(strcmp(type, "RGB") == 0)
-       {
-        ph->rgb = 1; ttype = 1; continue;
-       }
-        if(strcmp(type, "RGB_ALPHA") == 0)
-       {
-        ph->rgba = 1; ttype = 1; continue;
-       }
-    fprintf(stderr,"read_pnm_header:unknown P7 TUPLTYPE %s\n",type);
-    return;
- }
-    fprintf(stderr,"read_pnm_header:unknown P7 idf %s\n",idf);
-    return;
-  } /* if(format == 7) */
-
-    if( !have_wh)
-  {
-    s = skip_int(s, &ph->width);
-
-    s = skip_int(s, &ph->height);
-
-    have_wh = 1;
-
-    if(format == 1 || format == 4) break;
-
-    continue;
-  }
-    if(format == 2 || format == 3 || format == 5 || format == 6)
-  {
-/* P2, P3, P5, P6: */
-    s = skip_int(s, &ph->maxval);
-
-    if(ph->maxval > 65535) return;
-  }
-    break;
-   }/* while(fgets( ) */
-    if(format == 2 || format == 3 || format > 4)
-   {
-    if(ph->maxval < 1 || ph->maxval > 65535) return;
-   }
-    if(ph->width < 1 || ph->height < 1) return;
-
-    if(format == 7)
-   {
-    if(!end)
-  {
-    fprintf(stderr,"read_pnm_header:P7 without ENDHDR\n"); return;
-  }
-    if(ph->depth < 1 || ph->depth > 4) return;
-
-    if(ph->width && ph->height && ph->depth & ph->maxval && ttype)
-     ph->ok = 1;
-   }
-    else
-   {
-    if(format != 1 && format != 4)
-  {
-    if(ph->width && ph->height && ph->maxval) ph->ok = 1;
-  }
-    else
-  {
-    if(ph->width && ph->height) ph->ok = 1;
-    ph->maxval = 255;
-  }
-   }
-}
-
-static int has_prec(int val)
-{
-    if(val < 2) return 1;
-    if(val < 4) return 2;
-    if(val < 8) return 3;
-    if(val < 16) return 4;
-    if(val < 32) return 5;
-    if(val < 64) return 6;
-    if(val < 128) return 7;
-    if(val < 256) return 8;
-    if(val < 512) return 9;
-    if(val < 1024) return 10;
-    if(val < 2048) return 11;
-    if(val < 4096) return 12;
-    if(val < 8192) return 13;
-    if(val < 16384) return 14;
-    if(val < 32768) return 15;
-    return 16;
-}
-
-opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
-       int subsampling_dx = parameters->subsampling_dx;
-       int subsampling_dy = parameters->subsampling_dy;
-
-       FILE *fp = NULL;
-       int i, compno, numcomps, w, h, prec, format;
-       OPJ_COLOR_SPACE color_space;
-       opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */
-       opj_image_t * image = NULL;
-       struct pnm_header header_info;
-       
-       if((fp = fopen(filename, "rb")) == NULL)
-   {
-       fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n",filename);
-       return NULL;
-   }
-       memset(&header_info, 0, sizeof(struct pnm_header));
-
-       read_pnm_header(fp, &header_info);
-
-       if(!header_info.ok) { fclose(fp); return NULL; }
-
-       format = header_info.format;
-
-    switch(format)
-   {
-    case 1: /* ascii bitmap */
-    case 4: /* raw bitmap */
-        numcomps = 1;
-        break;
-
-    case 2: /* ascii greymap */
-    case 5: /* raw greymap */
-        numcomps = 1;
-        break;
-
-    case 3: /* ascii pixmap */
-    case 6: /* raw pixmap */
-        numcomps = 3;
-        break;
-
-    case 7: /* arbitrary map */
-        numcomps = header_info.depth;
-               break;
-
-    default: fclose(fp); return NULL;
-   }
-    if(numcomps < 3)
-     color_space = CLRSPC_GRAY;/* GRAY, GRAYA */
-    else
-     color_space = CLRSPC_SRGB;/* RGB, RGBA */
-
-    prec = has_prec(header_info.maxval);
-
-       if(prec < 8) prec = 8;
-
-    w = header_info.width;
-    h = header_info.height;
-    subsampling_dx = parameters->subsampling_dx;
-    subsampling_dy = parameters->subsampling_dy;
-
-    memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
-
-    for(i = 0; i < numcomps; i++)
-   {
-    cmptparm[i].prec = prec;
-    cmptparm[i].bpp = prec;
-    cmptparm[i].sgnd = 0;
-    cmptparm[i].dx = subsampling_dx;
-    cmptparm[i].dy = subsampling_dy;
-    cmptparm[i].w = w;
-    cmptparm[i].h = h;
-   }
-    image = opj_image_create(numcomps, &cmptparm[0], color_space);
-
-    if(!image) { fclose(fp); return NULL; }
-
-/* set image offset and reference grid */
-       image->x0 = parameters->image_offset_x0;
-       image->y0 = parameters->image_offset_y0;
-       image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
-       image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
-
-    if((format == 2) || (format == 3)) /* ascii pixmap */
-   {
-    unsigned int index;
-
-    for (i = 0; i < w * h; i++)
-  {
-    for(compno = 0; compno < numcomps; compno++)
- {
-       index = 0;
-    fscanf(fp, "%u", &index);
-
-    image->comps[compno].data[i] = (index * 255)/header_info.maxval;
- }
-  }
-   }
-    else
-    if((format == 5)
-    || (format == 6)
-    ||((format == 7)
-        && (   header_info.gray || header_info.graya
-            || header_info.rgb || header_info.rgba)))/* binary pixmap */
-   {
-    unsigned char c0, c1, one;
-
-    one = (prec < 9); 
-
-    for (i = 0; i < w * h; i++)
-  {
-    for(compno = 0; compno < numcomps; compno++)
- {
-        fread(&c0, 1, 1, fp);
-        if(one)
-       {
-        image->comps[compno].data[i] = c0;
-       }
-        else
-       {
-        fread(&c1, 1, 1, fp);
-/* netpbm: */
-               image->comps[compno].data[i] = ((c0<<8) | c1);
-       }
- }
-  }
-   }
-    else
-    if(format == 1) /* ascii bitmap */
-   {
-    for (i = 0; i < w * h; i++)
-  {
-    unsigned int index;
-
-    fscanf(fp, "%u", &index);
-
-    image->comps[0].data[i] = (index?0:255);
-  }
-   }
-    else
-    if(format == 4)
-   {
-    int x, y, bit;
-    unsigned char uc;
-
-    i = 0;
-    for(y = 0; y < h; ++y)
-  {
-    bit = -1; uc = 0;
-
-    for(x = 0; x < w; ++x)
- {
-        if(bit == -1)
-       {
-        bit = 7;
-        uc = (unsigned char)getc(fp);
-       }
-    image->comps[0].data[i] = (((uc>>bit) & 1)?0:255);
-    --bit; ++i;
- }
-  }
-   }
-       else
-       if((format == 7 && header_info.bw)) //MONO
-   {
-       unsigned char uc;
-
-       for(i = 0; i < w * h; ++i)
-  {
-       fread(&uc, 1, 1, fp);
-       image->comps[0].data[i] = (uc & 1)?0:255;
-  }
-   }
-    fclose(fp);
-
-    return image;
-}/* pnmtoimage() */
-
-int imagetopnm(opj_image_t * image, const char *outfile) 
-{
-       int *red, *green, *blue, *alpha;
-       int wr, hr, max;
-       int i, compno, ncomp;
-       int adjustR, adjustG, adjustB, adjustA;
-       int fails, two, want_gray, has_alpha, triple;
-       int prec, v;
-       FILE *fdest = NULL;
-       const char *tmp = outfile;
-       char *destname;
-
-    if((prec = image->comps[0].prec) > 16)
-   {
-       fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
-       "\n\t: refused.\n",__FILE__,__LINE__,prec);
-       return 1;
-   }
-    two = has_alpha = 0; fails = 1;
-       ncomp = image->numcomps;
-
-       while (*tmp) ++tmp; tmp -= 2; 
-       want_gray = (*tmp == 'g' || *tmp == 'G'); 
-       ncomp = image->numcomps;
-
-       if(want_gray) ncomp = 1;
-
-       if (ncomp == 2 /* GRAYA */
-       || (ncomp > 2 /* RGB, RGBA */
-               && image->comps[0].dx == image->comps[1].dx
-               && image->comps[1].dx == image->comps[2].dx
-               && image->comps[0].dy == image->comps[1].dy
-               && image->comps[1].dy == image->comps[2].dy
-               && image->comps[0].prec == image->comps[1].prec
-               && image->comps[1].prec == image->comps[2].prec
-          ))
-   {
-       fdest = fopen(outfile, "wb");
-
-       if (!fdest) 
-  {
-       fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
-       return fails;
-  }
-       two = (prec > 8);
-       triple = (ncomp > 2);
-       wr = image->comps[0].w; hr = image->comps[0].h;
-       max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);
-
-    red = image->comps[0].data;
-
-       if(triple)
-  {
-    green = image->comps[1].data;
-    blue = image->comps[2].data;
-  }
-       else green = blue = NULL;
-       
-       if(has_alpha)
-  {
-       const char *tt = (triple?"RGB_ALPHA":"GRAYSCALE_ALPHA");
-
-       fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %d\n"
-               "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
-               wr, hr, ncomp, max, tt);
-       alpha = image->comps[ncomp - 1].data;
-       adjustA = (image->comps[ncomp - 1].sgnd ?
-        1 << (image->comps[ncomp - 1].prec - 1) : 0);
-  }
-       else
-  {
-       fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n", 
-               opj_version(), wr, hr, max);
-       alpha = NULL; adjustA = 0;
-  }
-    adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
-
-       if(triple)
-  {
-    adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
-    adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
-  }
-       else adjustG = adjustB = 0;
-
-    for(i = 0; i < wr * hr; ++i)
-  {
-       if(two)
- {
-       v = *red + adjustR; ++red;
-/* netpbm: */
-       fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
-
-               if(triple)
-          {
-               v = *green + adjustG; ++green;
-/* netpbm: */
-               fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
-
-               v =  *blue + adjustB; ++blue;
-/* netpbm: */
-               fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
-
-          }/* if(triple) */
-
-        if(has_alpha)
-       {
-        v = *alpha + adjustA; ++alpha;
-/* netpbm: */
-               fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
-       }
-        continue;
-
- }     /* if(two) */
-
-/* prec <= 8: */
-
-       fprintf(fdest, "%c", (unsigned char)*red++);
-       if(triple)
-        fprintf(fdest, "%c%c",(unsigned char)*green++, (unsigned char)*blue++);
-
-       if(has_alpha)
-        fprintf(fdest, "%c", (unsigned char)*alpha++);
-
-  }    /* for(i */
-
-       fclose(fdest); return 0;
-   }
-
-/* YUV or MONO: */
-
-       if (image->numcomps > ncomp) 
-   {
-       fprintf(stderr,"WARNING -> [PGM file] Only the first component\n");
-       fprintf(stderr,"           is written to the file\n");
-   }
-       destname = (char*)malloc(strlen(outfile) + 8);
-
-       for (compno = 0; compno < ncomp; compno++) 
-   {
-       if (ncomp > 1) 
-        sprintf(destname, "%d.%s", compno, outfile);
-       else
-        sprintf(destname, "%s", outfile);
-
-       fdest = fopen(destname, "wb");
-       if (!fdest) 
-  {
-       fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
-       free(destname);
-       return 1;
-  }
-       wr = image->comps[compno].w; hr = image->comps[compno].h;
-       prec = image->comps[compno].prec;
-       max = (1<<prec) - 1;
-
-       fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n", 
-               opj_version(), wr, hr, max);
-
-       red = image->comps[compno].data;
-       adjustR = 
-       (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);
-
-    if(prec > 8)
-  {
-       for (i = 0; i < wr * hr; i++) 
- {
-       v = *red + adjustR; ++red;
-/* netpbm: */
-       fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
-
-        if(has_alpha)
-      {
-        v = *alpha++;
-/* netpbm: */
-               fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
-      }
- }/* for(i */
-  }
-       else /* prec <= 8 */
-  {
-       for(i = 0; i < wr * hr; ++i)
- {
-        fprintf(fdest, "%c", (unsigned char)(*red + adjustR)); ++red;
- }
-  }
-       fclose(fdest);
-   } /* for (compno */
-       free(destname);
-
-       return 0;
-}/* imagetopnm() */
-
-#ifdef HAVE_LIBTIFF
-/* -->> -->> -->> -->>
-
-       TIFF IMAGE FORMAT
-
- <<-- <<-- <<-- <<-- */
-
-typedef struct tiff_infoheader{
-       DWORD tiWidth;  // Width of Image in pixel
-       DWORD tiHeight; // Height of Image in pixel
-       DWORD tiPhoto;  // Photometric
-       WORD  tiBps;    // Bits per sample
-       WORD  tiSf;             // Sample Format
-       WORD  tiSpp;    // Sample per pixel 1-bilevel,gray scale , 2- RGB
-       WORD  tiPC;     // Planar config (1-Interleaved, 2-Planarcomp)
-}tiff_infoheader_t;
-
-int imagetotif(opj_image_t * image, const char *outfile) 
-{
-       int width, height, imgsize;
-       int bps,index,adjust, sgnd;
-       int ushift, dshift, has_alpha, force16;
-       unsigned int last_i=0;
-       TIFF *tif;
-       tdata_t buf;
-       tstrip_t strip;
-       tsize_t strip_size;
-
-       ushift = dshift = force16 = has_alpha = 0;
-       bps = image->comps[0].prec;
-
-       if(bps > 8 && bps < 16)
-   {
-       ushift = 16 - bps; dshift = bps - ushift;
-       bps = 16; force16 = 1;
-   }
-
-       if(bps != 8 && bps != 16)
-   {
-       fprintf(stderr,"imagetotif: Bits=%d, Only 8 and 16 bits implemented\n",
-        bps);
-       fprintf(stderr,"\tAborting\n");
-       return 1;
-   }
-       tif = TIFFOpen(outfile, "wb");
-
-       if (!tif) 
-   {
-       fprintf(stderr, "imagetotif:failed to open %s for writing\n", outfile);
-       return 1;
-   }
-       sgnd = image->comps[0].sgnd;
-       adjust = sgnd ? 1 << (image->comps[0].prec - 1) : 0;
-
-       if(image->numcomps >= 3 
-       && image->comps[0].dx == image->comps[1].dx
-       && image->comps[1].dx == image->comps[2].dx
-       && image->comps[0].dy == image->comps[1].dy
-       && image->comps[1].dy == image->comps[2].dy
-       && image->comps[0].prec == image->comps[1].prec
-       && image->comps[1].prec == image->comps[2].prec) 
-   {
-       has_alpha = (image->numcomps == 4);
-
-       width   = image->comps[0].w;
-       height  = image->comps[0].h;
-       imgsize = width * height ;
-       TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
-       TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
-       TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3 + has_alpha);
-       TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
-       TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
-       TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
-       TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
-       TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
-       strip_size = TIFFStripSize(tif);
-       buf = _TIFFmalloc(strip_size);
-       index=0;
-
-       for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
-  {
-       unsigned char *dat8;
-       tsize_t i, ssize;
-       ssize = TIFFStripSize(tif);
-       dat8 = (unsigned char*)buf;
-       int step, restx;
-
-       if(bps == 8)
- {
-       step = 3 + has_alpha;
-       restx = step - 1;
-
-               for(i=0; i < ssize - restx; i += step) 
-          {    
-               int r, g, b, a = 0;
-
-               if(index < imgsize)
-         {
-               r = image->comps[0].data[index];
-               g = image->comps[1].data[index];
-               b = image->comps[2].data[index];
-               if(has_alpha) a = image->comps[3].data[index];
-
-               if(sgnd)
-        {
-               r += adjust;
-               g += adjust;
-               b += adjust;
-               if(has_alpha) a += adjust;
-        }
-               dat8[i+0] = r ;
-               dat8[i+1] = g ;
-               dat8[i+2] = b ;
-               if(has_alpha) dat8[i+3] = a;
-
-               index++;
-               last_i = i + step;
-         }
-               else
-                break;
-          }//for(i = 0;)
-
-               if(last_i < ssize)
-          {
-               for(i = last_i; i < ssize; i += step) 
-         { 
-               int r, g, b, a = 0;
-
-               if(index < imgsize)
-        {
-               r = image->comps[0].data[index];
-               g = image->comps[1].data[index];
-               b = image->comps[2].data[index];
-               if(has_alpha) a = image->comps[3].data[index];
-
-               if(sgnd)
-       {
-               r += adjust;
-               g += adjust;
-               b += adjust;
-               if(has_alpha) a += adjust;
-       }
-               dat8[i+0] = r ;
-               if(i+1 < ssize) dat8[i+1] = g ;  else break;
-               if(i+2 < ssize) dat8[i+2] = b ;  else break;
-               if(has_alpha)
-       {
-               if(i+3 < ssize) dat8[i+3] = a ;  else break;
-       }
-               index++;
-        }
-               else
-                break;
-         }//for(i)
-          }//if(last_i < ssize)
-
- }     //if(bps == 8)
-       else 
-       if(bps == 16)
- {
-       step = 6 + has_alpha + has_alpha;
-       restx = step - 1;
-
-               for(i = 0; i < ssize - restx ; i += step) 
-          {  
-               int r, g, b, a = 0;
-
-               if(index < imgsize)
-         {
-               r = image->comps[0].data[index];
-               g = image->comps[1].data[index];
-               b = image->comps[2].data[index];
-               if(has_alpha) a = image->comps[3].data[index];
-
-               if(sgnd)
-        {
-               r += adjust;
-               g += adjust;
-               b += adjust;
-               if(has_alpha) a += adjust;
-        }
-               if(force16) 
-        { 
-               r = (r<<ushift) + (r>>dshift); 
-               g = (g<<ushift) + (g>>dshift); 
-               b = (b<<ushift) + (b>>dshift); 
-               if(has_alpha) a = (a<<ushift) + (a>>dshift);
-        }
-               dat8[i+0] =  r;//LSB
-               dat8[i+1] = (r >> 8);//MSB
-               dat8[i+2] =  g;
-               dat8[i+3] = (g >> 8);
-               dat8[i+4] =  b;
-               dat8[i+5] = (b >> 8);
-               if(has_alpha) 
-        { 
-               dat8[i+6] =  a; 
-               dat8[i+7] = (a >> 8); 
-        }
-               index++;
-               last_i = i + step;
-         }
-               else
-                break;
-          }//for(i = 0;)
-
-               if(last_i < ssize)
-          {
-               for(i = last_i ; i < ssize ; i += step) 
-         {    
-               int r, g, b, a = 0;
-
-               if(index < imgsize)
-        {
-               r = image->comps[0].data[index];
-               g = image->comps[1].data[index];
-               b = image->comps[2].data[index];
-               if(has_alpha) a = image->comps[3].data[index];
-
-               if(sgnd)
-       {
-               r += adjust;
-               g += adjust;
-               b += adjust;
-               if(has_alpha) a += adjust;
-       }
-           if(force16)
-       {
-           r = (r<<ushift) + (r>>dshift);
-           g = (g<<ushift) + (g>>dshift);
-           b = (b<<ushift) + (b>>dshift);
-           if(has_alpha) a = (a<<ushift) + (a>>dshift);
-       }
-               dat8[i+0] =  r;//LSB
-               if(i+1 < ssize) dat8[i+1] = (r >> 8);else break;//MSB
-               if(i+2 < ssize) dat8[i+2] =  g;      else break;
-               if(i+3 < ssize) dat8[i+3] = (g >> 8);else break;
-               if(i+4 < ssize) dat8[i+4] =  b;      else break;
-               if(i+5 < ssize) dat8[i+5] = (b >> 8);else break;
-
-               if(has_alpha)
-       {
-               if(i+6 < ssize) dat8[i+6] = a; else break;
-               if(i+7 < ssize) dat8[i+7] = (a >> 8); else break;
-       }
-               index++;
-        }
-               else
-                break;
-         }//for(i)
-          }//if(last_i < ssize)
-
- }//if(bps == 16)
-       (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
-  }//for(strip = 0; )
-
-       _TIFFfree((void*)buf);
-       TIFFClose(tif);
-
-       return 0;
-   }//RGB(A)
-
-       if(image->numcomps == 1 /* GRAY */
-       || (   image->numcomps == 2 /* GRAY_ALPHA */
-               && image->comps[0].dx == image->comps[1].dx
-               && image->comps[0].dy == image->comps[1].dy
-               && image->comps[0].prec == image->comps[1].prec))
-   {
-       int step;
-
-       has_alpha = (image->numcomps == 2);
-
-       width   = image->comps[0].w;
-       height  = image->comps[0].h;
-       imgsize = width * height;
-
-/* Set tags */
-       TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
-       TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
-       TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1 + has_alpha);
-       TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);
-       TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
-       TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
-       TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
-       TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);
-
-/* Get a buffer for the data */
-       strip_size = TIFFStripSize(tif);
-       buf = _TIFFmalloc(strip_size);
-       index = 0;
-
-       for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
-  {
-       unsigned char *dat8;
-       tsize_t i, ssize = TIFFStripSize(tif);
-       dat8 = (unsigned char*)buf;
-
-       if(bps == 8)
- {
-       step = 1 + has_alpha;
-
-               for(i=0; i < ssize; i += step) 
-          { 
-               if(index < imgsize)
-         {
-               int r, a = 0;
-
-               r = image->comps[0].data[index];
-               if(has_alpha) a = image->comps[1].data[index];
-
-               if(sgnd)
-        {
-               r += adjust;
-               if(has_alpha) a += adjust;
-        }
-               dat8[i+0] = r;
-               if(has_alpha) dat8[i+1] = a;
-               index++;
-        }
-               else
-                break;
-         }//for(i )
- }//if(bps == 8
-       else 
-       if(bps == 16)
- {
-       step = 2 + has_alpha + has_alpha;
-
-               for(i=0; i < ssize; i += step) 
-          {
-               if(index < imgsize)
-         {
-               int r, a = 0;
-
-               r = image->comps[0].data[index];
-               if(has_alpha) a = image->comps[1].data[index];
-
-               if(sgnd)
-        {
-               r += adjust;
-               if(has_alpha) a += adjust;
-        }
-               if(force16)
-        {
-               r = (r<<ushift) + (r>>dshift);
-               if(has_alpha) a = (a<<ushift) + (a>>dshift);
-        }
-               dat8[i+0] = r;//LSB
-               dat8[i+1] = r >> 8;//MSB
-               if(has_alpha)
-        {
-               dat8[i+2] = a;
-               dat8[i+3] = a >> 8;
-        }
-               index++;
-         }//if(index < imgsize)
-               else
-                break;
-          }//for(i )
- }
-       (void)TIFFWriteEncodedStrip(tif, strip, (void*)buf, strip_size);
-  }//for(strip
-
-       _TIFFfree(buf);
-       TIFFClose(tif);
-
-       return 0;
-   }
-
-       TIFFClose(tif);
-
-       fprintf(stderr,"imagetotif: Bad color format.\n"
-        "\tOnly RGB(A) and GRAY(A) has been implemented\n");
-       fprintf(stderr,"\tFOUND: numcomps(%d)\n\tAborting\n",
-        image->numcomps);
-
-       return 1;
-}/* imagetotif() */
-
-/*
- * libtiff/tif_getimage.c : 1,2,4,8,16 bitspersample accepted
- * CINEMA                 : 12 bit precision
-*/
-opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
-{
-       int subsampling_dx = parameters->subsampling_dx;
-       int subsampling_dy = parameters->subsampling_dy;
-       TIFF *tif;
-       tiff_infoheader_t Info;
-       tdata_t buf;
-       tstrip_t strip;
-       tsize_t strip_size;
-       int j, numcomps, w, h,index;
-       OPJ_COLOR_SPACE color_space;
-       opj_image_cmptparm_t cmptparm[4]; /* RGBA */
-       opj_image_t *image = NULL;
-       int imgsize = 0;
-       int has_alpha = 0;
-
-       tif = TIFFOpen(filename, "r");
-
-       if(!tif) 
-   {
-       fprintf(stderr, "tiftoimage:Failed to open %s for reading\n", filename);
-       return 0;
-   }
-       TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &Info.tiWidth);
-       TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &Info.tiHeight);
-       TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &Info.tiBps);
-       TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &Info.tiSf);
-       TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &Info.tiSpp);
-       Info.tiPhoto = 0;
-       TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &Info.tiPhoto);
-       TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &Info.tiPC);
-       w= Info.tiWidth;
-       h= Info.tiHeight;
-
-   {
-       int b, p;
-
-       if((b = Info.tiBps) != 8 && b != 16 && b != 12) b = 0;
-       if((p = Info.tiPhoto) != 1 && p != 2) p = 0;
-
-    if( !b || !p)
-  {
-       if( !b)
-     fprintf(stderr,"imagetotif: Bits=%d, Only 8 and 16 bits"
-      " implemented\n",Info.tiBps);
-       else
-       if( !p)
-     fprintf(stderr,"tiftoimage: Bad color format %d.\n\tOnly RGB(A)"
-      " and GRAY(A) has been implemented\n",(int) Info.tiPhoto);
-
-    fprintf(stderr,"\tAborting\n");
-       TIFFClose(tif);
-
-    return NULL;
-  }
-   }
-
-   {/* From: tiff-4.0.x/libtiff/tif_getimage.c : */
-       uint16* sampleinfo;
-       uint16 extrasamples;
-
-       TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
-        &extrasamples, &sampleinfo);
-
-       if(extrasamples >= 1)
-  {
-       switch(sampleinfo[0]) 
- {
-       case EXTRASAMPLE_UNSPECIFIED: 
-/* Workaround for some images without correct info about alpha channel
-*/
-               if(Info.tiSpp > 3)
-                has_alpha = 1;
-               break;
-
-       case EXTRASAMPLE_ASSOCALPHA: /* data pre-multiplied */
-       case EXTRASAMPLE_UNASSALPHA: /* data not pre-multiplied */
-               has_alpha = 1;
-               break;
- }
-  }
-   }
-/* initialize image components
-*/ 
-       memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
-
-       if(Info.tiPhoto == PHOTOMETRIC_RGB) /* RGB(A) */
-   {
-       numcomps = 3 + has_alpha;
-       color_space = CLRSPC_SRGB;
-
-       for(j = 0; j < numcomps; j++) 
-  {
-       if(parameters->cp_cinema) 
- {
-       cmptparm[j].prec = 12;
-       cmptparm[j].bpp = 12;
- }
-       else
- {
-       cmptparm[j].prec = Info.tiBps;
-       cmptparm[j].bpp = Info.tiBps;
- }
-       cmptparm[j].dx = subsampling_dx;
-       cmptparm[j].dy = subsampling_dy;
-       cmptparm[j].w = w;
-       cmptparm[j].h = h;
-  }
-
-       image = opj_image_create(numcomps, &cmptparm[0], color_space);
-
-       if(!image) 
-  {
-       TIFFClose(tif);
-       return NULL;
-  }
-/* set image offset and reference grid 
-*/
-       image->x0 = parameters->image_offset_x0;
-       image->y0 = parameters->image_offset_y0;
-       image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 :
-               image->x0 + (w - 1) * subsampling_dx + 1;
-       image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 :
-               image->y0 + (h - 1) * subsampling_dy + 1;
-
-       buf = _TIFFmalloc(TIFFStripSize(tif));
-
-       strip_size=TIFFStripSize(tif);
-       index = 0;
-       imgsize = image->comps[0].w * image->comps[0].h ;
-/* Read the Image components
-*/
-       for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
-  {
-       unsigned char *dat8;
-       int step;
-       tsize_t i, ssize;
-       ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
-       dat8 = (unsigned char*)buf;
-
-       if(Info.tiBps == 16)
- {
-       step = 6 + has_alpha + has_alpha;
-
-               for(i = 0; i < ssize; i += step) 
-          {
-               if(index < imgsize)
-         {
-               image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0]; // R 
-               image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2]; // G 
-               image->comps[2].data[index] = ( dat8[i+5] << 8 ) | dat8[i+4]; // B 
-               if(has_alpha)
-                image->comps[3].data[index] = ( dat8[i+7] << 8 ) | dat8[i+6];
-
-               if(parameters->cp_cinema)
-        {
-/* Rounding 16 to 12 bits
-*/
-               image->comps[0].data[index] = 
-                       (image->comps[0].data[index] + 0x08) >> 4 ;
-               image->comps[1].data[index] = 
-                       (image->comps[1].data[index] + 0x08) >> 4 ;
-               image->comps[2].data[index] = 
-                       (image->comps[2].data[index] + 0x08) >> 4 ;
-               if(has_alpha)
-                image->comps[3].data[index] =
-                       (image->comps[3].data[index] + 0x08) >> 4 ;
-        }
-               index++;
-         }
-               else
-                break;
-          }//for(i = 0)
- }//if(Info.tiBps == 16)
-       else 
-       if(Info.tiBps == 8)
- {
-       step = 3 + has_alpha;
-
-               for(i = 0; i < ssize; i += step) 
-          {
-               if(index < imgsize)
-         {
-               image->comps[0].data[index] = dat8[i+0];// R 
-               image->comps[1].data[index] = dat8[i+1];// G 
-               image->comps[2].data[index] = dat8[i+2];// B 
-               if(has_alpha)
-                image->comps[3].data[index] = dat8[i+3];
-
-               if(parameters->cp_cinema)
-        {
-/* Rounding 8 to 12 bits
-*/
-               image->comps[0].data[index] = image->comps[0].data[index] << 4 ;
-               image->comps[1].data[index] = image->comps[1].data[index] << 4 ;
-               image->comps[2].data[index] = image->comps[2].data[index] << 4 ;
-               if(has_alpha)
-                image->comps[3].data[index] = image->comps[3].data[index] << 4 ;
-        }
-               index++;
-         }//if(index
-               else
-                break;
-          }//for(i )
- }//if( Info.tiBps == 8)
-       else
-       if(Info.tiBps == 12)/* CINEMA file */
- {
-       step = 9;
-
-               for(i = 0; i < ssize; i += step) 
-          {
-               if((index < imgsize)&(index+1 < imgsize))
-         {
-               image->comps[0].data[index]   = ( dat8[i+0]<<4 )        |(dat8[i+1]>>4);
-               image->comps[1].data[index]   = ((dat8[i+1]& 0x0f)<< 8) | dat8[i+2];
-
-               image->comps[2].data[index]   = ( dat8[i+3]<<4)         |(dat8[i+4]>>4);
-               image->comps[0].data[index+1] = ((dat8[i+4]& 0x0f)<< 8) | dat8[i+5];
-
-               image->comps[1].data[index+1] = ( dat8[i+6] <<4)        |(dat8[i+7]>>4);
-               image->comps[2].data[index+1] = ((dat8[i+7]& 0x0f)<< 8) | dat8[i+8];
-
-               index += 2;
-         }
-               else
-                break;
-          }//for(i )
- }
-  }//for(strip = 0; )
-
-       _TIFFfree(buf);
-       TIFFClose(tif);
-
-       return image;
-   }//RGB(A)
-
-       if(Info.tiPhoto == PHOTOMETRIC_MINISBLACK) /* GRAY(A) */
-   {
-       numcomps = 1 + has_alpha;
-       color_space = CLRSPC_GRAY;
-
-       for(j = 0; j < numcomps; ++j)
-  {
-       cmptparm[j].prec = Info.tiBps;
-       cmptparm[j].bpp = Info.tiBps;
-       cmptparm[j].dx = subsampling_dx;
-       cmptparm[j].dy = subsampling_dy;
-       cmptparm[j].w = w;
-       cmptparm[j].h = h;
-  }
-       image = opj_image_create(numcomps, &cmptparm[0], color_space);
-
-       if(!image) 
-  {
-       TIFFClose(tif);
-       return NULL;
-  }
-/* set image offset and reference grid 
-*/
-       image->x0 = parameters->image_offset_x0;
-       image->y0 = parameters->image_offset_y0;
-       image->x1 =     !image->x0 ? (w - 1) * subsampling_dx + 1 :
-               image->x0 + (w - 1) * subsampling_dx + 1;
-       image->y1 =     !image->y0 ? (h - 1) * subsampling_dy + 1 :
-               image->y0 + (h - 1) * subsampling_dy + 1;
-
-       buf = _TIFFmalloc(TIFFStripSize(tif));
-
-       strip_size = TIFFStripSize(tif);
-       index = 0;
-       imgsize = image->comps[0].w * image->comps[0].h ;
-/* Read the Image components
-*/
-       for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++) 
-  {
-       unsigned char *dat8;
-       tsize_t i, ssize;
-       int step;
-
-       ssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);
-       dat8 = (unsigned char*)buf;
-
-               if(Info.tiBps == 16)
-          {
-               step = 2 + has_alpha + has_alpha;
-
-               for(i = 0; i < ssize; i += step) 
-         {
-               if(index < imgsize)
-        {
-               image->comps[0].data[index] = ( dat8[i+1] << 8 ) | dat8[i+0];
-               if(has_alpha)
-                image->comps[1].data[index] = ( dat8[i+3] << 8 ) | dat8[i+2];
-               index++;
-        }
-               else
-                break;
-         }//for(i )
-          }
-               else 
-               if(Info.tiBps == 8)
-          {
-               step = 1 + has_alpha;
-
-               for(i = 0; i < ssize; i += step) 
-         {
-               if(index < imgsize)
-        {
-               image->comps[0].data[index] = dat8[i+0];
-               if(has_alpha)
-                image->comps[1].data[index] = dat8[i+1];
-               index++;
-        }
-               else
-                break;
-         }//for(i )
-          }
-  }//for(strip = 0;
-
-       _TIFFfree(buf);
-       TIFFClose(tif);
-
-   }//GRAY(A)
-
-       return image;
-
-}/* tiftoimage() */
-
-#endif /* HAVE_LIBTIFF */
-
-/* -->> -->> -->> -->>
-
-       RAW IMAGE FORMAT
-
- <<-- <<-- <<-- <<-- */
-
-opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
-       int subsampling_dx = parameters->subsampling_dx;
-       int subsampling_dy = parameters->subsampling_dy;
-
-       FILE *f = NULL;
-       int i, compno, numcomps, w, h;
-       OPJ_COLOR_SPACE color_space;
-       opj_image_cmptparm_t *cmptparm; 
-       opj_image_t * image = NULL;
-       unsigned short ch;
-       
-       if((! (raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0)
-       {
-               fprintf(stderr,"\nError: invalid raw image parameters\n");
-               fprintf(stderr,"Please use the Format option -F:\n");
-               fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
-               fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
-               fprintf(stderr,"Aborting\n");
-               return NULL;
-       }
-
-       f = fopen(filename, "rb");
-       if (!f) {
-               fprintf(stderr, "Failed to open %s for reading !!\n", filename);
-               fprintf(stderr,"Aborting\n");
-               return NULL;
-       }
-       numcomps = raw_cp->rawComp;
-       color_space = CLRSPC_SRGB;
-       w = raw_cp->rawWidth;
-       h = raw_cp->rawHeight;
-       cmptparm = (opj_image_cmptparm_t*) malloc(numcomps * sizeof(opj_image_cmptparm_t));
-       
-       /* initialize image components */       
-       memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
-       for(i = 0; i < numcomps; i++) {         
-               cmptparm[i].prec = raw_cp->rawBitDepth;
-               cmptparm[i].bpp = raw_cp->rawBitDepth;
-               cmptparm[i].sgnd = raw_cp->rawSigned;
-               cmptparm[i].dx = subsampling_dx;
-               cmptparm[i].dy = subsampling_dy;
-               cmptparm[i].w = w;
-               cmptparm[i].h = h;
-       }
-       /* create the image */
-       image = opj_image_create(numcomps, &cmptparm[0], color_space);
-       if(!image) {
-               fclose(f);
-               return NULL;
-       }
-       /* set image offset and reference grid */
-       image->x0 = parameters->image_offset_x0;
-       image->y0 = parameters->image_offset_y0;
-       image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
-       image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
-
-       if(raw_cp->rawBitDepth <= 8)
-       {
-               unsigned char value = 0;
-               for(compno = 0; compno < numcomps; compno++) {
-                       for (i = 0; i < w * h; i++) {
-                               if (!fread(&value, 1, 1, f)) {
-                                       fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
-                                       return NULL;
-                               }
-                               image->comps[compno].data[i] = raw_cp->rawSigned?(char)value:value;
-                       }
-               }
-       }
-       else if(raw_cp->rawBitDepth <= 16)
-       {
-               unsigned short value;
-               for(compno = 0; compno < numcomps; compno++) {
-                       for (i = 0; i < w * h; i++) {
-                               unsigned char temp;
-                               if (!fread(&temp, 1, 1, f)) {
-                                       fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
-                                       return NULL;
-                               }
-                               value = temp << 8;
-                               if (!fread(&temp, 1, 1, f)) {
-                                       fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
-                                       return NULL;
-                               }
-                               value += temp;
-                               image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
-                       }
-               }
-       }
-       else {
-               fprintf(stderr,"OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n");
-               return NULL;
-       }
-
-       if (fread(&ch, 1, 1, f)) {
-               fprintf(stderr,"Warning. End of raw file not reached... processing anyway\n");
-       }
-       fclose(f);
-
-       return image;
-}
-
-int imagetoraw(opj_image_t * image, const char *outfile)
-{
-       FILE *rawFile = NULL;
-       int compno;
-       int w, h;
-       int line, row;
-       int *ptr;
-
-       if((image->numcomps * image->x1 * image->y1) == 0)
-       {
-               fprintf(stderr,"\nError: invalid raw image parameters\n");
-               return 1;
-       }
-
-       rawFile = fopen(outfile, "wb");
-       if (!rawFile) {
-               fprintf(stderr, "Failed to open %s for writing !!\n", outfile);
-               return 1;
-       }
-
-       fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
-
-       for(compno = 0; compno < image->numcomps; compno++)
-       {
-               fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
-                       image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
-
-               w = image->comps[compno].w;
-               h = image->comps[compno].h;
-
-               if(image->comps[compno].prec <= 8)
-               {
-                       if(image->comps[compno].sgnd == 1)
-                       {
-                               signed char curr;
-                               int mask = (1 << image->comps[compno].prec) - 1;
-                               ptr = image->comps[compno].data;
-                               for (line = 0; line < h; line++) {
-                                       for(row = 0; row < w; row++)    {                               
-                                               curr = (signed char) (*ptr & mask);
-                                               fwrite(&curr, sizeof(signed char), 1, rawFile);
-                                               ptr++;
-                                       }
-                               }
-                       }
-                       else if(image->comps[compno].sgnd == 0)
-                       {
-                               unsigned char curr;
-                               int mask = (1 << image->comps[compno].prec) - 1;
-                               ptr = image->comps[compno].data;
-                               for (line = 0; line < h; line++) {
-                                       for(row = 0; row < w; row++)    {       
-                                               curr = (unsigned char) (*ptr & mask);
-                                               fwrite(&curr, sizeof(unsigned char), 1, rawFile);
-                                               ptr++;
-                                       }
-                               }
-                       }
-               }
-               else if(image->comps[compno].prec <= 16)
-               {
-                       if(image->comps[compno].sgnd == 1)
-                       {
-                               signed short int curr;
-                               int mask = (1 << image->comps[compno].prec) - 1;
-                               ptr = image->comps[compno].data;
-                               for (line = 0; line < h; line++) {
-                                       for(row = 0; row < w; row++)    {                                       
-                                               unsigned char temp;
-                                               curr = (signed short int) (*ptr & mask);
-                                               temp = (unsigned char) (curr >> 8);
-                                               fwrite(&temp, 1, 1, rawFile);
-                                               temp = (unsigned char) curr;
-                                               fwrite(&temp, 1, 1, rawFile);
-                                               ptr++;
-                                       }
-                               }
-                       }
-                       else if(image->comps[compno].sgnd == 0)
-                       {
-                               unsigned short int curr;
-                               int mask = (1 << image->comps[compno].prec) - 1;
-                               ptr = image->comps[compno].data;
-                               for (line = 0; line < h; line++) {
-                                       for(row = 0; row < w; row++)    {                               
-                                               unsigned char temp;
-                                               curr = (unsigned short int) (*ptr & mask);
-                                               temp = (unsigned char) (curr >> 8);
-                                               fwrite(&temp, 1, 1, rawFile);
-                                               temp = (unsigned char) curr;
-                                               fwrite(&temp, 1, 1, rawFile);
-                                               ptr++;
-                                       }
-                               }
-                       }
-               }
-               else if (image->comps[compno].prec <= 32)
-               {
-                       fprintf(stderr,"More than 16 bits per component no handled yet\n");
-                       return 1;
-               }
-               else
-               {
-                       fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
-                       return 1;
-               }
-       }
-       fclose(rawFile);
-       return 0;
-}
-
-#ifdef HAVE_LIBPNG
-
-#define PNG_MAGIC "\x89PNG\x0d\x0a\x1a\x0a"
-#define MAGIC_SIZE 8
-/* PNG allows bits per sample: 1, 2, 4, 8, 16 */
-
-opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
-{
-       png_structp  png;
-       png_infop    info;
-       double gamma, display_exponent;
-       int bit_depth, interlace_type,compression_type, filter_type;
-       int unit;
-       png_uint_32 resx, resy;
-       unsigned int i, j;
-       png_uint_32  width, height;
-       int color_type, has_alpha, is16;
-       unsigned char *s;
-       FILE *reader;
-       unsigned char **rows;
-/* j2k: */
-       opj_image_t *image;
-       opj_image_cmptparm_t cmptparm[4];
-       int sub_dx, sub_dy;
-       unsigned int nr_comp;
-       int *r, *g, *b, *a;
-       unsigned char sigbuf[8];
-
-       if((reader = fopen(read_idf, "rb")) == NULL)
-   {
-       fprintf(stderr,"pngtoimage: can not open %s\n",read_idf);
-       return NULL;
-   }
-       image = NULL; png = NULL; rows = NULL;
-
-       if(fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE
-       || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0)
-   {
-       fprintf(stderr,"pngtoimage: %s is no valid PNG file\n",read_idf);
-       goto fin;
-   }
-/* libpng-VERSION/example.c: 
- * PC : screen_gamma = 2.2;
- * Mac: screen_gamma = 1.7 or 1.0;
-*/
-       display_exponent = 2.2;
-
-       if((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,
-                                   NULL, NULL, NULL)) == NULL)
-         goto fin;
-       if((info = png_create_info_struct(png)) == NULL)
-         goto fin;
-
-       if(setjmp(png_jmpbuf(png)))
-         goto fin;
-
-       png_init_io(png, reader);
-       png_set_sig_bytes(png, MAGIC_SIZE);
-
-       png_read_info(png, info);
-
-       if(png_get_IHDR(png, info, &width, &height,
-               &bit_depth, &color_type, &interlace_type, 
-               &compression_type, &filter_type) == 0)
-        goto fin;
-
-/* png_set_expand():
- * expand paletted images to RGB, expand grayscale images of
- * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
- * to alpha channels.
-*/
-       if(color_type == PNG_COLOR_TYPE_PALETTE)
-         png_set_expand(png);
-       else
-       if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
-         png_set_expand(png);
-
-       if(png_get_valid(png, info, PNG_INFO_tRNS))
-         png_set_expand(png);
-
-       is16 = (bit_depth == 16);
-
-/* GRAY => RGB; GRAY_ALPHA => RGBA
-*/
-       if(color_type == PNG_COLOR_TYPE_GRAY
-       || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
-   {
-       png_set_gray_to_rgb(png);
-       color_type = 
-        (color_type == PNG_COLOR_TYPE_GRAY? PNG_COLOR_TYPE_RGB:
-               PNG_COLOR_TYPE_RGB_ALPHA);
-   }
-       if( !png_get_gAMA(png, info, &gamma))
-         gamma = 0.45455;
-
-       png_set_gamma(png, display_exponent, gamma);
-
-       png_read_update_info(png, info);
-
-       png_get_pHYs(png, info, &resx, &resy, &unit);
-
-       color_type = png_get_color_type(png, info);
-
-       has_alpha = (color_type == PNG_COLOR_TYPE_RGB_ALPHA);
-
-       nr_comp = 3 + has_alpha;
-
-       bit_depth = png_get_bit_depth(png, info);
-
-       rows = (unsigned char**)calloc(height+1, sizeof(unsigned char*));
-       for(i = 0; i < height; ++i)
-        rows[i] = (unsigned char*)malloc(png_get_rowbytes(png,info));
-
-       png_read_image(png, rows);
-
-       memset(&cmptparm, 0, 4 * sizeof(opj_image_cmptparm_t));
-
-       sub_dx = params->subsampling_dx; sub_dy = params->subsampling_dy;
-
-       for(i = 0; i < nr_comp; ++i)
-   {
-       cmptparm[i].prec = bit_depth;
-/* bits_per_pixel: 8 or 16 */
-       cmptparm[i].bpp = bit_depth;
-       cmptparm[i].sgnd = 0;
-       cmptparm[i].dx = sub_dx;
-       cmptparm[i].dy = sub_dy;
-       cmptparm[i].w = width;
-       cmptparm[i].h = height;
-   }
-
-       image = opj_image_create(nr_comp, &cmptparm[0], CLRSPC_SRGB);
-
-       if(image == NULL) goto fin;
-
-    image->x0 = params->image_offset_x0;
-    image->y0 = params->image_offset_y0;
-    image->x1 = image->x0 + (width  - 1) * sub_dx + 1 + image->x0;
-    image->y1 = image->y0 + (height - 1) * sub_dy + 1 + image->y0;
-
-       r = image->comps[0].data;
-       g = image->comps[1].data;
-       b = image->comps[2].data;
-       a = image->comps[3].data;
-
-       for(i = 0; i < height; ++i)
-   {
-       s = rows[i];
-
-       for(j = 0; j < width; ++j)
-  {
-       if(is16)
- {
-       *r++ = s[0]<<8|s[1]; s += 2;
-
-       *g++ = s[0]<<8|s[1]; s += 2;
-       
-       *b++ = s[0]<<8|s[1]; s += 2;
-       
-       if(has_alpha) { *a++ = s[0]<<8|s[1]; s += 2; }
-
-       continue;
- }
-       *r++ = *s++; *g++ = *s++; *b++ = *s++;
-
-       if(has_alpha) *a++ = *s++;
-  }
-   }
-fin:
-       if(rows)
-   {
-       for(i = 0; i < height; ++i)
-        free(rows[i]);
-       free(rows);
-   }
-       if(png)
-         png_destroy_read_struct(&png, &info, NULL);
-
-       fclose(reader);
-
-       return image;
-
-}/* pngtoimage() */
-
-int imagetopng(opj_image_t * image, const char *write_idf)
-{
-       FILE *writer;
-       png_structp png;
-       png_infop info;
-       int *red, *green, *blue, *alpha;
-       unsigned char *row_buf, *d;
-       int has_alpha, width, height, nr_comp, color_type;
-       int adjustR, adjustG, adjustB, x, y, fails, is16, force16;
-  int opj_prec, prec, ushift, dshift;
-       unsigned short mask = 0xffff;
-       png_color_8 sig_bit;
-
-       is16 = force16 = ushift = dshift = 0; fails = 1;
-       prec = opj_prec = image->comps[0].prec;
-
-       if(prec > 8 && prec < 16)
-   {
-        prec = 16; force16 = 1;
-   }
-       if(prec != 1 && prec != 2 && prec != 4 && prec != 8 && prec != 16)
-   {
-       fprintf(stderr,"imagetopng: can not create %s"
-        "\n\twrong bit_depth %d\n", write_idf, prec);
-       return fails;
-   }
-       writer = fopen(write_idf, "wb");
-
-       if(writer == NULL) return fails;
-
-       info = NULL; has_alpha = 0;
-
-/* Create and initialize the png_struct with the desired error handler
- * functions.  If you want to use the default stderr and longjump method,
- * you can supply NULL for the last three parameters.  We also check that
- * the library version is compatible with the one used at compile time,
- * in case we are using dynamically linked libraries.  REQUIRED.
-*/
-       png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
-               NULL, NULL, NULL);
-/*png_voidp user_error_ptr, user_error_fn, user_warning_fn); */
-
-       if(png == NULL) goto fin;
-
-/* Allocate/initialize the image information data.  REQUIRED 
-*/
-       info = png_create_info_struct(png);
-
-       if(info == NULL) goto fin;
-
-/* Set error handling.  REQUIRED if you are not supplying your own
- * error handling functions in the png_create_write_struct() call.
-*/
-       if(setjmp(png_jmpbuf(png))) goto fin;
-
-/* I/O initialization functions is REQUIRED 
-*/
-       png_init_io(png, writer);
-
-/* Set the image information here.  Width and height are up to 2^31,
- * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
- * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
- * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
- * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
- * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
- * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. 
- * REQUIRED
-*/
-       png_set_compression_level(png, Z_BEST_COMPRESSION);
-
-       if(prec == 16) mask = 0xffff;
-       else
-       if(prec == 8) mask = 0x00ff;
-       else
-       if(prec == 4) mask = 0x000f;
-       else
-       if(prec == 2) mask = 0x0003;
-       else
-       if(prec == 1) mask = 0x0001;
-
-       nr_comp = image->numcomps;
-
-       if(nr_comp >= 3
-    && image->comps[0].dx == image->comps[1].dx
-    && image->comps[1].dx == image->comps[2].dx
-    && image->comps[0].dy == image->comps[1].dy
-    && image->comps[1].dy == image->comps[2].dy
-    && image->comps[0].prec == image->comps[1].prec
-    && image->comps[1].prec == image->comps[2].prec)
-   {
-       int v;
-
-    has_alpha = (nr_comp > 3); 
-
-       is16 = (prec == 16);
-       
-    width = image->comps[0].w;
-    height = image->comps[0].h;
-
-       red = image->comps[0].data;
-       green = image->comps[1].data;
-       blue = image->comps[2].data;
-
-    sig_bit.red = sig_bit.green = sig_bit.blue = prec;
-
-       if(has_alpha) 
-  {
-       sig_bit.alpha = prec;
-       alpha = image->comps[3].data; 
-       color_type = PNG_COLOR_TYPE_RGB_ALPHA;
-  }
-       else 
-  {
-       sig_bit.alpha = 0; alpha = NULL;
-       color_type = PNG_COLOR_TYPE_RGB;
-  }
-       png_set_sBIT(png, info, &sig_bit);
-
-       png_set_IHDR(png, info, width, height, prec, 
-        color_type,
-        PNG_INTERLACE_NONE,
-        PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
-
-/*=============================*/
-       png_write_info(png, info);
-/*=============================*/
-       if(opj_prec < 8)
-  {
-       png_set_packing(png);
-  }
-       if(force16)
-  {
-       ushift = 16 - opj_prec; dshift = opj_prec - ushift;     
-  }
-    adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
-    adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
-    adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
-
-       row_buf = (unsigned char*)malloc(width * nr_comp * 2);
-
-       for(y = 0; y < height; ++y)
-  {
-       d = row_buf;
-
-       for(x = 0; x < width; ++x)
- {
-               if(is16)
-          {
-               v = *red + adjustR; ++red;
-               
-               if(force16) { v = (v<<ushift) + (v>>dshift); }
-
-               *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
-
-               v = *green + adjustG; ++green;
-               
-               if(force16) { v = (v<<ushift) + (v>>dshift); }
-
-               *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
-
-               v =  *blue + adjustB; ++blue;
-               
-               if(force16) { v = (v<<ushift) + (v>>dshift); }
-
-               *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
-
-               if(has_alpha)
-         {
-               v = *alpha++;
-               
-               if(force16) { v = (v<<ushift) + (v>>dshift); }
-
-               *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
-         }
-               continue;
-          }
-               *d++ = (unsigned char)((*red + adjustR) & mask); ++red;
-               *d++ = (unsigned char)((*green + adjustG) & mask); ++green;
-               *d++ = (unsigned char)((*blue + adjustB) & mask); ++blue;
-
-               if(has_alpha)
-          {
-               *d++ = (unsigned char)(*alpha & mask); ++alpha;
-          }
- }     /* for(x) */
-
-       png_write_row(png, row_buf);
-
-  }    /* for(y) */
-       free(row_buf);
-
-   }/* nr_comp >= 3 */
-       else
-       if(nr_comp == 1 /* GRAY */
-       || (   nr_comp == 2 /* GRAY_ALPHA */
-               && image->comps[0].dx == image->comps[1].dx
-               && image->comps[0].dy == image->comps[1].dy
-               && image->comps[0].prec == image->comps[1].prec))
-   {
-       int v;
-
-       red = image->comps[0].data;
-
-    if(force16)
-  {
-    ushift = 16 - opj_prec; dshift = opj_prec - ushift;
-  }
-    sig_bit.gray = prec;
-    sig_bit.red = sig_bit.green = sig_bit.blue = sig_bit.alpha = 0;
-       alpha = NULL;
-       color_type = PNG_COLOR_TYPE_GRAY;
-
-    if(nr_comp == 2) 
-  { 
-       has_alpha = 1; sig_bit.alpha = prec;
-       alpha = image->comps[1].data;
-       color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
-  }
-    width = image->comps[0].w;
-    height = image->comps[0].h;
-
-       png_set_IHDR(png, info, width, height, sig_bit.gray,
-     color_type,
-     PNG_INTERLACE_NONE,
-     PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
-
-       png_set_sBIT(png, info, &sig_bit);
-/*=============================*/
-       png_write_info(png, info);
-/*=============================*/
-       adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
-
-       if(opj_prec < 8)
-  {
-       png_set_packing(png);
-  }
-
-       if(prec > 8)
-  {
-       row_buf = (unsigned char*)
-        malloc(width * nr_comp * sizeof(unsigned short));
-
-       for(y = 0; y < height; ++y)
- {
-       d = row_buf;
-
-               for(x = 0; x < width; ++x)
-          {
-               v = *red + adjustR; ++red;
-
-               if(force16) { v = (v<<ushift) + (v>>dshift); }
-
-               *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
-
-               if(has_alpha)
-         {
-               v = *alpha++;
-
-               if(force16) { v = (v<<ushift) + (v>>dshift); }
-
-               *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
-         }
-          }/* for(x) */
-       png_write_row(png, row_buf);
-
- }     /* for(y) */
-       free(row_buf);
-  }
-       else /* prec <= 8 */
-  {
-       row_buf = (unsigned char*)calloc(width, nr_comp * 2);
-
-       for(y = 0; y < height; ++y)
- {
-       d = row_buf;
-
-               for(x = 0; x < width; ++x)
-          {
-               *d++ = (unsigned char)((*red + adjustR) & mask); ++red;
-
-               if(has_alpha)
-         {
-               *d++ = (unsigned char)(*alpha & mask); ++alpha;
-         }
-          }/* for(x) */
-
-       png_write_row(png, row_buf);
-
- }     /* for(y) */
-       free(row_buf);
-  }
-   }
-       else
-   {
-       fprintf(stderr,"imagetopng: can not create %s\n",write_idf);
-       goto fin;
-   }
-       png_write_end(png, info);
-
-       fails = 0;
-
-fin:
-
-       if(png)
-   {
-    png_destroy_write_struct(&png, &info);
-   }
-       fclose(writer);
-
-       if(fails) remove(write_idf);
-
-       return fails;
-}/* imagetopng() */
-#endif /* HAVE_LIBPNG */
diff --git a/codec/convert.h b/codec/convert.h
deleted file mode 100644 (file)
index 1dc58d7..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
- * Copyright (c) 2002-2007, Professor Benoit Macq
- * Copyright (c) 2001-2003, David Janssens
- * Copyright (c) 2002-2003, Yannick Verschueren
- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
- * Copyright (c) 2005, Herve Drolon, FreeImage Team
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef __J2K_CONVERT_H
-#define __J2K_CONVERT_H
-
-/**@name RAW image encoding parameters */
-/*@{*/
-typedef struct raw_cparameters {
-       /** width of the raw image */
-       int rawWidth;
-       /** height of the raw image */
-       int rawHeight;
-       /** components of the raw image */
-       int rawComp;
-       /** bit depth of the raw image */
-       int rawBitDepth;
-       /** signed/unsigned raw image */
-       bool rawSigned;
-       /*@}*/
-} raw_cparameters_t;
-
-/* TGA conversion */
-opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters);
-int imagetotga(opj_image_t * image, const char *outfile);
-
-/* BMP conversion */
-opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters);
-int imagetobmp(opj_image_t *image, const char *outfile);
-
-/* TIFF conversion*/
-opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters);
-int imagetotif(opj_image_t *image, const char *outfile);
-/**
-Load a single image component encoded in PGX file format
-@param filename Name of the PGX file to load
-@param parameters *List ?*
-@return Returns a greyscale image if successful, returns NULL otherwise
-*/
-opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters);
-int imagetopgx(opj_image_t *image, const char *outfile);
-
-opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters);
-int imagetopnm(opj_image_t *image, const char *outfile);
-
-/* RAW conversion */
-int imagetoraw(opj_image_t * image, const char *outfile);
-opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp);
-
-/* PNG conversion*/
-extern int imagetopng(opj_image_t *image, const char *write_idf);
-extern opj_image_t* pngtoimage(const char *filename, opj_cparameters_t *parameters);
-
-#endif /* __J2K_CONVERT_H */
-
diff --git a/codec/image_to_j2k.c b/codec/image_to_j2k.c
deleted file mode 100644 (file)
index 66d2bf4..0000000
+++ /dev/null
@@ -1,1789 +0,0 @@
-/*
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
- * Copyright (c) 2002-2007, Professor Benoit Macq
- * Copyright (c) 2001-2003, David Janssens
- * Copyright (c) 2002-2003, Yannick Verschueren
- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
- * Copyright (c) 2005, Herve Drolon, FreeImage Team
- * Copyright (c) 2006-2007, Parvatha Elangovan
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <math.h>
-
-#ifdef _WIN32
-#include "windirent.h"
-#else
-#include <dirent.h>
-#endif /* _WIN32 */
-
-#ifdef _WIN32
-#include <windows.h>
-#else
-#include <strings.h>
-#define _stricmp strcasecmp
-#define _strnicmp strncasecmp
-#endif /* _WIN32 */
-
-#include "opj_config.h"
-#include "openjpeg.h"
-#include "getopt.h"
-#include "convert.h"
-#include "index.h"
-
-#include "format_defs.h"
-
-#define CINEMA_24_CS 1302083   /*Codestream length for 24fps*/
-#define CINEMA_48_CS 651041            /*Codestream length for 48fps*/
-#define COMP_24_CS 1041666             /*Maximum size per color component for 2K & 4K @ 24fps*/
-#define COMP_48_CS 520833              /*Maximum size per color component for 2K @ 48fps*/
-
-typedef struct dircnt{
-       /** Buffer for holding images read from Directory*/
-       char *filename_buf;
-       /** Pointer to the buffer*/
-       char **filename;
-}dircnt_t;
-
-typedef struct img_folder{
-       /** The directory path of the folder containing input images*/
-       char *imgdirpath;
-       /** Output format*/
-       char *out_format;
-       /** Enable option*/
-       char set_imgdir;
-       /** Enable Cod Format for output*/
-       char set_out_format;
-       /** User specified rate stored in case of cinema option*/
-       float *rates;
-}img_fol_t;
-
-void encode_help_display() {
-       fprintf(stdout,"HELP for image_to_j2k\n----\n\n");
-       fprintf(stdout,"- the -h option displays this help information on screen\n\n");
-
-/* UniPG>> */
-       fprintf(stdout,"List of parameters for the JPEG 2000 "
-#ifdef USE_JPWL
-               "+ JPWL "
-#endif /* USE_JPWL */
-               "encoder:\n");
-/* <<UniPG */
-       fprintf(stdout,"\n");
-       fprintf(stdout,"REMARKS:\n");
-       fprintf(stdout,"---------\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"The markers written to the main_header are : SOC SIZ COD QCD COM.\n");
-       fprintf(stdout,"COD and QCD never appear in the tile_header.\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"By default:\n");
-       fprintf(stdout,"------------\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout," * Lossless\n");
-       fprintf(stdout," * 1 tile\n");
-       fprintf(stdout," * Size of precinct : 2^15 x 2^15 (means 1 precinct)\n");
-       fprintf(stdout," * Size of code-block : 64 x 64\n");
-       fprintf(stdout," * Number of resolutions: 6\n");
-       fprintf(stdout," * No SOP marker in the codestream\n");
-       fprintf(stdout," * No EPH marker in the codestream\n");
-       fprintf(stdout," * No sub-sampling in x or y direction\n");
-       fprintf(stdout," * No mode switch activated\n");
-       fprintf(stdout," * Progression order: LRCP\n");
-       fprintf(stdout," * No index file\n");
-       fprintf(stdout," * No ROI upshifted\n");
-       fprintf(stdout," * No offset of the origin of the image\n");
-       fprintf(stdout," * No offset of the origin of the tiles\n");
-       fprintf(stdout," * Reversible DWT 5-3\n");
-/* UniPG>> */
-#ifdef USE_JPWL
-       fprintf(stdout," * No JPWL protection\n");
-#endif /* USE_JPWL */
-/* <<UniPG */
-       fprintf(stdout,"\n");
-       fprintf(stdout,"Parameters:\n");
-       fprintf(stdout,"------------\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"Required Parameters (except with -h):\n");
-       fprintf(stdout,"One of the two options -ImgDir or -i must be used\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-ImgDir      : Image file Directory path (example ../Images) \n");
-       fprintf(stdout,"    When using this option -OutFor must be used\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-OutFor \n");
-       fprintf(stdout,"    REQUIRED only if -ImgDir is used\n");
-       fprintf(stdout,"          Need to specify only format without filename <BMP>  \n");
-       fprintf(stdout,"    Currently accepts PBM, PGM, PPM, PNM, PAM, PGX, PNG, BMP, TIF, RAW and TGA formats\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-i           : source file  (-i source.pnm also *pbm, *.pgm, *.ppm, *.pam, *.pgx, *png, *.bmp, *.tif, *.raw, *.tga) \n");
-       fprintf(stdout,"    When using this option -o must be used\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-o           : destination file (-o dest.j2k or .jp2) \n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"Optional Parameters:\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-h           : display the help information \n ");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-cinema2K    : Digital Cinema 2K profile compliant codestream for 2K resolution.(-cinema2k 24 or 48) \n");
-  fprintf(stdout,"       Need to specify the frames per second for a 2K resolution. Only 24 or 48 fps is allowed\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-cinema4K    : Digital Cinema 4K profile compliant codestream for 4K resolution \n");
-       fprintf(stdout,"          Frames per second not required. Default value is 24fps\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-r           : different compression ratios for successive layers (-r 20,10,5)\n ");
-       fprintf(stdout,"                 - The rate specified for each quality level is the desired \n");
-       fprintf(stdout,"                   compression factor.\n");
-       fprintf(stdout,"                   Example: -r 20,10,1 means quality 1: compress 20x, \n");
-       fprintf(stdout,"                     quality 2: compress 10x and quality 3: compress lossless\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"               (options -r and -q cannot be used together)\n ");
-       fprintf(stdout,"\n");
-
-       fprintf(stdout,"-q           : different psnr for successive layers (-q 30,40,50) \n ");
-
-       fprintf(stdout,"               (options -r and -q cannot be used together)\n ");
-
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-n           : number of resolutions (-n 3) \n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-b           : size of code block (-b 32,32) \n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-c           : size of precinct (-c 128,128) \n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-t           : size of tile (-t 512,512) \n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-p           : progression order (-p LRCP) [LRCP, RLCP, RPCL, PCRL, CPRL] \n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-s           : subsampling factor (-s 2,2) [-s X,Y] \n");
-       fprintf(stdout,"             Remark: subsampling bigger than 2 can produce error\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-POC         : Progression order change (-POC T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL) \n");
-       fprintf(stdout,"      Example: T1=0,0,1,5,3,CPRL \n");
-       fprintf(stdout,"                         : Ttilenumber=Resolution num start,Component num start,Layer num end,Resolution num end,Component num end,Progression order\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-SOP         : write SOP marker before each packet \n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-EPH         : write EPH marker after each header packet \n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-M           : mode switch (-M 3) [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
-       fprintf(stdout,"                 8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)] \n");
-       fprintf(stdout,"                 Indicate multiple modes by adding their values. \n");
-       fprintf(stdout,"                 ex: RESTART(4) + RESET(2) + SEGMARK(32) = -M 38\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-x           : create an index file *.Idx (-x index_name.Idx) \n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-ROI         : c=%%d,U=%%d : quantization indices upshifted \n");
-       fprintf(stdout,"               for component c=%%d [%%d = 0,1,2]\n");
-       fprintf(stdout,"               with a value of U=%%d [0 <= %%d <= 37] (i.e. -ROI c=0,U=25) \n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-d           : offset of the origin of the image (-d 150,300) \n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-T           : offset of the origin of the tiles (-T 100,75) \n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-I           : use the irreversible DWT 9-7 (-I) \n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"-F           : characteristics of the raw input image\n");
-       fprintf(stdout,"               -F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
-       fprintf(stdout,"               Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
-       fprintf(stdout,"\n");
-/* UniPG>> */
-#ifdef USE_JPWL
-       fprintf(stdout,"-W           : adoption of JPWL (Part 11) capabilities (-W params)\n");
-       fprintf(stdout,"               The parameters can be written and repeated in any order:\n");
-       fprintf(stdout,"               [h<tilepart><=type>,s<tilepart><=method>,a=<addr>,...\n");
-       fprintf(stdout,"                ...,z=<size>,g=<range>,p<tilepart:pack><=type>]\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"                 h selects the header error protection (EPB): 'type' can be\n");
-       fprintf(stdout,"                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
-       fprintf(stdout,"                   if 'tilepart' is absent, it is for main and tile headers\n");
-       fprintf(stdout,"                   if 'tilepart' is present, it applies from that tile\n");
-       fprintf(stdout,"                     onwards, up to the next h<> spec, or to the last tilepart\n");
-       fprintf(stdout,"                     in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);
-       fprintf(stdout,"\n");
-       fprintf(stdout,"                 p selects the packet error protection (EEP/UEP with EPBs)\n");
-       fprintf(stdout,"                  to be applied to raw data: 'type' can be\n");
-       fprintf(stdout,"                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
-       fprintf(stdout,"                   if 'tilepart:pack' is absent, it is from tile 0, packet 0\n");
-       fprintf(stdout,"                   if 'tilepart:pack' is present, it applies from that tile\n");
-       fprintf(stdout,"                     and that packet onwards, up to the next packet spec\n");
-       fprintf(stdout,"                     or to the last packet in the last tilepart in the stream\n");
-       fprintf(stdout,"                     (max. %d specs)\n", JPWL_MAX_NO_PACKSPECS);
-       fprintf(stdout,"\n");
-       fprintf(stdout,"                 s enables sensitivity data insertion (ESD): 'method' can be\n");
-       fprintf(stdout,"                   [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR\n");
-       fprintf(stdout,"                    4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED]\n");
-       fprintf(stdout,"                   if 'tilepart' is absent, it is for main header only\n");
-       fprintf(stdout,"                   if 'tilepart' is present, it applies from that tile\n");
-       fprintf(stdout,"                     onwards, up to the next s<> spec, or to the last tilepart\n");
-       fprintf(stdout,"                     in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);
-       fprintf(stdout,"\n");
-       fprintf(stdout,"                 g determines the addressing mode: <range> can be\n");
-       fprintf(stdout,"                   [0=PACKET 1=BYTE RANGE 2=PACKET RANGE]\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"                 a determines the size of data addressing: <addr> can be\n");
-       fprintf(stdout,"                   2/4 bytes (small/large codestreams). If not set, auto-mode\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"                 z determines the size of sensitivity values: <size> can be\n");
-       fprintf(stdout,"                   1/2 bytes, for the transformed pseudo-floating point value\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"                 ex.:\n");
-       fprintf(stdout,"                   h,h0=64,h3=16,h5=32,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,\n");
-       fprintf(stdout,"                     s0=6,s3=-1,a=0,g=1,z=1\n");
-       fprintf(stdout,"                 means\n");
-       fprintf(stdout,"                   predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2,\n");
-       fprintf(stdout,"                   CRC-16 in TPH 3 and TPH 4, CRC-32 in remaining TPHs,\n");
-       fprintf(stdout,"                   UEP rs(78,32) for packets 0 to 23 of tile 0,\n");
-       fprintf(stdout,"                   UEP rs(56,32) for packs. 24 to the last of tilepart 0,\n");
-       fprintf(stdout,"                   UEP rs default for packets of tilepart 1,\n");
-       fprintf(stdout,"                   no UEP for packets 0 to 19 of tilepart 3,\n");
-       fprintf(stdout,"                   UEP CRC-32 for packs. 20 of tilepart 3 to last tilepart,\n");
-       fprintf(stdout,"                   relative sensitivity ESD for MH,\n");
-       fprintf(stdout,"                   TSE ESD from TPH 0 to TPH 2, byte range with automatic\n");
-       fprintf(stdout,"                   size of addresses and 1 byte for each sensitivity value\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"                 ex.:\n");
-       fprintf(stdout,"                       h,s,p\n");
-       fprintf(stdout,"                 means\n");
-       fprintf(stdout,"                   default protection to headers (MH and TPHs) as well as\n");
-       fprintf(stdout,"                   data packets, one ESD in MH\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"                 N.B.: use the following recommendations when specifying\n");
-       fprintf(stdout,"                       the JPWL parameters list\n");
-       fprintf(stdout,"                   - when you use UEP, always pair the 'p' option with 'h'\n");
-       fprintf(stdout,"                 \n");
-#endif /* USE_JPWL */
-/* <<UniPG */
-       fprintf(stdout,"IMPORTANT:\n");
-       fprintf(stdout,"-----------\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"The index file has the structure below:\n");
-       fprintf(stdout,"---------------------------------------\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"Image_height Image_width\n");
-       fprintf(stdout,"progression order\n");
-       fprintf(stdout,"Tiles_size_X Tiles_size_Y\n");
-       fprintf(stdout,"Tiles_nb_X Tiles_nb_Y\n");
-       fprintf(stdout,"Components_nb\n");
-       fprintf(stdout,"Layers_nb\n");
-       fprintf(stdout,"decomposition_levels\n");
-       fprintf(stdout,"[Precincts_size_X_res_Nr Precincts_size_Y_res_Nr]...\n");
-       fprintf(stdout,"   [Precincts_size_X_res_0 Precincts_size_Y_res_0]\n");
-       fprintf(stdout,"Main_header_start_position\n");
-       fprintf(stdout,"Main_header_end_position\n");
-       fprintf(stdout,"Codestream_size\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"INFO ON TILES\n");
-       fprintf(stdout,"tileno start_pos end_hd end_tile nbparts disto nbpix disto/nbpix\n");
-       fprintf(stdout,"Tile_0 start_pos end_Theader end_pos NumParts TotalDisto NumPix MaxMSE\n");
-       fprintf(stdout,"Tile_1   ''           ''        ''        ''       ''    ''      ''\n");
-       fprintf(stdout,"...\n");
-       fprintf(stdout,"Tile_Nt   ''           ''        ''        ''       ''    ''     ''\n");
-       fprintf(stdout,"...\n");
-       fprintf(stdout,"TILE 0 DETAILS\n");
-       fprintf(stdout,"part_nb tileno num_packs start_pos end_tph_pos end_pos\n");
-       fprintf(stdout,"...\n");
-       fprintf(stdout,"Progression_string\n");
-       fprintf(stdout,"pack_nb tileno layno resno compno precno start_pos end_ph_pos end_pos disto\n");
-       fprintf(stdout,"Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");
-       fprintf(stdout,"...\n");
-       fprintf(stdout,"Tpacket_Np ''   ''    ''   ''    ''       ''       ''     ''\n");
-
-       fprintf(stdout,"MaxDisto\n");
-
-       fprintf(stdout,"TotalDisto\n\n");
-}
-
-OPJ_PROG_ORDER give_progression(char progression[4]) {
-       if(strncmp(progression, "LRCP", 4) == 0) {
-               return LRCP;
-       }
-       if(strncmp(progression, "RLCP", 4) == 0) {
-               return RLCP;
-       }
-       if(strncmp(progression, "RPCL", 4) == 0) {
-               return RPCL;
-       }
-       if(strncmp(progression, "PCRL", 4) == 0) {
-               return PCRL;
-       }
-       if(strncmp(progression, "CPRL", 4) == 0) {
-               return CPRL;
-       }
-
-       return PROG_UNKNOWN;
-}
-
-int get_num_images(char *imgdirpath){
-       DIR *dir;
-       struct dirent* content;
-       int num_images = 0;
-
-       /*Reading the input images from given input directory*/
-
-       dir= opendir(imgdirpath);
-       if(!dir){
-               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
-               return 0;
-       }
-
-       num_images=0;
-       while((content=readdir(dir))!=NULL){
-               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
-                       continue;
-               num_images++;
-       }
-       return num_images;
-}
-
-int load_images(dircnt_t *dirptr, char *imgdirpath){
-       DIR *dir;
-       struct dirent* content;
-       int i = 0;
-
-       /*Reading the input images from given input directory*/
-
-       dir= opendir(imgdirpath);
-       if(!dir){
-               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
-               return 1;
-       }else   {
-               fprintf(stderr,"Folder opened successfully\n");
-       }
-
-       while((content=readdir(dir))!=NULL){
-               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
-                       continue;
-
-               strcpy(dirptr->filename[i],content->d_name);
-               i++;
-       }
-       return 0;
-}
-
-int get_file_format(char *filename) {
-       unsigned int i;
-       static const char *extension[] = {
-    "pgx", "pnm", "pgm", "ppm", "pbm", "pam", "bmp", "tif", "raw", "tga", "png", "j2k", "jp2", "j2c", "jpc"
-    };
-       static const int format[] = {
-    PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, TGA_DFMT, PNG_DFMT, J2K_CFMT, JP2_CFMT, J2K_CFMT, J2K_CFMT
-    };
-       char * ext = strrchr(filename, '.');
-       if (ext == NULL)
-               return -1;
-       ext++;
-       for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
-               if(_strnicmp(ext, extension[i], 3) == 0) {
-                       return format[i];
-               }
-       }
-       return -1;
-}
-
-char * get_file_name(char *name){
-       char *fname;
-       fname= (char*)malloc(OPJ_PATH_LEN*sizeof(char));
-       fname= strtok(name,".");
-       return fname;
-}
-
-char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_cparameters_t *parameters){
-       char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
-  char *temp_p, temp1[OPJ_PATH_LEN]="";
-
-       strcpy(image_filename,dirptr->filename[imageno]);
-       fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
-       parameters->decod_format = get_file_format(image_filename);
-       if (parameters->decod_format == -1)
-               return 1;
-       sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
-       strncpy(parameters->infile, infilename, sizeof(infilename));
-
-       //Set output file
-       strcpy(temp_ofname,get_file_name(image_filename));
-       while((temp_p = strtok(NULL,".")) != NULL){
-               strcat(temp_ofname,temp1);
-               sprintf(temp1,".%s",temp_p);
-       }
-       if(img_fol->set_out_format==1){
-               sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
-               strncpy(parameters->outfile, outfilename, sizeof(outfilename));
-       }
- return 0;
-}
-
-static int initialise_4K_poc(opj_poc_t *POC, int numres){
-       POC[0].tile  = 1;
-       POC[0].resno0  = 0;
-       POC[0].compno0 = 0;
-       POC[0].layno1  = 1;
-       POC[0].resno1  = numres-1;
-       POC[0].compno1 = 3;
-       POC[0].prg1 = CPRL;
-       POC[1].tile  = 1;
-       POC[1].resno0  = numres-1;
-       POC[1].compno0 = 0;
-       POC[1].layno1  = 1;
-       POC[1].resno1  = numres;
-       POC[1].compno1 = 3;
-       POC[1].prg1 = CPRL;
-       return 2;
-}
-
-void cinema_parameters(opj_cparameters_t *parameters){
-       parameters->tile_size_on = false;
-       parameters->cp_tdx=1;
-       parameters->cp_tdy=1;
-
-       /*Tile part*/
-       parameters->tp_flag = 'C';
-       parameters->tp_on = 1;
-
-       /*Tile and Image shall be at (0,0)*/
-       parameters->cp_tx0 = 0;
-       parameters->cp_ty0 = 0;
-       parameters->image_offset_x0 = 0;
-       parameters->image_offset_y0 = 0;
-
-       /*Codeblock size= 32*32*/
-       parameters->cblockw_init = 32;
-       parameters->cblockh_init = 32;
-       parameters->csty |= 0x01;
-
-       /*The progression order shall be CPRL*/
-       parameters->prog_order = CPRL;
-
-       /* No ROI */
-       parameters->roi_compno = -1;
-
-       parameters->subsampling_dx = 1;         parameters->subsampling_dy = 1;
-
-       /* 9-7 transform */
-       parameters->irreversible = 1;
-
-}
-
-void cinema_setup_encoder(opj_cparameters_t *parameters,opj_image_t *image, img_fol_t *img_fol){
-       int i;
-       float temp_rate;
-
-       switch (parameters->cp_cinema){
-       case CINEMA2K_24:
-       case CINEMA2K_48:
-               if(parameters->numresolution > 6){
-                       parameters->numresolution = 6;
-               }
-               if (!((image->comps[0].w == 2048) | (image->comps[0].h == 1080))){
-                       fprintf(stdout,"Image coordinates %d x %d is not 2K compliant.\nJPEG Digital Cinema Profile-3 "
-                               "(2K profile) compliance requires that at least one of coordinates match 2048 x 1080\n",
-                               image->comps[0].w,image->comps[0].h);
-                       parameters->cp_rsiz = STD_RSIZ;
-               }
-       break;
-
-       case CINEMA4K_24:
-               if(parameters->numresolution < 1){
-                               parameters->numresolution = 1;
-                       }else if(parameters->numresolution > 7){
-                               parameters->numresolution = 7;
-                       }
-               if (!((image->comps[0].w == 4096) | (image->comps[0].h == 2160))){
-                       fprintf(stdout,"Image coordinates %d x %d is not 4K compliant.\nJPEG Digital Cinema Profile-4"
-                               "(4K profile) compliance requires that at least one of coordinates match 4096 x 2160\n",
-                               image->comps[0].w,image->comps[0].h);
-                       parameters->cp_rsiz = STD_RSIZ;
-               }
-               parameters->numpocs = initialise_4K_poc(parameters->POC,parameters->numresolution);
-               break;
-       default :
-               break;
-       }
-
-       switch (parameters->cp_cinema){
-               case CINEMA2K_24:
-               case CINEMA4K_24:
-                       for(i=0 ; i<parameters->tcp_numlayers ; i++){
-                               temp_rate = 0 ;
-                               if (img_fol->rates[i]== 0){
-                                       parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
-                                       (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);
-                               }else{
-                                       temp_rate =((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
-                                               (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy);
-                                       if (temp_rate > CINEMA_24_CS ){
-                                               parameters->tcp_rates[i]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
-                                               (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);
-                                       }else{
-                                               parameters->tcp_rates[i]= img_fol->rates[i];
-                                       }
-                               }
-                       }
-                       parameters->max_comp_size = COMP_24_CS;
-                       break;
-
-               case CINEMA2K_48:
-                       for(i=0 ; i<parameters->tcp_numlayers ; i++){
-                               temp_rate = 0 ;
-                               if (img_fol->rates[i]== 0){
-                                       parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
-                                       (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);
-                               }else{
-                                       temp_rate =((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
-                                               (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy);
-                                       if (temp_rate > CINEMA_48_CS ){
-                                               parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
-                                               (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);
-                                       }else{
-                                               parameters->tcp_rates[i]= img_fol->rates[i];
-                                       }
-                               }
-                       }
-                       parameters->max_comp_size = COMP_48_CS;
-                       break;
-               default:
-                       break;
-       }
-       parameters->cp_disto_alloc = 1;
-}
-
-/* ------------------------------------------------------------------------------------ */
-
-int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *parameters,
-                                                                                                       img_fol_t *img_fol, raw_cparameters_t *raw_cp, char *indexfilename) {
-       int i, j,totlen;
-       option_t long_option[]={
-               {"cinema2K",REQ_ARG, NULL ,'w'},
-               {"cinema4K",NO_ARG, NULL ,'y'},
-               {"ImgDir",REQ_ARG, NULL ,'z'},
-               {"TP",REQ_ARG, NULL ,'v'},
-               {"SOP",NO_ARG, NULL ,'S'},
-               {"EPH",NO_ARG, NULL ,'E'},
-               {"OutFor",REQ_ARG, NULL ,'O'},
-               {"POC",REQ_ARG, NULL ,'P'},
-               {"ROI",REQ_ARG, NULL ,'R'},
-       };
-
-       /* parse the command line */
-       const char optlist[] = "i:o:r:q:n:b:c:t:p:s:SEM:x:R:d:T:If:P:C:F:"
-#ifdef USE_JPWL
-               "W:"
-#endif /* USE_JPWL */
-               "h";
-
-       totlen=sizeof(long_option);
-       img_fol->set_out_format=0;
-       raw_cp->rawWidth = 0;
-
-       while (1) {
-    int c = getopt_long(argc, argv, optlist,long_option,totlen);
-               if (c == -1)
-                       break;
-               switch (c) {
-                       case 'i':                       /* input file */
-                       {
-                               char *infile = optarg;
-                               parameters->decod_format = get_file_format(infile);
-                               switch(parameters->decod_format) {
-                                       case PGX_DFMT:
-                                       case PXM_DFMT:
-                                       case BMP_DFMT:
-                                       case TIF_DFMT:
-                                       case RAW_DFMT:
-                                       case TGA_DFMT:
-                                       case PNG_DFMT:
-                                               break;
-                                       default:
-                                               fprintf(stderr,
-                                                       "!! Unrecognized format for infile : %s "
-              "[accept only *.pnm, *.pgm, *.ppm, *.pgx, *png, *.bmp, *.tif, *.raw or *.tga] !!\n\n",
-                                                       infile);
-                                               return 1;
-                               }
-                               strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-
-                       case 'o':                       /* output file */
-                       {
-                               char *outfile = optarg;
-                               parameters->cod_format = get_file_format(outfile);
-                               switch(parameters->cod_format) {
-                                       case J2K_CFMT:
-                                       case JP2_CFMT:
-                                               break;
-                                       default:
-                                               fprintf(stderr, "Unknown output format image %s [only *.j2k, *.j2c or *.jp2]!! \n", outfile);
-                                               return 1;
-                               }
-                               strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-                       case 'O':                       /* output format */
-                               {
-                                       char outformat[50];
-                                       char *of = optarg;
-                                       sprintf(outformat,".%s",of);
-                                       img_fol->set_out_format = 1;
-                                       parameters->cod_format = get_file_format(outformat);
-                                       switch(parameters->cod_format) {
-                                               case J2K_CFMT:
-                                               case JP2_CFMT:
-                                                       img_fol->out_format = optarg;
-                                                       break;
-                                               default:
-                                                       fprintf(stderr, "Unknown output format image [only j2k, j2c, jp2]!! \n");
-                                                       return 1;
-                                       }
-                               }
-                               break;
-
-
-                               /* ----------------------------------------------------- */
-
-
-                       case 'r':                       /* rates rates/distorsion */
-                       {
-                               char *s = optarg;
-                               parameters->tcp_numlayers = 0;
-                               while (sscanf(s, "%f", &parameters->tcp_rates[parameters->tcp_numlayers]) == 1) {
-                                       parameters->tcp_numlayers++;
-                                       while (*s && *s != ',') {
-                                               s++;
-                                       }
-                                       if (!*s)
-                                               break;
-                                       s++;
-                               }
-                               parameters->cp_disto_alloc = 1;
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-
-
-                       case 'F':                       /* Raw image format parameters */
-                       {
-                               char signo;
-                               char *s = optarg;
-                               if (sscanf(s, "%d,%d,%d,%d,%c", &raw_cp->rawWidth, &raw_cp->rawHeight, &raw_cp->rawComp, &raw_cp->rawBitDepth, &signo) == 5) {
-                                       if (signo == 's') {
-                                               raw_cp->rawSigned = true;
-                                               fprintf(stdout,"\nRaw file parameters: %d,%d,%d,%d Signed\n", raw_cp->rawWidth, raw_cp->rawHeight, raw_cp->rawComp, raw_cp->rawBitDepth);
-                                       }
-                                       else if (signo == 'u') {
-                                               raw_cp->rawSigned = false;
-                                               fprintf(stdout,"\nRaw file parameters: %d,%d,%d,%d Unsigned\n", raw_cp->rawWidth, raw_cp->rawHeight, raw_cp->rawComp, raw_cp->rawBitDepth);
-                                       }
-                                       else {
-                                               fprintf(stderr,"\nError: invalid raw image parameters: Unknown sign of raw file\n");
-                                               fprintf(stderr,"Please use the Format option -F:\n");
-                                               fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
-                                               fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
-                                               fprintf(stderr,"Aborting\n");
-                                       }
-                               }
-                               else {
-                                       fprintf(stderr,"\nError: invalid raw image parameters\n");
-                                       fprintf(stderr,"Please use the Format option -F:\n");
-                                       fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
-                                               fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
-                                       fprintf(stderr,"Aborting\n");
-                                       return 1;
-                               }
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-
-                       case 'q':                       /* add fixed_quality */
-                       {
-                               char *s = optarg;
-                               while (sscanf(s, "%f", &parameters->tcp_distoratio[parameters->tcp_numlayers]) == 1) {
-                                       parameters->tcp_numlayers++;
-                                       while (*s && *s != ',') {
-                                               s++;
-                                       }
-                                       if (!*s)
-                                               break;
-                                       s++;
-                               }
-                               parameters->cp_fixed_quality = 1;
-                       }
-                       break;
-
-                               /* dda */
-                               /* ----------------------------------------------------- */
-
-                       case 'f':                       /* mod fixed_quality (before : -q) */
-                       {
-                               int *row = NULL, *col = NULL;
-                               int numlayers = 0, numresolution = 0, matrix_width = 0;
-
-                               char *s = optarg;
-                               sscanf(s, "%d", &numlayers);
-                               s++;
-                               if (numlayers > 9)
-                                       s++;
-
-                               parameters->tcp_numlayers = numlayers;
-                               numresolution = parameters->numresolution;
-                               matrix_width = numresolution * 3;
-                               parameters->cp_matrice = (int *) malloc(numlayers * matrix_width * sizeof(int));
-                               s = s + 2;
-
-                               for (i = 0; i < numlayers; i++) {
-                                       row = &parameters->cp_matrice[i * matrix_width];
-                                       col = row;
-                                       parameters->tcp_rates[i] = 1;
-                                       sscanf(s, "%d,", &col[0]);
-                                       s += 2;
-                                       if (col[0] > 9)
-                                               s++;
-                                       col[1] = 0;
-                                       col[2] = 0;
-                                       for (j = 1; j < numresolution; j++) {
-                                               col += 3;
-                                               sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);
-                                               s += 6;
-                                               if (col[0] > 9)
-                                                       s++;
-                                               if (col[1] > 9)
-                                                       s++;
-                                               if (col[2] > 9)
-                                                       s++;
-                                       }
-                                       if (i < numlayers - 1)
-                                               s++;
-                               }
-                               parameters->cp_fixed_alloc = 1;
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-
-                       case 't':                       /* tiles */
-                       {
-                               sscanf(optarg, "%d,%d", &parameters->cp_tdx, &parameters->cp_tdy);
-                               parameters->tile_size_on = true;
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-
-                       case 'n':                       /* resolution */
-                       {
-                               sscanf(optarg, "%d", &parameters->numresolution);
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-                       case 'c':                       /* precinct dimension */
-                       {
-                               char sep;
-                               int res_spec = 0;
-
-                               char *s = optarg;
-                               do {
-                                       sep = 0;
-                                       sscanf(s, "[%d,%d]%c", &parameters->prcw_init[res_spec],
-                                 &parameters->prch_init[res_spec], &sep);
-                                       parameters->csty |= 0x01;
-                                       res_spec++;
-                                       s = strpbrk(s, "]") + 2;
-                               }
-                               while (sep == ',');
-                               parameters->res_spec = res_spec;
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-
-                       case 'b':                       /* code-block dimension */
-                       {
-                               int cblockw_init = 0, cblockh_init = 0;
-                               sscanf(optarg, "%d,%d", &cblockw_init, &cblockh_init);
-                               if (cblockw_init * cblockh_init > 4096 || cblockw_init > 1024
-                                       || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {
-                                       fprintf(stderr,
-                                               "!! Size of code_block error (option -b) !!\n\nRestriction :\n"
-            "    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");
-                                       return 1;
-                               }
-                               parameters->cblockw_init = cblockw_init;
-                               parameters->cblockh_init = cblockh_init;
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-
-                       case 'x':                       /* creation of index file */
-                       {
-                               char *index = optarg;
-                               strncpy(indexfilename, index, OPJ_PATH_LEN);
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-
-                       case 'p':                       /* progression order */
-                       {
-                               char progression[4];
-
-                               strncpy(progression, optarg, 4);
-                               parameters->prog_order = give_progression(progression);
-                               if (parameters->prog_order == -1) {
-                                       fprintf(stderr, "Unrecognized progression order "
-            "[LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
-                                       return 1;
-                               }
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-
-                       case 's':                       /* subsampling factor */
-                       {
-                               if (sscanf(optarg, "%d,%d", &parameters->subsampling_dx,
-                                    &parameters->subsampling_dy) != 2) {
-                                       fprintf(stderr, "'-s' sub-sampling argument error !  [-s dx,dy]\n");
-                                       return 1;
-                               }
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-
-                       case 'd':                       /* coordonnate of the reference grid */
-                       {
-                               if (sscanf(optarg, "%d,%d", &parameters->image_offset_x0,
-                                    &parameters->image_offset_y0) != 2) {
-                                       fprintf(stderr, "-d 'coordonnate of the reference grid' argument "
-            "error !! [-d x0,y0]\n");
-                                       return 1;
-                               }
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-
-                       case 'h':                       /* display an help description */
-                               encode_help_display();
-                               return 1;
-
-                               /* ----------------------------------------------------- */
-
-                       case 'P':                       /* POC */
-                       {
-                               int numpocs = 0;                /* number of progression order change (POC) default 0 */
-                               opj_poc_t *POC = NULL;  /* POC : used in case of Progression order change */
-
-                               char *s = optarg;
-                               POC = parameters->POC;
-
-                               while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%4s", &POC[numpocs].tile,
-                                       &POC[numpocs].resno0, &POC[numpocs].compno0,
-                                       &POC[numpocs].layno1, &POC[numpocs].resno1,
-                                       &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
-                                       POC[numpocs].prg1 = give_progression(POC[numpocs].progorder);
-                                       numpocs++;
-                                       while (*s && *s != '/') {
-                                               s++;
-                                       }
-                                       if (!*s) {
-                                               break;
-                                       }
-                                       s++;
-                               }
-                               parameters->numpocs = numpocs;
-                       }
-                       break;
-
-                               /* ------------------------------------------------------ */
-
-                       case 'S':                       /* SOP marker */
-                       {
-                               parameters->csty |= 0x02;
-                       }
-                       break;
-
-                               /* ------------------------------------------------------ */
-
-                       case 'E':                       /* EPH marker */
-                       {
-                               parameters->csty |= 0x04;
-                       }
-                       break;
-
-                               /* ------------------------------------------------------ */
-
-                       case 'M':                       /* Mode switch pas tous au point !! */
-                       {
-                               int value = 0;
-                               if (sscanf(optarg, "%d", &value) == 1) {
-                                       for (i = 0; i <= 5; i++) {
-                                               int cache = value & (1 << i);
-                                               if (cache)
-                                                       parameters->mode |= (1 << i);
-                                       }
-                               }
-                       }
-                       break;
-
-                               /* ------------------------------------------------------ */
-
-                       case 'R':                       /* ROI */
-                       {
-                               if (sscanf(optarg, "c=%d,U=%d", &parameters->roi_compno,
-                                           &parameters->roi_shift) != 2) {
-                                       fprintf(stderr, "ROI error !! [-ROI c='compno',U='shift']\n");
-                                       return 1;
-                               }
-                       }
-                       break;
-
-                               /* ------------------------------------------------------ */
-
-                       case 'T':                       /* Tile offset */
-                       {
-                               if (sscanf(optarg, "%d,%d", &parameters->cp_tx0, &parameters->cp_ty0) != 2) {
-                                       fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");
-                                       return 1;
-                               }
-                       }
-                       break;
-
-                               /* ------------------------------------------------------ */
-
-                       case 'C':                       /* add a comment */
-                       {
-                               parameters->cp_comment = (char*)malloc(strlen(optarg) + 1);
-                               if(parameters->cp_comment) {
-                                       strcpy(parameters->cp_comment, optarg);
-                               }
-                       }
-                       break;
-
-
-                               /* ------------------------------------------------------ */
-
-                       case 'I':                       /* reversible or not */
-                       {
-                               parameters->irreversible = 1;
-                       }
-                       break;
-
-                       /* ------------------------------------------------------ */
-
-                       case 'v':                       /* Tile part generation*/
-                       {
-                               parameters->tp_flag = optarg[0];
-                               parameters->tp_on = 1;
-                       }
-                       break;
-
-                               /* ------------------------------------------------------ */
-
-                       case 'z':                       /* Image Directory path */
-                       {
-                               img_fol->imgdirpath = (char*)malloc(strlen(optarg) + 1);
-                               strcpy(img_fol->imgdirpath,optarg);
-                               img_fol->set_imgdir=1;
-                       }
-                       break;
-
-                               /* ------------------------------------------------------ */
-
-                       case 'w':                       /* Digital Cinema 2K profile compliance*/
-                       {
-                               int fps=0;
-                               sscanf(optarg,"%d",&fps);
-                               if(fps == 24){
-                                       parameters->cp_cinema = CINEMA2K_24;
-                               }else if(fps == 48 ){
-                                       parameters->cp_cinema = CINEMA2K_48;
-                               }else {
-                                       fprintf(stderr,"Incorrect value!! must be 24 or 48\n");
-                                       return 1;
-                               }
-                               fprintf(stdout,"CINEMA 2K compliant codestream\n");
-                               parameters->cp_rsiz = CINEMA2K;
-
-                       }
-                       break;
-
-                               /* ------------------------------------------------------ */
-
-                       case 'y':                       /* Digital Cinema 4K profile compliance*/
-                       {
-                               parameters->cp_cinema = CINEMA4K_24;
-                               fprintf(stdout,"CINEMA 4K compliant codestream\n");
-                               parameters->cp_rsiz = CINEMA4K;
-                       }
-                       break;
-
-                               /* ------------------------------------------------------ */
-
-/* UniPG>> */
-#ifdef USE_JPWL
-                               /* ------------------------------------------------------ */
-
-                       case 'W':                       /* JPWL capabilities switched on */
-                       {
-                               char *token = NULL;
-                               int hprot, pprot, sens, addr, size, range;
-
-                               /* we need to enable indexing */
-                               if (!indexfilename || !*indexfilename) {
-                                       strncpy(indexfilename, JPWL_PRIVATEINDEX_NAME, OPJ_PATH_LEN);
-                               }
-
-                               /* search for different protection methods */
-
-                               /* break the option in comma points and parse the result */
-                               token = strtok(optarg, ",");
-                               while(token != NULL) {
-
-                                       /* search header error protection method */
-                                       if (*token == 'h') {
-
-                                               static int tile = 0, tilespec = 0, lasttileno = 0;
-
-                                               hprot = 1; /* predefined method */
-
-                                               if(sscanf(token, "h=%d", &hprot) == 1) {
-                                                       /* Main header, specified */
-                                                       if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
-                                                               ((hprot >= 37) && (hprot <= 128)))) {
-                                                               fprintf(stderr, "ERROR -> invalid main header protection method h = %d\n", hprot);
-                                                               return 1;
-                                                       }
-                                                       parameters->jpwl_hprot_MH = hprot;
-
-                                               } else if(sscanf(token, "h%d=%d", &tile, &hprot) == 2) {
-                                                       /* Tile part header, specified */
-                                                       if (!((hprot == 0) || (hprot == 1) || (hprot == 16) || (hprot == 32) ||
-                                                               ((hprot >= 37) && (hprot <= 128)))) {
-                                                               fprintf(stderr, "ERROR -> invalid tile part header protection method h = %d\n", hprot);
-                                                               return 1;
-                                                       }
-                                                       if (tile < 0) {
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method t = %d\n", tile);
-                                                               return 1;
-                                                       }
-                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {
-                                                               parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
-                                                               parameters->jpwl_hprot_TPH[tilespec++] = hprot;
-                                                       }
-
-                                               } else if(sscanf(token, "h%d", &tile) == 1) {
-                                                       /* Tile part header, unspecified */
-                                                       if (tile < 0) {
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method t = %d\n", tile);
-                                                               return 1;
-                                                       }
-                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {
-                                                               parameters->jpwl_hprot_TPH_tileno[tilespec] = lasttileno = tile;
-                                                               parameters->jpwl_hprot_TPH[tilespec++] = hprot;
-                                                       }
-
-
-                                               } else if (!strcmp(token, "h")) {
-                                                       /* Main header, unspecified */
-                                                       parameters->jpwl_hprot_MH = hprot;
-
-                                               } else {
-                                                       fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
-                                                       return 1;
-                                               };
-
-                                       }
-
-                                       /* search packet error protection method */
-                                       if (*token == 'p') {
-
-                                               static int pack = 0, tile = 0, packspec = 0;
-
-                                               pprot = 1; /* predefined method */
-
-                                               if (sscanf(token, "p=%d", &pprot) == 1) {
-                                                       /* Method for all tiles and all packets */
-                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
-                                                               ((pprot >= 37) && (pprot <= 128)))) {
-                                                               fprintf(stderr, "ERROR -> invalid default packet protection method p = %d\n", pprot);
-                                                               return 1;
-                                                       }
-                                                       parameters->jpwl_pprot_tileno[0] = 0;
-                                                       parameters->jpwl_pprot_packno[0] = 0;
-                                                       parameters->jpwl_pprot[0] = pprot;
-
-                                               } else if (sscanf(token, "p%d=%d", &tile, &pprot) == 2) {
-                                                       /* method specified from that tile on */
-                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
-                                                               ((pprot >= 37) && (pprot <= 128)))) {
-                                                               fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
-                                                               return 1;
-                                                       }
-                                                       if (tile < 0) {
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);
-                                                               return 1;
-                                                       }
-                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {
-                                                               parameters->jpwl_pprot_tileno[packspec] = tile;
-                                                               parameters->jpwl_pprot_packno[packspec] = 0;
-                                                               parameters->jpwl_pprot[packspec++] = pprot;
-                                                       }
-
-                                               } else if (sscanf(token, "p%d:%d=%d", &tile, &pack, &pprot) == 3) {
-                                                       /* method fully specified from that tile and that packet on */
-                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
-                                                               ((pprot >= 37) && (pprot <= 128)))) {
-                                                               fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
-                                                               return 1;
-                                                       }
-                                                       if (tile < 0) {
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);
-                                                               return 1;
-                                                       }
-                                                       if (pack < 0) {
-                                                               fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n", pack);
-                                                               return 1;
-                                                       }
-                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {
-                                                               parameters->jpwl_pprot_tileno[packspec] = tile;
-                                                               parameters->jpwl_pprot_packno[packspec] = pack;
-                                                               parameters->jpwl_pprot[packspec++] = pprot;
-                                                       }
-
-                                               } else if (sscanf(token, "p%d:%d", &tile, &pack) == 2) {
-                                                       /* default method from that tile and that packet on */
-                                                       if (!((pprot == 0) || (pprot == 1) || (pprot == 16) || (pprot == 32) ||
-                                                               ((pprot >= 37) && (pprot <= 128)))) {
-                                                               fprintf(stderr, "ERROR -> invalid packet protection method p = %d\n", pprot);
-                                                               return 1;
-                                                       }
-                                                       if (tile < 0) {
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);
-                                                               return 1;
-                                                       }
-                                                       if (pack < 0) {
-                                                               fprintf(stderr, "ERROR -> invalid packet number on protection method p = %d\n", pack);
-                                                               return 1;
-                                                       }
-                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {
-                                                               parameters->jpwl_pprot_tileno[packspec] = tile;
-                                                               parameters->jpwl_pprot_packno[packspec] = pack;
-                                                               parameters->jpwl_pprot[packspec++] = pprot;
-                                                       }
-
-                                               } else if (sscanf(token, "p%d", &tile) == 1) {
-                                                       /* default from a tile on */
-                                                       if (tile < 0) {
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on protection method p = %d\n", tile);
-                                                               return 1;
-                                                       }
-                                                       if (packspec < JPWL_MAX_NO_PACKSPECS) {
-                                                               parameters->jpwl_pprot_tileno[packspec] = tile;
-                                                               parameters->jpwl_pprot_packno[packspec] = 0;
-                                                               parameters->jpwl_pprot[packspec++] = pprot;
-                                                       }
-
-
-                                               } else if (!strcmp(token, "p")) {
-                                                       /* all default */
-                                                       parameters->jpwl_pprot_tileno[0] = 0;
-                                                       parameters->jpwl_pprot_packno[0] = 0;
-                                                       parameters->jpwl_pprot[0] = pprot;
-
-                                               } else {
-                                                       fprintf(stderr, "ERROR -> invalid protection method selection = %s\n", token);
-                                                       return 1;
-                                               };
-
-                                       }
-
-                                       /* search sensitivity method */
-                                       if (*token == 's') {
-
-                                               static int tile = 0, tilespec = 0, lasttileno = 0;
-
-                                               sens = 0; /* predefined: relative error */
-
-                                               if(sscanf(token, "s=%d", &sens) == 1) {
-                                                       /* Main header, specified */
-                                                       if ((sens < -1) || (sens > 7)) {
-                                                               fprintf(stderr, "ERROR -> invalid main header sensitivity method s = %d\n", sens);
-                                                               return 1;
-                                                       }
-                                                       parameters->jpwl_sens_MH = sens;
-
-                                               } else if(sscanf(token, "s%d=%d", &tile, &sens) == 2) {
-                                                       /* Tile part header, specified */
-                                                       if ((sens < -1) || (sens > 7)) {
-                                                               fprintf(stderr, "ERROR -> invalid tile part header sensitivity method s = %d\n", sens);
-                                                               return 1;
-                                                       }
-                                                       if (tile < 0) {
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);
-                                                               return 1;
-                                                       }
-                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {
-                                                               parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
-                                                               parameters->jpwl_sens_TPH[tilespec++] = sens;
-                                                       }
-
-                                               } else if(sscanf(token, "s%d", &tile) == 1) {
-                                                       /* Tile part header, unspecified */
-                                                       if (tile < 0) {
-                                                               fprintf(stderr, "ERROR -> invalid tile part number on sensitivity method t = %d\n", tile);
-                                                               return 1;
-                                                       }
-                                                       if (tilespec < JPWL_MAX_NO_TILESPECS) {
-                                                               parameters->jpwl_sens_TPH_tileno[tilespec] = lasttileno = tile;
-                                                               parameters->jpwl_sens_TPH[tilespec++] = hprot;
-                                                       }
-
-                                               } else if (!strcmp(token, "s")) {
-                                                       /* Main header, unspecified */
-                                                       parameters->jpwl_sens_MH = sens;
-
-                                               } else {
-                                                       fprintf(stderr, "ERROR -> invalid sensitivity method selection = %s\n", token);
-                                                       return 1;
-                                               };
-
-                                               parameters->jpwl_sens_size = 2; /* 2 bytes for default size */
-                                       }
-
-                                       /* search addressing size */
-                                       if (*token == 'a') {
-
-
-                                               addr = 0; /* predefined: auto */
-
-                                               if(sscanf(token, "a=%d", &addr) == 1) {
-                                                       /* Specified */
-                                                       if ((addr != 0) && (addr != 2) && (addr != 4)) {
-                                                               fprintf(stderr, "ERROR -> invalid addressing size a = %d\n", addr);
-                                                               return 1;
-                                                       }
-                                                       parameters->jpwl_sens_addr = addr;
-
-                                               } else if (!strcmp(token, "a")) {
-                                                       /* default */
-                                                       parameters->jpwl_sens_addr = addr; /* auto for default size */
-
-                                               } else {
-                                                       fprintf(stderr, "ERROR -> invalid addressing selection = %s\n", token);
-                                                       return 1;
-                                               };
-
-                                       }
-
-                                       /* search sensitivity size */
-                                       if (*token == 'z') {
-
-
-                                               size = 1; /* predefined: 1 byte */
-
-                                               if(sscanf(token, "z=%d", &size) == 1) {
-                                                       /* Specified */
-                                                       if ((size != 0) && (size != 1) && (size != 2)) {
-                                                               fprintf(stderr, "ERROR -> invalid sensitivity size z = %d\n", size);
-                                                               return 1;
-                                                       }
-                                                       parameters->jpwl_sens_size = size;
-
-                                               } else if (!strcmp(token, "a")) {
-                                                       /* default */
-                                                       parameters->jpwl_sens_size = size; /* 1 for default size */
-
-                                               } else {
-                                                       fprintf(stderr, "ERROR -> invalid size selection = %s\n", token);
-                                                       return 1;
-                                               };
-
-                                       }
-
-                                       /* search range method */
-                                       if (*token == 'g') {
-
-
-                                               range = 0; /* predefined: 0 (packet) */
-
-                                               if(sscanf(token, "g=%d", &range) == 1) {
-                                                       /* Specified */
-                                                       if ((range < 0) || (range > 3)) {
-                                                               fprintf(stderr, "ERROR -> invalid sensitivity range method g = %d\n", range);
-                                                               return 1;
-                                                       }
-                                                       parameters->jpwl_sens_range = range;
-
-                                               } else if (!strcmp(token, "g")) {
-                                                       /* default */
-                                                       parameters->jpwl_sens_range = range;
-
-                                               } else {
-                                                       fprintf(stderr, "ERROR -> invalid range selection = %s\n", token);
-                                                       return 1;
-                                               };
-
-                                       }
-
-                                       /* next token or bust */
-                                       token = strtok(NULL, ",");
-                               };
-
-
-                               /* some info */
-                               fprintf(stdout, "Info: JPWL capabilities enabled\n");
-                               parameters->jpwl_epc_on = true;
-
-                       }
-                       break;
-#endif /* USE_JPWL */
-/* <<UniPG */
-
-                               /* ------------------------------------------------------ */
-
-                       default:
-                               fprintf(stderr, "ERROR -> Command line not valid\n");
-                               return 1;
-               }
-       }
-
-       /* check for possible errors */
-       if (parameters->cp_cinema){
-               if(parameters->tcp_numlayers > 1){
-                       parameters->cp_rsiz = STD_RSIZ;
-       fprintf(stdout,"Warning: DC profiles do not allow more than one quality layer. The codestream created will not be compliant with the DC profile\n");
-               }
-       }
-       if(img_fol->set_imgdir == 1){
-               if(!(parameters->infile[0] == 0)){
-                       fprintf(stderr, "Error: options -ImgDir and -i cannot be used together !!\n");
-                       return 1;
-               }
-               if(img_fol->set_out_format == 0){
-                       fprintf(stderr, "Error: When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
-                       fprintf(stderr, "Only one format allowed! Valid formats are j2k and jp2!!\n");
-                       return 1;
-               }
-               if(!((parameters->outfile[0] == 0))){
-                       fprintf(stderr, "Error: options -ImgDir and -o cannot be used together !!\n");
-                       fprintf(stderr, "Specify OutputFormat using -OutFor<FORMAT> !!\n");
-                       return 1;
-               }
-       }else{
-               if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
-                       fprintf(stderr, "Example: %s -i image.ppm  -o image.j2k\n",argv[0]);
-                       fprintf(stderr, "    Try: %s -h\n",argv[0]);
-                       return 1;
-               }
-       }
-
-       if (parameters->decod_format == RAW_DFMT && raw_cp->rawWidth == 0) {
-                       fprintf(stderr,"\nError: invalid raw image parameters\n");
-                       fprintf(stderr,"Please use the Format option -F:\n");
-                       fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
-                                               fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
-                       fprintf(stderr,"Aborting\n");
-                       return 1;
-       }
-
-       if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc || parameters->cp_fixed_quality)
-               && (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_alloc ^ parameters->cp_fixed_quality))) {
-               fprintf(stderr, "Error: options -r -q and -f cannot be used together !!\n");
-               return 1;
-       }                               /* mod fixed_quality */
-
-       /* if no rate entered, lossless by default */
-       if (parameters->tcp_numlayers == 0) {
-               parameters->tcp_rates[0] = 0;   /* MOD antonin : losslessbug */
-               parameters->tcp_numlayers++;
-               parameters->cp_disto_alloc = 1;
-       }
-
-       if((parameters->cp_tx0 > parameters->image_offset_x0) || (parameters->cp_ty0 > parameters->image_offset_y0)) {
-               fprintf(stderr,
-                       "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
-                       parameters->cp_tx0, parameters->image_offset_x0, parameters->cp_ty0, parameters->image_offset_y0);
-               return 1;
-       }
-
-       for (i = 0; i < parameters->numpocs; i++) {
-               if (parameters->POC[i].prg == -1) {
-                       fprintf(stderr,
-                               "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
-                               i + 1);
-               }
-       }
-
-       return 0;
-}
-
-/* -------------------------------------------------------------------------- */
-
-/**
-sample error callback expecting a FILE* client object
-*/
-void error_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[ERROR] %s", msg);
-}
-/**
-sample warning callback expecting a FILE* client object
-*/
-void warning_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[WARNING] %s", msg);
-}
-/**
-sample debug callback expecting a FILE* client object
-*/
-void info_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[INFO] %s", msg);
-}
-
-/* -------------------------------------------------------------------------- */
-
-int main(int argc, char **argv) {
-       bool bSuccess;
-       opj_cparameters_t parameters;   /* compression parameters */
-       img_fol_t img_fol;
-       opj_event_mgr_t event_mgr;              /* event manager */
-       opj_image_t *image = NULL;
-       int i,num_images;
-       int imageno;
-       dircnt_t *dirptr;
-       raw_cparameters_t raw_cp;
-       opj_codestream_info_t cstr_info;                /* Codestream information structure */
-       char indexfilename[OPJ_PATH_LEN];       /* index file name */
-
-       /*
-       configure the event callbacks (not required)
-       setting of each callback is optionnal
-       */
-       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
-       event_mgr.error_handler = error_callback;
-       event_mgr.warning_handler = warning_callback;
-       event_mgr.info_handler = info_callback;
-
-       /* set encoding parameters to default values */
-       opj_set_default_encoder_parameters(&parameters);
-
-       /* Initialize indexfilename and img_fol */
-       *indexfilename = 0;
-       memset(&img_fol,0,sizeof(img_fol_t));
-
-       /* parse input and get user encoding parameters */
-       if(parse_cmdline_encoder(argc, argv, &parameters,&img_fol, &raw_cp, indexfilename) == 1) {
-               return 1;
-       }
-
-       if (parameters.cp_cinema){
-               img_fol.rates = (float*)malloc(parameters.tcp_numlayers * sizeof(float));
-               for(i=0; i< parameters.tcp_numlayers; i++){
-                       img_fol.rates[i] = parameters.tcp_rates[i];
-               }
-               cinema_parameters(&parameters);
-       }
-
-       /* Create comment for codestream */
-       if(parameters.cp_comment == NULL) {
-    const char comment[] = "Created by OpenJPEG version ";
-               const size_t clen = strlen(comment);
-    const char *version = opj_version();
-/* UniPG>> */
-#ifdef USE_JPWL
-               parameters.cp_comment = (char*)malloc(clen+strlen(version)+11);
-               sprintf(parameters.cp_comment,"%s%s with JPWL", comment, version);
-#else
-               parameters.cp_comment = (char*)malloc(clen+strlen(version)+1);
-               sprintf(parameters.cp_comment,"%s%s", comment, version);
-#endif
-/* <<UniPG */
-       }
-
-       /* Read directory if necessary */
-       if(img_fol.set_imgdir==1){
-               num_images=get_num_images(img_fol.imgdirpath);
-               dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
-               if(dirptr){
-                       dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));     // Stores at max 10 image file names
-                       dirptr->filename = (char**) malloc(num_images*sizeof(char*));
-                       if(!dirptr->filename_buf){
-                               return 0;
-                       }
-                       for(i=0;i<num_images;i++){
-                               dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN;
-                       }
-               }
-               if(load_images(dirptr,img_fol.imgdirpath)==1){
-                       return 0;
-               }
-               if (num_images==0){
-                       fprintf(stdout,"Folder is empty\n");
-                       return 0;
-               }
-       }else{
-               num_images=1;
-       }
-       /*Encoding image one by one*/
-       for(imageno=0;imageno<num_images;imageno++)     {
-               image = NULL;
-               fprintf(stderr,"\n");
-
-               if(img_fol.set_imgdir==1){
-                       if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
-                               fprintf(stderr,"skipping file...\n");
-                               continue;
-                       }
-               }
-               switch(parameters.decod_format) {
-                       case PGX_DFMT:
-                               break;
-                       case PXM_DFMT:
-                               break;
-                       case BMP_DFMT:
-                               break;
-                       case TIF_DFMT:
-                               break;
-                       case RAW_DFMT:
-                               break;
-                       case TGA_DFMT:
-                               break;
-                       case PNG_DFMT:
-                               break;
-                       default:
-                               fprintf(stderr,"skipping file...\n");
-                               continue;
-               }
-
-                       /* decode the source image */
-                       /* ----------------------- */
-
-                       switch (parameters.decod_format) {
-                               case PGX_DFMT:
-                                       image = pgxtoimage(parameters.infile, &parameters);
-                                       if (!image) {
-                                               fprintf(stderr, "Unable to load pgx file\n");
-                                               return 1;
-                                       }
-                                       break;
-
-                               case PXM_DFMT:
-                                       image = pnmtoimage(parameters.infile, &parameters);
-                                       if (!image) {
-                                               fprintf(stderr, "Unable to load pnm file\n");
-                                               return 1;
-                                       }
-                                       break;
-
-                               case BMP_DFMT:
-                                       image = bmptoimage(parameters.infile, &parameters);
-                                       if (!image) {
-                                               fprintf(stderr, "Unable to load bmp file\n");
-                                               return 1;
-                                       }
-                                       break;
-#ifdef HAVE_LIBTIFF
-                               case TIF_DFMT:
-                                       image = tiftoimage(parameters.infile, &parameters);
-                                       if (!image) {
-                                               fprintf(stderr, "Unable to load tiff file\n");
-                                               return 1;
-                                       }
-                               break;
-#endif /* HAVE_LIBTIFF */
-                               case RAW_DFMT:
-                                       image = rawtoimage(parameters.infile, &parameters, &raw_cp);
-                                       if (!image) {
-                                               fprintf(stderr, "Unable to load raw file\n");
-                                               return 1;
-                                       }
-                               break;
-
-                               case TGA_DFMT:
-                                       image = tgatoimage(parameters.infile, &parameters);
-                                       if (!image) {
-                                               fprintf(stderr, "Unable to load tga file\n");
-                                               return 1;
-                                       }
-                               break;
-#ifdef HAVE_LIBPNG
-                               case PNG_DFMT:
-                                       image = pngtoimage(parameters.infile, &parameters);
-                                       if (!image) {
-                                               fprintf(stderr, "Unable to load png file\n");
-                                               return 1;
-                                       }
-                                       break;
-#endif /* HAVE_LIBPNG */
-               }
-/* Can happen if input file is TIFF or PNG 
- * and HAVE_LIBTIF or HAVE_LIBPNG is undefined
-*/
-                       if( !image)
-                  {
-                       fprintf(stderr, "Unable to load file: got no image\n");
-                       return 1;
-                  }
-                       /* Decide if MCT should be used */
-                       parameters.tcp_mct = image->numcomps == 3 ? 1 : 0;
-
-                       if(parameters.cp_cinema){
-                               cinema_setup_encoder(&parameters,image,&img_fol);
-                       }
-
-                       /* encode the destination image */
-                       /* ---------------------------- */
-
-                       if (parameters.cod_format == J2K_CFMT) {        /* J2K format output */
-                               int codestream_length;
-                               opj_cio_t *cio = NULL;
-                               FILE *f = NULL;
-
-                               /* get a J2K compressor handle */
-                               opj_cinfo_t* cinfo = opj_create_compress(CODEC_J2K);
-
-                               /* catch events using our callbacks and give a local context */
-                               opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
-
-                               /* setup the encoder parameters using the current image and user parameters */
-                               opj_setup_encoder(cinfo, &parameters, image);
-
-                               /* open a byte stream for writing */
-                               /* allocate memory for all tiles */
-                               cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
-
-                               /* encode the image */
-                               if (*indexfilename)                                     // If need to extract codestream information
-                                       bSuccess = opj_encode_with_info(cinfo, cio, image, &cstr_info);
-                               else
-                                       bSuccess = opj_encode(cinfo, cio, image, NULL);
-                               if (!bSuccess) {
-                                       opj_cio_close(cio);
-                                       fprintf(stderr, "failed to encode image\n");
-                                       return 1;
-                               }
-                               codestream_length = cio_tell(cio);
-
-                               /* write the buffer to disk */
-                               f = fopen(parameters.outfile, "wb");
-                               if (!f) {
-                                       fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
-                                       return 1;
-                               }
-                               fwrite(cio->buffer, 1, codestream_length, f);
-                               fclose(f);
-
-                               fprintf(stderr,"Generated outfile %s\n",parameters.outfile);
-                               /* close and free the byte stream */
-                               opj_cio_close(cio);
-
-                               /* Write the index to disk */
-                               if (*indexfilename) {
-                                       bSuccess = write_index_file(&cstr_info, indexfilename);
-                                       if (bSuccess) {
-                                               fprintf(stderr, "Failed to output index file into [%s]\n", indexfilename);
-                                       }
-                               }
-
-                               /* free remaining compression structures */
-                               opj_destroy_compress(cinfo);
-                               if (*indexfilename)
-                                       opj_destroy_cstr_info(&cstr_info);
-                       } else {                        /* JP2 format output */
-                               int codestream_length;
-                               opj_cio_t *cio = NULL;
-                               FILE *f = NULL;
-
-                               /* get a JP2 compressor handle */
-                               opj_cinfo_t* cinfo = opj_create_compress(CODEC_JP2);
-
-                               /* catch events using our callbacks and give a local context */
-                               opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
-
-                               /* setup the encoder parameters using the current image and using user parameters */
-                               opj_setup_encoder(cinfo, &parameters, image);
-
-                               /* open a byte stream for writing */
-                               /* allocate memory for all tiles */
-                               cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
-
-                               /* encode the image */
-                               if (*indexfilename)                                     // If need to extract codestream information
-                                       bSuccess = opj_encode_with_info(cinfo, cio, image, &cstr_info);
-                               else
-                                       bSuccess = opj_encode(cinfo, cio, image, NULL);
-                               if (!bSuccess) {
-                                       opj_cio_close(cio);
-                                       fprintf(stderr, "failed to encode image\n");
-                                       return 1;
-                               }
-                               codestream_length = cio_tell(cio);
-
-                               /* write the buffer to disk */
-                               f = fopen(parameters.outfile, "wb");
-                               if (!f) {
-                                       fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
-                                       return 1;
-                               }
-                               fwrite(cio->buffer, 1, codestream_length, f);
-                               fclose(f);
-                               fprintf(stderr,"Generated outfile %s\n",parameters.outfile);
-                               /* close and free the byte stream */
-                               opj_cio_close(cio);
-
-                               /* Write the index to disk */
-                               if (*indexfilename) {
-                                       bSuccess = write_index_file(&cstr_info, indexfilename);
-                                       if (bSuccess) {
-                                               fprintf(stderr, "Failed to output index file\n");
-                                       }
-                               }
-
-                               /* free remaining compression structures */
-                               opj_destroy_compress(cinfo);
-                               if (*indexfilename)
-                                       opj_destroy_cstr_info(&cstr_info);
-                       }
-
-                       /* free image data */
-                       opj_image_destroy(image);
-       }
-
-       /* free user parameters structure */
-  if(parameters.cp_comment) free(parameters.cp_comment);
-       if(parameters.cp_matrice) free(parameters.cp_matrice);
-
-       return 0;
-}
diff --git a/codec/index.c b/codec/index.c
deleted file mode 100644 (file)
index 873b340..0000000
+++ /dev/null
@@ -1,391 +0,0 @@
-/*\r
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
- * Copyright (c) 2002-2007, Professor Benoit Macq\r
- * Copyright (c) 2003-2007, Francois-Olivier Devaux \r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-\r
-#include <stdio.h>\r
-#include <math.h>\r
-#include <string.h>\r
-#include "openjpeg.h"\r
-#include "index.h"\r
-\r
-/* ------------------------------------------------------------------------------------ */\r
-\r
-/**\r
-Write a structured index to a file\r
-@param cstr_info Codestream information \r
-@param index Index filename\r
-@return Returns 0 if successful, returns 1 otherwise\r
-*/\r
-int write_index_file(opj_codestream_info_t *cstr_info, char *index) {\r
-       int tileno, compno, layno, resno, precno, pack_nb, x, y;\r
-       FILE *stream = NULL;\r
-       double total_disto = 0;\r
-/* UniPG>> */\r
-       int tilepartno;\r
-       char disto_on, numpix_on;\r
-\r
-#ifdef USE_JPWL\r
-       if (!strcmp(index, JPWL_PRIVATEINDEX_NAME))\r
-               return 0;\r
-#endif /* USE_JPWL */\r
-/* <<UniPG */\r
-\r
-       if (!cstr_info)         \r
-               return 1;\r
-\r
-       stream = fopen(index, "w");\r
-       if (!stream) {\r
-               fprintf(stderr, "failed to open index file [%s] for writing\n", index);\r
-               return 1;\r
-       }\r
-       \r
-       if (cstr_info->tile[0].distotile)\r
-               disto_on = 1;\r
-       else \r
-               disto_on = 0;\r
-\r
-       if (cstr_info->tile[0].numpix)\r
-               numpix_on = 1;\r
-       else \r
-               numpix_on = 0;\r
-\r
-       fprintf(stream, "%d %d\n", cstr_info->image_w, cstr_info->image_h);\r
-       fprintf(stream, "%d\n", cstr_info->prog);\r
-       fprintf(stream, "%d %d\n", cstr_info->tile_x, cstr_info->tile_y);\r
-       fprintf(stream, "%d %d\n", cstr_info->tw, cstr_info->th);\r
-       fprintf(stream, "%d\n", cstr_info->numcomps);\r
-       fprintf(stream, "%d\n", cstr_info->numlayers);\r
-       fprintf(stream, "%d\n", cstr_info->numdecompos[0]); /* based on component 0 */\r
-\r
-       for (resno = cstr_info->numdecompos[0]; resno >= 0; resno--) {\r
-               fprintf(stream, "[%d,%d] ", \r
-                       (1 << cstr_info->tile[0].pdx[resno]), (1 << cstr_info->tile[0].pdx[resno]));    /* based on tile 0 and component 0 */\r
-       }\r
-\r
-       fprintf(stream, "\n");\r
-/* UniPG>> */\r
-       fprintf(stream, "%d\n", cstr_info->main_head_start);\r
-/* <<UniPG */\r
-       fprintf(stream, "%d\n", cstr_info->main_head_end);\r
-       fprintf(stream, "%d\n", cstr_info->codestream_size);\r
-       \r
-       fprintf(stream, "\nINFO ON TILES\n");\r
-       fprintf(stream, "tileno start_pos  end_hd  end_tile   nbparts");\r
-       if (disto_on)\r
-               fprintf(stream,"         disto");\r
-       if (numpix_on)\r
-               fprintf(stream,"     nbpix");\r
-       if (disto_on && numpix_on)\r
-               fprintf(stream,"  disto/nbpix");\r
-       fprintf(stream, "\n");\r
-\r
-       for (tileno = 0; tileno < cstr_info->tw * cstr_info->th; tileno++) {\r
-               fprintf(stream, "%4d %9d %9d %9d %9d", \r
-                       cstr_info->tile[tileno].tileno,\r
-                       cstr_info->tile[tileno].start_pos,\r
-                       cstr_info->tile[tileno].end_header,\r
-                       cstr_info->tile[tileno].end_pos,\r
-                       cstr_info->tile[tileno].num_tps);\r
-               if (disto_on)\r
-                       fprintf(stream," %9e", cstr_info->tile[tileno].distotile);\r
-               if (numpix_on)\r
-                       fprintf(stream," %9d", cstr_info->tile[tileno].numpix);\r
-               if (disto_on && numpix_on)\r
-                       fprintf(stream," %9e", cstr_info->tile[tileno].distotile / cstr_info->tile[tileno].numpix);\r
-               fprintf(stream, "\n");\r
-       }\r
-               \r
-       for (tileno = 0; tileno < cstr_info->tw * cstr_info->th; tileno++) {\r
-               int start_pos, end_ph_pos, end_pos;\r
-               double disto = 0;\r
-               int max_numdecompos = 0;\r
-               pack_nb = 0;\r
-\r
-               for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
-                       if (max_numdecompos < cstr_info->numdecompos[compno])\r
-                               max_numdecompos = cstr_info->numdecompos[compno];\r
-               }       \r
-\r
-               fprintf(stream, "\nTILE %d DETAILS\n", tileno); \r
-               fprintf(stream, "part_nb tileno  start_pack num_packs  start_pos end_tph_pos   end_pos\n");\r
-               for (tilepartno = 0; tilepartno < cstr_info->tile[tileno].num_tps; tilepartno++)\r
-                       fprintf(stream, "%4d %9d   %9d %9d  %9d %11d %9d\n",\r
-                               tilepartno, tileno,\r
-                               cstr_info->tile[tileno].tp[tilepartno].tp_start_pack,\r
-                               cstr_info->tile[tileno].tp[tilepartno].tp_numpacks,\r
-                               cstr_info->tile[tileno].tp[tilepartno].tp_start_pos,\r
-                               cstr_info->tile[tileno].tp[tilepartno].tp_end_header,\r
-                               cstr_info->tile[tileno].tp[tilepartno].tp_end_pos\r
-                               );\r
-\r
-               if (cstr_info->prog == LRCP) {  /* LRCP */\r
-                       fprintf(stream, "LRCP\npack_nb tileno layno resno compno precno start_pos end_ph_pos end_pos");\r
-                       if (disto_on)\r
-                               fprintf(stream, " disto");\r
-                       fprintf(stream,"\n");\r
-\r
-                       for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
-                               for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
-                                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
-                                               int prec_max;\r
-                                               if (resno > cstr_info->numdecompos[compno])\r
-                                                       break;\r
-                                               prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
-                                               for (precno = 0; precno < prec_max; precno++) {\r
-                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
-                                                       end_ph_pos = cstr_info->tile[tileno].packet[pack_nb].end_ph_pos;\r
-                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
-                                                       disto = cstr_info->tile[tileno].packet[pack_nb].disto;\r
-                                                       fprintf(stream, "%4d %6d %7d %5d %6d  %6d    %6d     %6d %7d",\r
-                                                               pack_nb, tileno, layno, resno, compno, precno, start_pos, end_ph_pos, end_pos);\r
-                                                       if (disto_on)\r
-                                                               fprintf(stream, " %8e", disto);\r
-                                                       fprintf(stream, "\n");\r
-                                                       total_disto += disto;\r
-                                                       pack_nb++;\r
-                                               }\r
-                                       }\r
-                               }\r
-                       }\r
-               } /* LRCP */\r
-\r
-               else if (cstr_info->prog == RLCP) {     /* RLCP */                      \r
-                       fprintf(stream, "RLCP\npack_nb tileno resno layno compno precno start_pos end_ph_pos end_pos\n");\r
-                       if (disto_on)\r
-                               fprintf(stream, " disto");\r
-                       fprintf(stream,"\n");\r
-\r
-                       for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
-                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
-                                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
-                                               int prec_max; \r
-                                               if (resno > cstr_info->numdecompos[compno])\r
-                                                       break;\r
-                                               prec_max = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
-                                               for (precno = 0; precno < prec_max; precno++) {\r
-                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
-                                                       end_ph_pos = cstr_info->tile[tileno].packet[pack_nb].end_ph_pos;\r
-                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
-                                                       disto = cstr_info->tile[tileno].packet[pack_nb].disto;\r
-                                                       fprintf(stream, "%4d %6d %5d %7d %6d %6d %9d   %9d %7d",\r
-                                                               pack_nb, tileno, resno, layno, compno, precno, start_pos, end_ph_pos, end_pos);\r
-                                                       if (disto_on)\r
-                                                               fprintf(stream, " %8e", disto);\r
-                                                       fprintf(stream, "\n");\r
-                                                       total_disto += disto;\r
-                                                       pack_nb++;\r
-                                               }\r
-                                       }\r
-                               }\r
-                       }\r
-               } /* RLCP */\r
-\r
-               else if (cstr_info->prog == RPCL) {     /* RPCL */\r
-\r
-                       fprintf(stream, "RPCL\npack_nb tileno resno precno compno layno start_pos end_ph_pos end_pos"); \r
-                       if (disto_on)\r
-                               fprintf(stream, " disto");\r
-                       fprintf(stream,"\n");\r
-\r
-                       for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
-                               int numprec = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
-                               for (precno = 0; precno < numprec; precno++) {                                                          \r
-                                       /* I suppose components have same XRsiz, YRsiz */\r
-                                       int x0 = cstr_info->tile_Ox + tileno - (int)floor((float)tileno/(float)cstr_info->tw ) * cstr_info->tw * cstr_info->tile_x;\r
-                                       int y0 = cstr_info->tile_Ox + (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tile_y;\r
-                                       int x1 = x0 + cstr_info->tile_x;\r
-                                       int y1 = y0 + cstr_info->tile_y;\r
-                                       for (compno = 0; compno < cstr_info->numcomps; compno++) {                                      \r
-                                               int pcnx = cstr_info->tile[tileno].pw[resno];\r
-                                               int pcx = (int) pow( 2, cstr_info->tile[tileno].pdx[resno] + cstr_info->numdecompos[compno] - resno );\r
-                                               int pcy = (int) pow( 2, cstr_info->tile[tileno].pdy[resno] + cstr_info->numdecompos[compno] - resno );\r
-                                               int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
-                                               int precno_y = (int) floor( (float)precno/(float)pcnx );\r
-                                               if (resno > cstr_info->numdecompos[compno])\r
-                                                       break;\r
-                                               for(y = y0; y < y1; y++) {                                                      \r
-                                                       if (precno_y*pcy == y ) {\r
-                                                               for (x = x0; x < x1; x++) {                                                                     \r
-                                                                       if (precno_x*pcx == x ) {\r
-                                                                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
-                                                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
-                                                                                       end_ph_pos = cstr_info->tile[tileno].packet[pack_nb].end_ph_pos;\r
-                                                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
-                                                                                       disto = cstr_info->tile[tileno].packet[pack_nb].disto;\r
-                                                                                       fprintf(stream, "%4d %6d %5d %6d %6d %7d %9d   %9d %7d",\r
-                                                                                               pack_nb, tileno, resno, precno, compno, layno, start_pos, end_ph_pos, end_pos); \r
-                                                                                       if (disto_on)\r
-                                                                                               fprintf(stream, " %8e", disto);\r
-                                                                                       fprintf(stream, "\n");\r
-                                                                                       total_disto += disto;\r
-                                                                                       pack_nb++; \r
-                                                                               }\r
-                                                                       }\r
-                                                               }/* x = x0..x1 */\r
-                                                       } \r
-                                               }  /* y = y0..y1 */\r
-                                       } /* precno */\r
-                               } /* compno */\r
-                       } /* resno */\r
-               } /* RPCL */\r
-\r
-               else if (cstr_info->prog == PCRL) {     /* PCRL */\r
-                       /* I suppose components have same XRsiz, YRsiz */\r
-                       int x0 = cstr_info->tile_Ox + tileno - (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tw * cstr_info->tile_x;\r
-                       int y0 = cstr_info->tile_Ox + (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tile_y;\r
-                       int x1 = x0 + cstr_info->tile_x;\r
-                       int y1 = y0 + cstr_info->tile_y;\r
-\r
-                       // Count the maximum number of precincts \r
-                       int max_numprec = 0;\r
-                       for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
-                               int numprec = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
-                               if (numprec > max_numprec)\r
-                                       max_numprec = numprec;\r
-                       }\r
-\r
-                       fprintf(stream, "PCRL\npack_nb tileno precno compno resno layno start_pos end_ph_pos end_pos"); \r
-                       if (disto_on)\r
-                               fprintf(stream, " disto");\r
-                       fprintf(stream,"\n");\r
-\r
-                       for (precno = 0; precno < max_numprec; precno++) {\r
-                               for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
-                                       for (resno = 0; resno < cstr_info->numdecompos[compno] + 1; resno++) {\r
-                                               int numprec = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
-                                               int pcnx = cstr_info->tile[tileno].pw[resno];\r
-                                               int pcx = (int) pow( 2, cstr_info->tile[tileno].pdx[resno] + cstr_info->numdecompos[compno] - resno );\r
-                                               int pcy = (int) pow( 2, cstr_info->tile[tileno].pdy[resno] + cstr_info->numdecompos[compno] - resno );\r
-                                               int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
-                                               int precno_y = (int) floor( (float)precno/(float)pcnx );\r
-                                               if (precno >= numprec)\r
-                                                       continue;\r
-                                               for(y = y0; y < y1; y++) {                                                      \r
-                                                       if (precno_y*pcy == y ) {\r
-                                                               for (x = x0; x < x1; x++) {                                                                     \r
-                                                                       if (precno_x*pcx == x ) {\r
-                                                                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
-                                                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
-                                                                                       end_ph_pos = cstr_info->tile[tileno].packet[pack_nb].end_ph_pos;\r
-                                                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
-                                                                                       disto = cstr_info->tile[tileno].packet[pack_nb].disto;\r
-                                                                                       fprintf(stream, "%4d %6d %6d %6d %5d %7d %9d   %9d %7d",\r
-                                                                                               pack_nb, tileno, precno, compno, resno, layno, start_pos, end_ph_pos, end_pos); \r
-                                                                                       if (disto_on)\r
-                                                                                               fprintf(stream, " %8e", disto);\r
-                                                                                       fprintf(stream, "\n");\r
-                                                                                       total_disto += disto;\r
-                                                                                       pack_nb++; \r
-                                                                               }\r
-                                                                       }\r
-                                                               }/* x = x0..x1 */\r
-                                                       } \r
-                                               }  /* y = y0..y1 */\r
-                                       } /* resno */\r
-                               } /* compno */\r
-                       } /* precno */\r
-               } /* PCRL */\r
-\r
-               else {  /* CPRL */\r
-                       // Count the maximum number of precincts \r
-                       int max_numprec = 0;\r
-                       for (resno = 0; resno < max_numdecompos + 1; resno++) {\r
-                               int numprec = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
-                               if (numprec > max_numprec)\r
-                                       max_numprec = numprec;\r
-                       }\r
-\r
-                       fprintf(stream, "CPRL\npack_nb tileno compno precno resno layno start_pos end_ph_pos end_pos"); \r
-                       if (disto_on)\r
-                               fprintf(stream, " disto");\r
-                       fprintf(stream,"\n");\r
-\r
-                       for (compno = 0; compno < cstr_info->numcomps; compno++) {\r
-                               /* I suppose components have same XRsiz, YRsiz */\r
-                               int x0 = cstr_info->tile_Ox + tileno - (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tw * cstr_info->tile_x;\r
-                               int y0 = cstr_info->tile_Ox + (int)floor( (float)tileno/(float)cstr_info->tw ) * cstr_info->tile_y;\r
-                               int x1 = x0 + cstr_info->tile_x;\r
-                               int y1 = y0 + cstr_info->tile_y;\r
-\r
-                               for (precno = 0; precno < max_numprec; precno++) {\r
-                                       for (resno = 0; resno < cstr_info->numdecompos[compno] + 1; resno++) {\r
-                                               int numprec = cstr_info->tile[tileno].pw[resno] * cstr_info->tile[tileno].ph[resno];\r
-                                               int pcnx = cstr_info->tile[tileno].pw[resno];\r
-                                               int pcx = (int) pow( 2, cstr_info->tile[tileno].pdx[resno] + cstr_info->numdecompos[compno] - resno );\r
-                                               int pcy = (int) pow( 2, cstr_info->tile[tileno].pdy[resno] + cstr_info->numdecompos[compno] - resno );\r
-                                               int precno_x = precno - (int) floor( (float)precno/(float)pcnx ) * pcnx;\r
-                                               int precno_y = (int) floor( (float)precno/(float)pcnx );\r
-                                               if (precno >= numprec)\r
-                                                       continue;\r
-\r
-                                               for(y = y0; y < y1; y++) {\r
-                                                       if (precno_y*pcy == y ) {\r
-                                                               for (x = x0; x < x1; x++) {\r
-                                                                       if (precno_x*pcx == x ) {\r
-                                                                               for (layno = 0; layno < cstr_info->numlayers; layno++) {\r
-                                                                                       start_pos = cstr_info->tile[tileno].packet[pack_nb].start_pos;\r
-                                                                                       end_ph_pos = cstr_info->tile[tileno].packet[pack_nb].end_ph_pos;\r
-                                                                                       end_pos = cstr_info->tile[tileno].packet[pack_nb].end_pos;\r
-                                                                                       disto = cstr_info->tile[tileno].packet[pack_nb].disto;\r
-                                                                                       fprintf(stream, "%4d %6d %6d %6d %5d %7d %9d   %9d %7d",\r
-                                                                                               pack_nb, tileno, compno, precno, resno, layno, start_pos, end_ph_pos, end_pos); \r
-                                                                                       if (disto_on)\r
-                                                                                               fprintf(stream, " %8e", disto);\r
-                                                                                       fprintf(stream, "\n");\r
-                                                                                       total_disto += disto;\r
-                                                                                       pack_nb++; \r
-                                                                               }\r
-                                                                       }\r
-                                                               }/* x = x0..x1 */\r
-                                                       }\r
-                                               } /* y = y0..y1 */\r
-                                       } /* resno */\r
-                               } /* precno */\r
-                       } /* compno */\r
-               } /* CPRL */   \r
-       } /* tileno */\r
-       \r
-       if (disto_on) {\r
-               fprintf(stream, "%8e\n", cstr_info->D_max); /* SE max */        \r
-               fprintf(stream, "%.8e\n", total_disto); /* SE totale */\r
-       }\r
-/* UniPG>> */\r
-       /* print the markers' list */\r
-       if (cstr_info->marknum) {\r
-               fprintf(stream, "\nMARKER LIST\n");\r
-               fprintf(stream, "%d\n", cstr_info->marknum);\r
-               fprintf(stream, "type\tstart_pos    length\n");\r
-               for (x = 0; x < cstr_info->marknum; x++)\r
-                       fprintf(stream, "%X\t%9d %9d\n", cstr_info->marker[x].type, cstr_info->marker[x].pos, cstr_info->marker[x].len);\r
-       }\r
-/* <<UniPG */\r
-       fclose(stream);\r
-\r
-       fprintf(stderr,"Generated index file %s\n", index);\r
-\r
-       return 0;\r
-}\r
diff --git a/codec/index.h b/codec/index.h
deleted file mode 100644 (file)
index 29f673a..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-/*\r
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
- * Copyright (c) 2002-2007, Professor Benoit Macq\r
- * Copyright (c) 2003-2007, Francois-Olivier Devaux\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-\r
-#ifndef __J2K_INDEX_H\r
-#define __J2K_INDEX_H\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-/**\r
-Write a structured index to a file\r
-@param cstr_info Codestream information \r
-@param index Index filename\r
-@return Returns 0 if successful, returns 1 otherwise\r
-*/\r
-int write_index_file(opj_codestream_info_t *cstr_info, char *index);\r
-\r
-#ifdef __cplusplus\r
-}\r
-#endif\r
-\r
-#endif /* __J2K_INDEX_H */\r
-\r
diff --git a/codec/j2k_dump.c b/codec/j2k_dump.c
deleted file mode 100644 (file)
index 508dd65..0000000
+++ /dev/null
@@ -1,634 +0,0 @@
-/*
- * Copyright (c) 20010, Mathieu Malaterre, GDCM
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <math.h>
-
-#ifdef _WIN32
-#include "windirent.h"
-#else
-#include <dirent.h>
-#endif /* _WIN32 */
-
-#ifdef _WIN32
-#include <windows.h>
-#else
-#include <strings.h>
-#define _stricmp strcasecmp
-#define _strnicmp strncasecmp
-#endif /* _WIN32 */
-
-#include "opj_config.h"
-#include "openjpeg.h"
-#include "../libopenjpeg/j2k.h"
-#include "../libopenjpeg/jp2.h"
-#include "getopt.h"
-#include "convert.h"
-#include "index.h"
-
-#include "format_defs.h"
-
-typedef struct dircnt{
-       /** Buffer for holding images read from Directory*/
-       char *filename_buf;
-       /** Pointer to the buffer*/
-       char **filename;
-}dircnt_t;
-
-
-typedef struct img_folder{
-       /** The directory path of the folder containing input images*/
-       char *imgdirpath;
-       /** Output format*/
-       const char *out_format;
-       /** Enable option*/
-       char set_imgdir;
-       /** Enable Cod Format for output*/
-       char set_out_format;
-
-}img_fol_t;
-
-void decode_help_display() {
-       fprintf(stdout,"HELP for j2k_dump\n----\n\n");
-       fprintf(stdout,"- the -h option displays this help information on screen\n\n");
-
-/* UniPG>> */
-       fprintf(stdout,"List of parameters for the JPEG 2000 "
-#ifdef USE_JPWL
-               "+ JPWL "
-#endif /* USE_JPWL */
-               "decoder:\n");
-/* <<UniPG */
-       fprintf(stdout,"\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"  -ImgDir \n");
-       fprintf(stdout,"        Image file Directory path \n");
-       fprintf(stdout,"  -i <compressed file>\n");
-       fprintf(stdout,"    REQUIRED only if an Input image directory not specified\n");
-       fprintf(stdout,"    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n");
-       fprintf(stdout,"    is identified based on its suffix.\n");
-       fprintf(stdout,"\n");
-}
-
-/* -------------------------------------------------------------------------- */
-static void j2k_dump_image(FILE *fd, opj_image_t * img);
-static void j2k_dump_cp(FILE *fd, opj_image_t * img, opj_cp_t * cp);
-
-int get_num_images(char *imgdirpath){
-       DIR *dir;
-       struct dirent* content; 
-       int num_images = 0;
-
-       /*Reading the input images from given input directory*/
-
-       dir= opendir(imgdirpath);
-       if(!dir){
-               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
-               return 0;
-       }
-       
-       while((content=readdir(dir))!=NULL){
-               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
-                       continue;
-               num_images++;
-       }
-       return num_images;
-}
-
-int load_images(dircnt_t *dirptr, char *imgdirpath){
-       DIR *dir;
-       struct dirent* content; 
-       int i = 0;
-
-       /*Reading the input images from given input directory*/
-
-       dir= opendir(imgdirpath);
-       if(!dir){
-               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
-               return 1;
-       }else   {
-               fprintf(stderr,"Folder opened successfully\n");
-       }
-       
-       while((content=readdir(dir))!=NULL){
-               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
-                       continue;
-
-               strcpy(dirptr->filename[i],content->d_name);
-               i++;
-       }
-       return 0;       
-}
-
-int get_file_format(char *filename) {
-       unsigned int i;
-       static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc"  };
-       static const int format[] = { PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, TGA_DFMT, PNG_DFMT, J2K_CFMT, JP2_CFMT, JPT_CFMT, J2K_CFMT, J2K_CFMT };
-       char * ext = strrchr(filename, '.');
-       if (ext == NULL)
-               return -1;
-       ext++;
-       if(ext) {
-               for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
-                       if(_strnicmp(ext, extension[i], 3) == 0) {
-                               return format[i];
-                       }
-               }
-       }
-
-       return -1;
-}
-
-char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters){
-       char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
-       char *temp_p, temp1[OPJ_PATH_LEN]="";
-
-       strcpy(image_filename,dirptr->filename[imageno]);
-       fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
-       parameters->decod_format = get_file_format(image_filename);
-       if (parameters->decod_format == -1)
-               return 1;
-       sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
-       strncpy(parameters->infile, infilename, sizeof(infilename));
-
-       //Set output file
-       strcpy(temp_ofname,strtok(image_filename,"."));
-       while((temp_p = strtok(NULL,".")) != NULL){
-               strcat(temp_ofname,temp1);
-               sprintf(temp1,".%s",temp_p);
-       }
-       if(img_fol->set_out_format==1){
-               sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
-               strncpy(parameters->outfile, outfilename, sizeof(outfilename));
-       }
-       return 0;
-}
-
-/* -------------------------------------------------------------------------- */
-int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol, char *indexfilename) {
-       /* parse the command line */
-       int totlen;
-       option_t long_option[]={
-               {"ImgDir",REQ_ARG, NULL ,'y'},
-       };
-
-       const char optlist[] = "i:h";
-       totlen=sizeof(long_option);
-       img_fol->set_out_format = 0;
-       while (1) {
-               int c = getopt_long(argc, argv,optlist,long_option,totlen);
-               if (c == -1)
-                       break;
-               switch (c) {
-                       case 'i':                       /* input file */
-                       {
-                               char *infile = optarg;
-                               parameters->decod_format = get_file_format(infile);
-                               switch(parameters->decod_format) {
-                                       case J2K_CFMT:
-                                       case JP2_CFMT:
-                                       case JPT_CFMT:
-                                               break;
-                                       default:
-                                               fprintf(stderr, 
-                                                       "!! Unrecognized format for infile : %s [accept only *.j2k, *.jp2, *.jpc or *.jpt] !!\n\n", 
-                                                       infile);
-                                               return 1;
-                               }
-                               strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
-                       }
-                       break;
-                               
-                               /* ----------------------------------------------------- */
-
-                       case 'h':                       /* display an help description */
-                               decode_help_display();
-                               return 1;                               
-
-                               /* ------------------------------------------------------ */
-
-                       case 'y':                       /* Image Directory path */
-                               {
-                                       img_fol->imgdirpath = (char*)malloc(strlen(optarg) + 1);
-                                       strcpy(img_fol->imgdirpath,optarg);
-                                       img_fol->set_imgdir=1;
-                               }
-                               break;
-
-                               /* ----------------------------------------------------- */
-                       
-                       default:
-                               fprintf(stderr,"WARNING -> this option is not valid \"-%c %s\"\n",c, optarg);
-                               break;
-               }
-       }
-
-       /* check for possible errors */
-       if(img_fol->set_imgdir==1){
-               if(!(parameters->infile[0]==0)){
-                       fprintf(stderr, "Error: options -ImgDir and -i cannot be used together !!\n");
-                       return 1;
-               }
-               if(img_fol->set_out_format == 0){
-                       fprintf(stderr, "Error: When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
-                       fprintf(stderr, "Only one format allowed! Valid format PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA!!\n");
-                       return 1;
-               }
-               if(!((parameters->outfile[0] == 0))){
-                       fprintf(stderr, "Error: options -ImgDir and -o cannot be used together !!\n");
-                       return 1;
-               }
-       }else{
-               if((parameters->infile[0] == 0) ) {
-                       fprintf(stderr, "Example: %s -i image.j2k\n",argv[0]);
-                       fprintf(stderr, "    Try: %s -h\n",argv[0]);
-                       return 1;
-               }
-       }
-
-       return 0;
-}
-
-/* -------------------------------------------------------------------------- */
-
-/**
-sample error callback expecting a FILE* client object
-*/
-void error_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[ERROR] %s", msg);
-}
-/**
-sample warning callback expecting a FILE* client object
-*/
-void warning_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[WARNING] %s", msg);
-}
-/**
-sample debug callback expecting no client object
-*/
-void info_callback(const char *msg, void *client_data) {
-       (void)client_data;
-       fprintf(stdout, "[INFO] %s", msg);
-}
-
-/* -------------------------------------------------------------------------- */
-
-int main(int argc, char *argv[])
-{
-       opj_dparameters_t parameters;   /* decompression parameters */
-       img_fol_t img_fol;
-       opj_event_mgr_t event_mgr;              /* event manager */
-       opj_image_t *image = NULL;
-       FILE *fsrc = NULL;
-       unsigned char *src = NULL;
-       int file_length;
-       int num_images;
-       int i,imageno;
-       dircnt_t *dirptr = NULL;
-       opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */
-       opj_cio_t *cio = NULL;
-       opj_codestream_info_t cstr_info;  /* Codestream information structure */
-       char indexfilename[OPJ_PATH_LEN];       /* index file name */
-
-       /* configure the event callbacks (not required) */
-       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
-       event_mgr.error_handler = error_callback;
-       event_mgr.warning_handler = warning_callback;
-       event_mgr.info_handler = info_callback;
-
-       /* set decoding parameters to default values */
-       opj_set_default_decoder_parameters(&parameters);
-
-       /* Initialize indexfilename and img_fol */
-       *indexfilename = 0;
-       memset(&img_fol,0,sizeof(img_fol_t));
-
-       /* parse input and get user encoding parameters */
-       if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {
-               return 1;
-       }
-
-       /* Initialize reading of directory */
-       if(img_fol.set_imgdir==1){      
-               num_images=get_num_images(img_fol.imgdirpath);
-
-               dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
-               if(dirptr){
-                       dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));     // Stores at max 10 image file names
-                       dirptr->filename = (char**) malloc(num_images*sizeof(char*));
-
-                       if(!dirptr->filename_buf){
-                               return 1;
-                       }
-                       for(i=0;i<num_images;i++){
-                               dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN;
-                       }
-               }
-               if(load_images(dirptr,img_fol.imgdirpath)==1){
-                       return 1;
-               }
-               if (num_images==0){
-                       fprintf(stdout,"Folder is empty\n");
-                       return 1;
-               }
-       }else{
-               num_images=1;
-       }
-
-       /*Encoding image one by one*/
-       for(imageno = 0; imageno < num_images ; imageno++)
-  {
-               image = NULL;
-               fprintf(stderr,"\n");
-
-               if(img_fol.set_imgdir==1){
-                       if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
-                               fprintf(stderr,"skipping file...\n");
-                               continue;
-                       }
-               }
-
-               /* read the input file and put it in memory */
-               /* ---------------------------------------- */
-               fsrc = fopen(parameters.infile, "rb");
-               if (!fsrc) {
-                       fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);
-                       return 1;
-               }
-               fseek(fsrc, 0, SEEK_END);
-               file_length = ftell(fsrc);
-               fseek(fsrc, 0, SEEK_SET);
-               src = (unsigned char *) malloc(file_length);
-               fread(src, 1, file_length, fsrc);
-               fclose(fsrc);
-
-               /* decode the code-stream */
-               /* ---------------------- */
-
-               switch(parameters.decod_format) {
-               case J2K_CFMT:
-               {
-                       /* JPEG-2000 codestream */
-
-                       /* get a decoder handle */
-                       dinfo = opj_create_decompress(CODEC_J2K);
-
-                       /* catch events using our callbacks and give a local context */
-                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
-
-                       /* setup the decoder decoding parameters using user parameters */
-                       opj_setup_decoder(dinfo, &parameters);
-
-                       /* open a byte stream */
-                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
-
-                       /* decode the stream and fill the image structure */
-                       if (*indexfilename)                             // If need to extract codestream information
-                               image = opj_decode_with_info(dinfo, cio, &cstr_info);
-                       else
-                               image = opj_decode(dinfo, cio);
-                       if(!image) {
-                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
-                               opj_destroy_decompress(dinfo);
-                               opj_cio_close(cio);
-                               return 1;
-                       }
-                       /* dump image */
-      j2k_dump_image(stdout, image);
-
-                       /* dump cp */
-      j2k_dump_cp(stdout, image, ((opj_j2k_t*)dinfo->j2k_handle)->cp);
-
-                       /* close the byte stream */
-                       opj_cio_close(cio);
-
-                       /* Write the index to disk */
-                       if (*indexfilename) {
-                               char bSuccess;
-                               bSuccess = write_index_file(&cstr_info, indexfilename);
-                               if (bSuccess) {
-                                       fprintf(stderr, "Failed to output index file\n");
-                               }
-                       }
-               }
-               break;
-
-               case JP2_CFMT:
-               {
-                       /* JPEG 2000 compressed image data */
-
-                       /* get a decoder handle */
-                       dinfo = opj_create_decompress(CODEC_JP2);
-
-                       /* catch events using our callbacks and give a local context */
-                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
-
-                       /* setup the decoder decoding parameters using the current image and user parameters */
-                       opj_setup_decoder(dinfo, &parameters);
-
-                       /* open a byte stream */
-                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
-
-                       /* decode the stream and fill the image structure */
-                       if (*indexfilename)                             // If need to extract codestream information
-                               image = opj_decode_with_info(dinfo, cio, &cstr_info);
-                       else
-                               image = opj_decode(dinfo, cio);                 
-                       if(!image) {
-                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
-                               opj_destroy_decompress(dinfo);
-                               opj_cio_close(cio);
-                               return 1;
-                       }
-                       /* dump image */
-         if(image->icc_profile_buf)
-        {
-         free(image->icc_profile_buf); image->icc_profile_buf = NULL;
-        }      
-      j2k_dump_image(stdout, image);
-
-                       /* dump cp */
-      j2k_dump_cp(stdout, image, ((opj_jp2_t*)dinfo->jp2_handle)->j2k->cp);
-
-                       /* close the byte stream */
-                       opj_cio_close(cio);
-
-                       /* Write the index to disk */
-                       if (*indexfilename) {
-                               char bSuccess;
-                               bSuccess = write_index_file(&cstr_info, indexfilename);
-                               if (bSuccess) {
-                                       fprintf(stderr, "Failed to output index file\n");
-                               }
-                       }
-               }
-               break;
-
-               case JPT_CFMT:
-               {
-                       /* JPEG 2000, JPIP */
-
-                       /* get a decoder handle */
-                       dinfo = opj_create_decompress(CODEC_JPT);
-
-                       /* catch events using our callbacks and give a local context */
-                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
-
-                       /* setup the decoder decoding parameters using user parameters */
-                       opj_setup_decoder(dinfo, &parameters);
-
-                       /* open a byte stream */
-                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
-
-                       /* decode the stream and fill the image structure */
-                       if (*indexfilename)                             // If need to extract codestream information
-                               image = opj_decode_with_info(dinfo, cio, &cstr_info);
-                       else
-                               image = opj_decode(dinfo, cio);
-                       if(!image) {
-                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
-                               opj_destroy_decompress(dinfo);
-                               opj_cio_close(cio);
-                               return 1;
-                       }
-
-                       /* close the byte stream */
-                       opj_cio_close(cio);
-
-                       /* Write the index to disk */
-                       if (*indexfilename) {
-                               char bSuccess;
-                               bSuccess = write_index_file(&cstr_info, indexfilename);
-                               if (bSuccess) {
-                                       fprintf(stderr, "Failed to output index file\n");
-                               }
-                       }
-               }
-               break;
-
-               default:
-                       fprintf(stderr, "skipping file..\n");
-                       continue;
-       }
-
-               /* free the memory containing the code-stream */
-               free(src);
-               src = NULL;
-
-               /* free remaining structures */
-               if(dinfo) {
-                       opj_destroy_decompress(dinfo);
-               }
-               /* free codestream information structure */
-               if (*indexfilename)     
-                       opj_destroy_cstr_info(&cstr_info);
-               /* free image data structure */
-               opj_image_destroy(image);
-
-       }
-
-  return EXIT_SUCCESS;
-}
-
-
-static void j2k_dump_image(FILE *fd, opj_image_t * img) {
-       int compno;
-       fprintf(fd, "image {\n");
-       fprintf(fd, "  x0=%d, y0=%d, x1=%d, y1=%d\n", img->x0, img->y0, img->x1, img->y1);
-       fprintf(fd, "  numcomps=%d\n", img->numcomps);
-       for (compno = 0; compno < img->numcomps; compno++) {
-               opj_image_comp_t *comp = &img->comps[compno];
-               fprintf(fd, "  comp %d {\n", compno);
-               fprintf(fd, "    dx=%d, dy=%d\n", comp->dx, comp->dy);
-               fprintf(fd, "    prec=%d\n", comp->prec);
-               //fprintf(fd, "    bpp=%d\n", comp->bpp);
-               fprintf(fd, "    sgnd=%d\n", comp->sgnd);
-               fprintf(fd, "  }\n");
-       }
-       fprintf(fd, "}\n");
-}
-
-static void j2k_dump_cp(FILE *fd, opj_image_t * img, opj_cp_t * cp) {
-       int tileno, compno, layno, bandno, resno, numbands;
-       fprintf(fd, "coding parameters {\n");
-       fprintf(fd, "  tx0=%d, ty0=%d\n", cp->tx0, cp->ty0);
-       fprintf(fd, "  tdx=%d, tdy=%d\n", cp->tdx, cp->tdy);
-       fprintf(fd, "  tw=%d, th=%d\n", cp->tw, cp->th);
-       for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
-               opj_tcp_t *tcp = &cp->tcps[tileno];
-               fprintf(fd, "  tile %d {\n", tileno);
-               fprintf(fd, "    csty=%x\n", tcp->csty);
-               fprintf(fd, "    prg=%d\n", tcp->prg);
-               fprintf(fd, "    numlayers=%d\n", tcp->numlayers);
-               fprintf(fd, "    mct=%d\n", tcp->mct);
-               fprintf(fd, "    rates=");
-               for (layno = 0; layno < tcp->numlayers; layno++) {
-                       fprintf(fd, "%.1f ", tcp->rates[layno]);
-               }
-               fprintf(fd, "\n");
-               for (compno = 0; compno < img->numcomps; compno++) {
-                       opj_tccp_t *tccp = &tcp->tccps[compno];
-                       fprintf(fd, "    comp %d {\n", compno);
-                       fprintf(fd, "      csty=%x\n", tccp->csty);
-                       fprintf(fd, "      numresolutions=%d\n", tccp->numresolutions);
-                       fprintf(fd, "      cblkw=%d\n", tccp->cblkw);
-                       fprintf(fd, "      cblkh=%d\n", tccp->cblkh);
-                       fprintf(fd, "      cblksty=%x\n", tccp->cblksty);
-                       fprintf(fd, "      qmfbid=%d\n", tccp->qmfbid);
-                       fprintf(fd, "      qntsty=%d\n", tccp->qntsty);
-                       fprintf(fd, "      numgbits=%d\n", tccp->numgbits);
-                       fprintf(fd, "      roishift=%d\n", tccp->roishift);
-                       fprintf(fd, "      stepsizes=");
-                       numbands = tccp->qntsty == J2K_CCP_QNTSTY_SIQNT ? 1 : tccp->numresolutions * 3 - 2;
-                       for (bandno = 0; bandno < numbands; bandno++) {
-                               fprintf(fd, "(%d,%d) ", tccp->stepsizes[bandno].mant,
-                                       tccp->stepsizes[bandno].expn);
-                       }
-                       fprintf(fd, "\n");
-                       
-                       if (tccp->csty & J2K_CCP_CSTY_PRT) {
-                               fprintf(fd, "      prcw=");
-                               for (resno = 0; resno < tccp->numresolutions; resno++) {
-                                       fprintf(fd, "%d ", tccp->prcw[resno]);
-                               }
-                               fprintf(fd, "\n");
-                               fprintf(fd, "      prch=");
-                               for (resno = 0; resno < tccp->numresolutions; resno++) {
-                                       fprintf(fd, "%d ", tccp->prch[resno]);
-                               }
-                               fprintf(fd, "\n");
-                       }
-                       fprintf(fd, "    }\n");
-               }
-               fprintf(fd, "  }\n");
-       }
-       fprintf(fd, "}\n");
-}
-
diff --git a/codec/j2k_to_image.c b/codec/j2k_to_image.c
deleted file mode 100644 (file)
index ff6141e..0000000
+++ /dev/null
@@ -1,845 +0,0 @@
-/*
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
- * Copyright (c) 2002-2007, Professor Benoit Macq
- * Copyright (c) 2001-2003, David Janssens
- * Copyright (c) 2002-2003, Yannick Verschueren
- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
- * Copyright (c) 2005, Herve Drolon, FreeImage Team
- * Copyright (c) 2006-2007, Parvatha Elangovan
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <math.h>
-
-#ifdef _WIN32
-#include "windirent.h"
-#else
-#include <dirent.h>
-#endif /* _WIN32 */
-
-#ifdef _WIN32
-#include <windows.h>
-#else
-#include <strings.h>
-#define _stricmp strcasecmp
-#define _strnicmp strncasecmp
-#endif /* _WIN32 */
-
-#include "opj_config.h"
-#include "openjpeg.h"
-#include "getopt.h"
-#include "convert.h"
-#include "index.h"
-
-#ifdef HAVE_LIBLCMS2
-#include <lcms2.h>
-#endif
-#ifdef HAVE_LIBLCMS1
-#include <lcms.h>
-#endif
-#include "color.h"
-
-#include "format_defs.h"
-
-typedef struct dircnt{
-       /** Buffer for holding images read from Directory*/
-       char *filename_buf;
-       /** Pointer to the buffer*/
-       char **filename;
-}dircnt_t;
-
-
-typedef struct img_folder{
-       /** The directory path of the folder containing input images*/
-       char *imgdirpath;
-       /** Output format*/
-       const char *out_format;
-       /** Enable option*/
-       char set_imgdir;
-       /** Enable Cod Format for output*/
-       char set_out_format;
-
-}img_fol_t;
-
-void decode_help_display() {
-       fprintf(stdout,"HELP for j2k_to_image\n----\n\n");
-       fprintf(stdout,"- the -h option displays this help information on screen\n\n");
-
-/* UniPG>> */
-       fprintf(stdout,"List of parameters for the JPEG 2000 "
-#ifdef USE_JPWL
-               "+ JPWL "
-#endif /* USE_JPWL */
-               "decoder:\n");
-/* <<UniPG */
-       fprintf(stdout,"\n");
-       fprintf(stdout,"\n");
-       fprintf(stdout,"  -ImgDir \n");
-       fprintf(stdout,"        Image file Directory path \n");
-       fprintf(stdout,"  -OutFor \n");
-       fprintf(stdout,"    REQUIRED only if -ImgDir is used\n");
-       fprintf(stdout,"          Need to specify only format without filename <BMP>  \n");
-       fprintf(stdout,"    Currently accepts PGM, PPM, PNM, PGX, PNG, BMP, TIF, RAW and TGA formats\n");
-       fprintf(stdout,"  -i <compressed file>\n");
-       fprintf(stdout,"    REQUIRED only if an Input image directory not specified\n");
-       fprintf(stdout,"    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n");
-       fprintf(stdout,"    is identified based on its suffix.\n");
-       fprintf(stdout,"  -o <decompressed file>\n");
-       fprintf(stdout,"    REQUIRED\n");
-       fprintf(stdout,"    Currently accepts PGM, PPM, PNM, PGX, PNG, BMP, TIF, RAW and TGA files\n");
-       fprintf(stdout,"    Binary data is written to the file (not ascii). If a PGX\n");
-       fprintf(stdout,"    filename is given, there will be as many output files as there are\n");
-       fprintf(stdout,"    components: an indice starting from 0 will then be appended to the\n");
-       fprintf(stdout,"    output filename, just before the \"pgx\" extension. If a PGM filename\n");
-       fprintf(stdout,"    is given and there are more than one component, only the first component\n");
-       fprintf(stdout,"    will be written to the file.\n");
-       fprintf(stdout,"  -r <reduce factor>\n");
-       fprintf(stdout,"    Set the number of highest resolution levels to be discarded. The\n");
-       fprintf(stdout,"    image resolution is effectively divided by 2 to the power of the\n");
-       fprintf(stdout,"    number of discarded levels. The reduce factor is limited by the\n");
-       fprintf(stdout,"    smallest total number of decomposition levels among tiles.\n");
-       fprintf(stdout,"  -l <number of quality layers to decode>\n");
-       fprintf(stdout,"    Set the maximum number of quality layers to decode. If there are\n");
-       fprintf(stdout,"    less quality layers than the specified number, all the quality layers\n");
-       fprintf(stdout,"    are decoded.\n");
-       fprintf(stdout,"  -x  \n"); 
-       fprintf(stdout,"    Create an index file *.Idx (-x index_name.Idx) \n");
-       fprintf(stdout,"\n");
-/* UniPG>> */
-#ifdef USE_JPWL
-       fprintf(stdout,"  -W <options>\n");
-       fprintf(stdout,"    Activates the JPWL correction capability, if the codestream complies.\n");
-       fprintf(stdout,"    Options can be a comma separated list of <param=val> tokens:\n");
-       fprintf(stdout,"    c, c=numcomps\n");
-       fprintf(stdout,"       numcomps is the number of expected components in the codestream\n");
-       fprintf(stdout,"       (search of first EPB rely upon this, default is %d)\n", JPWL_EXPECTED_COMPONENTS);
-#endif /* USE_JPWL */
-/* <<UniPG */
-       fprintf(stdout,"\n");
-}
-
-/* -------------------------------------------------------------------------- */
-
-int get_num_images(char *imgdirpath){
-       DIR *dir;
-       struct dirent* content; 
-       int num_images = 0;
-
-       /*Reading the input images from given input directory*/
-
-       dir= opendir(imgdirpath);
-       if(!dir){
-               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
-               return 0;
-       }
-       
-       while((content=readdir(dir))!=NULL){
-               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
-                       continue;
-               num_images++;
-       }
-       return num_images;
-}
-
-int load_images(dircnt_t *dirptr, char *imgdirpath){
-       DIR *dir;
-       struct dirent* content; 
-       int i = 0;
-
-       /*Reading the input images from given input directory*/
-
-       dir= opendir(imgdirpath);
-       if(!dir){
-               fprintf(stderr,"Could not open Folder %s\n",imgdirpath);
-               return 1;
-       }else   {
-               fprintf(stderr,"Folder opened successfully\n");
-       }
-       
-       while((content=readdir(dir))!=NULL){
-               if(strcmp(".",content->d_name)==0 || strcmp("..",content->d_name)==0 )
-                       continue;
-
-               strcpy(dirptr->filename[i],content->d_name);
-               i++;
-       }
-       return 0;       
-}
-
-int get_file_format(char *filename) {
-       unsigned int i;
-       static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc" };
-       static const int format[] = { PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, TGA_DFMT, PNG_DFMT, J2K_CFMT, JP2_CFMT, JPT_CFMT, J2K_CFMT, J2K_CFMT };
-       char * ext = strrchr(filename, '.');
-       if (ext == NULL)
-               return -1;
-       ext++;
-       if(ext) {
-               for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
-                       if(_strnicmp(ext, extension[i], 3) == 0) {
-                               return format[i];
-                       }
-               }
-       }
-
-       return -1;
-}
-
-char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_dparameters_t *parameters){
-       char image_filename[OPJ_PATH_LEN], infilename[OPJ_PATH_LEN],outfilename[OPJ_PATH_LEN],temp_ofname[OPJ_PATH_LEN];
-       char *temp_p, temp1[OPJ_PATH_LEN]="";
-
-       strcpy(image_filename,dirptr->filename[imageno]);
-       fprintf(stderr,"File Number %d \"%s\"\n",imageno,image_filename);
-       parameters->decod_format = get_file_format(image_filename);
-       if (parameters->decod_format == -1)
-               return 1;
-       sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
-       strncpy(parameters->infile, infilename, sizeof(infilename));
-
-       //Set output file
-       strcpy(temp_ofname,strtok(image_filename,"."));
-       while((temp_p = strtok(NULL,".")) != NULL){
-               strcat(temp_ofname,temp1);
-               sprintf(temp1,".%s",temp_p);
-       }
-       if(img_fol->set_out_format==1){
-               sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
-               strncpy(parameters->outfile, outfilename, sizeof(outfilename));
-       }
-       return 0;
-}
-
-/* -------------------------------------------------------------------------- */
-int parse_cmdline_decoder(int argc, char **argv, opj_dparameters_t *parameters,img_fol_t *img_fol, char *indexfilename) {
-       /* parse the command line */
-       int totlen;
-       option_t long_option[]={
-               {"ImgDir",REQ_ARG, NULL ,'y'},
-               {"OutFor",REQ_ARG, NULL ,'O'},
-       };
-
-       const char optlist[] = "i:o:r:l:x:"
-
-/* UniPG>> */
-#ifdef USE_JPWL
-                                       "W:"
-#endif /* USE_JPWL */
-/* <<UniPG */
-                       "h"             ;
-       totlen=sizeof(long_option);
-       img_fol->set_out_format = 0;
-       while (1) {
-               int c = getopt_long(argc, argv,optlist,long_option,totlen);
-               if (c == -1)
-                       break;
-               switch (c) {
-                       case 'i':                       /* input file */
-                       {
-                               char *infile = optarg;
-                               parameters->decod_format = get_file_format(infile);
-                               switch(parameters->decod_format) {
-                                       case J2K_CFMT:
-                                       case JP2_CFMT:
-                                       case JPT_CFMT:
-                                               break;
-                                       default:
-                                               fprintf(stderr, 
-                                                       "!! Unrecognized format for infile : %s [accept only *.j2k, *.jp2, *.jpc or *.jpt] !!\n\n", 
-                                                       infile);
-                                               return 1;
-                               }
-                               strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
-                       }
-                       break;
-                               
-                               /* ----------------------------------------------------- */
-
-                       case 'o':                       /* output file */
-                       {
-                               char *outfile = optarg;
-                               parameters->cod_format = get_file_format(outfile);
-                               switch(parameters->cod_format) {
-                                       case PGX_DFMT:
-                                       case PXM_DFMT:
-                                       case BMP_DFMT:
-                                       case TIF_DFMT:
-                                       case RAW_DFMT:
-                                       case TGA_DFMT:
-                                       case PNG_DFMT:
-                                               break;
-                                       default:
-                                               fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outfile);
-                                               return 1;
-                               }
-                               strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);
-                       }
-                       break;
-                       
-                               /* ----------------------------------------------------- */
-
-                       case 'O':                       /* output format */
-                       {
-                               char outformat[50];
-                               char *of = optarg;
-                               sprintf(outformat,".%s",of);
-                               img_fol->set_out_format = 1;
-                               parameters->cod_format = get_file_format(outformat);
-                               switch(parameters->cod_format) {
-                                       case PGX_DFMT:
-                                               img_fol->out_format = "pgx";
-                                               break;
-                                       case PXM_DFMT:
-                                               img_fol->out_format = "ppm";
-                                               break;
-                                       case BMP_DFMT:
-                                               img_fol->out_format = "bmp";
-                                               break;
-                                       case TIF_DFMT:
-                                               img_fol->out_format = "tif";
-                                               break;
-                                       case RAW_DFMT:
-                                               img_fol->out_format = "raw";
-                                               break;
-                                       case TGA_DFMT:
-                                               img_fol->out_format = "raw";
-                                               break;
-                                       case PNG_DFMT:
-                                               img_fol->out_format = "png";
-                                               break;
-                                       default:
-                                               fprintf(stderr, "Unknown output format image %s [only *.pnm, *.pgm, *.ppm, *.pgx, *.bmp, *.tif, *.raw or *.tga]!! \n", outformat);
-                                               return 1;
-                                               break;
-                               }
-                       }
-                       break;
-
-                               /* ----------------------------------------------------- */
-
-
-                       case 'r':               /* reduce option */
-                       {
-                               sscanf(optarg, "%d", &parameters->cp_reduce);
-                       }
-                       break;
-                       
-                               /* ----------------------------------------------------- */
-      
-
-                       case 'l':               /* layering option */
-                       {
-                               sscanf(optarg, "%d", &parameters->cp_layer);
-                       }
-                       break;
-                       
-                               /* ----------------------------------------------------- */
-
-                       case 'h':                       /* display an help description */
-                               decode_help_display();
-                               return 1;                               
-
-                               /* ------------------------------------------------------ */
-
-                       case 'y':                       /* Image Directory path */
-                               {
-                                       img_fol->imgdirpath = (char*)malloc(strlen(optarg) + 1);
-                                       strcpy(img_fol->imgdirpath,optarg);
-                                       img_fol->set_imgdir=1;
-                               }
-                               break;
-                               /* ----------------------------------------------------- */                                                             
-                       case 'x':                       /* Creation of index file */
-                               {
-                                       char *index = optarg;
-                                       strncpy(indexfilename, index, OPJ_PATH_LEN);
-                               }
-                               break;
-                               /* ----------------------------------------------------- */
-                               /* UniPG>> */
-#ifdef USE_JPWL
-                       
-                       case 'W':                       /* activate JPWL correction */
-                       {
-                               char *token = NULL;
-
-                               token = strtok(optarg, ",");
-                               while(token != NULL) {
-
-                                       /* search expected number of components */
-                                       if (*token == 'c') {
-
-                                               static int compno;
-
-                                               compno = JPWL_EXPECTED_COMPONENTS; /* predefined no. of components */
-
-                                               if(sscanf(token, "c=%d", &compno) == 1) {
-                                                       /* Specified */
-                                                       if ((compno < 1) || (compno > 256)) {
-                                                               fprintf(stderr, "ERROR -> invalid number of components c = %d\n", compno);
-                                                               return 1;
-                                                       }
-                                                       parameters->jpwl_exp_comps = compno;
-
-                                               } else if (!strcmp(token, "c")) {
-                                                       /* default */
-                                                       parameters->jpwl_exp_comps = compno; /* auto for default size */
-
-                                               } else {
-                                                       fprintf(stderr, "ERROR -> invalid components specified = %s\n", token);
-                                                       return 1;
-                                               };
-                                       }
-
-                                       /* search maximum number of tiles */
-                                       if (*token == 't') {
-
-                                               static int tileno;
-
-                                               tileno = JPWL_MAXIMUM_TILES; /* maximum no. of tiles */
-
-                                               if(sscanf(token, "t=%d", &tileno) == 1) {
-                                                       /* Specified */
-                                                       if ((tileno < 1) || (tileno > JPWL_MAXIMUM_TILES)) {
-                                                               fprintf(stderr, "ERROR -> invalid number of tiles t = %d\n", tileno);
-                                                               return 1;
-                                                       }
-                                                       parameters->jpwl_max_tiles = tileno;
-
-                                               } else if (!strcmp(token, "t")) {
-                                                       /* default */
-                                                       parameters->jpwl_max_tiles = tileno; /* auto for default size */
-
-                                               } else {
-                                                       fprintf(stderr, "ERROR -> invalid tiles specified = %s\n", token);
-                                                       return 1;
-                                               };
-                                       }
-
-                                       /* next token or bust */
-                                       token = strtok(NULL, ",");
-                               };
-                               parameters->jpwl_correct = true;
-                               fprintf(stdout, "JPWL correction capability activated\n");
-                               fprintf(stdout, "- expecting %d components\n", parameters->jpwl_exp_comps);
-                       }
-                       break;  
-#endif /* USE_JPWL */
-/* <<UniPG */            
-
-                               /* ----------------------------------------------------- */
-                       
-                       default:
-                               fprintf(stderr,"WARNING -> this option is not valid \"-%c %s\"\n",c, optarg);
-                               break;
-               }
-       }
-
-       /* check for possible errors */
-       if(img_fol->set_imgdir==1){
-               if(!(parameters->infile[0]==0)){
-                       fprintf(stderr, "Error: options -ImgDir and -i cannot be used together !!\n");
-                       return 1;
-               }
-               if(img_fol->set_out_format == 0){
-                       fprintf(stderr, "Error: When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
-                       fprintf(stderr, "Only one format allowed! Valid format PGM, PPM, PNM, PGX, BMP, TIF, RAW and TGA!!\n");
-                       return 1;
-               }
-               if(!((parameters->outfile[0] == 0))){
-                       fprintf(stderr, "Error: options -ImgDir and -o cannot be used together !!\n");
-                       return 1;
-               }
-       }else{
-               if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
-                       fprintf(stderr, "Example: %s -i image.j2k -o image.pgm\n",argv[0]);
-                       fprintf(stderr, "    Try: %s -h\n",argv[0]);
-                       return 1;
-               }
-       }
-
-       return 0;
-}
-
-/* -------------------------------------------------------------------------- */
-
-/**
-sample error callback expecting a FILE* client object
-*/
-void error_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[ERROR] %s", msg);
-}
-/**
-sample warning callback expecting a FILE* client object
-*/
-void warning_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[WARNING] %s", msg);
-}
-/**
-sample debug callback expecting no client object
-*/
-void info_callback(const char *msg, void *client_data) {
-       (void)client_data;
-       fprintf(stdout, "[INFO] %s", msg);
-}
-
-/* -------------------------------------------------------------------------- */
-
-int main(int argc, char **argv) {
-       opj_dparameters_t parameters;   /* decompression parameters */
-       img_fol_t img_fol;
-       opj_event_mgr_t event_mgr;              /* event manager */
-       opj_image_t *image = NULL;
-       FILE *fsrc = NULL;
-       unsigned char *src = NULL;
-       int file_length;
-       int num_images;
-       int i,imageno;
-       dircnt_t *dirptr;
-       opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */
-       opj_cio_t *cio = NULL;
-       opj_codestream_info_t cstr_info;  /* Codestream information structure */
-       char indexfilename[OPJ_PATH_LEN];       /* index file name */
-
-       /* configure the event callbacks (not required) */
-       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
-       event_mgr.error_handler = error_callback;
-       event_mgr.warning_handler = warning_callback;
-       event_mgr.info_handler = info_callback;
-
-       /* set decoding parameters to default values */
-       opj_set_default_decoder_parameters(&parameters);
-
-       /* Initialize indexfilename and img_fol */
-       *indexfilename = 0;
-       memset(&img_fol,0,sizeof(img_fol_t));
-
-       /* parse input and get user encoding parameters */
-       if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {
-               return 1;
-       }
-
-       /* Initialize reading of directory */
-       if(img_fol.set_imgdir==1){      
-               num_images=get_num_images(img_fol.imgdirpath);
-
-               dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
-               if(dirptr){
-                       dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));     // Stores at max 10 image file names
-                       dirptr->filename = (char**) malloc(num_images*sizeof(char*));
-
-                       if(!dirptr->filename_buf){
-                               return 1;
-                       }
-                       for(i=0;i<num_images;i++){
-                               dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN;
-                       }
-               }
-               if(load_images(dirptr,img_fol.imgdirpath)==1){
-                       return 1;
-               }
-               if (num_images==0){
-                       fprintf(stdout,"Folder is empty\n");
-                       return 1;
-               }
-       }else{
-               num_images=1;
-       }
-
-       /*Encoding image one by one*/
-       for(imageno = 0; imageno < num_images ; imageno++)      {
-               image = NULL;
-               fprintf(stderr,"\n");
-
-               if(img_fol.set_imgdir==1){
-                       if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
-                               fprintf(stderr,"skipping file...\n");
-                               continue;
-                       }
-               }
-
-               /* read the input file and put it in memory */
-               /* ---------------------------------------- */
-               fsrc = fopen(parameters.infile, "rb");
-               if (!fsrc) {
-                       fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);
-                       return 1;
-               }
-               fseek(fsrc, 0, SEEK_END);
-               file_length = ftell(fsrc);
-               fseek(fsrc, 0, SEEK_SET);
-               src = (unsigned char *) malloc(file_length);
-               fread(src, 1, file_length, fsrc);
-               fclose(fsrc);
-
-               /* decode the code-stream */
-               /* ---------------------- */
-
-               switch(parameters.decod_format) {
-               case J2K_CFMT:
-               {
-                       /* JPEG-2000 codestream */
-
-                       /* get a decoder handle */
-                       dinfo = opj_create_decompress(CODEC_J2K);
-
-                       /* catch events using our callbacks and give a local context */
-                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
-
-                       /* setup the decoder decoding parameters using user parameters */
-                       opj_setup_decoder(dinfo, &parameters);
-
-                       /* open a byte stream */
-                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
-
-                       /* decode the stream and fill the image structure */
-                       if (*indexfilename)                             // If need to extract codestream information
-                               image = opj_decode_with_info(dinfo, cio, &cstr_info);
-                       else
-                               image = opj_decode(dinfo, cio);
-                       if(!image) {
-                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
-                               opj_destroy_decompress(dinfo);
-                               opj_cio_close(cio);
-                               return 1;
-                       }
-
-                       /* close the byte stream */
-                       opj_cio_close(cio);
-
-                       /* Write the index to disk */
-                       if (*indexfilename) {
-                               char bSuccess;
-                               bSuccess = write_index_file(&cstr_info, indexfilename);
-                               if (bSuccess) {
-                                       fprintf(stderr, "Failed to output index file\n");
-                               }
-                       }
-               }
-               break;
-
-               case JP2_CFMT:
-               {
-                       /* JPEG 2000 compressed image data */
-
-                       /* get a decoder handle */
-                       dinfo = opj_create_decompress(CODEC_JP2);
-
-                       /* catch events using our callbacks and give a local context */
-                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
-
-                       /* setup the decoder decoding parameters using the current image and user parameters */
-                       opj_setup_decoder(dinfo, &parameters);
-
-                       /* open a byte stream */
-                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
-
-                       /* decode the stream and fill the image structure */
-                       if (*indexfilename)                             // If need to extract codestream information
-                               image = opj_decode_with_info(dinfo, cio, &cstr_info);
-                       else
-                               image = opj_decode(dinfo, cio);                 
-                       if(!image) {
-                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
-                               opj_destroy_decompress(dinfo);
-                               opj_cio_close(cio);
-                               return 1;
-                       }
-
-                       /* close the byte stream */
-                       opj_cio_close(cio);
-
-                       /* Write the index to disk */
-                       if (*indexfilename) {
-                               char bSuccess;
-                               bSuccess = write_index_file(&cstr_info, indexfilename);
-                               if (bSuccess) {
-                                       fprintf(stderr, "Failed to output index file\n");
-                               }
-                       }
-               }
-               break;
-
-               case JPT_CFMT:
-               {
-                       /* JPEG 2000, JPIP */
-
-                       /* get a decoder handle */
-                       dinfo = opj_create_decompress(CODEC_JPT);
-
-                       /* catch events using our callbacks and give a local context */
-                       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
-
-                       /* setup the decoder decoding parameters using user parameters */
-                       opj_setup_decoder(dinfo, &parameters);
-
-                       /* open a byte stream */
-                       cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
-
-                       /* decode the stream and fill the image structure */
-                       if (*indexfilename)                             // If need to extract codestream information
-                               image = opj_decode_with_info(dinfo, cio, &cstr_info);
-                       else
-                               image = opj_decode(dinfo, cio);
-                       if(!image) {
-                               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
-                               opj_destroy_decompress(dinfo);
-                               opj_cio_close(cio);
-                               return 1;
-                       }
-
-                       /* close the byte stream */
-                       opj_cio_close(cio);
-
-                       /* Write the index to disk */
-                       if (*indexfilename) {
-                               char bSuccess;
-                               bSuccess = write_index_file(&cstr_info, indexfilename);
-                               if (bSuccess) {
-                                       fprintf(stderr, "Failed to output index file\n");
-                               }
-                       }
-               }
-               break;
-
-               default:
-                       fprintf(stderr, "skipping file..\n");
-                       continue;
-       }
-
-               /* free the memory containing the code-stream */
-               free(src);
-               src = NULL;
-
-       if(image->color_space == CLRSPC_SYCC)
-   {
-       color_sycc_to_rgb(image);
-   }
-
-       if(image->icc_profile_buf)
-   {
-#if defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2)
-       color_apply_icc_profile(image);
-#endif
-
-       free(image->icc_profile_buf);
-       image->icc_profile_buf = NULL; image->icc_profile_len = 0;
-   }
-
-               /* create output image */
-               /* ------------------- */
-               switch (parameters.cod_format) {
-               case PXM_DFMT:                  /* PNM PGM PPM */
-                       if (imagetopnm(image, parameters.outfile)) {
-                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
-                       }
-                       else {
-                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
-                       }
-                       break;
-
-               case PGX_DFMT:                  /* PGX */
-                       if(imagetopgx(image, parameters.outfile)){
-                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
-                       }
-                       else {
-                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
-                       }
-                       break;
-
-               case BMP_DFMT:                  /* BMP */
-                       if(imagetobmp(image, parameters.outfile)){
-                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
-                       }
-                       else {
-                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
-                       }
-                       break;
-#ifdef HAVE_LIBTIFF
-               case TIF_DFMT:                  /* TIFF */
-                       if(imagetotif(image, parameters.outfile)){
-                               fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
-                       }
-                       else {
-                               fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
-                       }
-                       break;
-#endif /* HAVE_LIBTIFF */
-               case RAW_DFMT:                  /* RAW */
-                       if(imagetoraw(image, parameters.outfile)){
-                               fprintf(stdout,"Error generating raw file. Outfile %s not generated\n",parameters.outfile);
-                       }
-                       else {
-                               fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile);
-                       }
-                       break;
-
-               case TGA_DFMT:                  /* TGA */
-                       if(imagetotga(image, parameters.outfile)){
-                               fprintf(stdout,"Error generating tga file. Outfile %s not generated\n",parameters.outfile);
-                       }
-                       else {
-                               fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile);
-                       }
-                       break;
-#ifdef HAVE_LIBPNG
-               case PNG_DFMT:                  /* PNG */
-                       if(imagetopng(image, parameters.outfile)){
-                               fprintf(stdout,"Error generating png file. Outfile %s not generated\n",parameters.outfile);
-                       }
-                       else {
-                               fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile);
-                       }
-                       break;
-#endif /* HAVE_LIBPNG */
-/* Can happen if output file is TIFF or PNG
- * and HAVE_LIBTIF or HAVE_LIBPNG is undefined
-*/
-                       default:
-                               fprintf(stderr,"Outfile %s not generated\n",parameters.outfile);
-               }
-
-               /* free remaining structures */
-               if(dinfo) {
-                       opj_destroy_decompress(dinfo);
-               }
-               /* free codestream information structure */
-               if (*indexfilename)     
-                       opj_destroy_cstr_info(&cstr_info);
-               /* free image data structure */
-               opj_image_destroy(image);
-
-       }
-       return 0;
-}
-//end main
-
-
-
-
diff --git a/codec/windirent.h b/codec/windirent.h
deleted file mode 100644 (file)
index 6bcc778..0000000
+++ /dev/null
@@ -1,679 +0,0 @@
-\r
-/*\r
- * uce-dirent.h - operating system independent dirent implementation\r
- * \r
- * Copyright (C) 1998-2002  Toni Ronkko\r
- * \r
- * Permission is hereby granted, free of charge, to any person obtaining\r
- * a copy of this software and associated documentation files (the\r
- * ``Software''), to deal in the Software without restriction, including\r
- * without limitation the rights to use, copy, modify, merge, publish,\r
- * distribute, sublicense, and/or sell copies of the Software, and to\r
- * permit persons to whom the Software is furnished to do so, subject to\r
- * the following conditions:\r
- * \r
- * The above copyright notice and this permission notice shall be included\r
- * in all copies or substantial portions of the Software.\r
- * \r
- * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS\r
- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r
- * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR\r
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\r
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r
- * OTHER DEALINGS IN THE SOFTWARE.\r
- * \r
- * \r
- * May 28 1998, Toni Ronkko <tronkko@messi.uku.fi>\r
- *\r
- * $Id: uce-dirent.h,v 1.7 2002/05/13 10:48:35 tr Exp $\r
- *\r
- * $Log: uce-dirent.h,v $\r
- * Revision 1.7  2002/05/13 10:48:35  tr\r
- * embedded some source code directly to the header so that no source\r
- * modules need to be included in the MS Visual C project using the\r
- * interface, removed all the dependencies to other headers of the `uce'\r
- * library so that the header can be made public\r
- *\r
- * Revision 1.6  2002/04/12 16:22:04  tr\r
- * Unified Compiling Environment (UCE) replaced `std' library\r
- *\r
- * Revision 1.5  2001/07/20 16:33:40  tr\r
- * moved to `std' library and re-named defines accordingly\r
- *\r
- * Revision 1.4  2001/07/10 16:47:18  tronkko\r
- * revised comments\r
- *\r
- * Revision 1.3  2001/01/11 13:16:43  tr\r
- * using ``uce-machine.h'' for finding out defines such as `FREEBSD'\r
- *\r
- * Revision 1.2  2000/10/08 16:00:41  tr\r
- * copy of FreeBSD man page\r
- *\r
- * Revision 1.1  2000/07/10 05:53:16  tr\r
- * Initial revision\r
- *\r
- * Revision 1.2  1998/07/19 18:29:14  tr\r
- * Added error reporting capabilities and some asserts.\r
- *\r
- * Revision 1.1  1998/07/04 16:27:51  tr\r
- * Initial revision\r
- *\r
- * \r
- * MSVC 1.0 scans automatic dependencies incorrectly when your project\r
- * contains this very header.  The problem is that MSVC cannot handle\r
- * include directives inside #if..#endif block those are never entered.\r
- * Since this header ought to compile in many different operating systems,\r
- * there had to be several conditional blocks that are compiled only in\r
- * operating systems for what they were designed for.  MSVC 1.0 cannot\r
- * handle inclusion of sys/dir.h in a part that is compiled only in Apollo\r
- * operating system.  To fix the problem you need to insert DIR.H into\r
- * SYSINCL.DAT located in MSVC\BIN directory and restart visual C++.\r
- * Consult manuals for more informaton about the problem.\r
- *\r
- * Since many UNIX systems have dirent.h we assume to have one also.\r
- * However, if your UNIX system does not have dirent.h you can download one\r
- * for example at: http://ftp.uni-mannheim.de/ftp/GNU/dirent/dirent.tar.gz.\r
- * You can also see if you have one of dirent.h, direct.h, dir.h, ndir.h,\r
- * sys/dir.h and sys/ndir.h somewhere.  Try defining HAVE_DIRENT_H,\r
- * HAVE_DIRECT_H, HAVE_DIR_H, HAVE_NDIR_H, HAVE_SYS_DIR_H and\r
- * HAVE_SYS_NDIR_H according to the files found.\r
- */\r
-#ifndef DIRENT_H\r
-#define DIRENT_H\r
-#define DIRENT_H_INCLUDED\r
-\r
-/* find out platform */\r
-#if defined(MSDOS)                             /* MS-DOS */\r
-#elif defined(__MSDOS__)                       /* Turbo C/Borland */\r
-# define MSDOS\r
-#elif defined(__DOS__)                         /* Watcom */\r
-# define MSDOS\r
-#endif\r
-\r
-#if defined(WIN32)                             /* MS-Windows */\r
-#elif defined(__NT__)                          /* Watcom */\r
-# define WIN32\r
-#elif defined(_WIN32)                          /* Microsoft */\r
-# define WIN32\r
-#elif defined(__WIN32__)                       /* Borland */\r
-# define WIN32\r
-#endif\r
-\r
-/*\r
- * See what kind of dirent interface we have unless autoconf has already\r
- * determinated that.\r
- */\r
-#if !defined(HAVE_DIRENT_H) && !defined(HAVE_DIRECT_H) && !defined(HAVE_SYS_DIR_H) && !defined(HAVE_NDIR_H) && !defined(HAVE_SYS_NDIR_H) && !defined(HAVE_DIR_H)\r
-# if defined(_MSC_VER)                         /* Microsoft C/C++ */\r
-    /* no dirent.h */\r
-# elif defined(__MINGW32__)                    /* MinGW */\r
-    /* no dirent.h */\r
-# elif defined(__BORLANDC__)                   /* Borland C/C++ */\r
-#   define HAVE_DIRENT_H\r
-#   define VOID_CLOSEDIR\r
-# elif defined(__TURBOC__)                     /* Borland Turbo C */\r
-    /* no dirent.h */\r
-# elif defined(__WATCOMC__)                    /* Watcom C/C++ */\r
-#   define HAVE_DIRECT_H\r
-# elif defined(__apollo)                       /* Apollo */\r
-#   define HAVE_SYS_DIR_H\r
-# elif defined(__hpux)                         /* HP-UX */\r
-#   define HAVE_DIRENT_H\r
-# elif (defined(__alpha) || defined(__alpha__)) && !defined(__linux__)  /* Alpha OSF1 */\r
-#   error "not implemented"\r
-# elif defined(__sgi)                          /* Silicon Graphics */\r
-#   define HAVE_DIRENT_H\r
-# elif defined(sun) || defined(_sun)           /* Sun Solaris */\r
-#   define HAVE_DIRENT_H\r
-# elif defined(__FreeBSD__)                    /* FreeBSD */\r
-#   define HAVE_DIRENT_H\r
-# elif defined(__linux__)                      /* Linux */\r
-#   define HAVE_DIRENT_H\r
-# elif defined(__GNUC__)                       /* GNU C/C++ */\r
-#   define HAVE_DIRENT_H\r
-# else\r
-#   error "not implemented"\r
-# endif\r
-#endif\r
-\r
-/* include proper interface headers */\r
-#if defined(HAVE_DIRENT_H)\r
-# include <dirent.h>\r
-# ifdef FREEBSD\r
-#   define NAMLEN(dp) ((int)((dp)->d_namlen))\r
-# else\r
-#   define NAMLEN(dp) ((int)(strlen((dp)->d_name)))\r
-# endif\r
-\r
-#elif defined(HAVE_NDIR_H)\r
-# include <ndir.h>\r
-# define NAMLEN(dp) ((int)((dp)->d_namlen))\r
-\r
-#elif defined(HAVE_SYS_NDIR_H)\r
-# include <sys/ndir.h>\r
-# define NAMLEN(dp) ((int)((dp)->d_namlen))\r
-\r
-#elif defined(HAVE_DIRECT_H)\r
-# include <direct.h>\r
-# define NAMLEN(dp) ((int)((dp)->d_namlen))\r
-\r
-#elif defined(HAVE_DIR_H)\r
-# include <dir.h>\r
-# define NAMLEN(dp) ((int)((dp)->d_namlen))\r
-\r
-#elif defined(HAVE_SYS_DIR_H)\r
-# include <sys/types.h>\r
-# include <sys/dir.h>\r
-# ifndef dirent\r
-#   define dirent direct\r
-# endif\r
-# define NAMLEN(dp) ((int)((dp)->d_namlen))\r
-\r
-#elif defined(MSDOS) || defined(WIN32)\r
-\r
-  /* figure out type of underlaying directory interface to be used */\r
-# if defined(WIN32)\r
-#   define DIRENT_WIN32_INTERFACE\r
-# elif defined(MSDOS)\r
-#   define DIRENT_MSDOS_INTERFACE\r
-# else\r
-#   error "missing native dirent interface"\r
-# endif\r
-\r
-  /*** WIN32 specifics ***/\r
-# if defined(DIRENT_WIN32_INTERFACE)\r
-#   include <windows.h>\r
-#   if !defined(DIRENT_MAXNAMLEN)\r
-#     define DIRENT_MAXNAMLEN (MAX_PATH)\r
-#   endif\r
-\r
-\r
-  /*** MS-DOS specifics ***/\r
-# elif defined(DIRENT_MSDOS_INTERFACE)\r
-#   include <dos.h>\r
-\r
-    /* Borland defines file length macros in dir.h */\r
-#   if defined(__BORLANDC__)\r
-#     include <dir.h>\r
-#     if !defined(DIRENT_MAXNAMLEN)\r
-#       define DIRENT_MAXNAMLEN ((MAXFILE)+(MAXEXT))\r
-#     endif\r
-#     if !defined(_find_t)\r
-#       define _find_t find_t\r
-#     endif\r
-\r
-    /* Turbo C defines ffblk structure in dir.h */\r
-#   elif defined(__TURBOC__)\r
-#     include <dir.h>\r
-#     if !defined(DIRENT_MAXNAMLEN)\r
-#       define DIRENT_MAXNAMLEN ((MAXFILE)+(MAXEXT))\r
-#     endif\r
-#     define DIRENT_USE_FFBLK\r
-\r
-    /* MSVC */\r
-#   elif defined(_MSC_VER)\r
-#     if !defined(DIRENT_MAXNAMLEN)\r
-#       define DIRENT_MAXNAMLEN (12)\r
-#     endif\r
-\r
-    /* Watcom */\r
-#   elif defined(__WATCOMC__)\r
-#     if !defined(DIRENT_MAXNAMLEN)\r
-#       if defined(__OS2__) || defined(__NT__)\r
-#         define DIRENT_MAXNAMLEN (255)\r
-#       else\r
-#         define DIRENT_MAXNAMLEN (12)\r
-#       endif\r
-#     endif\r
-\r
-#   endif\r
-# endif\r
-\r
-  /*** generic MS-DOS and MS-Windows stuff ***/\r
-# if !defined(NAME_MAX) && defined(DIRENT_MAXNAMLEN)\r
-#   define NAME_MAX DIRENT_MAXNAMLEN\r
-# endif\r
-# if NAME_MAX < DIRENT_MAXNAMLEN\r
-#   error "assertion failed: NAME_MAX >= DIRENT_MAXNAMLEN"\r
-# endif\r
-\r
-\r
-  /*\r
-   * Substitute for real dirent structure.  Note that `d_name' field is a\r
-   * true character array although we have it copied in the implementation\r
-   * dependent data.  We could save some memory if we had declared `d_name'\r
-   * as a pointer refering the name within implementation dependent data.\r
-   * We have not done that since some code may rely on sizeof(d_name) to be\r
-   * something other than four.  Besides, directory entries are typically so\r
-   * small that it takes virtually no time to copy them from place to place.\r
-   */\r
-  typedef struct dirent {\r
-    char d_name[NAME_MAX + 1];\r
-\r
-    /*** Operating system specific part ***/\r
-# if defined(DIRENT_WIN32_INTERFACE)       /*WIN32*/\r
-    WIN32_FIND_DATA data;\r
-# elif defined(DIRENT_MSDOS_INTERFACE)     /*MSDOS*/\r
-#   if defined(DIRENT_USE_FFBLK)\r
-    struct ffblk data;\r
-#   else\r
-    struct _find_t data;\r
-#   endif\r
-# endif\r
-  } dirent;\r
-\r
-  /* DIR substitute structure containing directory name.  The name is\r
-   * essential for the operation of ``rewinndir'' function. */\r
-  typedef struct DIR {\r
-    char          *dirname;                    /* directory being scanned */\r
-    dirent        current;                     /* current entry */\r
-    int           dirent_filled;               /* is current un-processed? */\r
-\r
-  /*** Operating system specific part ***/\r
-#  if defined(DIRENT_WIN32_INTERFACE)\r
-    HANDLE        search_handle;\r
-#  elif defined(DIRENT_MSDOS_INTERFACE)\r
-#  endif\r
-  } DIR;\r
-\r
-# ifdef __cplusplus\r
-extern "C" {\r
-# endif\r
-\r
-/* supply prototypes for dirent functions */\r
-static DIR *opendir (const char *dirname);\r
-static struct dirent *readdir (DIR *dirp);\r
-static int closedir (DIR *dirp);\r
-static void rewinddir (DIR *dirp);\r
-\r
-/*\r
- * Implement dirent interface as static functions so that the user does not\r
- * need to change his project in any way to use dirent function.  With this\r
- * it is sufficient to include this very header from source modules using\r
- * dirent functions and the functions will be pulled in automatically.\r
- */\r
-#include <stdio.h>\r
-#include <stdlib.h>\r
-#include <string.h>\r
-#include <assert.h>\r
-#include <errno.h>\r
-\r
-/* use ffblk instead of _find_t if requested */\r
-#if defined(DIRENT_USE_FFBLK)\r
-# define _A_ARCH   (FA_ARCH)\r
-# define _A_HIDDEN (FA_HIDDEN)\r
-# define _A_NORMAL (0)\r
-# define _A_RDONLY (FA_RDONLY)\r
-# define _A_SUBDIR (FA_DIREC)\r
-# define _A_SYSTEM (FA_SYSTEM)\r
-# define _A_VOLID  (FA_LABEL)\r
-# define _dos_findnext(dest) findnext(dest)\r
-# define _dos_findfirst(name,flags,dest) findfirst(name,dest,flags)\r
-#endif\r
-\r
-static int _initdir (DIR *p);\r
-static const char *_getdirname (const struct dirent *dp);\r
-static void _setdirname (struct DIR *dirp);\r
-\r
-/*\r
- * <function name="opendir">\r
- * <intro>open directory stream for reading\r
- * <syntax>DIR *opendir (const char *dirname);\r
- *\r
- * <desc>Open named directory stream for read and return pointer to the\r
- * internal working area that is used for retrieving individual directory\r
- * entries.  The internal working area has no fields of your interest.\r
- *\r
- * <ret>Returns a pointer to the internal working area or NULL in case the \r
- * directory stream could not be opened.  Global `errno' variable will set\r
- * in case of error as follows:\r
- *\r
- * <table>\r
- * [EACESS  |Permission denied.\r
- * [EMFILE  |Too many open files used by the process.\r
- * [ENFILE  |Too many open files in system.\r
- * [ENOENT  |Directory does not exist.\r
- * [ENOMEM  |Insufficient memory.\r
- * [ENOTDIR |dirname does not refer to directory.  This value is not\r
- *           reliable on MS-DOS and MS-Windows platforms.  Many\r
- *           implementations return ENOENT even when the name refers to a\r
- *           file.]\r
- * </table>\r
- * </function>\r
- */\r
-static DIR *opendir(const char *dirname)\r
-{\r
-  DIR *dirp;\r
-  assert (dirname != NULL);\r
-  \r
-  dirp = (DIR*)malloc (sizeof (struct DIR));\r
-  if (dirp != NULL) {\r
-    char *p;\r
-    \r
-    /* allocate room for directory name */\r
-    dirp->dirname = (char*) malloc (strlen (dirname) + 1 + strlen ("\\*.*"));\r
-    if (dirp->dirname == NULL) {\r
-      /* failed to duplicate directory name.  errno set by malloc() */\r
-      free (dirp);\r
-      return NULL;\r
-    }\r
-    /* Copy directory name while appending directory separator and "*.*".\r
-     * Directory separator is not appended if the name already ends with\r
-     * drive or directory separator.  Directory separator is assumed to be\r
-     * '/' or '\' and drive separator is assumed to be ':'. */\r
-    strcpy (dirp->dirname, dirname);\r
-    p = strchr (dirp->dirname, '\0');\r
-    if (dirp->dirname < p  &&\r
-        *(p - 1) != '\\'  &&  *(p - 1) != '/'  &&  *(p - 1) != ':')\r
-    {\r
-      strcpy (p++, "\\");\r
-    }\r
-# ifdef DIRENT_WIN32_INTERFACE\r
-    strcpy (p, "*"); /*scan files with and without extension in win32*/\r
-# else\r
-    strcpy (p, "*.*"); /*scan files with and without extension in DOS*/\r
-# endif\r
-\r
-    /* open stream */\r
-    if (_initdir (dirp) == 0) {\r
-      /* initialization failed */\r
-      free (dirp->dirname);\r
-      free (dirp);\r
-      return NULL;\r
-    }\r
-  }\r
-  return dirp;\r
-}\r
-\r
-\r
-/*\r
- * <function name="readdir">\r
- * <intro>read a directory entry\r
- * <syntax>struct dirent *readdir (DIR *dirp);\r
- *\r
- * <desc>Read individual directory entry and return pointer to a structure\r
- * containing the name of the entry.  Individual directory entries returned\r
- * include normal files, sub-directories, pseudo-directories "." and ".."\r
- * and also volume labels, hidden files and system files in MS-DOS and\r
- * MS-Windows.   You might want to use stat(2) function to determinate which\r
- * one are you dealing with.  Many dirent implementations already contain\r
- * equivalent information in dirent structure but you cannot depend on\r
- * this.\r
- *\r
- * The dirent structure contains several system dependent fields that\r
- * generally have no interest to you.  The only interesting one is char\r
- * d_name[] that is also portable across different systems.  The d_name\r
- * field contains the name of the directory entry without leading path.\r
- * While d_name is portable across different systems the actual storage\r
- * capacity of d_name varies from system to system and there is no portable\r
- * way to find out it at compile time as different systems define the\r
- * capacity of d_name with different macros and some systems do not define\r
- * capacity at all (besides actual declaration of the field). If you really\r
- * need to find out storage capacity of d_name then you might want to try\r
- * NAME_MAX macro. The NAME_MAX is defined in POSIX standard althought\r
- * there are many MS-DOS and MS-Windows implementations those do not define\r
- * it.  There are also systems that declare d_name as "char d_name[1]" and\r
- * then allocate suitable amount of memory at run-time.  Thanks to Alain\r
- * Decamps (Alain.Decamps@advalvas.be) for pointing it out to me.\r
- *\r
- * This all leads to the fact that it is difficult to allocate space\r
- * for the directory names when the very same program is being compiled on\r
- * number of operating systems.  Therefore I suggest that you always\r
- * allocate space for directory names dynamically.\r
- *\r
- * <ret>\r
- * Returns a pointer to a structure containing name of the directory entry\r
- * in `d_name' field or NULL if there was an error.  In case of an error the\r
- * global `errno' variable will set as follows:\r
- *\r
- * <table>\r
- * [EBADF  |dir parameter refers to an invalid directory stream.  This value\r
- *          is not set reliably on all implementations.]\r
- * </table>\r
- * </function>\r
- */\r
-static struct dirent *\r
-readdir (DIR *dirp)\r
-{\r
-  assert(dirp != NULL);\r
-  if (dirp == NULL) {\r
-    errno = EBADF;\r
-    return NULL;\r
-  }\r
-\r
-#if defined(DIRENT_WIN32_INTERFACE)\r
-  if (dirp->search_handle == INVALID_HANDLE_VALUE) {\r
-    /* directory stream was opened/rewound incorrectly or it ended normally */\r
-    errno = EBADF;\r
-    return NULL;\r
-  }\r
-#endif\r
-\r
-  if (dirp->dirent_filled != 0) {\r
-    /*\r
-     * Directory entry has already been retrieved and there is no need to\r
-     * retrieve a new one.  Directory entry will be retrieved in advance\r
-     * when the user calls readdir function for the first time.  This is so\r
-     * because real dirent has separate functions for opening and reading\r
-     * the stream whereas Win32 and DOS dirents open the stream\r
-     * automatically when we retrieve the first file.  Therefore, we have to\r
-     * save the first file when opening the stream and later we have to\r
-     * return the saved entry when the user tries to read the first entry.\r
-     */\r
-    dirp->dirent_filled = 0;\r
-  } else {\r
-    /* fill in entry and return that */\r
-#if defined(DIRENT_WIN32_INTERFACE)\r
-    if (FindNextFile (dirp->search_handle, &dirp->current.data) == FALSE) {\r
-      /* Last file has been processed or an error occured */\r
-      FindClose (dirp->search_handle);\r
-      dirp->search_handle = INVALID_HANDLE_VALUE;\r
-      errno = ENOENT;\r
-      return NULL;\r
-    }\r
-\r
-# elif defined(DIRENT_MSDOS_INTERFACE)\r
-    if (_dos_findnext (&dirp->current.data) != 0) {\r
-      /* _dos_findnext and findnext will set errno to ENOENT when no\r
-       * more entries could be retrieved. */\r
-      return NULL;\r
-    }\r
-# endif\r
-\r
-    _setdirname (dirp);\r
-    assert (dirp->dirent_filled == 0);\r
-  }\r
-  return &dirp->current;\r
-}\r
-\r
-\r
-/*\r
- * <function name="closedir">\r
- * <intro>close directory stream.\r
- * <syntax>int closedir (DIR *dirp);\r
- *\r
- * <desc>Close directory stream opened by the `opendir' function.  Close of\r
- * directory stream invalidates the DIR structure as well as previously read\r
- * dirent entry.\r
- *\r
- * <ret>The function typically returns 0 on success and -1 on failure but\r
- * the function may be declared to return void on same systems.  At least\r
- * Borland C/C++ and some UNIX implementations use void as a return type.\r
- * The dirent wrapper tries to define VOID_CLOSEDIR whenever closedir is\r
- * known to return nothing.  The very same definition is made by the GNU\r
- * autoconf if you happen to use it.\r
- *\r
- * The global `errno' variable will set to EBADF in case of error.\r
- * </function>\r
- */\r
-static int\r
-closedir (DIR *dirp)\r
-{   \r
-  int retcode = 0;\r
-\r
-  /* make sure that dirp points to legal structure */\r
-  assert (dirp != NULL);\r
-  if (dirp == NULL) {\r
-    errno = EBADF;\r
-    return -1;\r
-  }\r
\r
-  /* free directory name and search handles */\r
-  if (dirp->dirname != NULL) free (dirp->dirname);\r
-\r
-#if defined(DIRENT_WIN32_INTERFACE)\r
-  if (dirp->search_handle != INVALID_HANDLE_VALUE) {\r
-    if (FindClose (dirp->search_handle) == FALSE) {\r
-      /* Unknown error */\r
-      retcode = -1;\r
-      errno = EBADF;\r
-    }\r
-  }\r
-#endif                     \r
-\r
-  /* clear dirp structure to make sure that it cannot be used anymore*/\r
-  memset (dirp, 0, sizeof (*dirp));\r
-# if defined(DIRENT_WIN32_INTERFACE)\r
-  dirp->search_handle = INVALID_HANDLE_VALUE;\r
-# endif\r
-\r
-  free (dirp);\r
-  return retcode;\r
-}\r
-\r
-\r
-/*\r
- * <function name="rewinddir">\r
- * <intro>rewind directory stream to the beginning\r
- * <syntax>void rewinddir (DIR *dirp);\r
- *\r
- * <desc>Rewind directory stream to the beginning so that the next call of\r
- * readdir() returns the very first directory entry again.  However, note\r
- * that next call of readdir() may not return the same directory entry as it\r
- * did in first time.  The directory stream may have been affected by newly\r
- * created files.\r
- *\r
- * Almost every dirent implementation ensure that rewinddir will update\r
- * the directory stream to reflect any changes made to the directory entries\r
- * since the previous ``opendir'' or ``rewinddir'' call.  Keep an eye on\r
- * this if your program depends on the feature.  I know at least one dirent\r
- * implementation where you are required to close and re-open the stream to\r
- * see the changes.\r
- *\r
- * <ret>Returns nothing.  If something went wrong while rewinding, you will\r
- * notice it later when you try to retrieve the first directory entry.\r
- */\r
-static void\r
-rewinddir (DIR *dirp)\r
-{   \r
-  /* make sure that dirp is legal */\r
-  assert (dirp != NULL);\r
-  if (dirp == NULL) {\r
-    errno = EBADF;\r
-    return;\r
-  }\r
-  assert (dirp->dirname != NULL);\r
-  \r
-  /* close previous stream */\r
-#if defined(DIRENT_WIN32_INTERFACE)\r
-  if (dirp->search_handle != INVALID_HANDLE_VALUE) {\r
-    if (FindClose (dirp->search_handle) == FALSE) {\r
-      /* Unknown error */\r
-      errno = EBADF;\r
-    }\r
-  }\r
-#endif\r
-\r
-  /* re-open previous stream */\r
-  if (_initdir (dirp) == 0) {\r
-    /* initialization failed but we cannot deal with error.  User will notice\r
-     * error later when she tries to retrieve first directory enty. */\r
-    /*EMPTY*/;\r
-  }\r
-}\r
-\r
-\r
-/*\r
- * Open native directory stream object and retrieve first file.\r
- * Be sure to close previous stream before opening new one.\r
- */\r
-static int\r
-_initdir (DIR *dirp)\r
-{ \r
-  assert (dirp != NULL);\r
-  assert (dirp->dirname != NULL);\r
-  dirp->dirent_filled = 0;\r
-\r
-# if defined(DIRENT_WIN32_INTERFACE)\r
-  /* Open stream and retrieve first file */\r
-  dirp->search_handle = FindFirstFile (dirp->dirname, &dirp->current.data);\r
-  if (dirp->search_handle == INVALID_HANDLE_VALUE) {\r
-    /* something went wrong but we don't know what.  GetLastError() could\r
-     * give us more information about the error, but then we should map\r
-     * the error code into errno. */\r
-    errno = ENOENT;\r
-    return 0;\r
-  }\r
-\r
-# elif defined(DIRENT_MSDOS_INTERFACE)\r
-  if (_dos_findfirst (dirp->dirname,\r
-          _A_SUBDIR | _A_RDONLY | _A_ARCH | _A_SYSTEM | _A_HIDDEN,\r
-          &dirp->current.data) != 0)\r
-  {\r
-    /* _dos_findfirst and findfirst will set errno to ENOENT when no \r
-     * more entries could be retrieved. */\r
-    return 0;\r
-  }\r
-# endif\r
-\r
-  /* initialize DIR and it's first entry */\r
-  _setdirname (dirp);\r
-  dirp->dirent_filled = 1;\r
-  return 1;\r
-}\r
-\r
-\r
-/*\r
- * Return implementation dependent name of the current directory entry.\r
- */\r
-static const char *\r
-_getdirname (const struct dirent *dp)\r
-{\r
-#if defined(DIRENT_WIN32_INTERFACE)\r
-  return dp->data.cFileName;\r
-  \r
-#elif defined(DIRENT_USE_FFBLK)\r
-  return dp->data.ff_name;\r
-  \r
-#else\r
-  return dp->data.name;\r
-#endif  \r
-}\r
-\r
-\r
-/*\r
- * Copy name of implementation dependent directory entry to the d_name field.\r
- */\r
-static void\r
-_setdirname (struct DIR *dirp) {\r
-  /* make sure that d_name is long enough */\r
-  assert (strlen (_getdirname (&dirp->current)) <= NAME_MAX);\r
-  \r
-  strncpy (dirp->current.d_name,\r
-      _getdirname (&dirp->current),\r
-      NAME_MAX);\r
-  dirp->current.d_name[NAME_MAX] = '\0'; /*char d_name[NAME_MAX+1]*/\r
-}\r
-  \r
-# ifdef __cplusplus\r
-}\r
-# endif\r
-# define NAMLEN(dp) ((int)(strlen((dp)->d_name)))\r
-\r
-#else\r
-# error "missing dirent interface"\r
-#endif\r
-\r
-\r
-#endif /*DIRENT_H*/\r
diff --git a/common/color.c b/common/color.c
deleted file mode 100644 (file)
index ac0921a..0000000
+++ /dev/null
@@ -1,463 +0,0 @@
-/*
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
- * Copyright (c) 2002-2007, Professor Benoit Macq
- * Copyright (c) 2001-2003, David Janssens
- * Copyright (c) 2002-2003, Yannick Verschueren
- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
- * Copyright (c) 2005, Herve Drolon, FreeImage Team
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <math.h>
-
-#include "opj_config.h"
-#include "openjpeg.h"
-#include "color.h"
-
-#ifdef HAVE_LIBLCMS2
-#include <lcms2.h>
-#endif
-#ifdef HAVE_LIBLCMS1
-#include <lcms.h>
-#endif
-
-/*--------------------------------------------------------
-Matrix f�r sYCC, Amendment 1 to IEC 61966-2-1
-
-Y :   0.299   0.587    0.114   :R
-Cb:  -0.1687 -0.3312   0.5     :G
-Cr:   0.5    -0.4187  -0.0812  :B
-
-Inverse:
-
-R: 1        -3.68213e-05    1.40199      :Y
-G: 1.00003  -0.344125      -0.714128     :Cb - 2^(prec - 1)
-B: 0.999823  1.77204       -8.04142e-06  :Cr - 2^(prec - 1)
-
------------------------------------------------------------*/
-static void sycc_to_rgb(int offset, int upb, int y, int cb, int cr,
-       int *out_r, int *out_g, int *out_b)
-{
-       int r, g, b;
-
-       cb -= offset; cr -= offset;
-       r = y + (int)(1.402 * (float)cr);
-       if(r < 0) r = 0; else if(r > upb) r = upb; *out_r = r;
-
-       g = y - (int)(0.344 * (float)cb + 0.714 * (float)cr);
-       if(g < 0) g = 0; else if(g > upb) g = upb; *out_g = g;
-
-       b = y + (int)(1.772 * (float)cb);
-       if(b < 0) b = 0; else if(b > upb) b = upb; *out_b = b;
-}
-
-static void sycc444_to_rgb(opj_image_t *img)
-{
-       int *d0, *d1, *d2, *r, *g, *b;
-       const int *y, *cb, *cr;
-       int maxw, maxh, max, i, offset, upb;
-
-       i = img->comps[0].prec;
-       offset = 1<<(i - 1); upb = (1<<i)-1;
-
-       maxw = img->comps[0].w; maxh = img->comps[0].h;
-       max = maxw * maxh;
-
-       y = img->comps[0].data;
-       cb = img->comps[1].data;
-       cr = img->comps[2].data;
-
-       d0 = r = (int*)malloc(sizeof(int) * max);
-       d1 = g = (int*)malloc(sizeof(int) * max);
-       d2 = b = (int*)malloc(sizeof(int) * max);
-
-       for(i = 0; i < max; ++i)
-   {
-       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);        
-
-       ++y; ++cb; ++cr; ++r; ++g; ++b;
-   }   
-       free(img->comps[0].data); img->comps[0].data = d0;
-       free(img->comps[1].data); img->comps[1].data = d1;
-       free(img->comps[2].data); img->comps[2].data = d2;
-
-}/* sycc444_to_rgb() */
-
-static void sycc422_to_rgb(opj_image_t *img)
-{      
-       int *d0, *d1, *d2, *r, *g, *b;
-       const int *y, *cb, *cr;
-       int maxw, maxh, max, offset, upb;
-       int i, j;
-
-       i = img->comps[0].prec;
-       offset = 1<<(i - 1); upb = (1<<i)-1;
-
-       maxw = img->comps[0].w; maxh = img->comps[0].h;
-       max = maxw * maxh;
-
-       y = img->comps[0].data;
-       cb = img->comps[1].data;
-       cr = img->comps[2].data;
-
-       d0 = r = (int*)malloc(sizeof(int) * max);
-       d1 = g = (int*)malloc(sizeof(int) * max);
-       d2 = b = (int*)malloc(sizeof(int) * max);
-
-       for(i=0; i < maxh; ++i)
-   {
-       for(j=0; j < maxw; j += 2)
-  {
-       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
-
-       ++y; ++r; ++g; ++b;
-
-       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
-
-       ++y; ++r; ++g; ++b; ++cb; ++cr;
-  }
-   }
-       free(img->comps[0].data); img->comps[0].data = d0;
-       free(img->comps[1].data); img->comps[1].data = d1;
-       free(img->comps[2].data); img->comps[2].data = d2;
-
-       img->comps[1].w = maxw; img->comps[1].h = maxh;
-       img->comps[2].w = maxw; img->comps[2].h = maxh;
-       img->comps[1].dx = img->comps[0].dx;
-       img->comps[2].dx = img->comps[0].dx;
-       img->comps[1].dy = img->comps[0].dy;
-       img->comps[2].dy = img->comps[0].dy;
-
-}/* sycc422_to_rgb() */
-
-static void sycc420_to_rgb(opj_image_t *img)
-{
-       int *d0, *d1, *d2, *r, *g, *b, *nr, *ng, *nb;
-       const int *y, *cb, *cr, *ny;
-       int maxw, maxh, max, offset, upb;
-       int i, j;
-
-       i = img->comps[0].prec;
-       offset = 1<<(i - 1); upb = (1<<i)-1;
-
-       maxw = img->comps[0].w; maxh = img->comps[0].h;
-       max = maxw * maxh;
-
-       y = img->comps[0].data;
-       cb = img->comps[1].data;
-       cr = img->comps[2].data;
-
-       d0 = r = (int*)malloc(sizeof(int) * max);
-       d1 = g = (int*)malloc(sizeof(int) * max);
-       d2 = b = (int*)malloc(sizeof(int) * max);
-
-       for(i=0; i < maxh; i += 2)
-   {
-       ny = y + maxw;
-       nr = r + maxw; ng = g + maxw; nb = b + maxw;
-
-       for(j=0; j < maxw;  j += 2)
-  {
-       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
-
-       ++y; ++r; ++g; ++b;
-
-       sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
-
-       ++y; ++r; ++g; ++b;
-
-       sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
-
-       ++ny; ++nr; ++ng; ++nb;
-
-       sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
-
-       ++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
-  }
-       y += maxw; r += maxw; g += maxw; b += maxw;
-   }
-       free(img->comps[0].data); img->comps[0].data = d0;
-       free(img->comps[1].data); img->comps[1].data = d1;
-       free(img->comps[2].data); img->comps[2].data = d2;
-
-       img->comps[1].w = maxw; img->comps[1].h = maxh;
-       img->comps[2].w = maxw; img->comps[2].h = maxh;
-       img->comps[1].dx = img->comps[0].dx;
-       img->comps[2].dx = img->comps[0].dx;
-       img->comps[1].dy = img->comps[0].dy;
-       img->comps[2].dy = img->comps[0].dy;
-
-}/* sycc420_to_rgb() */
-
-void color_sycc_to_rgb(opj_image_t *img)
-{
-       if(img->numcomps < 3) 
-   {
-       img->color_space = CLRSPC_GRAY;
-       return;
-   }
-
-       if((img->comps[0].dx == 1)
-       && (img->comps[1].dx == 2)
-       && (img->comps[2].dx == 2)
-       && (img->comps[0].dy == 1)
-       && (img->comps[1].dy == 2)
-       && (img->comps[2].dy == 2))/* horizontal and vertical sub-sample */
-  {
-       sycc420_to_rgb(img);
-  }
-       else
-       if((img->comps[0].dx == 1)
-       && (img->comps[1].dx == 2)
-       && (img->comps[2].dx == 2)
-       && (img->comps[0].dy == 1)
-       && (img->comps[1].dy == 1)
-       && (img->comps[2].dy == 1))/* horizontal sub-sample only */
-  {
-       sycc422_to_rgb(img);
-  }
-       else
-       if((img->comps[0].dx == 1)
-       && (img->comps[1].dx == 1)
-       && (img->comps[2].dx == 1)
-       && (img->comps[0].dy == 1)
-       && (img->comps[1].dy == 1)
-       && (img->comps[2].dy == 1))/* no sub-sample */
-  {
-       sycc444_to_rgb(img);
-  }
-       else
-  {
-       fprintf(stderr,"%s:%d:color_sycc_to_rgb\n\tCAN NOT CONVERT\n",
-        __FILE__,__LINE__);
-       return;
-  }
-       img->color_space = CLRSPC_SRGB;
-
-}/* color_sycc_to_rgb() */
-
-#if defined(HAVE_LIBLCMS2) || defined(HAVE_LIBLCMS1)
-#ifdef HAVE_LIBLCMS1
-/* Bob Friesenhahn proposed:*/
-#define cmsSigXYZData   icSigXYZData
-#define cmsSigLabData   icSigLabData
-#define cmsSigCmykData  icSigCmykData
-#define cmsSigYCbCrData icSigYCbCrData
-#define cmsSigLuvData   icSigLuvData
-#define cmsSigGrayData  icSigGrayData
-#define cmsSigRgbData   icSigRgbData
-#define cmsUInt32Number DWORD
-
-#define cmsColorSpaceSignature icColorSpaceSignature
-#define cmsGetHeaderRenderingIntent cmsTakeRenderingIntent
-
-#endif /* HAVE_LIBLCMS1 */
-
-void color_apply_icc_profile(opj_image_t *image)
-{
-       cmsHPROFILE in_prof, out_prof;
-       cmsHTRANSFORM transform;
-       cmsColorSpaceSignature in_space, out_space;
-       cmsUInt32Number intent, in_type, out_type, nr_samples;
-       int *r, *g, *b;
-       int prec, i, max, max_w, max_h;
-       OPJ_COLOR_SPACE oldspace;
-
-       in_prof = 
-        cmsOpenProfileFromMem(image->icc_profile_buf, image->icc_profile_len);
-       in_space = cmsGetPCS(in_prof);
-       out_space = cmsGetColorSpace(in_prof);
-       intent = cmsGetHeaderRenderingIntent(in_prof);
-
-       
-       max_w = image->comps[0].w; max_h = image->comps[0].h;
-       prec = image->comps[0].prec;
-       oldspace = image->color_space;
-
-       if(out_space == cmsSigRgbData) /* enumCS 16 */
-   {
-       in_type = TYPE_RGB_16;
-       out_type = TYPE_RGB_16;
-       out_prof = cmsCreate_sRGBProfile();
-       image->color_space = CLRSPC_SRGB;
-   }
-       else
-       if(out_space == cmsSigGrayData) /* enumCS 17 */
-   {
-       in_type = TYPE_GRAY_8;
-       out_type = TYPE_RGB_8;
-       out_prof = cmsCreate_sRGBProfile();
-       image->color_space = CLRSPC_SRGB;
-   }
-       else
-       if(out_space == cmsSigYCbCrData) /* enumCS 18 */
-   {
-       in_type = TYPE_YCbCr_16;
-       out_type = TYPE_RGB_16;
-       out_prof = cmsCreate_sRGBProfile();
-       image->color_space = CLRSPC_SRGB;
-   }
-       else
-   {
-#ifdef DEBUG_PROFILE
-fprintf(stderr,"%s:%d: color_apply_icc_profile\n\tICC Profile has unknown "
-"output colorspace(%#x)(%c%c%c%c)\n\tICC Profile ignored.\n",
-__FILE__,__LINE__,out_space,
-(out_space>>24) & 0xff,(out_space>>16) & 0xff,
-(out_space>>8) & 0xff, out_space & 0xff);
-#endif
-       return;
-   }
-
-#ifdef DEBUG_PROFILE
-fprintf(stderr,"%s:%d:color_apply_icc_profile\n\tchannels(%d) prec(%d) w(%d) h(%d)"
-"\n\tprofile: in(%p) out(%p)\n",__FILE__,__LINE__,image->numcomps,prec,
-max_w,max_h, (void*)in_prof,(void*)out_prof);
-
-fprintf(stderr,"\trender_intent (%u)\n\t"
-"color_space: in(%#x)(%c%c%c%c)   out:(%#x)(%c%c%c%c)\n\t"
-"       type: in(%u)              out:(%u)\n",
-intent,
-in_space,
-(in_space>>24) & 0xff,(in_space>>16) & 0xff,
-(in_space>>8) & 0xff, in_space & 0xff,
-
-out_space,
-(out_space>>24) & 0xff,(out_space>>16) & 0xff,
-(out_space>>8) & 0xff, out_space & 0xff,
-
-in_type,out_type
- );
-#endif /* DEBUG_PROFILE */
-
-       transform = cmsCreateTransform(in_prof, in_type,
-        out_prof, out_type, intent, 0);
-
-#ifdef HAVE_LIBLCMS2
-/* Possible for: LCMS_VERSION >= 2000 :*/
-       cmsCloseProfile(in_prof);
-       cmsCloseProfile(out_prof);
-#endif
-
-       if(transform == NULL)
-   {
-#ifdef DEBUG_PROFILE
-fprintf(stderr,"%s:%d:color_apply_icc_profile\n\tcmsCreateTransform failed. "
-"ICC Profile ignored.\n",__FILE__,__LINE__);
-#endif
-       image->color_space = oldspace;
-#ifdef HAVE_LIBLCMS1
-       cmsCloseProfile(in_prof);
-       cmsCloseProfile(out_prof);
-#endif
-       return;
-   }
-
-       if(image->numcomps > 2)/* RGB, RGBA */
-   {
-       unsigned short *inbuf, *outbuf, *in, *out;
-       max = max_w * max_h; nr_samples = max * 3 * sizeof(unsigned short);
-       in = inbuf = (unsigned short*)malloc(nr_samples);
-       out = outbuf = (unsigned short*)malloc(nr_samples);
-
-       r = image->comps[0].data;
-       g = image->comps[1].data;
-       b = image->comps[2].data;
-
-       for(i = 0; i < max; ++i)
-  {
-       *in++ = (unsigned short)*r++;
-       *in++ = (unsigned short)*g++;
-       *in++ = (unsigned short)*b++;
-  }
-
-       cmsDoTransform(transform, inbuf, outbuf, max);
-
-       r = image->comps[0].data;
-       g = image->comps[1].data;
-       b = image->comps[2].data;
-
-       for(i = 0; i < max; ++i)
-  {
-       *r++ = (int)*out++;
-       *g++ = (int)*out++;
-       *b++ = (int)*out++;
-  }
-       free(inbuf); free(outbuf);
-   }
-       else /* GRAY, GRAYA */
-   {
-       unsigned char *in, *inbuf, *out, *outbuf;
-
-       max = max_w * max_h; nr_samples = max * 3 * sizeof(unsigned char);
-       in = inbuf = (unsigned char*)malloc(nr_samples);
-       out = outbuf = (unsigned char*)malloc(nr_samples);
-
-       image->comps = (opj_image_comp_t*)
-        realloc(image->comps, (image->numcomps+2)*sizeof(opj_image_comp_t));
-
-       if(image->numcomps == 2)
-        image->comps[3] = image->comps[1];
-
-       image->comps[1] = image->comps[0];
-       image->comps[2] = image->comps[0];
-
-       image->comps[1].data = (int*)calloc(max, sizeof(int));
-       image->comps[2].data = (int*)calloc(max, sizeof(int));
-
-       image->numcomps += 2;
-
-       r = image->comps[0].data;
-
-       for(i = 0; i < max; ++i)
-  {
-       *in++ = (unsigned char)*r++;
-  }
-       cmsDoTransform(transform, inbuf, outbuf, max);
-
-       r = image->comps[0].data;
-       g = image->comps[1].data;
-       b = image->comps[2].data;
-
-       for(i = 0; i < max; ++i)
-  {
-       *r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++;
-  }
-       free(inbuf); free(outbuf);
-
-   }/* if(image->numcomps */
-
-       cmsDeleteTransform(transform);
-
-#ifdef HAVE_LIBLCMS1
-       cmsCloseProfile(in_prof);
-       cmsCloseProfile(out_prof);
-#endif
-}/* color_apply_icc_profile() */
-
-#endif /* HAVE_LIBLCMS2 || HAVE_LIBLCMS1 */
-
diff --git a/common/color.h b/common/color.h
deleted file mode 100644 (file)
index 26117b0..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
- * Copyright (c) 2002-2007, Professor Benoit Macq
- * Copyright (c) 2001-2003, David Janssens
- * Copyright (c) 2002-2003, Yannick Verschueren
- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
- * Copyright (c) 2005, Herve Drolon, FreeImage Team
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef _OPJ_COLOR_H_
-#define _OPJ_COLOR_H_
-
-extern void color_sycc_to_rgb(opj_image_t *img);
-extern void color_apply_icc_profile(opj_image_t *image);
-
-#endif /* _OPJ_COLOR_H_ */
diff --git a/common/format_defs.h b/common/format_defs.h
deleted file mode 100644 (file)
index d4be93b..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
- * Copyright (c) 2002-2007, Professor Benoit Macq
- * Copyright (c) 2001-2003, David Janssens
- * Copyright (c) 2002-2003, Yannick Verschueren
- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
- * Copyright (c) 2005, Herve Drolon, FreeImage Team
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef _OPJ_FORMAT_DEFS_H_
-#define _OPJ_FORMAT_DEFS_H_
-
-#define J2K_CFMT 0
-#define JP2_CFMT 1
-#define JPT_CFMT 2
-
-#define PXM_DFMT 10
-#define PGX_DFMT 11
-#define BMP_DFMT 12
-#define YUV_DFMT 13
-#define TIF_DFMT 14
-#define RAW_DFMT 15
-#define TGA_DFMT 16
-#define PNG_DFMT 17
-
-#endif /* _OPJ_FORMAT_DEFS_H_ */
\ No newline at end of file
diff --git a/common/getopt.c b/common/getopt.c
deleted file mode 100644 (file)
index 5e444d3..0000000
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * Copyright (c) 1987, 1993, 1994
- *     The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- *    must display the following acknowledgement:
- *     This product includes software developed by the University of
- *     California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-/* last review : october 29th, 2002 */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)getopt.c   8.3 (Berkeley) 4/27/95";
-#endif                         /* LIBC_SCCS and not lint */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-int opterr = 1,                        /* if error message should be printed */
- optind = 1,                   /* index into parent argv vector */
- optopt,                       /* character checked for validity */
- optreset;                     /* reset getopt */
-const char *optarg;                    /* argument associated with option */
-
-typedef struct option
-{
-       const char *name;
-       int has_arg;
-       int *flag;
-       int val;
-}option_t;
-
-#define        BADCH   (int)'?'
-#define        BADARG  (int)':'
-#define        EMSG    ""
-
-/* As this class remembers its values from one Java call to the other, reset the values before each use */
-void reset_options_reading() {
-       opterr = 1;
-       optind = 1;
-}
-
-/*
- * getopt --
- *     Parse argc/argv argument vector.
- */
-int getopt(int nargc, char *const *nargv, const char *ostr) {
-#  define __progname nargv[0]
-  static const char *place = EMSG;     /* option letter processing */
-  char *oli;                   /* option letter list index */
-
-  if (optreset || !*place) {   /* update scanning pointer */
-    optreset = 0;
-    if (optind >= nargc || *(place = nargv[optind]) != '-') {
-      place = EMSG;
-      return (-1);
-    }
-    if (place[1] && *++place == '-') { /* found "--" */
-      ++optind;
-      place = EMSG;
-      return (-1);
-    }
-  }                            /* option letter okay? */
-  if ((optopt = (int) *place++) == (int) ':' ||
-      !(oli = strchr(ostr, optopt))) {
-    /*
-     * if the user didn't specify '-' as an option,
-     * assume it means -1.
-     */
-    if (optopt == (int) '-')
-      return (-1);
-    if (!*place)
-      ++optind;
-               if (opterr && *ostr != ':') {
-      fprintf(stderr,
-                    "%s: illegal option -- %c\n", __progname, optopt);
-                       return (BADCH);
-               }
-  }
-  if (*++oli != ':') {         /* don't need argument */
-    optarg = NULL;
-    if (!*place)
-      ++optind;
-  } else {                     /* need an argument */
-    if (*place)                        /* no white space */
-      optarg = place;
-    else if (nargc <= ++optind) {      /* no arg */
-      place = EMSG;
-      if (*ostr == ':')
-       return (BADARG);
-                       if (opterr) {
-                               fprintf(stderr,
-                      "%s: option requires an argument -- %c\n",
-                      __progname, optopt);
-                               return (BADCH);
-                       }
-    } else                     /* white space */
-      optarg = nargv[optind];
-    place = EMSG;
-    ++optind;
-  }
-  return (optopt);             /* dump back option letter */
-}
-
-
-int getopt_long(int argc, char * const argv[], const char *optstring,
-struct option *longopts, int totlen) {
-       static int lastidx,lastofs;
-       char *tmp;
-       int i,len;
-       char param = 1;
-
-again:
-       if (optind >= argc || !argv[optind] || *argv[optind]!='-')
-               return -1;
-
-       if (argv[optind][0]=='-' && argv[optind][1]==0) {
-               if(optind >= (argc - 1)){ /* no more input parameters */
-                       param = 0;
-               }
-               else{ /* more input parameters */
-                       if(argv[optind + 1][0] == '-'){
-                               param = 0; /* Missing parameter after '-' */
-                       }
-                       else{
-                               param = 2;
-                       }
-               }
-       }
-
-       if (param == 0) {
-               ++optind;
-               return (BADCH);
-       }
-
-       if (argv[optind][0]=='-') {     /* long option */
-               char* arg=argv[optind]+1;
-               const struct option* o;
-               o=longopts;
-               len=sizeof(longopts[0]);
-
-               if (param > 1){
-                       arg = argv[optind+1];
-                       optind++;
-               }
-               else
-                       arg = argv[optind]+1;
-
-               if(strlen(arg)>1){
-                       for (i=0;i<totlen;i=i+len,o++) {
-                               if (!strcmp(o->name,arg)) {     /* match */
-                                       if (o->has_arg == 0) {
-                                               if ((argv[optind+1])&&(!(argv[optind+1][0]=='-'))){
-                                                       fprintf(stderr,"%s: option does not require an argument. Ignoring %s\n",arg,argv[optind+1]);
-                                                       ++optind;
-                                               }
-                                       }else{ 
-                                               optarg=argv[optind+1];
-                                               if(optarg){
-                                                       if (optarg[0] == '-'){ /* Has read next input parameter: No arg for current parameter */                                                                
-                                                               if (opterr) {
-                                                                       fprintf(stderr,"%s: option requires an argument\n",arg);
-                                                                       return (BADCH);
-                                                               }
-                                                       }
-                                               }
-                                               if (!optarg && o->has_arg==1) { /* no argument there */
-                                                       if (opterr) {
-                                                               fprintf(stderr,"%s: option requires an argument \n",arg);
-                                                               return (BADCH);
-                                                       }
-                                               }
-                                               ++optind;
-                                       }
-                                       ++optind;
-                                       if (o->flag)
-                                               *(o->flag)=o->val;
-                                       else
-                                               return o->val;
-                                       return 0;
-                               }
-                       }//(end for)String not found in the list
-                       fprintf(stderr,"Invalid option %s\n",arg);
-                       ++optind;
-                       return (BADCH);
-               }else{ /*Single character input parameter*/
-                       if (*optstring==':') return ':';
-                       if (lastidx!=optind) {
-                               lastidx=optind; lastofs=0;
-                       }
-                       optopt=argv[optind][lastofs+1];
-                       if ((tmp=strchr(optstring,optopt))) {/*Found input parameter in list*/
-                               if (*tmp==0) {  /* apparently, we looked for \0, i.e. end of argument */
-                                       ++optind;
-                                       goto again;
-                               }
-                               if (tmp[1]==':') {      /* argument expected */
-                                       if (tmp[2]==':' || argv[optind][lastofs+2]) {   /* "-foo", return "oo" as optarg */
-                                               if (!*(optarg=argv[optind]+lastofs+2)) optarg=0;
-                                               goto found;
-                                       }
-                                       optarg=argv[optind+1];
-                                       if(optarg){
-                                               if (optarg[0] == '-'){ /* Has read next input parameter: No arg for current parameter */
-                                                       if (opterr) {
-                                                               fprintf(stderr,"%s: option requires an argument\n",arg);
-                                                               return (BADCH);
-                                                       }
-                                               }
-                                       }
-                                       if (!optarg) {  /* missing argument */
-                                               if (opterr) {
-                                                       fprintf(stderr,"%s: option requires an argument\n",arg);
-                                                       return (BADCH);
-                                               }
-                                       }
-                                       ++optind;
-                               }else {/*Argument not expected*/
-                                       ++lastofs;
-                                       return optopt;
-                               }
-found:
-                               ++optind;
-                               return optopt;
-                       }       else {  /* not found */
-                               fprintf(stderr,"Invalid option %s\n",arg);
-                               ++optind;
-                               return (BADCH);
-                       }//end of not found
-               
-               }// end of single character
-       }//end '-'
-       fprintf(stderr,"Invalid option\n");
-       ++optind;
-       return (BADCH);;
-}//end function
diff --git a/common/getopt.h b/common/getopt.h
deleted file mode 100644 (file)
index 779fe47..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/* last review : october 29th, 2002 */
-
-#ifndef _GETOPT_H_
-#define _GETOPT_H_
-
-typedef struct option
-{
-       const char *name;
-       int has_arg;
-       int *flag;
-       int val;
-}option_t;
-
-#define        NO_ARG  0
-#define REQ_ARG        1
-#define OPT_ARG        2
-
-extern int opterr;
-extern int optind;
-extern int optopt;
-extern int optreset;
-extern char *optarg;
-
-extern int getopt(int nargc, char *const *nargv, const char *ostr);
-extern int getopt_long(int argc, char * const argv[], const char *optstring,
-                       const struct option *longopts, int totlen);
-extern void reset_options_reading();
-
-#endif                         /* _GETOPT_H_ */
diff --git a/indexer_JPIP/CMakeLists.txt b/indexer_JPIP/CMakeLists.txt
deleted file mode 100644 (file)
index c8e378d..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-# index_create
-
-ADD_EXECUTABLE(index_create
-bio.c cio.c int.c pi.c t2.c tgt.c tcd.c index_create.c jpip.c jp2.c
-)
-INSTALL(TARGETS index_create
-  EXPORT OpenJPEGTargets
-  DESTINATION ${OPENJPEG_INSTALL_BIN_DIR} COMPONENT Applications
-)
diff --git a/indexer_JPIP/Makefile b/indexer_JPIP/Makefile
deleted file mode 100644 (file)
index 40c049e..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-CC = gcc
-
-LDFLAGS = -lm
-CFLAGS = -Wall
-
-all: index_create
-
-
-bio.o : bio.c bio.h
-cio.o : cio.c cio.h
-int.o : int.c
-pi.o  : pi.c pi.h int.h
-index_create.o : index_create.c j2k.h cio.h tcd.h int.h
-t2.o  : t2.c t2.h tcd.h bio.h j2k.h pi.h tgt.h int.h cio.h
-tgt.o : tgt.c bio.h tgt.h
-tcd.o : tcd.c tcd.h t2.h int.h
-jpip.o : jpip.c j2k.h cio.h tcd.h int.h
-jp2.o : jp2.c j2k.h cio.h tcd.h int.h
-
-index_create : bio.o cio.o int.o pi.o t2.o tgt.o tcd.o index_create.o jpip.o jp2.o
-
-clean:
-       rm -rf *.o *.*~ *~ core.*
diff --git a/indexer_JPIP/bio.c b/indexer_JPIP/bio.c
deleted file mode 100644 (file)
index 2c989e5..0000000
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "bio.h"
-#include <setjmp.h>
-
-static unsigned char *bio_start, *bio_end, *bio_bp;
-static unsigned int bio_buf;
-static int bio_ct;
-
-extern jmp_buf j2k_error;
-
-/// <summary>
-/// Number of bytes written.
-/// </summary>
-int bio_numbytes() {
-    return bio_bp-bio_start;
-}
-
-/// <summary>
-/// Init decoder.
-/// </summary>
-/// <param name="bp">Input buffer</param>
-/// <param name="len">Input buffer length</param>
-void bio_init_dec(unsigned char *bp, int len) {
-    bio_start=bp;
-    bio_end=bp+len;
-    bio_bp=bp;
-    bio_buf=0;
-    bio_ct=0;
-}
-
-int bio_byteout()
-{
-       bio_buf = (bio_buf << 8) & 0xffff;
-       bio_ct = bio_buf == 0xff00 ? 7 : 8;
-       if (bio_bp >= bio_end)
-               return 1;
-       *bio_bp++ = bio_buf >> 8;
-       return 0;
-}
-
-/// <summary>
-/// Read byte. 
-/// </summary>
-int bio_bytein() {
-    bio_buf=(bio_buf<<8)&0xffff;
-    bio_ct=bio_buf==0xff00?7:8;
-    if (bio_bp>=bio_end) return 1; //longjmp(j2k_error, 1);
-    bio_buf|=*bio_bp++;
-    return 0;
-}
-
-/// <summary>
-/// Read bit.
-/// </summary>
-int bio_getbit() {
-    if (bio_ct==0) {
-        bio_bytein();
-    }
-    bio_ct--;
-    return (bio_buf>>bio_ct)&1;
-}
-
-/// <summary>
-/// Read bits.
-/// </summary>
-/// <param name="n">Number of bits to read</param>
-int bio_read(int n) {
-    int i, v;
-    v=0;
-    for (i=n-1; i>=0; i--) {
-        v+=bio_getbit()<<i;
-    }
-    return v;
-}
-
-/// <summary>
-/// Flush bits.
-/// </summary>
-int bio_flush() {
-    bio_ct=0;
-    bio_byteout();
-    if (bio_ct==7) {
-        bio_ct=0;
-       if ( bio_byteout()) return 1;;
-    }
-    return 0;
-}
-
-/// <summary>
-/// </summary>
-int bio_inalign() {
-    bio_ct=0;
-    if ((bio_buf&0xff)==0xff) {
-       if( bio_bytein()) return 1;
-        bio_ct=0;
-    }
-    return 0;
-}
diff --git a/indexer_JPIP/bio.h b/indexer_JPIP/bio.h
deleted file mode 100644 (file)
index eea6cff..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003-2004, Yannick Verschueren
- * Copyright (c) 2003-2004, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __BIO_H
-#define __BIO_H
-
-int bio_numbytes();
-void bio_init_dec(unsigned char *bp, int len);
-int bio_read(int n);
-int bio_flush();
-int bio_inalign();
-
-#endif
diff --git a/indexer_JPIP/cio.c b/indexer_JPIP/cio.c
deleted file mode 100644 (file)
index 29f160e..0000000
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "cio.h"
-#include <setjmp.h>
-
-static unsigned char *cio_start, *cio_end, *cio_bp;
-
-extern jmp_buf j2k_error;
-
-/// <summary>
-/// Number of bytes written.
-/// </summary>
-int cio_numbytes() {
-    return cio_bp-cio_start;
-}
-
-/// <summary>
-/// Get position in byte stream.
-/// </summary>
-int cio_tell() {
-    return cio_bp-cio_start;
-}
-
-/// <summary>
-/// Set position in byte stream.
-/// </summary>
-void cio_seek(int pos) {
-    cio_bp=cio_start+pos;
-}
-
-/// <summary>
-/// Number of bytes left before the end of the stream.
-/// </summary>
-int cio_numbytesleft() {
-    return cio_end-cio_bp;
-}
-
-/// <summary>
-/// Get pointer to the current position in the stream.
-/// </summary>
-unsigned char *cio_getbp() {
-    return cio_bp;
-}
-
-/// <summary>
-/// Initialize byte IO.
-/// </summary>
-void cio_init(unsigned char *bp, int len) {
-    cio_start=bp;
-    cio_end=bp+len;
-    cio_bp=bp;
-}
-
-/// <summary>
-/// Write a byte.
-/// </summary>
-void cio_byteout(unsigned char v) {
-  if (cio_bp>=cio_end) longjmp(j2k_error, 1);
-  *cio_bp++=v;
-    
-}
-
-/// <summary>
-/// Read a byte.
-/// </summary>
-unsigned char cio_bytein() {
-    if (cio_bp>=cio_end) longjmp(j2k_error, 1);
-    return *cio_bp++;
-}
-
-/// <summary>
-/// Write a byte.
-/// </summary>
-//void cio_write(unsigned int v, int n) {
-void cio_write(long long v, int n) {
-    int i;
-    for (i=n-1; i>=0; i--) 
-      {
-       cio_byteout((unsigned char)((v>>(i<<3))&0xff));
-      }
-}
-
-/// <summary>
-/// Read some bytes.
-/// </summary>
-/* unsigned int cio_read(int n) { */
-long long cio_read(int n) {
-    int i;
-    /*unsigned int v;*/
-    long long v;
-    v=0;
-    for (i=n-1; i>=0; i--) {
-      v+=cio_bytein()<<(i<<3);
-    }
-    return v;
-}
-
-/// <summary>
-/// Write some bytes.
-/// </summary>
-void cio_skip(int n) {
-    cio_bp+=n;
-}
diff --git a/indexer_JPIP/cio.h b/indexer_JPIP/cio.h
deleted file mode 100644 (file)
index 3e29789..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003-2004, Yannick Verschueren
- * Copyright (c) 2003-2004, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __CIO_H
-#define __CIO_H
-
-int cio_tell();
-void cio_seek(int pos);
-int cio_numbytes();
-int cio_numbytesleft();
-unsigned char *cio_getbp();
-void cio_init(unsigned char *bp, int len);
-/* void cio_write(unsigned int v, int n); */
-void cio_write(long long v, int n);
-/* unsigned int cio_read(int n); */
-long long cio_read(int n);
-void cio_skip(int n);
-
-#endif
diff --git a/indexer_JPIP/fix.c b/indexer_JPIP/fix.c
deleted file mode 100644 (file)
index 6bf08c6..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "fix.h"
-
-#ifdef _WIN32
-#include <windows.h>
-
-#define int64 __int64
-#else
-#define int64 long long
-#endif /* _WIN32 */
-
-/// <summary>
-/// Multiply two fixed-precision rational numbers.
-/// </summary>
-int fix_mul(int a, int b) {
-    return (int)((int64)a*(int64)b>>13);
-}
diff --git a/indexer_JPIP/fix.h b/indexer_JPIP/fix.h
deleted file mode 100644 (file)
index 4b6e1b5..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __FIX_H
-#define __FIX_H
-
-int fix_mul(int a, int b);
-
-#endif
diff --git a/indexer_JPIP/index_create.c b/indexer_JPIP/index_create.c
deleted file mode 100644 (file)
index 518e70f..0000000
+++ /dev/null
@@ -1,1219 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003-2004, Yannick Verschueren
- * Copyright (c) 2003-2004, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <setjmp.h>
-#include <math.h>
-
-#include "j2k.h"
-#include "cio.h"
-#include "tcd.h"
-#include "int.h"
-#include "jpip.h"
-#include "jp2.h"
-
-#define J2K_MS_SOC 0xff4f
-#define J2K_MS_SOT 0xff90
-#define J2K_MS_SOD 0xff93
-#define J2K_MS_EOC 0xffd9
-#define J2K_MS_SIZ 0xff51
-#define J2K_MS_COD 0xff52
-#define J2K_MS_COC 0xff53
-#define J2K_MS_RGN 0xff5e
-#define J2K_MS_QCD 0xff5c
-#define J2K_MS_QCC 0xff5d
-#define J2K_MS_POC 0xff5f
-#define J2K_MS_TLM 0xff55
-#define J2K_MS_PLM 0xff57
-#define J2K_MS_PLT 0xff58
-#define J2K_MS_PPM 0xff60
-#define J2K_MS_PPT 0xff61
-#define J2K_MS_SOP 0xff91
-#define J2K_MS_EPH 0xff92
-#define J2K_MS_CRG 0xff63
-#define J2K_MS_COM 0xff64
-
-#define J2K_STATE_MHSOC 0x0001
-#define J2K_STATE_MHSIZ 0x0002
-#define J2K_STATE_MH 0x0004
-#define J2K_STATE_TPHSOT 0x0008
-#define J2K_STATE_TPH 0x0010
-#define J2K_STATE_MT 0x0020
-
-#define START_NB 5
-#define INCREMENT 5
-
-jmp_buf j2k_error;
-
-static int j2k_state;
-static int j2k_curtileno;
-static j2k_tcp_t j2k_default_tcp;
-static unsigned char *j2k_eot;
-
-static j2k_image_t *j2k_img;
-static j2k_cp_t *j2k_cp;
-
-static unsigned char **j2k_tile_data;
-static int *j2k_tile_len;
-
-static info_image_t img;
-
-
-void j2k_clean() {
-  int tileno = 0;
-  int compno=0, resno=0, precno=0;
-
-  tcd_free(j2k_img, j2k_cp);
-  for (tileno = 0; tileno < j2k_cp->tw * j2k_cp->th; tileno++) {
-    info_tile_t *tile_Idx = &img.tile[tileno];
-    
-    for (compno = 0; compno < img.Comp; compno++)
-      {
-       info_compo_t *compo_Idx = &tile_Idx->compo[compno];
-       for(resno = 0; resno < img.Decomposition + 1; resno++)
-         {
-           info_reso_t *reso_Idx = &compo_Idx->reso[resno];
-           for (precno = 0; precno < img.tile[tileno].pw * img.tile[tileno].ph; precno++)
-             {
-               info_prec_t *prec_Idx = &reso_Idx->prec[precno];
-               free(prec_Idx->layer);
-             }
-           free(reso_Idx->prec);
-         }
-       free(compo_Idx->reso);
-      }
-    free(tile_Idx->compo);
-    free(tile_Idx->marker);
-    free(tile_Idx->tile_parts);
-    free(tile_Idx->marker_mul.COC);
-    free(tile_Idx->marker_mul.RGN);
-    free(tile_Idx->marker_mul.QCC);
-    free(tile_Idx->marker_mul.PLT);
-    free(tile_Idx->marker_mul.PPT);
-    free(tile_Idx->marker_mul.COM);
-}
-  free(img.tile);
-  free(img.marker);
-  free(img.marker_mul.COC);
-  free(img.marker_mul.RGN);
-  free(img.marker_mul.QCC);
-  free(img.marker_mul.PLM);
-  free(img.marker_mul.PPM);
-  free(img.marker_mul.COM);
-}
-
-
-
-void j2k_read_soc() {
-  j2k_state=J2K_STATE_MHSIZ;
-}
-
-
-
-void j2k_read_siz() {
-    int len, i;
-    info_tile_t *tile;
-
-    len = cio_read(2);
-
-    /* <INDEX> [MHIX BOX] */
-    img.marker[img.num_marker].type = J2K_MS_SIZ;
-    img.marker[img.num_marker].start_pos = cio_tell()-2;
-    img.marker[img.num_marker].len = len;
-    img.num_marker++;
-    /* </INDEX> [MHIX BOX] */
-    
-    cio_read(2);                      /* Rsiz (capabilities) */
-    j2k_img->x1 = cio_read(4);        /* Xsiz                */
-    j2k_img->y1 = cio_read(4);        /* Ysiz                */
-    j2k_img->x0 = cio_read(4);        /* X0siz               */
-    j2k_img->y0 = cio_read(4);        /* Y0siz               */
-    j2k_cp->tdx = cio_read(4);        /* XTsiz               */
-    j2k_cp->tdy = cio_read(4);        /* YTsiz               */
-    j2k_cp->tx0 = cio_read(4);        /* XT0siz              */
-    j2k_cp->ty0 = cio_read(4);        /* YTOsiz              */
-
-    j2k_img->numcomps = cio_read(2);  /* Csiz                */
-    j2k_img->comps = (j2k_comp_t*)malloc(j2k_img->numcomps * sizeof(j2k_comp_t));
-    for (i = 0; i < j2k_img->numcomps; i++) {
-        int tmp, w, h;
-        tmp = cio_read(1);
-        j2k_img->comps[i].prec = (tmp & 0x7f) + 1;
-        j2k_img->comps[i].sgnd = tmp >> 7;
-        j2k_img->comps[i].dx = cio_read(1);
-        j2k_img->comps[i].dy = cio_read(1);
-        w = int_ceildiv(j2k_img->x1-j2k_img->x0, j2k_img->comps[i].dx);
-        h = int_ceildiv(j2k_img->y1-j2k_img->y0, j2k_img->comps[i].dy);
-        j2k_img->comps[i].data = (int*)malloc(sizeof(int) * w * h);
-    }
-    j2k_cp->tw = int_ceildiv(j2k_img->x1 - j2k_cp->tx0, j2k_cp->tdx);
-    j2k_cp->th = int_ceildiv(j2k_img->y1 - j2k_cp->ty0, j2k_cp->tdy);
-
-    j2k_cp->tcps = (j2k_tcp_t*)calloc((j2k_cp->tw * j2k_cp->th), sizeof(j2k_tcp_t));
-
-    for (i = 0; i < j2k_cp->tw * j2k_cp->th; i++)
-      {
-       j2k_cp->tcps[i].POC = 0;
-       j2k_cp->tcps[i].numpocs = 0;
-       // j2k_cp->tcps[i].first=1;
-      }
-
-    /* Initialization for PPM marker */
-    j2k_cp->ppm = 0;
-    j2k_cp->ppm_data = NULL;
-    j2k_cp->ppm_previous = 0;
-    j2k_cp->ppm_store = 0;
-
-    j2k_default_tcp.tccps = (j2k_tccp_t*)malloc(j2k_img->numcomps * sizeof(j2k_tccp_t));
-    for (i = 0; i < j2k_cp->tw * j2k_cp->th; i++) {
-       j2k_cp->tcps[i].tccps = (j2k_tccp_t*)malloc(j2k_img->numcomps * sizeof(j2k_tccp_t));
-    }
-    j2k_tile_data = (unsigned char**)calloc(j2k_cp->tw * j2k_cp->th, sizeof(char*));
-    j2k_tile_len = (int*)calloc(j2k_cp->tw * j2k_cp->th, sizeof(int));
-    j2k_state = J2K_STATE_MH;
-
-    /* <INDEX> */
-    img.Im_w = j2k_img->x1 - j2k_img->x0;
-    img.Im_h = j2k_img->y1 - j2k_img->y0;
-    img.Tile_x = j2k_cp->tdx;
-    img.Tile_y = j2k_cp->tdy;
-    img.Comp = j2k_img->numcomps;
-    img.tw = j2k_cp->tw;
-    img.th = j2k_cp->th;
-    img.tile = (info_tile_t*)malloc(img.tw * img.th * sizeof(info_tile_t));
-
-    for (i = 0; i < img.tw * img.th; i++)
-      {
-       tile = &img.tile[i];
-       tile->marker = (info_marker_t*)malloc(32 * sizeof(info_marker_t));
-       tile->num_marker = 0;
-       tile->marker_mul.num_COC = 0;
-       tile->marker_mul.CzCOC = START_NB;
-       tile->marker_mul.num_RGN = 0;
-       tile->marker_mul.CzRGN = START_NB;
-       tile->marker_mul.num_QCC = 0;
-       tile->marker_mul.CzQCC = START_NB;
-       tile->marker_mul.num_PLT = 0;
-       tile->marker_mul.CzPLT = START_NB;
-       tile->marker_mul.num_PPT = 0;
-       tile->marker_mul.CzPPT = START_NB;
-       tile->marker_mul.num_COM = 0;
-       tile->marker_mul.CzCOM = START_NB;
-      }
-    /* </INDEX> */
-
-
- }
-
-void j2k_read_com() {
-    int len;
-    info_tile_t *tile;
-    info_marker_t *tmp;
-
-    len = cio_read(2);
-
-    /* <INDEX> [MHIX BOX] */
-    if (j2k_state == J2K_STATE_MH)
-      {
-       if (!img.marker_mul.num_COM) 
-         img.marker_mul.COM = (info_marker_t*)malloc(img.marker_mul.CzCOM * sizeof(info_marker_t));
-       if (img.marker_mul.num_COM >= img.marker_mul.CzCOM)
-         {
-           tmp = (info_marker_t*)malloc(2 * img.marker_mul.CzCOM * sizeof(info_marker_t));
-           memcpy(tmp,img.marker_mul.COM,img.marker_mul.CzCOM);
-           img.marker_mul.CzCOM *= 2;
-           free(img.marker_mul.COM);
-           img.marker_mul.COM = tmp;
-         }
-
-       img.marker_mul.COM[img.marker_mul.num_COM].type = J2K_MS_COM;
-       img.marker_mul.COM[img.marker_mul.num_COM].start_pos = cio_tell()-2;
-       img.marker_mul.COM[img.marker_mul.num_COM].len = len;
-       img.marker_mul.num_COM++;
-      } else
-       {
-         tile = &img.tile[j2k_curtileno];
-         if (!tile->marker_mul.num_COM)
-           tile->marker_mul.COM = (info_marker_t*)calloc(START_NB, sizeof(info_marker_t));
-         if (tile->marker_mul.num_COM >= tile->marker_mul.CzCOM)
-           {
-             tmp = (info_marker_t*)malloc(2 * tile->marker_mul.CzCOM * sizeof(info_marker_t));
-             memcpy(tmp,tile->marker_mul.COM,tile->marker_mul.CzCOM);
-             tile->marker_mul.CzCOM *= 2;
-             free(tile->marker_mul.COM);
-             tile->marker_mul.COM = tmp;
-           }
-         tile->marker_mul.COM[tile->marker_mul.num_COM].type = J2K_MS_COM;
-         tile->marker_mul.COM[tile->marker_mul.num_COM].start_pos = cio_tell()-2;
-         tile->marker_mul.COM[tile->marker_mul.num_COM].len = len;
-         tile->marker_mul.num_COM++;
-       }
-    /* </INDEX> [MHIX BOX] */
-
-    cio_skip(len - 2);
-}
-
-
-
-
-void j2k_read_cox(int compno) {
-    int i;
-    j2k_tcp_t *tcp;
-    j2k_tccp_t *tccp;
-
-    tcp = j2k_state == J2K_STATE_TPH ? &j2k_cp->tcps[j2k_curtileno] : &j2k_default_tcp;
-    tccp = &tcp->tccps[compno];
-    tccp->numresolutions = cio_read(1) + 1;
-
-    img.Decomposition = tccp->numresolutions - 1; /* <INDEX> */
-
-    tccp->cblkw = cio_read(1) + 2;
-    tccp->cblkh = cio_read(1) + 2;
-    tccp->cblksty = cio_read(1);
-    tccp->qmfbid = cio_read(1);
-    if (tccp->csty&J2K_CP_CSTY_PRT) {
-        for (i = 0; i < tccp->numresolutions; i++) {
-            int tmp = cio_read(1);
-            tccp->prcw[i] = tmp&0xf;
-            tccp->prch[i] = tmp>>4; 
-        }
-    }
-}
-
-
-
-
-void j2k_read_cod() {
-    int len, i, pos;
-    j2k_tcp_t *tcp;
-    info_tile_t *tile;
-
-    tcp = j2k_state == J2K_STATE_TPH ? &j2k_cp->tcps[j2k_curtileno] : &j2k_default_tcp;
-    len = cio_read(2);
-
-    /* <INDEX> [MHIX BOX] */
-    if (j2k_state == J2K_STATE_MH)
-      {
-       img.marker[img.num_marker].type = J2K_MS_SIZ;
-       img.marker[img.num_marker].start_pos = cio_tell()-2;
-       img.marker[img.num_marker].len = len;
-       img.num_marker++;
-      }
-    else
-      {
-       tile = &img.tile[j2k_curtileno];
-       tile->marker[tile->num_marker].type = J2K_MS_SIZ;
-       tile->marker[tile->num_marker].start_pos = cio_tell()-2;
-       tile->marker[tile->num_marker].len = len;
-       tile->num_marker++;
-  }
-    /* </INDEX> [MHIX BOX] */
-    
-    tcp->csty = cio_read(1);
-    tcp->prg = cio_read(1);
-    tcp->numlayers = cio_read(2);
-    tcp->mct = cio_read(1);
-
-    pos = cio_tell();
-    for (i = 0; i < j2k_img->numcomps; i++) {
-        tcp->tccps[i].csty = tcp->csty&J2K_CP_CSTY_PRT;
-        cio_seek(pos);
-        j2k_read_cox(i);
-    }
-    
-    /* <INDEX> */
-    img.Prog = tcp->prg;
-    img.Layer = tcp->numlayers;
-    /* </INDEX> */
-}
-
-
-
-
-void j2k_read_coc() {
-    int len, compno;
-    j2k_tcp_t *tcp;
-    info_tile_t *tile;
-    info_marker_t *tmp;
-
-    tcp = j2k_state == J2K_STATE_TPH ? &j2k_cp->tcps[j2k_curtileno] : &j2k_default_tcp;
-    len = cio_read(2);
-    
-    /* <INDEX> [MHIX BOX] */
-    if (j2k_state == J2K_STATE_MH)
-      {
-       if (!img.marker_mul.num_COC)
-         img.marker_mul.COC = (info_marker_t*)malloc(img.marker_mul.CzCOC * sizeof(info_marker_t));
-       if (img.marker_mul.num_COC >= img.marker_mul.CzCOC)
-         {
-           tmp = (info_marker_t*)malloc((INCREMENT + img.marker_mul.CzCOC) * sizeof(info_marker_t));
-           memcpy(tmp,img.marker_mul.COC,img.marker_mul.CzCOC);
-           img.marker_mul.CzCOC += INCREMENT;
-           free(img.marker_mul.COC);
-           img.marker_mul.COC = tmp;
-         }
-       img.marker_mul.COC[img.marker_mul.num_COC].type = J2K_MS_COC;
-       img.marker_mul.COC[img.marker_mul.num_COC].start_pos = cio_tell()-2;
-       img.marker_mul.COC[img.marker_mul.num_COC].len = len;
-       img.marker_mul.num_COC++;
-      } else
-       {
-         tile = &img.tile[j2k_curtileno];
-         if (!tile->marker_mul.num_COC)
-           tile->marker_mul.COC = (info_marker_t*)malloc(tile->marker_mul.CzCOC * sizeof(info_marker_t));
-         if (tile->marker_mul.num_COC >= tile->marker_mul.CzCOC)
-           {
-             tmp = (info_marker_t*)malloc((INCREMENT + tile->marker_mul.CzCOC) * sizeof(info_marker_t));
-             memcpy(tmp,tile->marker_mul.COC,tile->marker_mul.CzCOC);
-             tile->marker_mul.CzCOC += INCREMENT;
-             free(tile->marker_mul.COC);
-             tile->marker_mul.COC = tmp;
-           }
-         tile->marker_mul.COC[tile->marker_mul.num_COC].type = J2K_MS_COC;
-         tile->marker_mul.COC[tile->marker_mul.num_COC].start_pos = cio_tell() - 2;
-         tile->marker_mul.COC[tile->marker_mul.num_COC].len = len;
-         tile->marker_mul.num_COC++;
-       }
-    /* </INDEX> [MHIX BOX] */
-    
-    compno =cio_read(j2k_img->numcomps <= 256 ? 1 : 2);
-
-    tcp->tccps[compno].csty = cio_read(1);
-    j2k_read_cox(compno);
-}
-
-
-
-
-void j2k_read_qcx(int compno, int len) {
-    int tmp;
-    j2k_tcp_t *tcp;
-    j2k_tccp_t *tccp;
-    int bandno, numbands;
-
-    tcp = j2k_state == J2K_STATE_TPH ? &j2k_cp->tcps[j2k_curtileno] : &j2k_default_tcp;
-    tccp = &tcp->tccps[compno];
-    tmp = cio_read(1);
-    tccp->qntsty = tmp & 0x1f;
-    tccp->numgbits = tmp >> 5;
-    numbands = tccp->qntsty == J2K_CCP_QNTSTY_SIQNT ? 1 : (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT ? len - 1 : (len - 1) / 2);
-    for (bandno = 0; bandno < numbands; bandno++) {
-        int expn, mant;
-        if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) { /* WHY STEPSIZES WHEN NOQNT ? */
-            expn = cio_read(1) >> 3;
-            mant = 0;
-        } else {
-            tmp = cio_read(2);
-            expn = tmp >> 11;
-            mant = tmp & 0x7ff;
-        }
-        tccp->stepsizes[bandno].expn = expn;
-        tccp->stepsizes[bandno].mant = mant;
-    }
-}
-
-
-
-
-void j2k_read_qcd() {
-    int len, i, pos;
-    info_tile_t *tile;
-
-    len = cio_read(2);    
-
-    /* <INDEX> [MHIX BOX] */
-    if (j2k_state == J2K_STATE_MH)
-      {
-       img.marker[img.num_marker].type = J2K_MS_QCD;
-       img.marker[img.num_marker].start_pos = cio_tell()-2;
-       img.marker[img.num_marker].len = len;
-       img.num_marker++;
-      }         else
-       {
-         tile = &img.tile[j2k_curtileno];
-         tile->marker[tile->num_marker].type = J2K_MS_QCD;
-         tile->marker[tile->num_marker].start_pos = cio_tell()-2;
-         tile->marker[tile->num_marker].len = len;
-         tile->num_marker++;
-       }
-    /* </INDEX> [MHIX BOX] */
-    
-    
-    pos=cio_tell();
-    for (i = 0; i < j2k_img->numcomps; i++) {
-        cio_seek(pos);
-        j2k_read_qcx(i, len - 2);
-    }
-}
-
-
-
-
-void j2k_read_qcc() {
-  int len, compno;
-  info_tile_t *tile;
-  info_marker_t *tmp;
-
-  len = cio_read(2);  
-  /* <INDEX> [MHIX BOX] */
-  if (j2k_state == J2K_STATE_MH)
-    {
-      if (!img.marker_mul.num_QCC)
-       img.marker_mul.QCC = (info_marker_t*)malloc(img.marker_mul.CzQCC * sizeof(info_marker_t));
-       if (img.marker_mul.num_QCC >= img.marker_mul.CzQCC)
-         {
-           tmp = (info_marker_t*)malloc((INCREMENT + img.marker_mul.CzQCC) * sizeof(info_marker_t));
-           memcpy(tmp,img.marker_mul.QCC,img.marker_mul.CzQCC);
-           img.marker_mul.CzQCC += INCREMENT;
-           free(img.marker_mul.QCC);
-           img.marker_mul.QCC = tmp;
-         }
-      img.marker_mul.QCC[img.marker_mul.num_QCC].type = J2K_MS_QCC;
-      img.marker_mul.QCC[img.marker_mul.num_QCC].start_pos = cio_tell() - 2;
-      img.marker_mul.QCC[img.marker_mul.num_QCC].len = len;
-      img.marker_mul.num_QCC++;
-    } else
-      {
-       tile = &img.tile[j2k_curtileno];
-       if (!tile->marker_mul.num_QCC)
-         tile->marker_mul.QCC = (info_marker_t*)malloc(tile->marker_mul.CzQCC * sizeof(info_marker_t));
-       if (tile->marker_mul.num_QCC >= tile->marker_mul.CzQCC)
-         {
-           tmp = (info_marker_t*)malloc((INCREMENT + tile->marker_mul.CzQCC) * sizeof(info_marker_t));
-           memcpy(tmp,tile->marker_mul.QCC,tile->marker_mul.CzQCC);
-           tile->marker_mul.CzQCC += INCREMENT;
-           free(tile->marker_mul.QCC);
-           tile->marker_mul.QCC = tmp;
-         }
-       tile->marker_mul.QCC[tile->marker_mul.num_QCC].type = J2K_MS_QCC;
-       tile->marker_mul.QCC[tile->marker_mul.num_QCC].start_pos = cio_tell()-2;
-       tile->marker_mul.QCC[tile->marker_mul.num_QCC].len = len;
-       tile->marker_mul.num_QCC++;
-      }
-  /* </INDEX> [MHIX BOX] */
-  compno = cio_read(j2k_img->numcomps <= 256 ? 1 : 2);
-  j2k_read_qcx(compno, len - 2 - (j2k_img->numcomps <= 256 ? 1 : 2));
-}
-
-
-
-
-void j2k_read_poc() {
-  int len, numpchgs, i, old_poc;
-  j2k_tcp_t *tcp;
-  j2k_tccp_t *tccp;
-  info_tile_t *tile;
-
-  tcp = j2k_state == J2K_STATE_TPH ? &j2k_cp->tcps[j2k_curtileno] : &j2k_default_tcp;
-  old_poc = tcp->POC ? tcp->numpocs+1 : 0;
-  tcp->POC = 1;
-  tccp = &tcp->tccps[0];
-  len = cio_read(2);
-  
-  /* <INDEX> [MHIX BOX] */
-  if (j2k_state == J2K_STATE_MH)
-    {
-      img.marker[img.num_marker].type = J2K_MS_POC;
-      img.marker[img.num_marker].start_pos = cio_tell()-2;
-      img.marker[img.num_marker].len = len;
-      img.num_marker++;
-    } else
-      {
-       tile = &img.tile[j2k_curtileno];
-       tile->marker[tile->num_marker].type = J2K_MS_POC;
-       tile->marker[tile->num_marker].start_pos = cio_tell()-2;
-       tile->marker[tile->num_marker].len = len;
-       tile->num_marker++;
-      }
-  /* </INDEX> [MHIX BOX] */
-
-    numpchgs = (len - 2) / (5 + 2 * (j2k_img->numcomps <= 256 ? 1 : 2));
-    for (i = 0; i < numpchgs; i++) {
-      j2k_poc_t *poc;
-      poc = &tcp->pocs[i];
-      poc->resno0 = cio_read(1);
-      poc->compno0 = cio_read(j2k_img->numcomps <= 256 ? 1 : 2);
-      poc->layno1 = int_min(cio_read(2), tcp->numlayers);
-      poc->resno1 = int_min(cio_read(1), tccp->numresolutions);
-      poc->compno1 = int_min(cio_read(j2k_img->numcomps <= 256 ? 1 : 2), j2k_img->numcomps);
-      poc->prg = cio_read(1);
-    }
-
-    tcp->numpocs = numpchgs + old_poc - 1;
-}
-
-
-
-
-void j2k_read_crg() {
-    int len, i, Xcrg_i, Ycrg_i;
-
-    len = cio_read(2);
-
-    /* <INDEX> [MHIX BOX] */
-    img.marker[img.num_marker].type = J2K_MS_CRG;
-    img.marker[img.num_marker].start_pos = cio_tell()-2;
-    img.marker[img.num_marker].len = len;
-    img.num_marker++;
-    /* </INDEX> [MHIX BOX] */
-
-    for (i = 0; i < j2k_img->numcomps; i++)
-      {  
-       Xcrg_i = cio_read(2);
-       Ycrg_i = cio_read(2);
-      }
-}
-
-
-
-
-void j2k_read_tlm() {
-    int len, Ztlm, Stlm, ST, SP, tile_tlm, i;
-    long int Ttlm_i, Ptlm_i;
-    info_marker_t *tmp;
-
-    len = cio_read(2);
-
-    /* <INDEX> [MHIX BOX] */
-    if (!img.marker_mul.num_TLM)
-      img.marker_mul.TLM = (info_marker_t*)malloc(img.marker_mul.CzTLM * sizeof(info_marker_t));
-    if (img.marker_mul.num_TLM >= img.marker_mul.CzTLM)
-      {
-       tmp = (info_marker_t*)malloc((INCREMENT + img.marker_mul.CzTLM) * sizeof(info_marker_t));
-       memcpy(tmp,img.marker_mul.TLM,img.marker_mul.CzTLM);
-       img.marker_mul.CzTLM += INCREMENT;
-       free(img.marker_mul.TLM);
-       img.marker_mul.TLM = tmp;
-      }
-    img.marker_mul.TLM[img.marker_mul.num_TLM].type = J2K_MS_TLM;
-    img.marker_mul.TLM[img.marker_mul.num_TLM].start_pos = cio_tell()-2;
-    img.marker_mul.TLM[img.marker_mul.num_TLM].len = len;
-    img.marker_mul.num_TLM++;
-    /* </INDEX> [MHIX BOX] */
-    
-    Ztlm = cio_read(1);
-    Stlm = cio_read(1);
-    ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
-    SP = (Stlm >> 6) & 0x01;
-    tile_tlm = (len - 4) / ((SP + 1) * 2 + ST);
-    for (i = 0; i < tile_tlm; i++)
-      {
-       Ttlm_i = cio_read(ST);
-       Ptlm_i = cio_read(SP ? 4 : 2);
-      }
-}
-
-
-
-
-void j2k_read_plm() {
-    int len, i, Z_plm, N_plm, add, packet_len=0;
-    info_marker_t *tmp;
-
-    len=cio_read(2);
-
-    /* <INDEX> [MHIX BOX] */
-    if (!img.marker_mul.num_PLM)
-      img.marker_mul.PLM = (info_marker_t*)malloc(img.marker_mul.CzPLM * sizeof(info_marker_t));
-    if (img.marker_mul.num_PLM >= img.marker_mul.CzPLM)
-      {
-       tmp = (info_marker_t*)malloc((INCREMENT + img.marker_mul.CzPLM) * sizeof(info_marker_t));
-       memcpy(tmp,img.marker_mul.PLM,img.marker_mul.CzPLM);
-       img.marker_mul.CzPLM += INCREMENT;
-       free(img.marker_mul.PLM);
-       img.marker_mul.PLM = tmp;
-      }
-    img.marker_mul.PLM[img.marker_mul.num_PLM].type = J2K_MS_PLM;
-    img.marker_mul.PLM[img.marker_mul.num_PLM].start_pos = cio_tell()-2;
-    img.marker_mul.PLM[img.marker_mul.num_PLM].len = len;
-    img.marker_mul.num_PLM++;
-    /* </INDEX> [MHIX BOX] */
-
-    Z_plm = cio_read(1);
-    len -= 3;
-    while (len > 0)
-      {
-       N_plm = cio_read(4);
-       len -= 4;
-       for (i = N_plm ; i > 0 ; i--)
-         {
-           add = cio_read(1);
-           len--;
-           packet_len = (packet_len << 7) + add;
-           if ((add & 0x80) == 0)
-             {
-               /* New packet */
-               packet_len = 0;
-             }
-           if (len <= 0) break;
-         } 
-      }
-}
-
-
-
-
-void j2k_read_plt() {
-    int len, i, Zplt, packet_len=0, add;
-    info_tile_t *tile;
-    info_marker_t *tmp;
-;
-    len = cio_read(2);
-    /* <INDEX> [MHIX BOX] */
-    tile = &img.tile[j2k_curtileno];
-    if (!tile->marker_mul.num_PLT)
-      tile->marker_mul.PLT = (info_marker_t*)malloc(tile->marker_mul.CzPLT * sizeof(info_marker_t));
-    if (tile->marker_mul.num_PLT >= tile->marker_mul.CzPLT)
-      {
-       tmp = (info_marker_t*)malloc((INCREMENT + tile->marker_mul.CzPLT) * sizeof(info_marker_t));
-       memcpy(tmp,tile->marker_mul.PLT,tile->marker_mul.CzPLT);
-       tile->marker_mul.CzPLT += INCREMENT;
-       free(tile->marker_mul.PLT);
-       tile->marker_mul.PLT = tmp;
-      }
-
-    tile->marker_mul.PLT[tile->marker_mul.num_PLT].type = J2K_MS_PLT;
-    tile->marker_mul.PLT[tile->marker_mul.num_PLT].start_pos = cio_tell()-2;
-    tile->marker_mul.PLT[tile->marker_mul.num_PLT].len = len;
-    tile->marker_mul.num_PLT++;
-    /* </INDEX> [MHIX BOX] */
-    
-    Zplt = cio_read(1);
-    for (i = len-3; i > 0; i--)
-      {
-       add = cio_read(1);
-       packet_len = (packet_len << 7) + add;
-       if ((add & 0x80) == 0)
-         {
-           /* New packet */
-           packet_len = 0;
-         }
-      }
-}
-
-
-
-
-void j2k_read_ppm() {
-    int len, Z_ppm, i, j;
-    int N_ppm;
-    info_marker_t *tmp;
-
-    len = cio_read(2);
-    
-    /* <INDEX> [MHIX BOX] */
-    if (!img.marker_mul.num_PPM)
-      img.marker_mul.PPM = (info_marker_t*)malloc(img.marker_mul.CzPPM * sizeof(info_marker_t));
-    if (img.marker_mul.num_PPM >= img.marker_mul.CzPPM)
-      {
-       tmp = (info_marker_t*)malloc((INCREMENT + img.marker_mul.CzPPM) * sizeof(info_marker_t));
-       memcpy(tmp,img.marker_mul.PPM,img.marker_mul.CzPPM);
-       img.marker_mul.CzPPM += INCREMENT;
-       free(img.marker_mul.PPM);
-       img.marker_mul.PPM = tmp;
-      }
-    img.marker_mul.PLM[img.marker_mul.num_PPM].type = J2K_MS_PPM;
-    img.marker_mul.PLM[img.marker_mul.num_PPM].start_pos = cio_tell()-2;
-    img.marker_mul.PLM[img.marker_mul.num_PPM].len = len;
-    img.marker_mul.num_PPM++;
-    /* </INDEX> [MHIX BOX] */
-    
-    j2k_cp->ppm = 1;
-    
-    Z_ppm = cio_read(1); /* Z_ppm */
-    len -= 3;
-    while (len > 0)
-      {
-       if (j2k_cp->ppm_previous == 0)
-         {
-           N_ppm = cio_read(4); /* N_ppm */
-           len -= 4;
-         } else
-           {
-             N_ppm = j2k_cp->ppm_previous;
-           }
-       
-       j = j2k_cp->ppm_store;
-       if (Z_ppm == 0) /* First PPM marker */
-         j2k_cp->ppm_data = (unsigned char*)calloc(N_ppm, sizeof(unsigned char));
-       else      /* NON-first PPM marker */
-         j2k_cp->ppm_data = (unsigned char*)realloc(j2k_cp->ppm_data, (N_ppm + j2k_cp->ppm_store) * sizeof(unsigned char));
-       
-       for (i = N_ppm ; i > 0 ; i--) /* Read packet header */
-         {
-           j2k_cp->ppm_data[j] = cio_read(1);
-           j++;
-           len--;
-           if (len == 0) break; /* Case of non-finished packet header in present marker but finished in next one */
-         }
-       
-       j2k_cp->ppm_previous = i - 1;
-       j2k_cp->ppm_store = j;
-      }
-}
-
-
-
-
-void j2k_read_ppt() {
-    int len, Z_ppt, i, j = 0;
-    j2k_tcp_t *tcp;
-    info_tile_t *tile;
-    len=cio_read(2);
-
-    /* <INDEX> [MHIX BOX] */
-    tile = & img.tile[j2k_curtileno];
-    tile->marker[tile->num_marker].type = J2K_MS_PPT;
-    tile->marker[tile->num_marker].start_pos = cio_tell()-2;
-    tile->marker[tile->num_marker].len = len;
-    tile->num_marker++;
-    /* </INDEX> [MHIX BOX] */
-
-    Z_ppt = cio_read(1);
-    tcp = &j2k_cp->tcps[j2k_curtileno];
-    tcp->ppt = 1;
-    if (Z_ppt == 0) /* First PPT marker */
-      {
-       tcp->ppt_data = (unsigned char*)calloc(len - 3, sizeof(unsigned char));
-       tcp->ppt_store = 0;
-      }
-    else      /* NON-first PPT marker */
-      tcp->ppt_data = (unsigned char*)realloc(tcp->ppt_data, (len - 3 + tcp->ppt_store) * sizeof(unsigned char));
-    
-    j = tcp->ppt_store;
-    for (i = len - 3 ; i > 0 ; i--)
-      {
-       tcp->ppt_data[j] = cio_read(1);
-       j++;
-      }
-    tcp->ppt_store = j;
-}
-
-
-
-
-void j2k_read_sot() {
-    int len, tileno, totlen, partno, numparts, i;
-    j2k_tcp_t *tcp;
-    j2k_tccp_t *tmp;
-    info_tile_t *tile;
-    info_tile_part_t *tilepart_tmp;
-    
-    //fprintf(stderr,"SOT\n");
-    len = cio_read(2);
-    tileno = cio_read(2);
-    /* <INDEX> [MHIX BOX] */
-    tile = & img.tile[tileno];
-    tile->marker[tile->num_marker].type = J2K_MS_SOT;
-    tile->marker[tile->num_marker].start_pos = cio_tell() - 4;
-    tile->marker[tile->num_marker].len = len;
-    tile->num_marker++;
-    /* </INDEX> [MHIX BOX] */
-    totlen = cio_read(4);
-    if (!totlen) totlen = cio_numbytesleft() + 8;
-    partno = cio_read(1);
-    numparts = cio_read(1);
-
-    /* <INDEX> */
-    if (tileno == 0 && partno == 0 ) 
-      img.Main_head_end = cio_tell() - 7;  /* Correction End = First byte of first SOT */
-    
-    img.tile[tileno].num_tile = tileno;
-    /* </INDEX> */
-  
-    tile->numparts = partno + 1;                                               /* INDEX : Number of tile_parts for the tile */ 
-    img.num_max_tile_parts = int_max(tile->numparts, img.num_max_tile_parts);  /* INDEX : Maximum number of tile_part per tile */
-
-    if (partno == 0)
-    {
-      tile->tile_parts = (info_tile_part_t*)malloc(START_NB * sizeof(info_tile_part_t*));
-      tile->Cztile_parts = START_NB;
-    }
-    if (partno >= tile->Cztile_parts)
-      {
-       tilepart_tmp = (info_tile_part_t*)malloc((INCREMENT + tile->Cztile_parts) * sizeof(info_tile_part_t));
-       memcpy(tilepart_tmp, tile->tile_parts, tile->Cztile_parts);
-       tile->Cztile_parts += INCREMENT;
-       free(tile->tile_parts);
-       tile->tile_parts = tilepart_tmp;
-      }
-
-    tile->tile_parts[partno].start_pos = cio_tell() - 12;        /* INDEX : start_pos of the tile_part       */
-    tile->tile_parts[partno].length = totlen;                    /* INDEX : length of the tile_part          */  
-    tile->tile_parts[partno].end_pos = totlen + cio_tell() - 12; /* INDEX : end position of the tile_part    */
-
-
-    j2k_curtileno = tileno;
-    j2k_eot = cio_getbp() - 12 + totlen;
-    j2k_state = J2K_STATE_TPH;
-    tcp = &j2k_cp->tcps[j2k_curtileno];
-    
-    tile->tile_parts[numparts].num_reso_AUX = tcp->tccps[0].numresolutions; /* INDEX : AUX value for TPIX       */
-
-     if (partno == 0)
-       //  if (tcp->first == 1) 
-      {
-       tmp = tcp->tccps;
-       *tcp = j2k_default_tcp;
-       /* Initialization PPT */
-       tcp->ppt = 0; 
-       tcp->ppt_data = NULL;
-       
-       tcp->tccps = tmp;
-       for (i = 0; i < j2k_img->numcomps; i++) {
-         tcp->tccps[i] = j2k_default_tcp.tccps[i];
-       }
-       //j2k_cp->tcps[j2k_curtileno].first=0;
-      }
-}
-
-
-
-void j2k_read_rgn() {
-    int len, compno, roisty;
-    j2k_tcp_t *tcp;
-    info_tile_t *tile;
-    info_marker_t *tmp;
-    // fprintf(stderr,"RGN\n");
-    tcp = j2k_state == J2K_STATE_TPH ? &j2k_cp->tcps[j2k_curtileno] : &j2k_default_tcp;
-    len = cio_read(2);
-    
-    /* <INDEX> [MHIX BOX]*/
-    if (j2k_state == J2K_STATE_MH)
-      {
-       if (!img.marker_mul.num_RGN)
-         img.marker_mul.RGN = (info_marker_t*)malloc(img.marker_mul.CzRGN * sizeof(info_marker_t));
-       if (img.marker_mul.num_RGN >= img.marker_mul.CzRGN)
-         {
-           tmp = (info_marker_t*)malloc((INCREMENT + img.marker_mul.CzRGN) * sizeof(info_marker_t));
-           memcpy(tmp,img.marker_mul.RGN, img.marker_mul.CzRGN);
-           img.marker_mul.CzRGN += INCREMENT;
-           free(img.marker_mul.RGN);
-           img.marker_mul.RGN = tmp;
-         }
-       img.marker_mul.RGN[img.marker_mul.num_RGN].type = J2K_MS_RGN;
-       img.marker_mul.RGN[img.marker_mul.num_RGN].start_pos = cio_tell() - 2;
-       img.marker_mul.RGN[img.marker_mul.num_RGN].len = len;
-       img.marker_mul.num_RGN++;
-      } else
-      {
-       tile = &img.tile[j2k_curtileno];
-       if (!tile->marker_mul.num_RGN)
-         tile->marker_mul.RGN = (info_marker_t*)malloc(tile->marker_mul.CzRGN * sizeof(info_marker_t));
-       if (tile->marker_mul.num_RGN >= tile->marker_mul.CzRGN)
-         {
-           tmp = (info_marker_t*)malloc((INCREMENT + tile->marker_mul.CzRGN) * sizeof(info_marker_t));
-           memcpy(tmp,tile->marker_mul.RGN,tile->marker_mul.CzRGN);
-           tile->marker_mul.CzRGN += INCREMENT;
-           free(tile->marker_mul.RGN);
-           tile->marker_mul.RGN = tmp;
-         }
-
-       tile->marker_mul.RGN[tile->marker_mul.num_RGN].type = J2K_MS_RGN;
-       tile->marker_mul.RGN[tile->marker_mul.num_RGN].start_pos = cio_tell() - 2;
-        tile->marker_mul.RGN[tile->marker_mul.num_RGN].len = len;
-       tile->marker_mul.num_RGN++;
-      }
-    /* </INDEX> [MHIX BOX] */
-    
-    compno = cio_read(j2k_img->numcomps <= 256 ? 1 : 2);
-    roisty = cio_read(1);
-    tcp->tccps[compno].roishift = cio_read(1);
-}
-
-
-
-
-
-void j2k_read_sod() {
-    int len;
-    unsigned char *data;
-    info_tile_t *tile;
-    info_tile_part_t *tile_part;
-    // fprintf(stderr,"SOD\n");
-    /* <INDEX> [MHIX BOX] */
-    tile = &img.tile[j2k_curtileno];
-    tile->marker[tile->num_marker].type = J2K_MS_SOD;
-    tile->marker[tile->num_marker].start_pos = cio_tell();
-    tile->marker[tile->num_marker].len = 0;
-    tile->num_marker++;
-    /* </INDEX> [MHIX BOX] */
-
-    tile_part = &tile->tile_parts[tile->numparts - 1];                   /* INDEX : Current tilepart of a tile                  */
-    tile_part->length_header = cio_tell() - 1 - tile_part->start_pos;    /* INDEX : length of the tile-part header              */
-    tile_part->end_header = cio_tell() - 1;                              /* INDEX : end header position of the tile-part header */
-
-    len = int_min(j2k_eot - cio_getbp(), cio_numbytesleft());
-    
-    j2k_tile_len[j2k_curtileno] += len;
-    data = (unsigned char*)realloc(j2k_tile_data[j2k_curtileno], j2k_tile_len[j2k_curtileno]);   
-    memcpy(data, cio_getbp(), len);
-    j2k_tile_data[j2k_curtileno] = data;
-    cio_skip(len);
-    j2k_state = J2K_STATE_TPHSOT;
-}
-
-void j2k_read_eoc() {
-    int tileno;
-    tcd_init(j2k_img, j2k_cp, &img);
-    for (tileno = 0; tileno<j2k_cp->tw * j2k_cp->th; tileno++) {
-        tcd_decode_tile(j2k_tile_data[tileno], j2k_tile_len[tileno], tileno, &img);
-    }
-
-    j2k_state = J2K_STATE_MT;
-     longjmp(j2k_error, 1);
-}
-
-
-
-
-void j2k_read_unk() {
-    fprintf(stderr, "warning: unknown marker\n");
-}
-
-
-
-
-int j2k_index_JPIP(char *Idx_file, char *J2K_file, int len, int version){
-  FILE *dest;
-  unsigned char *index;
-  int pos_iptr, end_pos;
-  int len_cidx, pos_cidx;
-  int len_jp2c, pos_jp2c;
-  int len_fidx, pos_fidx;
-
-  dest=fopen(Idx_file, "wb");
-  if (!dest) {
-    fprintf(stderr, "Failed to open %s for reading !!\n", Idx_file);
-    return 0;
-  }
-
-  /* INDEX MODE JPIP */
- index = (unsigned char*)malloc(len); 
- cio_init(index, len);
- jp2_write_jp();
- jp2_write_ftyp();
- jp2_write_jp2h(j2k_img);
- jp2_write_dbtl(Idx_file);
-
- pos_iptr=cio_tell();
- cio_skip(24); /* IPTR further ! */
- pos_jp2c = cio_tell();
- len_jp2c = jp2_write_jp2c(J2K_file);
-
- pos_cidx = cio_tell();
- len_cidx = jpip_write_cidx(pos_jp2c + 8,img, j2k_cp, version); /* Correction len_jp2C --> pos_jp2c + 8 */  
-
- pos_fidx = cio_tell();
- len_fidx = jpip_write_fidx(pos_jp2c, len_jp2c, pos_cidx, len_cidx);
-
-end_pos = cio_tell();
-
- cio_seek(pos_iptr);
- jpip_write_iptr(pos_fidx,len_fidx);
- cio_seek(end_pos);
- fwrite(index, 1, cio_tell(), dest);
- free(index);
-
- fclose(dest);
- return 1;
-}
-
-
-
-typedef struct {
-  int id;
-    int states;
-    void (*handler)();
-} j2k_dec_mstabent_t;
-
-j2k_dec_mstabent_t j2k_dec_mstab[]={
-    {J2K_MS_SOC, J2K_STATE_MHSOC, j2k_read_soc},
-    {J2K_MS_SOT, J2K_STATE_MH|J2K_STATE_TPHSOT, j2k_read_sot},
-    {J2K_MS_SOD, J2K_STATE_TPH, j2k_read_sod},
-    {J2K_MS_EOC, J2K_STATE_TPHSOT, j2k_read_eoc},
-    {J2K_MS_SIZ, J2K_STATE_MHSIZ, j2k_read_siz},
-    {J2K_MS_COD, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_cod},
-    {J2K_MS_COC, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_coc},
-    {J2K_MS_RGN, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_rgn},
-    {J2K_MS_QCD, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_qcd},
-    {J2K_MS_QCC, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_qcc},
-    {J2K_MS_POC, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_poc},
-    {J2K_MS_TLM, J2K_STATE_MH, j2k_read_tlm},
-    {J2K_MS_PLM, J2K_STATE_MH, j2k_read_plm},
-    {J2K_MS_PLT, J2K_STATE_TPH, j2k_read_plt},
-    {J2K_MS_PPM, J2K_STATE_MH, j2k_read_ppm},
-    {J2K_MS_PPT, J2K_STATE_TPH, j2k_read_ppt},
-    {J2K_MS_SOP, 0, 0},
-    {J2K_MS_CRG, J2K_STATE_MH, j2k_read_crg},
-    {J2K_MS_COM, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_com},
-    {0, J2K_STATE_MH|J2K_STATE_TPH, j2k_read_unk}
-};
-
-j2k_dec_mstabent_t *j2k_dec_mstab_lookup(int id) {
-  j2k_dec_mstabent_t *e;
-  for (e = j2k_dec_mstab; e->id != 0; e++) {
-    if (e->id == id) {
-      break;
-    }
-  }
-  return e;
-}
-
-int j2k_decode(unsigned char *src, int len, j2k_image_t **image, j2k_cp_t **cp) {
-    if (setjmp(j2k_error)) {
-        if (j2k_state != J2K_STATE_MT) {
-            fprintf(stderr, "WARNING: incomplete bitstream\n");
-            return 0;
-        }
-        return cio_numbytes();
-    }
-    j2k_img = (j2k_image_t*)calloc(1, sizeof(j2k_image_t));
-    j2k_cp = (j2k_cp_t*)calloc(1, sizeof(j2k_cp_t));
-    *image = j2k_img;
-    *cp = j2k_cp;
-    j2k_state = J2K_STATE_MHSOC;
-    cio_init(src, len);
-    for (;;) {
-        j2k_dec_mstabent_t *e;
-        int id = cio_read(2);
-        if (id >> 8 != 0xff) {
-            fprintf(stderr, "%.8x: expected a marker instead of %x\n", cio_tell() - 2, id);
-            return 0;
-        }
-        e = j2k_dec_mstab_lookup(id);
-        if (!(j2k_state & e->states)) {
-            fprintf(stderr, "%.8x: unexpected marker %x\n", cio_tell() - 2, id);
-            return 0;
-        }
-        if (e->handler) {
-            (*e->handler)();
-        }
-    }
-
-}
-
-
-#ifdef _WIN32
-#include <windows.h>
-
-BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
-    switch (ul_reason_for_call) {
-               case DLL_PROCESS_ATTACH:
-               case DLL_THREAD_ATTACH:
-               case DLL_THREAD_DETACH:
-               case DLL_PROCESS_DETACH:
-                       break;
-    }
-    return TRUE;
-}
-#endif /* _WIN32 */
-
-int main(int argc, char **argv)
-{  
-  FILE *src;
-  int totlen;
-  unsigned char *j2kfile;
-  j2k_image_t *imgg;
-  j2k_cp_t *cp;
-  int version;
-
-  if (argc != 4)
-    {
-      fprintf(stderr,"\nUSAGE : ./index_create J2K-file JP2-file version\n\nVersion : 0, 1, 2 or 3\n  0 : [faix] 4-byte and no AUX fields\n  1 : [faix] 8-byte and no AUX fields\n  2 : [faix] 4-byte and AUX fields\n  3 : [faix] 8-byte and AUX fields\n\nReference Document : annex I from JPIP-FCD-version 2 (SC 29 N5727)\n\n");
-      return 1;
-    }
-
-  src=fopen(argv[1], "rb");
-  if (!src) {
-    fprintf(stderr, "Failed to open %s for reading !!\n", argv[1]);
-    return 1;
-  }
-
-  /* length of the codestream */
-  fseek(src, 0, SEEK_END);
-  totlen = ftell(src);
-  fseek(src, 0, SEEK_SET);
-  
-  j2kfile = (unsigned char*)malloc(totlen);
-  fread(j2kfile, 1, totlen, src);
-  fclose(src);
-
-  img.marker = (info_marker_t*)malloc(32 * sizeof(info_marker_t));
-  img.num_marker = 0;
-  img.num_max_tile_parts = 0;
-  img.marker_mul.num_COC = 0;
-  img.marker_mul.CzCOC = START_NB;
-  img.marker_mul.num_RGN = 0;
-  img.marker_mul.CzRGN = START_NB;
-  img.marker_mul.num_QCC = 0;
-  img.marker_mul.CzQCC = START_NB;
-  img.marker_mul.num_TLM = 0;
-  img.marker_mul.CzTLM = START_NB;
-  img.marker_mul.num_PLM = 0;
-  img.marker_mul.CzPLM = START_NB;
-  img.marker_mul.num_PPM = 0;
-  img.marker_mul.CzPPM = START_NB;
-  img.marker_mul.num_COM = 0;
-  img.marker_mul.CzCOM = START_NB;
-
-  /* decode */ 
-
-  if (!j2k_decode(j2kfile, totlen, &imgg, &cp)) {
-    fprintf(stderr, "Index_creator: failed to decode image!\n");
-    free(j2kfile);
-    return 1;
-  }
-  free(j2kfile);
-  
-  // fseek(src, 0, SEEK_SET);
-  img.codestream_size = totlen;
-  sscanf(argv[3], "%d", &version);
-  if (version > 3)
-    {
-      fprintf(stderr,"Error : value of version unauthorized !!  Value accepted : 0, 1, 2 or 3 !!\n");
-      return 0;
-    }
-
-  j2k_index_JPIP(argv[2], argv[1], totlen * 2 > 60000 ? totlen * 2 : 60000, version);
-  
-  j2k_clean();
-  return 0;
-}
diff --git a/indexer_JPIP/int.c b/indexer_JPIP/int.c
deleted file mode 100644 (file)
index 29f778c..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-/// <summary>
-/// Get the minimum of two integers.
-/// </summary>
-int int_min(int a, int b) {
-    return a<b?a:b;
-}
-
-/// <summary>
-/// Get the maximum of two integers.
-/// </summary>
-int int_max(int a, int b) {
-    return a>b?a:b;
-}
-
-/// <summary>
-/// Clamp an integer inside an interval.
-/// </summary>
-int int_clamp(int a, int min, int max) {
-    if (a<min) return min;
-    if (a>max) return max;
-    return a;
-}
-
-/// <summary>
-/// Get absolute value of integer.
-/// </summary>
-int int_abs(int a) {
-    return a<0?-a:a;
-}
-
-/// <summary>
-/// Divide an integer and round upwards.
-/// </summary>
-int int_ceildiv(int a, int b) {
-    return (a+b-1)/b;
-}
-
-/// <summary>
-/// Divide an integer by a power of 2 and round upwards.
-/// </summary>
-int int_ceildivpow2(int a, int b) {
-    return (a+(1<<b)-1)>>b;
-}
-
-/// <summary>
-/// Divide an integer by a power of 2 and round downwards.
-/// </summary>
-int int_floordivpow2(int a, int b) {
-    return a>>b;
-}
-
-/// <summary>
-/// Get logarithm of an integer and round downwards.
-/// </summary>
-int int_floorlog2(int a) {
-    int l;
-    for (l=0; a>1; l++) {
-        a>>=1;
-    }
-    return l;
-}
diff --git a/indexer_JPIP/int.h b/indexer_JPIP/int.h
deleted file mode 100644 (file)
index 4921ff4..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __INT_H
-#define __INT_H
-
-int int_min(int a, int b);
-int int_max(int a, int b);
-int int_clamp(int a, int min, int max);
-int int_abs(int a);
-int int_ceildiv(int a, int b);
-int int_ceildivpow2(int a, int b);
-int int_floordivpow2(int a, int b);
-int int_floorlog2(int a);
-
-#endif
diff --git a/indexer_JPIP/j2k.h b/indexer_JPIP/j2k.h
deleted file mode 100644 (file)
index 6c9a3c6..0000000
+++ /dev/null
@@ -1,288 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003-2004, Yannick Verschueren
- * Copyright (c) 2003-2004, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved. 
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#define VERSION "0.0.8"
-
-#ifdef _WIN32
-#ifdef LIBJ2K_EXPORTS
-#define LIBJ2K_API __declspec(dllexport)
-#else
-#define LIBJ2K_API __declspec(dllimport)
-#endif
-#else
-#define LIBJ2K_API
-#endif
-
-#ifndef __J2K_H
-#define __J2K_H
-
-#define J2K_MAXRLVLS 33
-#define J2K_MAXBANDS (3*J2K_MAXRLVLS+1)
-
-#define J2K_CP_CSTY_PRT 0x01
-#define J2K_CP_CSTY_SOP 0x02
-#define J2K_CP_CSTY_EPH 0x04
-#define J2K_CCP_CSTY_PRT 0x01
-#define J2K_CCP_CBLKSTY_LAZY 0x01
-#define J2K_CCP_CBLKSTY_RESET 0x02
-#define J2K_CCP_CBLKSTY_TERMALL 0x04
-#define J2K_CCP_CBLKSTY_VSC 0x08
-#define J2K_CCP_CBLKSTY_PTERM 0x10
-#define J2K_CCP_CBLKSTY_SEGSYM 0x20
-#define J2K_CCP_QNTSTY_NOQNT 0
-#define J2K_CCP_QNTSTY_SIQNT 1
-#define J2K_CCP_QNTSTY_SEQNT 2
-
-typedef struct 
-{
-  int dx, dy;   /* XRsiz, YRsiz            */
-  int prec;     /* precision               */
-  int bpp;      /* deapth of image in bits */
-  int sgnd;     /* signed                  */
-  int *data;    /* image-component data    */
-} j2k_comp_t;
-
-typedef struct {
-  int version;
-  int x0, y0;          /* XOsiz, YOsiz              */
-  int x1, y1;          /* Xsiz, Ysiz                */ 
-  int numcomps;        /* number of components      */
-  int index_on;        /* 0 = no index || 1 = index */
-  j2k_comp_t *comps;   /* image-components          */
-} j2k_image_t;
-
-typedef struct {
-  int expn;     /* exponent */
-  int mant;     /* mantissa */
-} j2k_stepsize_t;
-
-typedef struct {
-  int csty;                                /* coding style                          */
-  int numresolutions;                      /* number of resolutions                 */
-  int cblkw;                               /* width of code-blocks                  */
-  int cblkh;                               /* height of code-blocks                 */
-  int cblksty;                             /* code-block coding style               */
-  int qmfbid;                              /* discrete wavelet transform identifier */
-  int qntsty;                              /* quantisation style                    */
-  j2k_stepsize_t stepsizes[J2K_MAXBANDS];  /* stepsizes used for quantisation       */
-  int numgbits;                            /* number of guard bits                  */
-  int roishift;                            /* Region of Interest shift              */
-  int prcw[J2K_MAXRLVLS];                  /* Precinct width                        */
-  int prch[J2K_MAXRLVLS];                  /* Precinct height                       */
-} j2k_tccp_t;
-
-typedef struct {
-    int resno0, compno0; 
-    int layno1, resno1, compno1;
-    int prg;
-    int tile;
-    char progorder[4];
-} j2k_poc_t;
-
-typedef struct {
-  int csty;                  /* coding style                                                            */  
-  int prg;                   /* progression order                                                       */
-  int numlayers;             /* number of layers                                                        */
-  int mct;                   /* multi-component transform identifier                                    */
-  int rates[100];            /* rates of layers                                                         */
-  int numpocs;               /* number of progression order changes                                     */
-  int POC;                   /* Precise if a POC marker has been used O:NO, 1:YES                       */
-  j2k_poc_t pocs[32];        /* progression order changes                                               */
-  unsigned char *ppt_data;   /* packet header store there for futur use in t2_decode_packet             */
-  int ppt;                   /* If ppt == 1 --> there was a PPT marker for the present tile             */
-  int ppt_store;             /* Use in case of multiple marker PPT (number of info already store)       */
-  j2k_tccp_t *tccps;         /* tile-component coding parameters                                        */
-} j2k_tcp_t;
-
-typedef struct {
-  int tx0, ty0;              /* XTOsiz, YTOsiz                                                          */
-  int tdx, tdy;              /* XTsiz, YTsiz                                                            */
-  int tw, th;
-  unsigned char *ppm_data;   /* packet header store there for futur use in t2_decode_packet             */
-  int ppm;                   /* If ppm == 1 --> there was a PPM marker for the present tile             */
-  int ppm_store;             /* Use in case of multiple marker PPM (number of info already store)       */
-  int ppm_previous;          /* Use in case of multiple marker PPM (case on non-finished previous info) */
-  j2k_tcp_t *tcps;           /* tile coding parameters                                                  */
-} j2k_cp_t;
-
-
-
-
-
-/* Packet information : Layer level */
-typedef struct {  
-  int len;               /* Length of the body of the packet   */
-  int len_header;        /* Length of the header of the packet */
-  int offset;            /* Offset of the body of the packet   */
-  int offset_header;     /* Offset of the header of the packet */
-} info_layer_t;
-
-
-/* Access to packet information : precinct level */
-typedef struct {  
-  info_layer_t *layer;
-} info_prec_t;
-
-
-/* Access to packet information : resolution level */
-typedef struct {  
-  info_prec_t *prec;
-} info_reso_t;
-
-
-/* Access to packet information : component level */
-typedef struct {  
-  info_reso_t *reso;
-} info_compo_t;
-
-
-/* Information about the marker */
-typedef struct {
-  int type;       /* type of marker [SIZ, QCD, POC, PPM, CRG, COD] appearing only once */
-  int start_pos;  /* Start position of the marker                                      */
-  int len;        /* Length of the marker                                              */
-} info_marker_t;
-
-
-/* Multiple marker in tile header */
-typedef struct{
-  info_marker_t *COC;    /* COC markers                    */
-  int num_COC;           /* Number of COC marker           */
-  int CzCOC;             /* Current size of the vector COC */
-  
-  info_marker_t *RGN;    /* RGN markers                    */
-  int num_RGN;           /* Number of RGN marker           */
-  int CzRGN;             /* Current size of the vector RGN */
-  
-  info_marker_t *QCC;    /* QCC markers                    */
-  int num_QCC;           /* Number of QCC marker           */
-  int CzQCC;             /* Current size of the vector QCC */
-  
-  info_marker_t *PLT;    /* PLT markers                    */
-  int num_PLT;           /* Number of PLT marker           */
-  int CzPLT;             /* Current size of the vector PLT */
-  
-  info_marker_t *PPT;    /* PPT markers                    */
-  int num_PPT;           /* Number of PPT marker           */
-  int CzPPT;             /* Current size of the vector PPT */
-  
-  info_marker_t *COM;    /* COM markers                    */
-  int num_COM;           /* Number of COM marker           */
-  int CzCOM;             /* Current size of the vector COC */
-} info_marker_mul_tile_t; 
-
-
-/* Information about each tile_part for a particulary tile */
-typedef struct{
-  int start_pos;                      /* Start position of the tile_part       */ 
-  int length;                         /* Length of the tile_part header + body */
-  int length_header;                  /* Length of the header                  */
-  int end_pos;                        /* End position of the tile part         */
-  int end_header;                     /* End position of the tile part header  */
-
-  int num_reso_AUX;                   /* Number of resolution level completed  */
-} info_tile_part_t;
-
-
-/* Information about each tile */
-typedef struct {
-  int num_tile;                       /* Number of Tile                                                    */
-  int pw, ph;                         /* number of precinct by tile                                        */
-  int num_packet;                     /* number of packet in the tile                                      */
-  info_compo_t *compo;                /* component [packet]                                                */
-  
-  info_marker_t *marker;              /* information concerning markers inside image [only one apparition] */
-  info_marker_mul_tile_t marker_mul;  /* information concerning markers inside image [multiple apparition] */ 
-  int num_marker;                     /* number of marker                                                  */
-  
-  int numparts;                       /* number of tile_part for this tile                                 */
-  info_tile_part_t *tile_parts;       /* Information about each tile_part                                  */
-  int Cztile_parts;                   /* Current size of the tile_parts vector                             */
-} info_tile_t;                        /* index struct                                                      */
-
-
-/* Multiple marker in main header */
-typedef struct{
-  info_marker_t *COC;    /* COC markers                    */
-  int num_COC;           /* Number of COC marker           */
-  int CzCOC;             /* Current size of the vector COC */
-  info_marker_t *RGN;    /* RGN markers                    */
-  int num_RGN;           /* Number of RGN marker           */
-  int CzRGN;             /* Current size of the vector RGN */
-  
-  info_marker_t *QCC;    /* QCC markers                    */
-  int num_QCC;           /* Number of QCC marker           */
-  int CzQCC;             /* Current size of the vector QCC */
-  
-  info_marker_t *TLM;    /* TLM markers                    */
-  int num_TLM;           /* Number of TLM marker           */
-  int CzTLM;             /* Current size of the vector TLM */
-  
-  info_marker_t *PLM;    /* PLM markers                    */
-  int num_PLM;           /* Number of PLM marker           */
-  int CzPLM;             /* Current size of the vector PLM */
-  
-  info_marker_t *PPM;    /* PPM markers                    */
-  int num_PPM;           /* Number of PPM marker           */
-  int CzPPM;             /* Current size of the vector PPM */
-  
-  info_marker_t *COM;    /* COM markers                    */
-  int num_COM;           /* Number of COM marker           */
-  int CzCOM;             /* Current size of the vector COM */
-} info_marker_mul_t; /* index struct */
-
-
-/* Information about image */
-typedef struct {
-  int Im_w, Im_h;                /* Image width and Height                                            */
-  int Tile_x, Tile_y;            /* Number of Tile in X and Y                                         */
-  int tw, th;
-  int pw, ph;                    /* nombre precinct in X and Y                                        */
-  int pdx, pdy;                  /* size of precinct in X and Y                                       */
-
-  int Prog;                      /* progression order                                                 */
-  int Comp;                      /* Component numbers                                                 */
-  int Layer;                     /* number of layer                                                   */
-  int Decomposition;             /* number of decomposition                                           */
-
-  int Main_head_end;             /* Main header position                                              */
-  int codestream_size;           /* codestream's size                                                 */
-
-  info_marker_t *marker;         /* information concerning markers inside image [only one apparition] */
-  info_marker_mul_t marker_mul;  /* information concerning markers inside image [multiple apparition] */ 
-  int num_marker;                /* number of marker                                                  */
-
-  int num_packet_max;            /* Maximum number of packet                                          */
-
-  int num_max_tile_parts;        /* Maximum number of tile-part                                       */
-  info_tile_t *tile;             /* information concerning tiles inside image                         */
-} info_image_t; /* index struct */
-
-
-#endif
diff --git a/indexer_JPIP/jp2.c b/indexer_JPIP/jp2.c
deleted file mode 100644 (file)
index ff2d22e..0000000
+++ /dev/null
@@ -1,302 +0,0 @@
-/*
- * Copyright (c) 2003-2004, Yannick Verschueren
- * Copyright (c) 2003-2004,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "j2k.h"
-#include "cio.h"
-#include "tcd.h"
-#include "int.h"
-
-#define JPIP_JPIP 0x6a706970
-
-#define JP2_JP   0x6a502020
-#define JP2_FTYP 0x66747970
-#define JP2_JP2H 0x6a703268
-#define JP2_IHDR 0x69686472
-#define JP2_COLR 0x636f6c72
-#define JP2_JP2C 0x6a703263
-#define JP2_URL  0x75726c20
-#define JP2_DBTL 0x6474626c
-#define JP2_BPCC 0x62706363
-#define JP2      0x6a703220
-
-
-void jp2_write_url(char *Idx_file)
-{
-  int len, lenp; 
-  unsigned int i;
-  char str[256];
-
-  sprintf(str, "%s", Idx_file);
-  lenp=cio_tell();
-  cio_skip(4);
-  cio_write(JP2_URL, 4);  // DBTL
-  cio_write(0,1);          // VERS
-  cio_write(0,3);          // FLAG
-
-  for (i=0; i<strlen(str); i++) {
-        cio_write(str[i], 1);
-    }
-
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len,4);         // L
-  cio_seek(lenp+len);
-}
-
-void jp2_write_dbtl(char *Idx_file)
-{
-  int len, lenp;
-
-  lenp=cio_tell();
-  cio_skip(4);
-  cio_write(JP2_DBTL, 4);  // DBTL
-  cio_write(1,2);           // NDR : Only 1
-  
-  jp2_write_url(Idx_file); // URL Box
-
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len,4);         // L
-  cio_seek(lenp+len);
-}
-
-int jp2_write_ihdr(j2k_image_t *j2k_img)
-{
-  int len, lenp,i; 
-  int depth_0,depth, sign, BPC_ok=1;
-
-  lenp=cio_tell();
-  cio_skip(4);
-  cio_write(JP2_IHDR, 4);  // IHDR
-
-  cio_write(j2k_img->y1-j2k_img->x0,4);   // HEIGHT
-  cio_write(j2k_img->x1-j2k_img->x0,4);   // WIDTH
-  cio_write(j2k_img->numcomps,2);   // NC
-
-  depth_0=j2k_img->comps[0].prec-1;
-  sign=j2k_img->comps[0].sgnd;
-
-  for(i=1;i<j2k_img->numcomps;i++)
-    {
-      depth=j2k_img->comps[i].prec-1;
-      sign=j2k_img->comps[i].sgnd;
-      if(depth_0!=depth) BPC_ok=0;
-    }
-  
-  if (BPC_ok)
-    cio_write(depth_0+(sign<<7),1);
-  else
-    cio_write(255,1);
-
-  cio_write(7,1);          // C : Always 7
-  cio_write(1,1);          // UnkC, colorspace unknow
-  cio_write(0,1);          // IPR, no intellectual property
-
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len,4);         // L
-  cio_seek(lenp+len);
-
-  return BPC_ok;
-}
-
-void jp2_write_bpcc(j2k_image_t *j2k_img)
-{
-  int len, lenp, i;
-  
-  lenp=cio_tell();
-  cio_skip(4);
-  cio_write(JP2_BPCC, 4);  // BPCC
-  
-  for(i=0;i<j2k_img->numcomps;i++)
-    cio_write(j2k_img->comps[i].prec-1+(j2k_img->comps[i].sgnd<<7),1);
-
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len,4);         // L
-  cio_seek(lenp+len);
-}
-
-void jp2_write_colr(int BPC_ok, j2k_image_t *j2k_img)
-{
-  int len, lenp, meth;
-  
-  lenp=cio_tell();
-  cio_skip(4);
-  cio_write(JP2_COLR, 4);  // COLR
-
-  if ((j2k_img->numcomps==1 || j2k_img->numcomps==3) && (BPC_ok && j2k_img->comps[0].prec==8))
-    meth=1;
-  else
-    meth=2;
-
-  cio_write(meth,1);       // METH
-  cio_write(0,1);          // PREC
-  cio_write(0,1);          // APPROX
-  
-  if (meth==1)
-    cio_write(j2k_img->numcomps>1?16:17,4);          // EnumCS
-
-  if (meth==2)
-    cio_write(0,1);        // PROFILE (??) 
-
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len,4);         // L
-  cio_seek(lenp+len);
-}
-
-/*
- * Write the JP2H box
- *
- * JP2 Header box
- *
- */
-void jp2_write_jp2h(j2k_image_t *j2k_img)
-{
-  int len, lenp, BPC_ok;
-  
-  lenp=cio_tell();
-  cio_skip(4);
-  cio_write(JP2_JP2H, 4);           /* JP2H */
-
-  BPC_ok=jp2_write_ihdr(j2k_img);
-
-  if (!BPC_ok)
-    jp2_write_bpcc(j2k_img);
-  jp2_write_colr(BPC_ok, j2k_img);
-
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len,4);         /* L */
-  cio_seek(lenp+len);
-}
-
-/*
- * Write the FTYP box
- *
- * File type box
- *
- */
-void jp2_write_ftyp()
-{
-  int len, lenp;
-  
-  lenp=cio_tell();
-  cio_skip(4);
-  cio_write(JP2_FTYP, 4);   /* FTYP       */
-
-  cio_write(JP2,4);         /* BR         */
-  cio_write(0,4);           /* MinV       */
-  cio_write(JP2,4);         /* CL0 : JP2  */
-  cio_write(JPIP_JPIP,4);   /* CL1 : JPIP */
-
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len,4);         /* L          */
-  cio_seek(lenp+len);
-}
-
-/*
- * Read the FTYP box
- *
- * File type box
- *
- */
-void jp2_read_ftyp(int length)
-{
-  int BR, MinV, type, i;
-
-  BR = cio_read(4);         /* BR              */
-  MinV = cio_read(4);       /* MinV            */
-  length-=8;
-  
-  for (i=length/4;i>0;i--)
-    type = cio_read(4);     /* CLi : JP2, JPIP */
-}
-
-int jp2_write_jp2c(char *J2K_file)
-{
-  int len, lenp, totlen, i;
-  FILE *src;
-  char *j2kfile;
-
-  lenp=cio_tell();
-  cio_skip(4);
-  cio_write(JP2_JP2C, 4);  // JP2C
-
-  src=fopen(J2K_file, "rb");
-  fseek(src, 0, SEEK_END);
-  totlen=ftell(src);
-  fseek(src, 0, SEEK_SET);
-  
-  j2kfile=(char*)malloc(totlen);
-  fread(j2kfile, 1, totlen, src);
-  fclose(src);
-
-  for (i=0;i<totlen;i++)
-    cio_write(j2kfile[i],1);
-  
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len,4);         // L
-  cio_seek(lenp+len);
-  return lenp;
-}
-
-void jp2_write_jp()
-{
-  int len, lenp;
-  
-  lenp=cio_tell();
-  cio_skip(4);
-  cio_write(JP2_JP, 4);  // JP
-  cio_write(0x0d0a870a,4);
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len,4);         // L
-  cio_seek(lenp+len);
-}
-
-/*
- * Read the JP box
- *
- * JPEG 2000 signature
- *
- * return 1 if error else 0
- */
-int jp2_read_jp()
-{
-  if (0x0d0a870a!=cio_read(4))
-    return 1;
-  else
-    return 0;
-}
diff --git a/indexer_JPIP/jp2.h b/indexer_JPIP/jp2.h
deleted file mode 100644 (file)
index d5510f5..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef __JP2_H
-#define __JP2_H
-
-#include "j2k.h"
-
-void jp2_write_url(char *Idx_file);
-
-void jp2_write_dbtl(char *Idx_file);
-
-void jp2_write_jp2h(j2k_image_t *j2k_img);
-
-void jp2_write_ftyp();
-
-int jp2_write_jp2c(char *J2K_file);
-
-void jp2_write_jp();
-
-#endif
diff --git a/indexer_JPIP/jpip.c b/indexer_JPIP/jpip.c
deleted file mode 100644 (file)
index a86fbca..0000000
+++ /dev/null
@@ -1,768 +0,0 @@
-/*
- * Copyright (c) 2003-2004, Yannick Verschueren
- * Copyright (c) 2003-2004, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <setjmp.h>
-#include <math.h>
-
-#include "j2k.h"
-#include "cio.h"
-#include "tcd.h"
-#include "int.h"
-
-#define JPIP_CIDX 0x63696478   /* Codestream index                */
-#define JPIP_CPTR 0x63707472   /* Codestream Finder Box           */
-#define JPIP_MANF 0x6d616e66   /* Manifest Box                    */
-#define JPIP_FAIX 0x66616978   /* Fragment array Index box        */
-#define JPIP_MHIX 0x6d686978   /* Main Header Index Table         */
-#define JPIP_TPIX 0x74706978   /* Tile-part Index Table box       */
-#define JPIP_THIX 0x74686978   /* Tile header Index Table box     */
-#define JPIP_PPIX 0x70706978   /* Precinct Packet Index Table box */
-#define JPIP_PHIX 0x70686978   /* Packet Header index Table       */
-#define JPIP_FIDX 0x66696478   /* File Index                      */
-#define JPIP_FPTR 0x66707472   /* File Finder                     */
-#define JPIP_PRXY 0x70727879   /* Proxy boxes                     */
-#define JPIP_IPTR 0x69707472   /* Index finder box                */
-#define JPIP_PHLD 0x70686c64   /* Place holder                    */
-
-#define JP2C      0x6a703263
-
-//static info_marker_t marker_jpip[32], marker_local_jpip[32];  /* SIZE to precise ! */
-//static int num_marker_jpip, num_marker_local_jpip;
-
-/* 
- * Write the CPTR box
- *
- * Codestream finder box (box)
- *
- */
-void jpip_write_cptr(int offset, info_image_t img)
-{
-  int len, lenp;
-
-  lenp=cio_tell(); 
-  cio_skip(4);                       /* L [at the end]     */
-  cio_write(JPIP_CPTR,4);            /* T                  */
-  cio_write(0,2);                    /* DR  A PRECISER !!  */
-  cio_write(0,2);                    /* CONT               */
-  cio_write(offset,8);               /* COFF A PRECISER !! */
-  cio_write(img.codestream_size,8);  /* CLEN               */
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len, 4);                 /* L                  */
-  cio_seek(lenp+len);
-}
-
-/* 
- * Read the CPTR box
- *
- * Codestream finder box (box)
- *
- */
-void jpip_read_cptr()
-{
-  int DR, CONT;
-  long long Coff, codestream_size;
-
-  DR = cio_read(2);               /* DR   */
-  CONT = cio_read(2);             /* CONT */
-  Coff = cio_read(8);             /* COFF */
-  codestream_size = cio_read(8);  /* CLEN */
-}
-
-/* 
- * Write the MANF box
- *
- * Manifest box (box)
- *
- */
-void jpip_write_manf(int second, int v, info_marker_t *marker)
-{
-  int len, lenp, i;
-  lenp=cio_tell(); 
-  cio_skip(4);                         /* L [at the end]                    */
-  cio_write(JPIP_MANF,4);              /* T                                 */
-
-  if (second)                          /* Write only during the second pass */
-    {
-      for(i=0;i<v;i++)
-       {
-         cio_write(marker[i].len,4);  /* Marker length                     */ 
-         cio_write(marker[i].type,4); /* Marker type                       */
-       }
-    }
-
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len, 4);                   /* L                                 */
-  cio_seek(lenp+len);
-}
-
-/* 
- * Read the MANF box
- *
- * Manifest box (box)
- *
- */
-void jpip_read_manf(int len)
-{
-  int i, v, marker_len, marker_type;
-  
-  v = (len - 8)/ 8;
-  
-  for(i=0;i<v;i++)
-    {
-      marker_len = cio_read(4);       /* Marker length */ 
-      marker_type = cio_read(4);      /* Marker type   */
-    }
-}
-
-/* 
- * Write the MHIX box
- *
- * Main Header Index Table (box)
- *
- */
-int jpip_write_mhix(info_image_t img, int status, int tileno)
-{
-  int len, lenp, i;
-  info_tile_t *tile;
-  lenp=cio_tell();
-  cio_skip(4);                               /* L [at the end]                    */
-  cio_write(JPIP_MHIX, 4);                   /* MHIX                              */
-
-  if (status) /* MAIN HEADER */
-    {
-      cio_write(img.Main_head_end,8);        /* TLEN                              */
-      
-      for(i = 0; i < img.num_marker; i++)    /* Marker restricted to 1 apparition */
-       {
-         cio_write(img.marker[i].type, 2);
-         cio_write(0, 2);
-         cio_write(img.marker[i].start_pos, 8);
-         cio_write(img.marker[i].len, 2);
-       }
-      
-      /* Marker NOT restricted to 1 apparition */
-      for(i = img.marker_mul.num_COC - 1; i >= 0; i--) /* COC */
-       {
-         cio_write(img.marker_mul.COC[i].type, 2);
-         cio_write(i, 2);
-         cio_write(img.marker_mul.COC[i].start_pos, 8);
-         cio_write(img.marker_mul.COC[i].len, 2);
-       }
-      
-      for(i = img.marker_mul.num_RGN - 1; i >= 0; i--) /* RGN */
-       {
-         cio_write(img.marker_mul.RGN[i].type, 2);
-         cio_write(i, 2);
-         cio_write(img.marker_mul.RGN[i].start_pos, 8);
-         cio_write(img.marker_mul.RGN[i].len, 2);
-       }
-      
-      for(i = img.marker_mul.num_QCC - 1; i >= 0; i--) /* QCC */
-       {
-         cio_write(img.marker_mul.QCC[i].type, 2);
-         cio_write(i, 2);
-         cio_write(img.marker_mul.QCC[i].start_pos, 8);
-         cio_write(img.marker_mul.QCC[i].len, 2);
-       }
-      
-      for(i = img.marker_mul.num_TLM - 1; i >= 0; i--) /* TLM */
-       {
-         cio_write(img.marker_mul.TLM[i].type, 2);
-         cio_write(i, 2);
-         cio_write(img.marker_mul.TLM[i].start_pos, 8);
-         cio_write(img.marker_mul.TLM[i].len, 2);
-       }
-      
-      for(i = img.marker_mul.num_PLM - 1; i >= 0; i--) /* PLM */
-       {
-         cio_write(img.marker_mul.PLM[i].type, 2);
-         cio_write(i, 2);
-         cio_write(img.marker_mul.PLM[i].start_pos, 8);
-         cio_write(img.marker_mul.PLM[i].len, 2);
-       }
-      
-      for(i = img.marker_mul.num_PPM - 1; i >= 0; i--) /* PPM */
-       {
-         cio_write(img.marker_mul.PPM[i].type, 2);
-         cio_write(i, 2);
-         cio_write(img.marker_mul.PPM[i].start_pos, 8);
-         cio_write(img.marker_mul.PPM[i].len, 2);
-       }
-
-      for(i = img.marker_mul.num_COM - 1; i >= 0; i--) /* COM */
-       {
-         cio_write(img.marker_mul.COM[i].type, 2);
-         cio_write(i, 2);
-         cio_write(img.marker_mul.COM[i].start_pos, 8);
-         cio_write(img.marker_mul.COM[i].len, 2);
-       }
-    } 
-  else /* TILE HEADER */
-    {
-      tile = &img.tile[tileno];
-      cio_write(tile->tile_parts[0].length_header, 8);  /* TLEN                              */ 
-      
-      for(i = 0; i < tile->num_marker; i++)             /* Marker restricted to 1 apparition */
-       {
-         cio_write(tile->marker[i].type, 2);
-         cio_write(0, 2);
-         cio_write(tile->marker[i].start_pos, 8);
-         cio_write(tile->marker[i].len, 2);
-       }
-      
-      /* Marker NOT restricted to 1 apparition */
-      for(i = tile->marker_mul.num_COC - 1; i >= 0; i--) /* COC */
-       {
-         cio_write(tile->marker_mul.COC[i].type, 2);
-         cio_write(i, 2);
-         cio_write(tile->marker_mul.COC[i].start_pos, 8);
-         cio_write(tile->marker_mul.COC[i].len, 2);
-       }
-      
-      for(i = tile->marker_mul.num_RGN - 1; i >= 0; i--) /* RGN */
-       {
-         cio_write(tile->marker_mul.RGN[i].type, 2);
-         cio_write(i, 2);
-         cio_write(tile->marker_mul.RGN[i].start_pos, 8);
-         cio_write(tile->marker_mul.RGN[i].len, 2);
-       }
-      
-      for(i = tile->marker_mul.num_QCC - 1; i >= 0; i--) /* QCC */
-       {
-         cio_write(tile->marker_mul.QCC[i].type, 2);
-         cio_write(i, 2);
-         cio_write(tile->marker_mul.QCC[i].start_pos, 8);
-         cio_write(tile->marker_mul.QCC[i].len, 2);
-       }
-      
-      for(i = tile->marker_mul.num_PLT - 1; i >= 0; i--) /* PLT */
-       {
-         cio_write(tile->marker_mul.PLT[i].type,2);
-         cio_write(i,2);
-         cio_write(tile->marker_mul.PLT[i].start_pos,8);
-         cio_write(tile->marker_mul.PLT[i].len,2);
-       }
-      
-      for(i = tile->marker_mul.num_PPT - 1; i >= 0; i--) /* PPT */
-       {
-         cio_write(tile->marker_mul.PPT[i].type, 2);
-         cio_write(i, 2);
-         cio_write(tile->marker_mul.PPT[i].start_pos, 8);
-         cio_write(tile->marker_mul.PPT[i].len, 2);
-       }
-      
-      for(i = tile->marker_mul.num_COM - 1; i >= 0; i--) /* COM */
-       {
-         cio_write(tile->marker_mul.COM[i].type, 2);
-         cio_write(i, 2);
-         cio_write(tile->marker_mul.COM[i].start_pos, 8);
-         cio_write(tile->marker_mul.COM[i].len, 2);
-       } 
-    }      
-  
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len, 4);        /* L           */
-  cio_seek(lenp+len);
-  
-  return len;
-}
-
-/* 
- * Read the MHIX box
- *
- * Main Header Index Table (box)
- *
- */
-void jpip_read_mhix(int len)
-{
-  int i, v, marker_type, marker_start_pos, marker_len, marker_remains;
-
-  v = (len - 8) / 14;
-
-  for (i=0; i<v ; i++)
-    {
-      marker_type = cio_read(2);       /* Type of the marker               */ 
-      marker_remains = cio_read(2);    /* Number of same markers following */
-      marker_start_pos = cio_read(2);  /* Start position of the marker     */
-      marker_len = cio_read(2);        /* Length of the marker             */
-    }
-}
-
-/* 
- * Write the FAIX box
- *
- * Fragment array Index box (box)
- *
- */
-int jpip_write_faix(int v, int compno, info_image_t img, j2k_cp_t *j2k_cp, int version)
-{
-  int len, lenp, i, j;
-  /*int version = 0;*/
-  int tileno, resno, precno, layno, num_packet=0;
-
-  lenp=cio_tell();
-  cio_skip(4);              /* L [at the end]      */
-  cio_write(JPIP_FAIX, 4);  /* FAIX                */ 
-  cio_write(version,1);     /* Version 0 = 4 bytes */
-  
-  switch(v)
-    {
-    case 0:   /* TPIX */
-      cio_write(img.num_max_tile_parts,(version & 0x01)?8:4);                      /* NMAX           */
-      cio_write(img.tw*img.th,(version & 0x01)?8:4);                               /* M              */
-      for (i = 0; i < img.tw*img.th; i++)
-       {
-         for (j = 0; j < img.tile[i].numparts ; j++)
-           {
-             cio_write(img.tile[i].tile_parts[j].start_pos,(version & 0x01)?8:4); /* start position */
-             cio_write(img.tile[i].tile_parts[j].length,(version & 0x01)?8:4);    /* length         */
-             if (version & 0x02)
-               cio_write(img.tile[i].tile_parts[j].num_reso_AUX,4); /* Aux_i,j : Auxiliary value */
-             //cio_write(0,4);
-           }
-         /* PADDING */
-         while (j < img.num_max_tile_parts)
-           {
-             cio_write(0,(version & 0x01)?8:4); /* start position            */
-             cio_write(0,(version & 0x01)?8:4); /* length                    */
-             if (version & 0x02)
-               cio_write(0,4);                  /* Aux_i,j : Auxiliary value */
-             j++;
-           }
-       }
-      break;
-      
-      /*   case 1: */   /* THIX */
-      /* cio_write(1,(version & 0x01)?8:4);  */           /* NMAX */
-      /* cio_write(img.tw*img.th,(version & 0x01)?8:4); */ /* M    */
-      /* for (i=0;i<img.tw*img.th;i++) */
-      /* { */
-      /* cio_write(img.tile[i].start_pos,(version & 0x01)?8:4); */                         /* start position */
-      /* cio_write(img.tile[i].end_header-img.tile[i].start_pos,(version & 0x01)?8:4); */  /* length         */
-      /* if (version & 0x02)*/
-      /* cio_write(0,4); */ /* Aux_i,j : Auxiliary value */
-      /* } */
-      /* break; */
-
-    case 2:  /* PPIX  NOT FINISHED !! */
-      cio_write(img.num_packet_max,(version & 0x01)?8:4); /* NMAX */
-      cio_write(img.tw*img.th,(version & 0x01)?8:4);      /* M    */
-      for(tileno=0;tileno<img.tw*img.th;tileno++)
-       {
-         info_tile_t *tile_Idx = &img.tile[tileno];
-         info_compo_t *compo_Idx = &tile_Idx->compo[compno];
-         int correction;
-         
-         num_packet=0;
-         
-         if(j2k_cp->tcps[tileno].csty&J2K_CP_CSTY_EPH)
-           correction=3;
-         else
-           correction=1;
-         for(resno=0;resno<img.Decomposition+1;resno++)
-           {
-             info_reso_t *reso_Idx = &compo_Idx->reso[resno];
-             for (precno=0;precno<img.tile[tileno].pw*img.tile[tileno].ph;precno++)
-               {
-                 info_prec_t *prec_Idx = &reso_Idx->prec[precno];
-                 for(layno=0;layno<img.Layer;layno++)
-                   {
-                     info_layer_t *layer_Idx = &prec_Idx->layer[layno];
-                     cio_write(layer_Idx->offset,(version & 0x01)?8:4);                                   /* start position */
-                     cio_write((layer_Idx->len_header-correction)?0:layer_Idx->len,(version & 0x01)?8:4); /* length         */
-                     if (version & 0x02)
-                       cio_write(0,4); /* Aux_i,j : Auxiliary value */
-                     num_packet++;
-                   }
-               }
-           }
-         /* PADDING */
-         while (num_packet < img.num_packet_max)
-           {
-             cio_write(0,(version & 0x01)?8:4); /* start position            */
-             cio_write(0,(version & 0x01)?8:4); /* length                    */
-             if (version & 0x02)
-               cio_write(0,4);                  /* Aux_i,j : Auxiliary value */
-             num_packet++;
-           }
-       }
-      
-      break;
-      
-    case 3:  /* PHIX NOT FINISHED !! */
-      cio_write(img.num_packet_max,(version & 0x01)?8:4); /* NMAX */
-      cio_write(img.tw*img.th,(version & 0x01)?8:4);      /* M    */
-      for(tileno=0;tileno<img.tw*img.th;tileno++)
-       {
-         info_tile_t *tile_Idx = &img.tile[tileno];
-         info_compo_t *compo_Idx = &tile_Idx->compo[compno];
-         int correction;
-
-         num_packet = 0;
-         if(j2k_cp->tcps[tileno].csty&J2K_CP_CSTY_EPH)
-           correction=3;
-         else
-           correction=1;
-         for(resno=0;resno<img.Decomposition+1;resno++)
-           {
-             info_reso_t *reso_Idx = &compo_Idx->reso[resno];
-             for (precno=0;precno<img.tile[tileno].pw*img.tile[tileno].ph;precno++)
-               {
-                 info_prec_t *prec_Idx = &reso_Idx->prec[precno];
-                 for(layno=0;layno<img.Layer;layno++)
-                   {
-                     info_layer_t *layer_Idx = &prec_Idx->layer[layno];
-                     cio_write(layer_Idx->offset_header,(version & 0x01)?8:4);                                   /* start position */
-                     cio_write((layer_Idx->len_header-correction)?0:layer_Idx->len_header,(version & 0x01)?8:4); /* length         */
-                     if (version & 0x02)
-                       cio_write(0,4); /* Aux_i,j : Auxiliary value */
-                     num_packet++;
-                   }
-               }
-           }
-         /* PADDING */
-         while (num_packet<img.num_packet_max)
-           {
-             cio_write(0,(version & 0x01)?8:4); /* start position            */
-             cio_write(0,(version & 0x01)?8:4); /* length                    */
-             if (version & 0x02)
-               cio_write(0,4);                  /* Aux_i,j : Auxiliary value */
-             num_packet++;
-           }
-       }
-      break;
-    }
-  
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len, 4);        /* L  */
-  cio_seek(lenp+len);
-
-  return len;
-}
-
-/* 
- * Write the TPIX box
- *
- * Tile-part Index table box (superbox)
- *
- */
-int jpip_write_tpix(info_image_t img, j2k_cp_t *j2k_cp, int version)
-{
-  int len, lenp;
-  lenp=cio_tell();
-  cio_skip(4);              /* L [at the end] */
-  cio_write(JPIP_TPIX, 4);  /* TPIX           */
-  
-  jpip_write_faix(0,0,img, j2k_cp, version);
-
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len, 4);        /* L              */
-  cio_seek(lenp+len);
-
-  return len;
-}
-
-/* 
- * Write the THIX box
- *
- * Tile header Index table box (superbox)
- *
- */
-//int jpip_write_thix(info_image_t img, j2k_cp_t *j2k_cp)
-//  {
-//  int len, lenp;
-//  lenp=cio_tell();
-//  cio_skip(4);              /* L [at the end] */
-//  cio_write(JPIP_THIX, 4);  /* THIX           */
-  
-//  jpip_write_faix(1,0,img, j2k_cp);
-
-//  len=cio_tell()-lenp;
-//  cio_seek(lenp);
-//  cio_write(len, 4);        /* L              */
-//  cio_seek(lenp+len);
-
-//  return len;
-//}
-
-int jpip_write_thix(info_image_t img, j2k_cp_t *j2k_cp)
-{
-  int len, lenp, i;
-  int tileno;
-  info_marker_t *marker;
-  int num_marker_local_jpip;
-
-  marker = (info_marker_t*)calloc(sizeof(info_marker_t), j2k_cp->tw*j2k_cp->th);
-
-  for ( i = 0; i < 2 ; i++ )
-    {
-      if (i) cio_seek(lenp);
-      
-      lenp = cio_tell();
-      cio_skip(4);              /* L [at the end] */
-      cio_write(JPIP_THIX, 4);  /* THIX           */
-      jpip_write_manf(i, j2k_cp->tw*j2k_cp->th, marker);
-      num_marker_local_jpip=img.Comp;
-      
-      for (tileno = 0; tileno < j2k_cp->tw*j2k_cp->th; tileno++)
-       {
-         marker[tileno].len = jpip_write_mhix(img, 1, tileno);
-         marker[tileno].type = JPIP_MHIX;
-       }
-      
-      len=cio_tell()-lenp;
-      cio_seek(lenp);
-      cio_write(len, 4);        /* L              */
-      cio_seek(lenp+len);
-    }
-
-  free(marker);
-
-  return len;
-}
-/* 
- * Write the PPIX box
- *
- * Precinct Packet Index table box (superbox)
- *
- */
-int jpip_write_ppix(info_image_t img,j2k_cp_t *j2k_cp)
-{
-  int len, lenp, compno, i;
-  info_marker_t *marker;
-  int num_marker_local_jpip;
-  marker = (info_marker_t*)calloc(sizeof(info_marker_t), img.Comp);
-  
-  for (i=0;i<2;i++)
-    {
-      if (i) cio_seek(lenp);
-      
-      lenp=cio_tell();
-      cio_skip(4);              /* L [at the end] */
-      cio_write(JPIP_PPIX, 4);  /* PPIX           */
-      jpip_write_manf(i,img.Comp,marker);
-      num_marker_local_jpip=img.Comp;
-      
-      for (compno=0; compno<img.Comp; compno++)
-       {
-         marker[compno].len=jpip_write_faix(2,compno,img, j2k_cp, 0);
-         marker[compno].type=JPIP_FAIX;
-       }
-   
-      len=cio_tell()-lenp;
-      cio_seek(lenp);
-      cio_write(len, 4);        /* L              */
-      cio_seek(lenp+len);
-    }
-  
-  free(marker);
-
-  return len;
-}
-
-/* 
- * Write the PHIX box
- *
- * Packet Header Index table box (superbox)
- *
- */
-int jpip_write_phix(info_image_t img, j2k_cp_t *j2k_cp)
-{
-  int len, lenp=0, compno, i;
-  info_marker_t *marker;
-
-  marker = (info_marker_t*)calloc(sizeof(info_marker_t), img.Comp);
-
-  for (i=0;i<2;i++)
-    {
-      if (i) cio_seek(lenp);
-      
-      lenp=cio_tell();
-      cio_skip(4);              /* L [at the end] */
-      cio_write(JPIP_PHIX, 4);  /* PHIX           */
-      
-      jpip_write_manf(i,img.Comp,marker);
-
-      for (compno=0; compno<img.Comp; compno++)
-       {       
-         marker[compno].len=jpip_write_faix(3,compno,img, j2k_cp, 0);
-         marker[compno].type=JPIP_FAIX;
-       }
-
-      len=cio_tell()-lenp;
-      cio_seek(lenp);
-      cio_write(len, 4);        /* L              */
-      cio_seek(lenp+len);
-    }
-
-  free(marker);
-
-  return len;
-}
-
-/* 
- * Write the CIDX box
- *
- * Codestream Index box (superbox)
- *
- */
-int jpip_write_cidx(int offset, info_image_t img, j2k_cp_t *j2k_cp, int version)
-{
-  int len, lenp = 0, i;
-  info_marker_t *marker_jpip;
-  int num_marker_jpip = 0;
-
-  marker_jpip = (info_marker_t*)calloc(sizeof(info_marker_t), 32);
-
-  for (i=0;i<2;i++)
-    {
-      if(i)
-       cio_seek(lenp);
-
-      lenp=cio_tell();
-
-      cio_skip(4);              /* L [at the end] */
-      cio_write(JPIP_CIDX, 4);  /* CIDX           */
-      jpip_write_cptr(offset, img);
-
-      jpip_write_manf(i,num_marker_jpip, marker_jpip);
-
-      num_marker_jpip=0;
-      marker_jpip[num_marker_jpip].len=jpip_write_mhix(img, 0, 0);
-      marker_jpip[num_marker_jpip].type=JPIP_MHIX;
-      num_marker_jpip++;
-
-      marker_jpip[num_marker_jpip].len=jpip_write_tpix(img, j2k_cp, version);
-      marker_jpip[num_marker_jpip].type=JPIP_TPIX;
-      num_marker_jpip++;
-
-      marker_jpip[num_marker_jpip].len=jpip_write_thix(img, j2k_cp);
-      marker_jpip[num_marker_jpip].type=JPIP_THIX;
-      num_marker_jpip++;
-
-      marker_jpip[num_marker_jpip].len=jpip_write_ppix(img, j2k_cp);
-      marker_jpip[num_marker_jpip].type=JPIP_PPIX;
-      num_marker_jpip++;
-
-      marker_jpip[num_marker_jpip].len=jpip_write_phix(img, j2k_cp);
-      marker_jpip[num_marker_jpip].type=JPIP_PHIX;
-      num_marker_jpip++;
-
-      len=cio_tell()-lenp;
-      cio_seek(lenp);
-      cio_write(len, 4);        /* L             */
-      cio_seek(lenp+len);
-    }
-
-  free(marker_jpip);
-
-  return len;
-
-}
-
-/* 
- * Write the IPTR box
- *
- * Index Finder box
- *
- */
-void jpip_write_iptr(int offset, int length)
-{
-  int len, lenp;
-  lenp=cio_tell();
-  cio_skip(4);              /* L [at the end] */
-  cio_write(JPIP_IPTR, 4);  /* IPTR           */
-  
-  cio_write(offset,8);
-  cio_write(length,8);
-
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len, 4);        /* L             */
-  cio_seek(lenp+len);
-}
-
-/* 
- * Write the PRXY box
- *
- * proxy (box)
- *
- */
-void jpip_write_prxy(int offset_jp2c, int length_jp2c, int offset_idx, int length_idx)
-{
-  int len, lenp;
-  lenp=cio_tell();
-  cio_skip(4);              /* L [at the end] */
-  cio_write(JPIP_PRXY, 4);  /* IPTR           */
-  
-  cio_write(offset_jp2c,8); /* OOFF           */
-  cio_write(length_jp2c,4); /* OBH part 1     */
-  cio_write(JP2C,4);        /* OBH part 2     */
-  
-  cio_write(1,1);           /* NI             */
-
-  cio_write(offset_idx,8);  /* IOFF           */
-  cio_write(length_idx,4);  /* IBH part 1     */
-  cio_write(JPIP_CIDX,4);   /* IBH part 2     */
-
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len, 4);        /* L              */
-  cio_seek(lenp+len);
-}
-
-
-/* 
- * Write the FIDX box
- *
- * File Index (superbox)
- *
- */
-int jpip_write_fidx(int offset_jp2c, int length_jp2c, int offset_idx, int length_idx)
-{
-  int len, lenp;
-  lenp=cio_tell();
-  cio_skip(4);              /* L [at the end] */
-  cio_write(JPIP_FIDX, 4);  /* IPTR           */
-  
-  jpip_write_prxy(offset_jp2c, length_jp2c, offset_idx, offset_jp2c);
-
-  len=cio_tell()-lenp;
-  cio_seek(lenp);
-  cio_write(len, 4);        /* L              */
-  cio_seek(lenp+len);
-
-  return len;
-}
diff --git a/indexer_JPIP/jpip.h b/indexer_JPIP/jpip.h
deleted file mode 100644 (file)
index 84df355..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __JPIP_H
-#define __JPIP_H
-
-#include "j2k.h"
-
-// Codestream index box (superbox)
-int jpip_write_cidx(int offset, info_image_t img, j2k_cp_t *j2k_cp, int version);
-
-// Index Finder Box
-void jpip_write_iptr(int offset, int length);
-
-// File Index Box
-int jpip_write_fidx(int offset_jp2c, int length_jp2c, int offset_idx, int length_idx);
-
-#endif
diff --git a/indexer_JPIP/pi.c b/indexer_JPIP/pi.c
deleted file mode 100644 (file)
index 691ef49..0000000
+++ /dev/null
@@ -1,465 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003-2004, Yannick Verschueren
- * Copyright (c) 2003-2004, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "pi.h"
-#include "int.h"
-#include <stdlib.h>
-#include <stdio.h>
-
-
-/* <summary> */
-/* Create a packet iterator.   */
-/* </summary> */
-pi_iterator_t *pi_create(j2k_image_t * img, j2k_cp_t * cp, int tileno)
-{
-       int p, q;
-       int compno, resno, pino;
-       int maxres = 0;
-       pi_iterator_t *pi;
-       j2k_tcp_t *tcp;
-       j2k_tccp_t *tccp;
-
-       tcp = &cp->tcps[tileno];
-       pi = (pi_iterator_t *) malloc((tcp->numpocs + 1) * sizeof(pi_iterator_t));
-
-       for (pino = 0; pino < tcp->numpocs + 1; pino++) {       /* change */
-               p = tileno % cp->tw;
-               q = tileno / cp->tw;
-
-               pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, img->x0);
-               pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, img->y0);
-               pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, img->x1);
-               pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, img->y1);
-               pi[pino].numcomps = img->numcomps;
-               pi[pino].comps = (pi_comp_t *) malloc(img->numcomps * sizeof(pi_comp_t));
-
-               for (compno = 0; compno < pi->numcomps; compno++) {
-                       int tcx0, tcy0, tcx1, tcy1;
-                       pi_comp_t *comp = &pi[pino].comps[compno];
-                       tccp = &tcp->tccps[compno];
-                       comp->dx = img->comps[compno].dx;
-                       comp->dy = img->comps[compno].dy;
-                       comp->numresolutions = tccp->numresolutions;
-                       comp->resolutions =
-                               (pi_resolution_t *) malloc(comp->numresolutions *
-                                                                                                                                        sizeof(pi_resolution_t));
-                       tcx0 = int_ceildiv(pi->tx0, comp->dx);
-                       tcy0 = int_ceildiv(pi->ty0, comp->dy);
-                       tcx1 = int_ceildiv(pi->tx1, comp->dx);
-                       tcy1 = int_ceildiv(pi->ty1, comp->dy);
-                       if (comp->numresolutions > maxres) {
-                               maxres = comp->numresolutions;
-                       }
-                       for (resno = 0; resno < comp->numresolutions; resno++) {
-                               int levelno;
-                               int rx0, ry0, rx1, ry1;
-                               int px0, py0, px1, py1;
-                               pi_resolution_t *res = &comp->resolutions[resno];
-                               if (tccp->csty & J2K_CCP_CSTY_PRT) {
-                                       res->pdx = tccp->prcw[resno];
-                                       res->pdy = tccp->prch[resno];
-                               } else {
-                                       res->pdx = 15;
-                                       res->pdy = 15;
-                               }
-                               levelno = comp->numresolutions - 1 - resno;
-                               rx0 = int_ceildivpow2(tcx0, levelno);
-                               ry0 = int_ceildivpow2(tcy0, levelno);
-                               rx1 = int_ceildivpow2(tcx1, levelno);
-                               ry1 = int_ceildivpow2(tcy1, levelno);
-                               px0 = int_floordivpow2(rx0, res->pdx) << res->pdx;
-                               py0 = int_floordivpow2(ry0, res->pdy) << res->pdy;
-                               px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx;
-                               py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy;
-                               res->pw = (px1 - px0) >> res->pdx;
-                               res->ph = (py1 - py0) >> res->pdy;
-                       }
-               }
-               
-               tccp = &tcp->tccps[0];
-               pi[pino].step_p=1;
-               pi[pino].step_c=100*pi[pino].step_p;
-               pi[pino].step_r=img->numcomps*pi[pino].step_c;
-               pi[pino].step_l=maxres*pi[pino].step_r;
-               
-               if (pino==0)
-                 pi[pino].include=(short int*)calloc(img->numcomps*maxres*tcp->numlayers*100,sizeof(short int));
-               else
-                 pi[pino].include=pi[pino-1].include;
-
-               /*if (pino == tcp->numpocs) {*/
-                 if (tcp->POC == 0) {
-                       pi[pino].first = 1;
-                       pi[pino].poc.resno0 = 0;
-                       pi[pino].poc.compno0 = 0;
-                       pi[pino].poc.layno1 = tcp->numlayers;
-                       pi[pino].poc.resno1 = maxres;
-                       pi[pino].poc.compno1 = img->numcomps;
-                       pi[pino].poc.prg = tcp->prg;
-               } else {
-                       pi[pino].first = 1;
-                       pi[pino].poc.resno0 = tcp->pocs[pino].resno0;
-                       pi[pino].poc.compno0 = tcp->pocs[pino].compno0;
-                       pi[pino].poc.layno1 = tcp->pocs[pino].layno1;
-                       pi[pino].poc.resno1 = tcp->pocs[pino].resno1;
-                       pi[pino].poc.compno1 = tcp->pocs[pino].compno1;
-                       pi[pino].poc.prg = tcp->pocs[pino].prg;
-               }
-       }
-       return pi;
-}
-
-/* <summary> */
-/* Get next packet in layer=resolution-component-precinct order.   */
-/* </summary> */
-int pi_next_lrcp(pi_iterator_t * pi)
-{
-       pi_comp_t *comp;
-       pi_resolution_t *res;
-
-       if (!pi->first) {
-               comp = &pi->comps[pi->compno];
-               res = &comp->resolutions[pi->resno];
-               goto skip;
-       } else {
-               pi->first = 0;
-       }
-       for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {
-               for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1;
-                                pi->resno++) {
-                       for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1;
-                                        pi->compno++) {
-                               comp = &pi->comps[pi->compno];
-                               if (pi->resno >= comp->numresolutions) {
-
-                                       continue;
-                               }
-                               res = &comp->resolutions[pi->resno];
-                               for (pi->precno = 0; pi->precno < res->pw * res->ph; pi->precno++) {
-                                 if (!pi->include[pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p]){
-                                   pi->include[pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p] = 1;
-                                   return 1;
-                                       }
-                               skip:;
-                               }
-                       }
-               }
-       }
-       return 0;
-}
-
-/* <summary> */
-/* Get next packet in resolution-layer-component-precinct order.   */
-/* </summary> */
-int pi_next_rlcp(pi_iterator_t * pi)
-{
-       pi_comp_t *comp;
-       pi_resolution_t *res;
-       if (!pi->first) {
-               comp = &pi->comps[pi->compno];
-               res = &comp->resolutions[pi->resno];
-               goto skip;
-       } else {
-               pi->first = 0;
-       }
-       for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
-               for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {
-                       for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1;
-                                        pi->compno++) {
-                               comp = &pi->comps[pi->compno];
-                               if (pi->resno >= comp->numresolutions) {
-                                       continue;
-                               }
-                               res = &comp->resolutions[pi->resno];
-                               for (pi->precno = 0; pi->precno < res->pw * res->ph; pi->precno++) {
-                                 if (!pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p]){
-                                   pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p] = 1;
-                                   return 1;
-                                 }
-                               skip:;
-                               }
-                       }
-               }
-       }
-       return 0;
-}
-
-/* <summary> */
-/* Get next packet in resolution-precinct-component-layer order.   */
-/* </summary> */
-int pi_next_rpcl(pi_iterator_t * pi)
-{
-       pi_comp_t *comp;
-       pi_resolution_t *res;
-       if (!pi->first) {
-               goto skip;
-       } else {
-               int compno, resno;
-               pi->first = 0;
-               pi->dx = 0;
-               pi->dy = 0;
-               for (compno = 0; compno < pi->numcomps; compno++) {
-                       comp = &pi->comps[compno];
-                       for (resno = 0; resno < comp->numresolutions; resno++) {
-                               int dx, dy;
-                               res = &comp->resolutions[resno];
-                               dx =
-                                       comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
-                               dy =
-                                       comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
-                               pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
-                               pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
-                       }
-               }
-       }
-       for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
-               for (pi->y = pi->ty0; pi->y < pi->ty1;
-                                pi->y += pi->dy - (pi->y % pi->dy)) {
-                       for (pi->x = pi->tx0; pi->x < pi->tx1;
-                                        pi->x += pi->dx - (pi->x % pi->dx)) {
-                               for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1;
-                                                pi->compno++) {
-                                       int levelno;
-                                       int trx0, try0;
-                                       int rpx, rpy;
-                                       int prci, prcj;
-                                       comp = &pi->comps[pi->compno];
-                                       if (pi->resno >= comp->numresolutions) {
-                                               continue;
-                                       }
-                                       res = &comp->resolutions[pi->resno];
-                                       levelno = comp->numresolutions - 1 - pi->resno;
-                                       trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
-                                       try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
-                                       rpx = res->pdx + levelno;
-                                       rpy = res->pdy + levelno;
-                                       if (!
-                                                       (pi->x % (comp->dx << rpx) == 0
-                                                        || (pi->x == pi->tx0 && (trx0 << levelno) % (1 << rpx)))) {
-                                               continue;
-                                       }
-                                       if (!
-                                                       (pi->y % (comp->dy << rpy) == 0
-                                                        || (pi->y == pi->ty0 && (try0 << levelno) % (1 << rpx)))) {
-                                               continue;
-                                       }
-                                       prci =
-                                               int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno),
-                                                                                                                res->pdx) - int_floordivpow2(trx0, res->pdx);
-                                       prcj =
-                                               int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno),
-                                                                                                                res->pdy) - int_floordivpow2(try0, res->pdy);
-                                       pi->precno = prci + prcj * res->pw;
-                                       for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {
-                                         if (!pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p]){
-                                           pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p] = 1;
-                                           return 1;
-                                               }
-                                       skip:;
-                                       }
-                               }
-                       }
-               }
-       }
-       return 0;
-}
-
-/* <summary> */
-/* Get next packet in precinct-component-resolution-layer order.   */
-/* </summary> */
-int pi_next_pcrl(pi_iterator_t * pi)
-{
-       pi_comp_t *comp;
-       pi_resolution_t *res;
-       if (!pi->first) {
-               comp = &pi->comps[pi->compno];
-               goto skip;
-       } else {
-               int compno, resno;
-               pi->first = 0;
-               pi->dx = 0;
-               pi->dy = 0;
-               for (compno = 0; compno < pi->numcomps; compno++) {
-                       comp = &pi->comps[compno];
-                       for (resno = 0; resno < comp->numresolutions; resno++) {
-                               int dx, dy;
-                               res = &comp->resolutions[resno];
-                               dx =
-                                       comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
-                               dy =
-                                       comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
-                               pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
-                               pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
-                       }
-               }
-       }
-       for (pi->y = pi->ty0; pi->y < pi->ty1;
-                        pi->y += pi->dy - (pi->y % pi->dy)) {
-               for (pi->x = pi->tx0; pi->x < pi->tx1;
-                                pi->x += pi->dx - (pi->x % pi->dx)) {
-                       for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1;
-                                        pi->compno++) {
-                               comp = &pi->comps[pi->compno];
-                               for (pi->resno = pi->poc.resno0;
-                                                pi->resno < int_min(pi->poc.resno1, comp->numresolutions);
-                                                pi->resno++) {
-                                       int levelno;
-                                       int trx0, try0;
-                                       int rpx, rpy;
-                                       int prci, prcj;
-                                       res = &comp->resolutions[pi->resno];
-                                       levelno = comp->numresolutions - 1 - pi->resno;
-                                       trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
-                                       try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
-                                       rpx = res->pdx + levelno;
-                                       rpy = res->pdy + levelno;
-                                       if (!
-                                                       (pi->x % (comp->dx << rpx) == 0
-                                                        || (pi->x == pi->tx0 && (trx0 << levelno) % (1 << rpx)))) {
-                                               continue;
-                                       }
-                                       if (!
-                                                       (pi->y % (comp->dy << rpy) == 0
-                                                        || (pi->y == pi->ty0 && (try0 << levelno) % (1 << rpx)))) {
-                                               continue;
-                                       }
-                                       prci =
-                                               int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno),
-                                                                                                                res->pdx) - int_floordivpow2(trx0, res->pdx);
-                                       prcj =
-                                               int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno),
-                                                                                                                res->pdy) - int_floordivpow2(try0, res->pdy);
-                                       pi->precno = prci + prcj * res->pw;
-                                       for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {
-                                         if (! pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p]){
-                                           pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p] = 1;
-                                                       return 1;
-                                               }
-                                       skip:;
-                                       }
-                               }
-                       }
-               }
-       }
-       return 0;
-}
-
-/* <summary> */
-/* Get next packet in component-precinct-resolution-layer order.   */
-/* </summary> */
-int pi_next_cprl(pi_iterator_t * pi)
-{
-       pi_comp_t *comp;
-       pi_resolution_t *res;
-       if (!pi->first) {
-               comp = &pi->comps[pi->compno];
-               goto skip;
-       } else {
-               pi->first = 0;
-       }
-       for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1;
-                        pi->compno++) {
-               int resno;
-               comp = &pi->comps[pi->compno];
-               pi->dx = 0;
-               pi->dy = 0;
-               for (resno = 0; resno < comp->numresolutions; resno++) {
-                       int dx, dy;
-                       res = &comp->resolutions[resno];
-                       dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
-                       dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
-                       pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
-                       pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
-               }
-               for (pi->y = pi->ty0; pi->y < pi->ty1;
-                                pi->y += pi->dy - (pi->y % pi->dy)) {
-                       for (pi->x = pi->tx0; pi->x < pi->tx1;
-                                        pi->x += pi->dx - (pi->x % pi->dx)) {
-                               for (pi->resno = pi->poc.resno0;
-                                                pi->resno < int_min(pi->poc.resno1, comp->numresolutions);
-                                                pi->resno++) {
-                                       int levelno;
-                                       int trx0, try0;
-                                       int rpx, rpy;
-                                       int prci, prcj;
-                                       res = &comp->resolutions[pi->resno];
-                                       levelno = comp->numresolutions - 1 - pi->resno;
-                                       trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
-                                       try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
-                                       rpx = res->pdx + levelno;
-                                       rpy = res->pdy + levelno;
-                                       if (!
-                                                       (pi->x % (comp->dx << rpx) == 0
-                                                        || (pi->x == pi->tx0 && (trx0 << levelno) % (1 << rpx)))) {
-                                               continue;
-                                       }
-                                       if (!
-                                                       (pi->y % (comp->dy << rpy) == 0
-                                                        || (pi->y == pi->ty0 && (try0 << levelno) % (1 << rpx)))) {
-                                               continue;
-                                       }
-                                       prci =
-                                               int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno),
-                                                                                                                res->pdx) - int_floordivpow2(trx0, res->pdx);
-                                       prcj =
-                                               int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno),
-                                                                                                                res->pdy) - int_floordivpow2(try0, res->pdy);
-                                       pi->precno = prci + prcj * res->pw;
-                                       for (pi->layno = 0; pi->layno < pi->poc.layno1; pi->layno++) {
-                                         if (! pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p]){
-                                           pi->include[pi->layno*pi->step_l+pi->resno*pi->step_r+pi->compno*pi->step_c+pi->precno*pi->step_p] = 1;
-                                           return 1;
-                                               }
-                                       skip:;
-                                       }
-                               }
-                       }
-               }
-       }
-       return 0;
-}
-
-/* <summary> */
-/* Get next packet.   */
-/* </summary> */
-int pi_next(pi_iterator_t * pi)
-{
-       switch (pi->poc.prg) {
-       case 0:
-               return pi_next_lrcp(pi);
-       case 1:
-               return pi_next_rlcp(pi);
-       case 2:
-               return pi_next_rpcl(pi);
-       case 3:
-               return pi_next_pcrl(pi);
-       case 4:
-               return pi_next_cprl(pi);
-       }
-       return 0;
-}
diff --git a/indexer_JPIP/pi.h b/indexer_JPIP/pi.h
deleted file mode 100644 (file)
index b300b9e..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __PI_H
-#define __PI_H
-
-#include "j2k.h"
-#include "tcd.h"
-
-typedef struct {
-       int pdx, pdy;
-       int pw, ph;
-} pi_resolution_t;
-
-typedef struct {
-       int dx, dy;
-       int numresolutions;
-       pi_resolution_t *resolutions;
-} pi_comp_t;
-
-typedef struct {
-       short int *include;
-  int step_l, step_r, step_c, step_p; 
-       int compno, resno, precno, layno;       /* component, resolution, precinct and layer that indentify the packet */
-       int first;
-       j2k_poc_t poc;
-       int numcomps;
-       pi_comp_t *comps;
-       int tx0, ty0, tx1, ty1;
-       int x, y, dx, dy;
-} pi_iterator_t;                                                               /* packet iterator */
-
-/*
- * Create a packet iterator
- * img: raw image for which the packets will be listed
- * cp: coding paremeters
- * tileno: number that identifies the tile for which to list the packets
- * return value: returns a packet iterator that points to the first packet of the tile
- */
-pi_iterator_t *pi_create(j2k_image_t * img, j2k_cp_t * cp, int tileno);
-
-/* 
- * Modify the packet iterator to point to the next packet
- * pi: packet iterator to modify
- * return value: returns 0 if pi pointed to the last packet or else returns 1 
- */
-int pi_next(pi_iterator_t * pi);
-
-#endif
diff --git a/indexer_JPIP/t2.c b/indexer_JPIP/t2.c
deleted file mode 100644 (file)
index 14a44be..0000000
+++ /dev/null
@@ -1,389 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "t2.h"
-#include "tcd.h"
-#include "bio.h"
-#include "j2k.h"
-#include "pi.h"
-#include "tgt.h"
-#include "int.h"
-#include "cio.h"
-#include <stdio.h>
-#include <setjmp.h>
-#include <string.h>
-#include <stdlib.h> 
-
-#define RESTART 0x04
-
-extern jmp_buf j2k_error;
-
-int t2_getcommacode() {
-    int n;
-    for (n=0; bio_read(1); n++) {}
-    return n;
-}
-
-int t2_getnumpasses()
-{
-    int n;
-    if (!bio_read(1)) return 1;
-    if (!bio_read(1)) return 2;
-    if ((n=bio_read(2))!=3) return 3+n;
-    if ((n=bio_read(5))!=31) return 6+n;
-    return 37+bio_read(7);
-}
-
-void t2_init_seg(tcd_seg_t *seg, int cblksty) {
-    seg->numpasses=0;
-    seg->len=0;
-    seg->maxpasses=cblksty&J2K_CCP_CBLKSTY_TERMALL?1:100;
-}
-
-int t2_decode_packet(unsigned char *src, int len, tcd_tile_t *tile, j2k_cp_t * cp, j2k_tcp_t *tcp, int compno, int resno, int precno, int layno, info_layer_t *layer_Idx) {
-    int bandno, cblkno;
-    tcd_tilecomp_t *tilec = &tile->comps[compno];
-    tcd_resolution_t *res = &tilec->resolutions[resno];
-    unsigned char *c = src;
-    unsigned char *d = c;
-    int e;
-    int present;
-
-    if (layno == 0) {
-        for (bandno = 0; bandno < res->numbands; bandno++) {
-            tcd_band_t *band = &res->bands[bandno];
-            tcd_precinct_t *prc = &band->precincts[precno];
-            tgt_reset(prc->incltree);
-            tgt_reset(prc->imsbtree);
-            for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
-                tcd_cblk_t *cblk = &prc->cblks[cblkno];
-                cblk->numsegs = 0;
-            }
-        }  
-    }
-    /* INDEX */
-    layer_Idx->len_header = 0;
-
-    /* When the marker PPT/PPM is used the packet header are store in PPT/PPM marker
-       This part deal with this caracteristic
-       step 1: Read packet header in the saved structure
-       step 2: (futher) return to codestream for decoding */
-    if (cp->ppm == 1) /* PPM */
-      {            
-       c = cp->ppm_data;
-       d = c;
-       bio_init_dec(c, 1000);
-      } else 
-       {
-         if (tcp->ppt == 1) /* PPT */
-           {
-             c = tcp->ppt_data;
-             d = c;
-             bio_init_dec(c, 1000);
-           } else /* Normal Case */
-             {
-               if (tcp->csty & J2K_CP_CSTY_SOP) 
-                 {
-                   if ((*c) != 255 || (*(c+1) != 145)) {printf("Error : expected SOP marker [1]!!!\n");}
-                   c += 6;
-                 }
-               bio_init_dec(c, src + len - c);
-               layer_Idx->len_header = -6;
-             }
-       }
-    
-    present = bio_read(1);
-    
-    if (!present) 
-      {
-       bio_inalign();
-       /* Normal case */
-       c += bio_numbytes();
-       if (tcp->csty & J2K_CP_CSTY_EPH) 
-         {
-           if ((*c) != 255 || (*(c+1) != 146)) {printf("Error : expected EPH marker [1]!!!\n");}
-           c += 2;
-         }
-       /* INDEX */
-       layer_Idx->len_header += (c-d);
-
-       /* PPT and PPM dealing */
-       if (cp->ppm == 1) /* PPM */
-         {     
-           cp->ppm_data = c;       
-           return 0;
-         }
-       if (tcp->ppt == 1) /* PPT */
-         {
-           tcp->ppt_data = c;
-           return 0;
-         }
-       return c - src;
-      }
-    
-    for (bandno=0; bandno<res->numbands; bandno++) {
-        tcd_band_t *band = &res->bands[bandno];
-        tcd_precinct_t *prc = &band->precincts[precno];
-        for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
-            int included, increment, n;
-            tcd_cblk_t *cblk = &prc->cblks[cblkno];
-            tcd_seg_t *seg;
-            if (!cblk->numsegs) {
-                included = tgt_decode(prc->incltree, cblkno, layno+1);
-            } else {
-                included = bio_read(1);
-            }
-            if (!included) {
-                cblk->numnewpasses = 0;
-                continue;
-            }
-            if (!cblk->numsegs) {
-                int i, numimsbs;
-                for (i = 0; !tgt_decode(prc->imsbtree, cblkno, i); i++) {}
-                numimsbs = i-1;
-                cblk->numbps = band->numbps - numimsbs;
-                cblk->numlenbits = 3;
-            }
-            cblk->numnewpasses = t2_getnumpasses();
-            increment = t2_getcommacode();
-            cblk->numlenbits += increment;
-            if (!cblk->numsegs) {
-                seg = &cblk->segs[0];
-                t2_init_seg(seg, tcp->tccps[compno].cblksty);
-            } else {
-                seg = &cblk->segs[cblk->numsegs - 1];
-                if (seg->numpasses == seg->maxpasses) {
-                    t2_init_seg(++seg, tcp->tccps[compno].cblksty);
-                }
-            }
-            n = cblk->numnewpasses;
-            do {
-                seg->numnewpasses = int_min(seg->maxpasses-seg->numpasses, n);
-                seg->newlen = bio_read(cblk->numlenbits + int_floorlog2(seg->numnewpasses));
-                n -= seg->numnewpasses;
-                if (n > 0) {
-                    t2_init_seg(++seg, tcp->tccps[compno].cblksty);
-                }
-            } while (n > 0);
-        }
-    }
-    if(bio_inalign()) return -999;
-    c += bio_numbytes();
-
-    if (tcp->csty & J2K_CP_CSTY_EPH) { /* EPH marker */
-      if ((*c) != 255 || (*(c+1) != 146)) {printf("Error : expected EPH marker [2]!!!\n"); }
-      c += 2;
-    }
-    
-    /* INDEX */
-    layer_Idx->len_header += (c-d);
-
-    /* PPT Step 2 : see above for details */
-    if (cp->ppm == 1)
-      {
-       cp->ppm_data = c; /* Update pointer */
-
-       /* INDEX */
-       layer_Idx->len_header = c-d;
-
-       c = src;
-       d = c;
-       if (tcp->csty & J2K_CP_CSTY_SOP) 
-         {
-           if ((*c) != 255 || (*(c+1) != 145)) {printf("Error : expected SOP marker [2] !!!\n"); }
-           c += 6;
-         }
-       bio_init_dec(c, src + len - c);
-      } else 
-       {
-         if (tcp->ppt == 1)
-           { 
-             tcp->ppt_data = c; /* Update pointer */
-             /* INDEX */
-             layer_Idx->len_header = c-d;
-
-             c = src;
-             d = c;
-             if (tcp->csty & J2K_CP_CSTY_SOP) /* SOP marker */
-               { 
-                 if ((*c) != 255 || (*(c+1) != 145)) {printf("Error : expected SOP marker [2] !!!\n"); }
-                 c += 6;
-               }
-             bio_init_dec(c, src + len - c);
-             
-           }
-       }
-
-    for (bandno = 0; bandno < res->numbands; bandno++) {
-        tcd_band_t *band = &res->bands[bandno];
-        tcd_precinct_t *prc = &band->precincts[precno];
-        for (cblkno = 0; cblkno < prc->cw*prc->ch; cblkno++) {
-            tcd_cblk_t *cblk = &prc->cblks[cblkno];
-            tcd_seg_t *seg;
-            if (!cblk->numnewpasses) continue;
-            if (!cblk->numsegs) {
-                seg = &cblk->segs[cblk->numsegs++];
-                cblk->len = 0;
-            } else {
-                seg = &cblk->segs[cblk->numsegs-1];
-                if (seg->numpasses == seg->maxpasses) {
-                    seg++;
-                    cblk->numsegs++;
-                }
-            }
-            do {
-             if (c + seg->newlen > src + len) return -999;
-                memcpy(cblk->data + cblk->len, c, seg->newlen);
-                if (seg->numpasses == 0) {
-                    seg->data = cblk->data + cblk->len;
-                }
-                c += seg->newlen;
-                cblk->len += seg->newlen;
-                seg->len += seg->newlen;
-                seg->numpasses += seg->numnewpasses;
-                cblk->numnewpasses -= seg->numnewpasses;
-                if (cblk->numnewpasses > 0) {
-                    seg++;
-                    cblk->numsegs++;
-                }
-            } while (cblk->numnewpasses > 0);
-        }
-    }
-    /* <INDEX> */
-    e = c-d;
-    layer_Idx->len = e;
-    /* </INDEX> */
-
-    return c-src;
-}
-
-void t2_init_info_packets(info_image_t *img, j2k_cp_t *cp)
-{
-  int compno, tileno, resno, precno, layno;
-
-  for(compno = 0; compno < img->Comp; compno++)
-    {
-      for(tileno = 0; tileno < img->tw*img->th; tileno++)
-       {
-         info_tile_t *tile_Idx = &img->tile[tileno];
-         info_compo_t *compo_Idx = &tile_Idx->compo[compno];
-         for(resno = 0; resno < img->Decomposition + 1 ; resno++)
-           {
-             info_reso_t *reso_Idx = &compo_Idx->reso[resno];
-             for (precno = 0; precno < img->tile[tileno].pw * img->tile[tileno].ph; precno++)
-               {
-                 info_prec_t *prec_Idx = &reso_Idx->prec[precno];
-                 for(layno = 0; layno < img->Layer ; layno++)
-                   {
-                     info_layer_t *layer_Idx = &prec_Idx->layer[layno];
-                     layer_Idx->offset = 0;        /* start position */
-                     layer_Idx->len_header = 0;    /* length         */
-                   }
-               }
-           }
-       }
-    }
-}
-
-int t2_decode_packets(unsigned char *src, int len, j2k_image_t *img, j2k_cp_t *cp, int tileno, tcd_tile_t *tile, info_image_t *imgg) {
-    unsigned char *c = src;
-    pi_iterator_t *pi;
-    int pino, compno,e;
-    int partno;
-    info_tile_part_t *tile_part;
-    int position;
-    int length_read;
-    info_tile_t *tile_Idx;
-    info_compo_t *compo_Idx;
-    info_reso_t *reso_Idx;
-    info_prec_t *prec_Idx;
-    info_layer_t *layer_Idx;
-
-    t2_init_info_packets(imgg, cp); /* Initialize the packets information : LEN and OFFSET to 0 */
-
-    tile_Idx = &imgg->tile[tileno];
-    tile_Idx->num_packet = 0;
-    pi = pi_create(img, cp, tileno);
-    partno = 0;
-    tile_part = &tile_Idx->tile_parts[partno];
-    position = tile_part->end_header + 1;
-    length_read = 0;
-
-    for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++)
-      {
-       while (pi_next(&pi[pino])) 
-         {   
-           compo_Idx = &tile_Idx->compo[pi[pino].compno];
-           reso_Idx = &compo_Idx->reso[pi[pino].resno];
-           prec_Idx = &reso_Idx->prec[pi[pino].precno];
-           layer_Idx = &prec_Idx->layer[pi[pino].layno];
-           
-           layer_Idx->offset = position;
-           layer_Idx->offset_header = position;
-           
-           e = t2_decode_packet(c, src+len-c, tile, cp, &cp->tcps[tileno], pi[pino].compno, pi[pino].resno, pi[pino].precno, pi[pino].layno,layer_Idx);
-           if (e == -999)
-             {
-               break;
-             } else
-               c += e;
-           position += e;
-           
-           /* Update position in case of multiple tile-parts for a tile >> */
-           length_read += e;
-           if (length_read >= (tile_part->end_pos - tile_part->end_header))
-             {
-               partno++;
-               tile_part = &tile_Idx->tile_parts[partno];
-               position = tile_part->end_header + 1;
-               length_read = 0;
-             }
-           /* << end_update */
-           
-           tile_Idx->num_packet++;
-         }
-       
-       // FREE space memory taken by pi
-       for (compno = 0; compno < pi[pino].numcomps; compno++) 
-         { 
-           free(pi[pino].comps[compno].resolutions);
-         } 
-       free(pi[pino].comps);
-      }
-    
-    free(pi[0].include);
-    free(pi);
-    if (e==-999)
-      return e;
-    else
-      {
-       imgg->num_packet_max=int_max(imgg->num_packet_max,tile_Idx->num_packet);
-       return c-src;
-      }
-}
diff --git a/indexer_JPIP/t2.h b/indexer_JPIP/t2.h
deleted file mode 100644 (file)
index f495107..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __T2_H
-#define __T2_H
-
-#include "tcd.h"
-#include "j2k.h"
-
-/*
- * Decode the packets of a tile from a source buffer
- * src: the source buffer
- * len: length of the source buffer
- * img: destination image
- * cp: image coding parameters
- * tileno: number that identifies the tile for which to decode the packets
- * tile: tile for which to decode the packets
- */
-int t2_decode_packets(unsigned char *src, int len, j2k_image_t *img, j2k_cp_t *cp, int tileno, tcd_tile_t *tile, info_image_t *imgg);
-
-#endif
diff --git a/indexer_JPIP/tcd.c b/indexer_JPIP/tcd.c
deleted file mode 100644 (file)
index c4045c7..0000000
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "tcd.h"
-#include "int.h"
-#include "t2.h"
-#include <setjmp.h>
-#include <float.h>
-#include <stdio.h>
-#include <time.h>
-#include <math.h>
-#include <stdlib.h>
-#include <string.h>
-
-static tcd_image_t tcd_image;
-
-static j2k_image_t *tcd_img;
-static j2k_cp_t *tcd_cp;
-
-extern jmp_buf j2k_error;
-
-void tcd_init(j2k_image_t *img, j2k_cp_t *cp, info_image_t *imgg) {
-    int tileno, compno, resno, bandno, precno, cblkno;
-    tcd_img=img;
-    tcd_cp=cp;
-    tcd_image.tw=cp->tw;
-    tcd_image.th=cp->th;
-    tcd_image.tiles=(tcd_tile_t*)malloc(cp->tw*cp->th*sizeof(tcd_tile_t));
-    for (tileno=0; tileno<cp->tw*cp->th; tileno++) {
-        j2k_tcp_t *tcp=&cp->tcps[tileno];
-        tcd_tile_t *tile=&tcd_image.tiles[tileno];
-        // cfr p59 ISO/IEC FDIS15444-1 : 2000 (18 august 2000)
-        int p=tileno%cp->tw;  // si numerotation matricielle ..
-        int q=tileno/cp->tw;  // .. coordonnees de la tile (q,p) q pour ligne et p pour colonne
-       info_tile_t *tile_Idx=&imgg->tile[tileno]; // INDEX
-
-       // 4 borders of the tile rescale on the image if necessary
-        tile->x0=int_max(cp->tx0+p*cp->tdx, img->x0);
-        tile->y0=int_max(cp->ty0+q*cp->tdy, img->y0);
-        tile->x1=int_min(cp->tx0+(p+1)*cp->tdx, img->x1);
-        tile->y1=int_min(cp->ty0+(q+1)*cp->tdy, img->y1);
-       
-        tile->numcomps=img->numcomps;
-        tile->comps=(tcd_tilecomp_t*)malloc(img->numcomps*sizeof(tcd_tilecomp_t));
-        tile_Idx->compo=(info_compo_t*)malloc(img->numcomps*sizeof(info_compo_t)); // INDEX
-       for (compno=0; compno<tile->numcomps; compno++) {
-            j2k_tccp_t *tccp=&tcp->tccps[compno];
-            tcd_tilecomp_t *tilec=&tile->comps[compno];
-           info_compo_t *compo_Idx=&tile_Idx->compo[compno]; // INDEX
-
-           // border of each tile component (global)
-            tilec->x0=int_ceildiv(tile->x0, img->comps[compno].dx);
-            tilec->y0=int_ceildiv(tile->y0, img->comps[compno].dy);
-           tilec->x1=int_ceildiv(tile->x1, img->comps[compno].dx);
-            tilec->y1=int_ceildiv(tile->y1, img->comps[compno].dy);
-           
-            tilec->data=(int*)malloc(sizeof(int)*(tilec->x1-tilec->x0)*(tilec->y1-tilec->y0));
-            tilec->numresolutions=tccp->numresolutions;
-            tilec->resolutions=(tcd_resolution_t*)malloc(tilec->numresolutions*sizeof(tcd_resolution_t));
-           compo_Idx->reso=(info_reso_t*)malloc(tilec->numresolutions*sizeof(info_reso_t)); // INDEX
-            for (resno=0; resno<tilec->numresolutions; resno++) {
-                int pdx, pdy;
-                int levelno=tilec->numresolutions-1-resno;
-                int tlprcxstart, tlprcystart, brprcxend, brprcyend;
-                int tlcbgxstart, tlcbgystart, brcbgxend, brcbgyend;
-                int cbgwidthexpn, cbgheightexpn;
-                int cblkwidthexpn, cblkheightexpn;
-                tcd_resolution_t *res=&tilec->resolutions[resno];
-               info_reso_t *res_Idx=&compo_Idx->reso[resno]; // INDEX
-               int precno_Idx; // INDEX
-
-               // border for each resolution level (global)
-                res->x0=int_ceildivpow2(tilec->x0, levelno);
-                res->y0=int_ceildivpow2(tilec->y0, levelno);
-                res->x1=int_ceildivpow2(tilec->x1, levelno);
-                res->y1=int_ceildivpow2(tilec->y1, levelno);
-               
-               res->numbands=resno==0?1:3;
-               // p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000)
-                if (tccp->csty&J2K_CCP_CSTY_PRT) {
-                    pdx=tccp->prcw[resno];
-                    pdy=tccp->prch[resno];
-               } else {
-                    pdx=15;
-                    pdy=15;
-                }
-               // p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000) 
-                tlprcxstart=int_floordivpow2(res->x0, pdx)<<pdx;
-                tlprcystart=int_floordivpow2(res->y0, pdy)<<pdy;
-                brprcxend=int_ceildivpow2(res->x1, pdx)<<pdx;
-                brprcyend=int_ceildivpow2(res->y1, pdy)<<pdy;
-                res->pw=(brprcxend-tlprcxstart)>>pdx;
-                res->ph=(brprcyend-tlprcystart)>>pdy;
-
-               // <INDEX>
-               imgg->tile[tileno].pw=res->pw;
-               imgg->tile[tileno].ph=res->ph;
-               
-               res_Idx->prec=(info_prec_t*)malloc(res->pw*res->ph*sizeof(info_prec_t));
-               for (precno_Idx=0;precno_Idx<res->pw*res->ph;precno_Idx++)
-                 {
-                   info_prec_t *prec_Idx = &res_Idx->prec[precno_Idx];
-                   prec_Idx->layer=(info_layer_t*)malloc(imgg->Layer*sizeof(info_layer_t));
-                 }
-               
-               imgg->pw=res->pw;  // old parser version
-               imgg->ph=res->ph;  // old parser version
-               imgg->pdx=1<<pdx;
-               imgg->pdy=1<<pdy;
-               // </INDEX>
-
-                if (resno==0) {
-                    tlcbgxstart=tlprcxstart;
-                    tlcbgystart=tlprcystart;
-                    brcbgxend=brprcxend;
-                    brcbgyend=brprcyend;
-                    cbgwidthexpn=pdx;
-                    cbgheightexpn=pdy;
-                } else {
-                    tlcbgxstart=int_ceildivpow2(tlprcxstart, 1);
-                    tlcbgystart=int_ceildivpow2(tlprcystart, 1);
-                    brcbgxend=int_ceildivpow2(brprcxend, 1);
-                    brcbgyend=int_ceildivpow2(brprcyend, 1);
-                    cbgwidthexpn=pdx-1;
-                    cbgheightexpn=pdy-1;
-                }
-
-                cblkwidthexpn=int_min(tccp->cblkw, cbgwidthexpn);
-                cblkheightexpn=int_min(tccp->cblkh, cbgheightexpn);
-
-                for (bandno=0; bandno<res->numbands; bandno++) {
-                    int x0b, y0b;
-                    tcd_band_t *band=&res->bands[bandno];
-                    band->bandno=resno==0?0:bandno+1;
-                    x0b=(band->bandno==1)||(band->bandno==3)?1:0;
-                    y0b=(band->bandno==2)||(band->bandno==3)?1:0;
-
-                    if (band->bandno==0) {
-                     // band border (global)
-                     band->x0=int_ceildivpow2(tilec->x0, levelno);
-                     band->y0=int_ceildivpow2(tilec->y0, levelno);
-                     band->x1=int_ceildivpow2(tilec->x1, levelno);
-                     band->y1=int_ceildivpow2(tilec->y1, levelno);
-                    } else {
-                     // band border (global)
-                     band->x0=int_ceildivpow2(tilec->x0-(1<<levelno)*x0b, levelno+1);
-                     band->y0=int_ceildivpow2(tilec->y0-(1<<levelno)*y0b, levelno+1);
-                     band->x1=int_ceildivpow2(tilec->x1-(1<<levelno)*x0b, levelno+1);
-                     band->y1=int_ceildivpow2(tilec->y1-(1<<levelno)*y0b, levelno+1);
-                    }
-
-                    band->precincts=(tcd_precinct_t*)malloc(res->pw*res->ph*sizeof(tcd_precinct_t));
-
-                    for (precno=0; precno<res->pw*res->ph; precno++) {
-                        int tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend;
-                        int cbgxstart=tlcbgxstart+(precno%res->pw)*(1<<cbgwidthexpn);
-                        int cbgystart=tlcbgystart+(precno/res->pw)*(1<<cbgheightexpn);
-                        int cbgxend=cbgxstart+(1<<cbgwidthexpn);
-                        int cbgyend=cbgystart+(1<<cbgheightexpn);
-                        tcd_precinct_t *prc=&band->precincts[precno];
-                       // precinct size (global)
-                        prc->x0=int_max(cbgxstart, band->x0);
-                        prc->y0=int_max(cbgystart, band->y0);
-                        prc->x1=int_min(cbgxend, band->x1);
-                        prc->y1=int_min(cbgyend, band->y1);
-
-                        tlcblkxstart=int_floordivpow2(prc->x0, cblkwidthexpn)<<cblkwidthexpn;
-                        tlcblkystart=int_floordivpow2(prc->y0, cblkheightexpn)<<cblkheightexpn;
-                        brcblkxend=int_ceildivpow2(prc->x1, cblkwidthexpn)<<cblkwidthexpn;
-                        brcblkyend=int_ceildivpow2(prc->y1, cblkheightexpn)<<cblkheightexpn;
-                        prc->cw=(brcblkxend-tlcblkxstart)>>cblkwidthexpn;
-                        prc->ch=(brcblkyend-tlcblkystart)>>cblkheightexpn;
-
-                        prc->cblks=(tcd_cblk_t*)malloc(prc->cw*prc->ch*sizeof(tcd_cblk_t));
-
-                        prc->incltree=tgt_create(prc->cw, prc->ch);
-                        prc->imsbtree=tgt_create(prc->cw, prc->ch);
-
-                        for (cblkno=0; cblkno<prc->cw*prc->ch; cblkno++) {
-                            int cblkxstart=tlcblkxstart+(cblkno%prc->cw)*(1<<cblkwidthexpn);
-                            int cblkystart=tlcblkystart+(cblkno/prc->cw)*(1<<cblkheightexpn);
-                            int cblkxend=cblkxstart+(1<<cblkwidthexpn);
-                            int cblkyend=cblkystart+(1<<cblkheightexpn);
-                            tcd_cblk_t *cblk=&prc->cblks[cblkno];
-                           // code-block size (global)
-                            cblk->x0=int_max(cblkxstart, prc->x0);
-                            cblk->y0=int_max(cblkystart, prc->y0);
-                            cblk->x1=int_min(cblkxend, prc->x1);
-                            cblk->y1=int_min(cblkyend, prc->y1);
-                        }
-                    }
-                }
-            }
-        }
-    }
-}
-
-
-void tcd_free(j2k_image_t *img, j2k_cp_t *cp) {
-  int tileno, compno, resno, bandno, precno;
-  tcd_img=img;
-  tcd_cp=cp;
-  tcd_image.tw=cp->tw;
-  tcd_image.th=cp->th;
-  for (tileno=0; tileno<tcd_image.tw*tcd_image.th; tileno++) 
-    {
-      //  j2k_tcp_t *tcp=&cp->tcps[curtileno];
-      tcd_tile_t *tile=&tcd_image.tiles[tileno];
-      for (compno=0; compno<tile->numcomps; compno++) 
-       {
-        tcd_tilecomp_t *tilec=&tile->comps[compno];
-         for (resno=0; resno<tilec->numresolutions; resno++) 
-           {
-             tcd_resolution_t *res=&tilec->resolutions[resno];
-             for (bandno=0; bandno<res->numbands; bandno++) 
-               {
-                tcd_band_t *band=&res->bands[bandno];
-                 for (precno=0; precno<res->pw*res->ph; precno++) 
-                   {
-                    tcd_precinct_t *prc=&band->precincts[precno];
-                     
-                     if (prc->incltree!=NULL)
-                       tgt_destroy(prc->incltree);
-                     if (prc->imsbtree!=NULL)
-                       tgt_destroy(prc->imsbtree);
-                     free(prc->cblks);
-                   } // for (precno
-                 free(band->precincts);
-               } // for (bandno
-           }   // for (resno
-         free(tilec->resolutions);
-       }       // for (compno
-      free(tile->comps);
-    }  // for (tileno
-  free(tcd_image.tiles);
-}
-
-
-int tcd_decode_tile(unsigned char *src, int len, int tileno, info_image_t *imgg) {
-    int l;
-    int eof=0;
-    tcd_tile_t *tile;
-
-    tile = &tcd_image.tiles[tileno];
-
-    l = t2_decode_packets(src, len, tcd_img, tcd_cp, tileno, tile, imgg);
-
-    if (l==-999)
-      {
-       eof=1;
-       fprintf(stderr, "tcd_decode: incomplete bistream\n");
-      }
-    
-     if (eof) {
-       longjmp(j2k_error, 1);
-     }
-
-    l=1;
-    return l;
-}
diff --git a/indexer_JPIP/tcd.h b/indexer_JPIP/tcd.h
deleted file mode 100644 (file)
index 9a31723..0000000
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __TCD_H
-#define __TCD_H
-
-#include "j2k.h"
-#include "tgt.h"
-
-typedef struct {
-    int numpasses;
-    int len;
-    unsigned char *data;
-    int maxpasses;
-    int numnewpasses;
-    int newlen;
-} tcd_seg_t;
-
-typedef struct {
-    int rate;
-    double distortiondec;
-} tcd_pass_t;
-
-typedef struct {
-    int numpasses;
-    int len;
-    unsigned char *data;
-} tcd_layer_t;
-
-typedef struct {
-    int x0, y0, x1, y1;
-    int numbps;
-    int numlenbits;
-    int len;
-    int numpasses;
-    int numnewpasses;
-    int numsegs;
-    tcd_seg_t segs[100];
-    unsigned char data[8192];
-    int numpassesinlayers;
-    tcd_layer_t layers[100];
-    int totalpasses;
-    tcd_pass_t passes[100];
-} tcd_cblk_t;
-
-typedef struct {
-    int x0, y0, x1, y1;
-    int cw, ch;
-    tcd_cblk_t *cblks;
-    tgt_tree_t *incltree;
-    tgt_tree_t *imsbtree;
-} tcd_precinct_t;
-
-typedef struct {
-    int x0, y0, x1, y1;
-    int bandno;
-    tcd_precinct_t *precincts;
-    int numbps;
-    int stepsize;
-} tcd_band_t;
-
-typedef struct {
-    int x0, y0, x1, y1;  
-  int previous_x0, previous_y0, previous_x1, previous_y1; // usefull for the DWT
-  int cas_col, cas_row; // usefull for the DWT
-    int pw, ph;
-    int numbands;
-    tcd_band_t bands[3];
-} tcd_resolution_t;
-
-typedef struct {
-    int x0, y0, x1, y1;
-  int previous_row, previous_col; // usefull for the DWT
-    int numresolutions;
-    tcd_resolution_t *resolutions;
-    int *data;
-} tcd_tilecomp_t;
-
-typedef struct {
-    int x0, y0, x1, y1;
-    int numcomps;
-  //int PPT;
-  //int len_ppt;
-    tcd_tilecomp_t *comps;
-} tcd_tile_t;
-
-typedef struct {
-    int tw, th;
-    tcd_tile_t *tiles;
-} tcd_image_t;
-
-/*
- * Initialize the tile coder/decoder
- * img: raw image
- * cp: coding parameters
- * imgg: creation of index file
- */
-
-void tcd_init(j2k_image_t *img, j2k_cp_t *cp, info_image_t *imgg);
-
-void tcd_free(j2k_image_t *img, j2k_cp_t *cp);
-
-/*
- * Decode a tile from a buffer into a raw image
- * src: source buffer
- * len: length of the source buffer
- * tileno: number that identifies the tile that will be decoded
- * imgg : Structure for index file
- */
-int tcd_decode_tile(unsigned char *src, int len, int tileno, info_image_t *imgg);
-
-#endif
diff --git a/indexer_JPIP/tgt.c b/indexer_JPIP/tgt.c
deleted file mode 100644 (file)
index c2b4682..0000000
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "tgt.h"
-#include "bio.h"
-#include <stdlib.h>
-#include <stdio.h>
-
-/// <summary>
-/// Reset tag-tree.
-/// </summary>
-void tgt_reset(tgt_tree_t *tree)
-{
-    int i;
-    for (i=0; i<tree->numnodes; i++) {
-        tree->nodes[i].value=999;
-        tree->nodes[i].low=0;
-        tree->nodes[i].known=0;
-    }
-}
-
-/// <summary>
-/// Create tag-tree.
-/// </summary>
-tgt_tree_t *tgt_create(int numleafsh, int numleafsv)
-{
-    int nplh[32];
-    int nplv[32];
-    tgt_node_t *node;
-    tgt_node_t *parentnode;
-    tgt_node_t *parentnode0;
-    tgt_tree_t *tree;
-    int i, j, k;
-    int numlvls;
-    int n;
-
-    tree=(tgt_tree_t*)malloc(sizeof(tgt_tree_t));
-    tree->numleafsh=numleafsh;
-    tree->numleafsv=numleafsv;
-
-    numlvls=0;
-    nplh[0]=numleafsh;
-    nplv[0]=numleafsv;
-    tree->numnodes=0;
-    do {
-        n=nplh[numlvls]*nplv[numlvls];
-        nplh[numlvls+1]=(nplh[numlvls]+1)/2;
-        nplv[numlvls+1]=(nplv[numlvls]+1)/2;
-        tree->numnodes+=n;
-        ++numlvls;
-    } while (n>1);
-
-    tree->nodes=(tgt_node_t*)malloc(tree->numnodes*sizeof(tgt_node_t));
-
-    node=tree->nodes;
-    parentnode=&tree->nodes[tree->numleafsh*tree->numleafsv];
-    parentnode0=parentnode;
-
-    for (i=0; i<numlvls-1; ++i) {
-        for (j=0; j<nplv[i]; ++j) {
-            k=nplh[i];
-            while (--k>=0) {
-                node->parent=parentnode;
-                ++node;
-                if (--k >= 0) {
-                    node->parent=parentnode;
-                    ++node;
-                }
-                ++parentnode;
-            }
-            if ((j&1)||j==nplv[i]-1) {
-                parentnode0=parentnode;
-            } else {
-                parentnode=parentnode0;
-                parentnode0+=nplh[i];
-            }
-        }
-    }
-    node->parent=0;
-
-    tgt_reset(tree);
-
-    return tree;
-}
-
-/// <summary>
-/// Destroy tag-tree.
-/// </summary>
-void tgt_destroy(tgt_tree_t *t) {
-    free(t->nodes);
-    free(t);
-}
-
-/// <summary>
-/// Set the value of a leaf of the tag-tree.
-/// </summary>
-void tgt_setvalue(tgt_tree_t *tree, int leafno, int value) {
-    tgt_node_t *node;
-    node=&tree->nodes[leafno];
-    while (node && node->value>value) {
-        node->value=value;
-        node=node->parent;
-    }
-}
-
-/// <summary>
-/// Decode the value of a leaf of the tag-tree.
-/// </summary>
-int tgt_decode(tgt_tree_t *tree, int leafno, int threshold)
-{
-    tgt_node_t *stk[31];
-    tgt_node_t **stkptr;
-    tgt_node_t *node;
-    int low;
-
-    stkptr=stk;
-    node=&tree->nodes[leafno];
-    while (node->parent) {
-        *stkptr++=node;
-        node=node->parent;
-    }
-
-    low=0;
-    for (;;) {
-        if (low>node->low) {
-            node->low=low;
-        } else {
-            low=node->low;
-        }
-        while (low<threshold && low<node->value) {
-            if (bio_read(1)) {
-                node->value=low;
-            } else {
-                ++low;
-            }
-        }
-        node->low=low;
-        if (stkptr==stk) {
-            break;
-        }
-        node=*--stkptr;
-    }
-
-    return (node->value<threshold)?1:0;
-}
diff --git a/indexer_JPIP/tgt.h b/indexer_JPIP/tgt.h
deleted file mode 100644 (file)
index 9d85ade..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (c) 2001-2002, David Janssens
- * Copyright (c) 2003, Yannick Verschueren
- * Copyright (c) 2003,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __TGT_H
-#define __TGT_H
-
-typedef struct tgt_node {
-       struct tgt_node *parent;
-       int value;
-       int low;
-       int known;
-} tgt_node_t;
-
-typedef struct {
-       int numleafsh;
-       int numleafsv;
-       int numnodes;
-       tgt_node_t *nodes;
-} tgt_tree_t;
-
-/*
- * Create a tag-tree
- * numleafsh: width of the array of leafs of the tree
- * numleafsv: height of the array of leafs of the tree
- */
-tgt_tree_t *tgt_create(int numleafsh, int numleafsv);
-
-/*
- * Reset a tag-tree (set all leafs to 0)
- * tree: tag-tree to reset
- */
-void tgt_reset(tgt_tree_t *tree);
-
-/*
- * Destroy a tag-tree, liberating memory
- * tree: tag-tree to destroy
- */
-void tgt_destroy(tgt_tree_t *tree);
-
-/*
- * Set the value of a leaf of a tag-tree
- * tree: tag-tree to modify
- * leafno: number that identifies the leaf to modify
- * value: new value of the leaf
- */
-void tgt_setvalue(tgt_tree_t *tree, int leafno, int value);
-
-/*
- * Decode the value of a leaf of the tag-tree up to a given threshold
- * leafno: number that identifies the leaf to decode
- * threshold: threshold to use when decoding value of the leaf
- */
-int tgt_decode(tgt_tree_t *tree, int leafno, int threshold);
-
-#endif
diff --git a/jpwl/CMakeLists.txt b/jpwl/CMakeLists.txt
deleted file mode 100755 (executable)
index 7dbb3d6..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-# Makefile for the main JPWL OpenJPEG codecs: JPWL_ j2k_to_image and JPWL_image_to_j2k
-
-ADD_DEFINITIONS(-DUSE_JPWL)
-
-SET(OPJ_SRCS
-../libopenjpeg/bio.c
-../libopenjpeg/cio.c
-../libopenjpeg/dwt.c
-../libopenjpeg/event.c
-../libopenjpeg/image.c
-../libopenjpeg/j2k.c
-../libopenjpeg/j2k_lib.c
-../libopenjpeg/jp2.c
-../libopenjpeg/jpt.c
-../libopenjpeg/mct.c
-../libopenjpeg/mqc.c
-../libopenjpeg/openjpeg.c
-../libopenjpeg/pi.c
-../libopenjpeg/raw.c
-../libopenjpeg/t1.c
-../libopenjpeg/t2.c
-../libopenjpeg/tcd.c
-../libopenjpeg/tgt.c
-)
-SET(JPWL_SRCS crc.c jpwl.c jpwl_lib.c rs.c)
-
-SET(common_SRCS "")
-# If not getopt was found then add it to the lib:
-IF(DONT_HAVE_GETOPT)
-  SET(common_SRCS ${OPENJPEG_SOURCE_DIR}/common/getopt.c)
-ENDIF(DONT_HAVE_GETOPT)
-
-# Build the library
-IF(WIN32)
-  IF(BUILD_SHARED_LIBS)
-    ADD_DEFINITIONS(-DOPJ_EXPORTS)
-  ELSE(BUILD_SHARED_LIBS)
-    ADD_DEFINITIONS(-DOPJ_STATIC)
-  ENDIF(BUILD_SHARED_LIBS)
-ENDIF(WIN32)
-ADD_LIBRARY(${OPENJPEG_LIBRARY_NAME}_JPWL ${JPWL_SRCS} ${OPJ_SRCS})
-SET_TARGET_PROPERTIES(${OPENJPEG_LIBRARY_NAME}_JPWL 
-  PROPERTIES ${OPENJPEG_LIBRARY_PROPERTIES})
-
-# Install library
-INSTALL(TARGETS ${OPENJPEG_LIBRARY_NAME}_JPWL
-  DESTINATION ${OPENJPEG_INSTALL_LIB_DIR} COMPONENT Libraries
-)
-
-# Build executables
-
-INCLUDE_DIRECTORIES(
-  ${OPENJPEG_SOURCE_DIR}/libopenjpeg
-  ${OPENJPEG_SOURCE_DIR}/common
-  ${ZLIB_INCLUDE_DIRNAME}
-  ${LCMS_INCLUDE_DIRNAME}
-  ${PNG_INCLUDE_DIRNAME}
-  ${TIFF_INCLUDE_DIRNAME}
-  )
-
-ADD_EXECUTABLE(JPWL_j2k_to_image
-../codec/j2k_to_image.c
-../codec/convert.c
-../codec/index.c
-${OPENJPEG_SOURCE_DIR}/common/color.c
-${common_SRCS}
-)
-
-TARGET_LINK_LIBRARIES(JPWL_j2k_to_image ${OPENJPEG_LIBRARY_NAME}_JPWL
-  ${LCMS_LIBNAME} ${Z_LIBNAME} ${PNG_LIBNAME} ${TIFF_LIBNAME})
-#
-IF(UNIX)
-  TARGET_LINK_LIBRARIES(JPWL_j2k_to_image m)
-ENDIF(UNIX)
-
-
-ADD_EXECUTABLE(JPWL_image_to_j2k
-../codec/convert.c
-../codec/index.c
-../codec/image_to_j2k.c
-${common_SRCS}
-)
-
-TARGET_LINK_LIBRARIES(JPWL_image_to_j2k ${OPENJPEG_LIBRARY_NAME}_JPWL 
-       ${LCMS_LIBNAME} ${Z_LIBNAME} ${PNG_LIBNAME} ${TIFF_LIBNAME})
-#
-IF(UNIX)
-  TARGET_LINK_LIBRARIES(JPWL_image_to_j2k m)
-ENDIF(UNIX)
-
-INSTALL(TARGETS JPWL_image_to_j2k JPWL_j2k_to_image
-  DESTINATION ${OPENJPEG_INSTALL_BIN_DIR} COMPONENT Binaries
-)
diff --git a/jpwl/Makefile.am b/jpwl/Makefile.am
deleted file mode 100644 (file)
index 3bbce01..0000000
+++ /dev/null
@@ -1,116 +0,0 @@
-MAINTAINERCLEANFILES = Makefile.in
-
-lib_LTLIBRARIES = libopenjpeg_JPWL.la
-
-OPJ_SRC = \
-../libopenjpeg/bio.c \
-../libopenjpeg/cio.c \
-../libopenjpeg/dwt.c \
-../libopenjpeg/event.c \
-../libopenjpeg/image.c \
-../libopenjpeg/j2k.c \
-../libopenjpeg/j2k_lib.c \
-../libopenjpeg/jp2.c \
-../libopenjpeg/jpt.c \
-../libopenjpeg/mct.c \
-../libopenjpeg/mqc.c \
-../libopenjpeg/openjpeg.c \
-../libopenjpeg/pi.c \
-../libopenjpeg/raw.c \
-../libopenjpeg/t1.c \
-../libopenjpeg/t2.c \
-../libopenjpeg/tcd.c \
-../libopenjpeg/tgt.c
-
-libopenjpeg_JPWL_la_CPPFLAGS = \
--I. \
--I$(top_srcdir)/libopenjpeg \
--I$(top_builddir)/libopenjpeg \
--I$(top_srcdir)/jpwl \
--I$(top_builddir)/jpwl \
--DUSE_JPWL
-libopenjpeg_JPWL_la_CFLAGS =
-libopenjpeg_JPWL_la_LIBADD = -lm
-libopenjpeg_JPWL_la_LDFLAGS = -no-undefined -version-info @lt_version@
-libopenjpeg_JPWL_la_SOURCES = \
-$(OPJ_SRC) \
-crc.c \
-jpwl.c \
-jpwl_lib.c \
-rs.c \
-jpwl.h \
-crc.h \
-rs.h
-
-bin_PROGRAMS = JPWL_j2k_to_image JPWL_image_to_j2k
-
-JPWL_j2k_to_image_CPPFLAGS = \
--I. \
--I$(top_srcdir)/common \
--I$(top_builddir)/common \
--I$(top_srcdir)/libopenjpeg \
--I$(top_builddir)/libopenjpeg \
--I$(top_srcdir)/jpwl \
--I$(top_builddir)/jpwl \
--DUSE_JPWL \
-@TIFF_CFLAGS@ \
-@PNG_CFLAGS@ \
-@LCMS1_CFLAGS@ \
-@LCMS2_CFLAGS@
-JPWL_j2k_to_image_CFLAGS =
-JPWL_j2k_to_image_LDADD = $(top_builddir)/jpwl/libopenjpeg_JPWL.la  @LCMS1_LIBS@ @LCMS2_LIBS@ @TIFF_LIBS@ @PNG_LIBS@
-JPWL_j2k_to_image_SOURCES = \
-$(top_builddir)/common/color.c \
-$(top_builddir)/common/getopt.c \
-$(top_builddir)/codec/index.c \
-$(top_builddir)/codec/convert.c \
-$(top_builddir)/codec/j2k_to_image.c
-
-JPWL_image_to_j2k_CPPFLAGS = \
--I. \
--I$(top_srcdir)/common \
--I$(top_builddir)/common \
--I$(top_srcdir)/libopenjpeg \
--I$(top_builddir)/libopenjpeg \
--I$(top_srcdir)/jpwl \
--I$(top_builddir)/jpwl \
--DUSE_JPWL \
-@TIFF_CFLAGS@ \
-@PNG_CFLAGS@
-JPWL_image_to_j2k_CFLAGS =
-JPWL_image_to_j2k_LDADD = $(top_builddir)/jpwl/libopenjpeg_JPWL.la @TIFF_LIBS@ @PNG_LIBS@
-
-JPWL_image_to_j2k_SOURCES = \
-$(top_builddir)/common/getopt.c \
-$(top_builddir)/codec/index.c \
-$(top_builddir)/codec/convert.c \
-$(top_builddir)/codec/image_to_j2k.c
-
-EXTRA_DIST = \
-CMakeLists.txt
-
-install-data-hook:
-       @echo -e " (B)\t$(bindir)/JPWL_j2k_to_image$(EXEEXT)" >> $(top_builddir)/report.txt
-       @echo -e " (B)\t$(bindir)/JPWL_image_to_j2k$(EXEEXT)" >> $(top_builddir)/report.txt
-       @echo -e " (LA)\t$(libdir)/libopenjpeg_JPWL.la" >> $(top_builddir)/report.txt
-       @( $(call solist) ) >> $(top_builddir)/report.txt
-       @echo -e " (A)\t$(base)/$(a)" >> $(top_builddir)/report.txt
-
-solist    = $(foreach f, $(dll) $(so), echo -e ' $(SO_PREFIX)\t$(base)/$(f)' ;)
-get_tok   = $(shell grep -E "^$(1)=" $(lib_LTLIBRARIES) | cut -d "'" -f 2)
-base      = $(call get_tok,libdir)
-so        = $(call get_tok,library_names)
-a         = $(call get_tok,old_library)
-
-if HAVE_WIN32
-SO_PREFIX = (DLL)
-dll       = $(call get_tok,dlname)
-else
-if HAVE_DARWIN
-SO_PREFIX = (DY)
-dll       =
-else
-SO_PREFIX = (SO)
-dll       =
-endif
-endif
diff --git a/jpwl/Makefile.nix b/jpwl/Makefile.nix
deleted file mode 100644 (file)
index a266cd1..0000000
+++ /dev/null
@@ -1,152 +0,0 @@
-#jpwl Makefile
-include ../config.nix
-
-TARGET  = openjpeg_JPWL
-COMPILERFLAGS = -Wall -ffast-math -std=c99 -fPIC
-USERLIBS =
-
-JPWL_SRCS = ./crc.c ./jpwl.c ./jpwl_lib.c ./rs.c
-
-SRCS = ../libopenjpeg/bio.c ../libopenjpeg/cio.c ../libopenjpeg/dwt.c \
-  ../libopenjpeg/event.c ../libopenjpeg/image.c ../libopenjpeg/j2k.c \
-  ../libopenjpeg/j2k_lib.c ../libopenjpeg/jp2.c ../libopenjpeg/jpt.c \
-  ../libopenjpeg/mct.c ../libopenjpeg/mqc.c ../libopenjpeg/openjpeg.c \
-  ../libopenjpeg/pi.c ../libopenjpeg/raw.c ../libopenjpeg/t1.c \
-  ../libopenjpeg/t2.c ../libopenjpeg/tcd.c ../libopenjpeg/tgt.c \
-  $(JPWL_SRCS)
-
-INCLS = ../libopenjpeg/bio.h ../libopenjpeg/cio.h ../libopenjpeg/dwt.h \
-  ../libopenjpeg/event.h ../libopenjpeg/fix.h ../libopenjpeg/image.h \
-  ../libopenjpeg/int.h ../libopenjpeg/j2k.h ../libopenjpeg/j2k_lib.h \
-  ../libopenjpeg/jp2.h ../libopenjpeg/jpt.h ../libopenjpeg/mct.h \
-  ../libopenjpeg/mqc.h ../libopenjpeg/openjpeg.h ../libopenjpeg/pi.h \
-  ../libopenjpeg/raw.h ../libopenjpeg/t1.h ../libopenjpeg/t2.h \
-  ../libopenjpeg/tcd.h ../libopenjpeg/tgt.h ../libopenjpeg/opj_malloc.h \
-  ../libopenjpeg/opj_includes.h
-
-INCLUDE = -I.. -I. -I../libopenjpeg -I../common
-
-INSTALL_LIBDIR = $(prefix)/lib
-INSTALL_BIN = $(prefix)/bin
-
-# Converts cr/lf to just lf
-DOS2UNIX = dos2unix
-
-
-LIBRARIES = -lstdc++
-
-ifeq ($(WITH_TIFF),yes)
-INCLUDE += $(TIFF_INCLUDE)
-USERLIBS += $(TIFF_LIB)
-endif
-
-ifeq ($(WITH_PNG),yes)
-INCLUDE += $(PNG_INCLUDE)
-USERLIBS += $(PNG_LIB)
-endif
-
-ifeq ($(WITH_LCMS2),yes)
-INCLUDE += $(LCMS2_INCLUDE)
-USERLIBS += $(LCMS2_LIB)
-endif
-
-ifeq ($(WITH_LCMS1),yes)
-INCLUDE += $(LCMS1_INCLUDE)
-USERLIBS += $(LCMS1_LIB)
-endif
-
-USERLIBS += -lm
-
-MODULES = $(SRCS:.c=.o)
-
-CFLAGS = $(COMPILERFLAGS) $(INCLUDE) -DUSE_JPWL
-
-LIBNAME = lib$(TARGET)
-
-ifeq ($(ENABLE_SHARED),yes)
-SHAREDLIB = $(LIBNAME).so.$(MAJOR).$(MINOR).$(BUILD)
-else
-STATICLIB = $(LIBNAME).a
-endif
-
-default: all
-
-all: OpenJPEG_JPWL JPWL_image_to_j2k JPWL_j2k_to_image
-       install -d ../bin
-ifeq ($(ENABLE_SHARED),yes)
-       install -m 755 $(SHAREDLIB) ../bin
-       (cd ../bin && ln -sf $(SHAREDLIB) $(LIBNAME).so.$(MAJOR).$(MINOR))
-       (cd ../bin && ln -sf $(LIBNAME).so.$(MAJOR).$(MINOR) $(LIBNAME).so)
-else
-       install -m 644 $(STATICLIB) ../bin
-endif
-       install JPWL_image_to_j2k JPWL_j2k_to_image ../bin
-
-dos2unix:
-       @$(DOS2UNIX) $(SRCS) $(INCLS)
-
-OpenJPEG_JPWL: $(STATICLIB) $(SHAREDLIB)
-
-JPWL_codec: JPWL_j2k_to_image JPWL_image_to_j2k $(STATICLIB)
-
-.c.o:
-       $(CC) $(CFLAGS) -c $< -o $@
-
-ifeq ($(ENABLE_SHARED),yes)
-$(SHAREDLIB): $(MODULES)
-       $(CC) -shared -Wl,-soname,$(LIBNAME) -o $@ $(MODULES) $(LIBRARIES)
-else
-$(STATICLIB): $(MODULES)
-       $(AR) r $@ $(MODULES)
-endif
-
-ifeq ($(ENABLE_SHARED),yes)
-ELIB = $(SHAREDLIB)
-else
-ELIB = $(STATICLIB)
-endif
-
-JPWL_j2k_to_image: ../codec/j2k_to_image.c
-       $(CC) $(CFLAGS) ../common/getopt.c ../codec/index.c \
-       ../codec/convert.c ../common/color.c ../codec/j2k_to_image.c \
-       -o JPWL_j2k_to_image $(ELIB) $(USERLIBS)
-
-JPWL_image_to_j2k: ../codec/image_to_j2k.c
-       $(CC) $(CFLAGS) ../common/getopt.c ../codec/index.c \
-       ../codec/convert.c ../codec/image_to_j2k.c \
-       -o JPWL_image_to_j2k $(ELIB) $(USERLIBS)
-
-install: OpenJPEG_JPWL
-       install -d $(DESTDIR)$(INSTALL_LIBDIR)
-ifeq ($(ENABLE_SHARED),yes)
-       install -m 755 -o root -g root $(SHAREDLIB) $(DESTDIR)$(INSTALL_LIBDIR)
-       (cd $(DESTDIR)$(INSTALL_LIBDIR) && \
-       ln -sf $(SHAREDLIB) $(LIBNAME).so.$(MAJOR).$(MINOR) )
-       (cd $(DESTDIR)$(INSTALL_LIBDIR) && \
-       ln -sf $(LIBNAME).so.$(MAJOR).$(MINOR) $(LIBNAME).so )
-else
-       install -m 644 -o root -g root $(STATICLIB) $(DESTDIR)$(INSTALL_LIBDIR)
-       (cd $(DESTDIR)$(INSTALL_LIBDIR) && ranlib $(STATICLIB))
-endif
-       install -d $(DESTDIR)$(INSTALL_BIN)
-       install -m 755 -o root -g root JPWL_j2k_to_image $(DESTDIR)$(INSTALL_BIN)
-       install -m 755 -o root -g root JPWL_image_to_j2k $(DESTDIR)$(INSTALL_BIN)
-       
-cleanlib:
-       rm -f core u2dtmp* $(MODULES) $(STATICLIB) $(SHAREDLIB)
-
-cleancodec:
-       rm -f JPWL_j2k_to_image JPWL_image_to_j2k JPWL_j2k_to_image.o \
-       JPWL_image_to_j2k.o
-
-clean: cleanlib cleancodec
-
-uninstall:
-ifeq ($(ENABLE_SHARED),yes)
-       (cd $(DESTDIR)$(INSTALL_LIBDIR) && \
-       rm -f $(LIBNAME).so $(LIBNAME).so.$(MAJOR).$(MINOR) $(SHAREDLIB))
-else
-       rm -f $(DESTDIR)$(INSTALL_LIBDIR)/$(STATICLIB)
-endif
-       rm -f $(DESTDIR)$(INSTALL_BIN)/JPWL_j2k_to_image
-       rm -f $(DESTDIR)$(INSTALL_BIN)/JPWL_image_to_j2k
diff --git a/jpwl/README.txt b/jpwl/README.txt
deleted file mode 100644 (file)
index 66e9d5b..0000000
+++ /dev/null
@@ -1,136 +0,0 @@
-===============================================================================
-       JPEG2000 Part 11 (ISO/IEC 15444-11 JPWL) Software
-
-\r
-\r
-               Version 20061213
-===============================================================================
-
-
-\r
-\r
-\r
-1. Scope\r
-=============\r
-\r
-This document describes the installation and use of the JPWL module in the framework of OpenJPEG library.\r
-\r
-This implementation has been developed from OpenJPEG implementation of JPEG2000 standard, and for this reason it is written in C language.\r
-\r
-If you find some bugs or if you have problems using the encoder/decoder, please send an e-mail to jpwl@diei.unipg.it
-\r
-\r
-2. Installing the code\r
-==========================\r
-\r
-The JPWL code is integrated with the standard OpenJPEG library and codecs: it is activated by setting the macro USE_JPWL to defined in the preprocessor configuration options of your preferred C compiler.\r
-\r
-2.1. Compiling the source code in Windows\r
--------------------------------------------\r
-\r
-The "jpwl" directory is already populated with a couple of Visual C++ 6.0 workspaces\r
-\r
- * JPWL_image_to_j2k.dsw - Creates the encoder with JPWL functionalities\r
- * JPWL_j2k_to_image.dsw - Creates the decoder with JPWL functionalities\r
-\r
-2.2. Compiling the source code in Unix-like systems\r
------------------------------------------------------\r
-\r
-Under linux, enter the jpwl directory and type "make clean" and "make".\r
-\r
-\r
-3. Running the JPWL software\r
-=========================\r
-\r
-The options available at the command line are exactly the same of the base OpenJPEG codecs. In addition, there is a "-W" switch that activates JPWL functionalities.\r
-\r
-3.1. JPWL Encoder\r
--------------------\r
-\r
--W           : adoption of JPWL (Part 11) capabilities (-W params)\r
-               The parameters can be written and repeated in any order:\r
-               [h<tile><=type>,s<tile><=method>,a=<addr>,z=<size>,g=<range>,...\r
-                ...,p<tile:pack><=type>]\r
-\r
-                 h selects the header error protection (EPB): 'type' can be\r
-                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\r
-                   if 'tile' is absent, it applies to main and tile headers\r
-                   if 'tile' is present, it applies from that tile\r
-                     onwards, up to the next h<tile> spec, or to the last tile\r
-                     in the codestream (max. 16 specs)\r
-\r
-                 p selects the packet error protection (EEP/UEP with EPBs)\r
-                  to be applied to raw data: 'type' can be\r
-                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\r
-                   if 'tile:pack' is absent, it starts from tile 0, packet 0\r
-                   if 'tile:pack' is present, it applies from that tile\r
-                     and that packet onwards, up to the next packet spec\r
-                     or to the last packet in the last tile in the codestream\r
-                     (max. 16 specs)\r
-\r
-                 s enables sensitivity data insertion (ESD): 'method' can be\r
-                   [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR\r
-                    4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED]\r
-                   if 'tile' is absent, it applies to main header only\r
-                   if 'tile' is present, it applies from that tile\r
-                     onwards, up to the next s<tile> spec, or to the last tile\r
-                     in the codestream (max. 16 specs)\r
-\r
-                 g determines the addressing mode: <range> can be\r
-                   [0=PACKET 1=BYTE RANGE 2=PACKET RANGE]\r
-\r
-                 a determines the size of data addressing: <addr> can be\r
-                   2/4 bytes (small/large codestreams). If not set, auto-mode\r
-\r
-                 z determines the size of sensitivity values: <size> can be\r
-                   1/2 bytes, for the transformed pseudo-floating point value\r
-\r
-                 ex.:\r
- h,h0=64,h3=16,h5=32,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,s0=6,s3=-1,a=0,g=1,z=1\r
-                 means\r
-                   predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2,\r
-                   CRC-16 in TPH 3 and TPH 4, CRC-32 in remaining TPHs,\r
-                   UEP rs(78,32) for packets 0 to 23 of tile 0,\r
-                   UEP rs(56,32) for packets 24 to the last of tile 0,\r
-                   UEP rs default for packets of tile 1,\r
-                   no UEP for packets 0 to 19 of tile 3,\r
-                   UEP CRC-32 for packets 20 of tile 3 to last tile,\r
-                   relative sensitivity ESD for MH,\r
-                   TSE ESD from TPH 0 to TPH 2, byte range with automatic\r
-                   size of addresses and 1 byte for each sensitivity value\r
-\r
-                 ex.:\r
-                       h,s,p\r
-                 means\r
-                   default protection to headers (MH and TPHs) as well as\r
-                   data packets, one ESD in MH\r
-\r
-                 N.B.: use the following recommendations when specifying\r
-                       the JPWL parameters list\r
-                   - when you use UEP, always pair the 'p' option with 'h'\r
-\r
-3.2. JPWL Decoder\r
--------------------\r
-\r
-  -W <options>\r
-    Activates the JPWL correction capability, if the codestream complies.\r
-    Options can be a comma separated list of <param=val> tokens:\r
-    c, c=numcomps\r
-       numcomps is the number of expected components in the codestream\r
-       (search of first EPB rely upon this, default is 3)\r
-\r
-\r
-4. Known bugs and limitations\r
-===============================\r
-\r
-4.1. Bugs\r
------------\r
-\r
-* It is not possible to save a JPWL encoded codestream using the wrapped file format (i.e. JP2): only raw file format (i.e. J2K) is working\r
-\r
-4.2. Limitations\r
-------------------\r
-\r
-* When specifying an UEP protection, you need to activate even TPH protection for those tiles where there is a protection of the packets\r
-* RED insertion is not currently implemented at the decoder\r
-* JPWL at entropy coding level is not implemented\r
diff --git a/jpwl/crc.c b/jpwl/crc.c
deleted file mode 100644 (file)
index f65e4e1..0000000
+++ /dev/null
@@ -1,160 +0,0 @@
-/*\r
- * Copyright (c) 2001-2003, David Janssens\r
- * Copyright (c) 2002-2003, Yannick Verschueren\r
- * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe\r
- * Copyright (c) 2005, Herve Drolon, FreeImage Team\r
- * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium\r
- * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-\r
-#ifdef USE_JPWL\r
-\r
-#include "crc.h"\r
-\r
-/**\r
-@file crc.c\r
-@brief Functions used to compute the 16- and 32-bit CRC of byte arrays\r
-\r
-*/\r
-\r
-/** file: CRC16.CPP\r
- *\r
- * CRC - Cyclic Redundancy Check (16-bit)\r
- *\r
- * A CRC-checksum is used to be sure, the data hasn't changed or is false.\r
- * To create a CRC-checksum, initialise a check-variable (unsigned short),\r
- * and set this to zero. Than call for every byte in the file (e.g.) the\r
- * procedure updateCRC16 with this check-variable as the first parameter,\r
- * and the byte as the second. At the end, the check-variable contains the\r
- * CRC-checksum.\r
- *\r
- * implemented by Michael Neumann, 14.06.1998\r
- * \r
- */\r
-const unsigned short CRC16_table[256] = {\r
-       0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, \r
-       0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, \r
-       0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, \r
-       0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,\r
-       0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, \r
-       0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, \r
-       0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, \r
-       0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, \r
-       0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, \r
-       0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, \r
-       0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, \r
-       0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,\r
-       0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, \r
-       0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, \r
-       0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, \r
-       0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, \r
-       0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, \r
-       0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,\r
-       0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, \r
-       0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, \r
-       0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,\r
-       0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, \r
-       0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, \r
-       0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, \r
-       0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, \r
-       0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, \r
-       0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, \r
-       0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, \r
-       0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, \r
-       0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, \r
-       0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, \r
-       0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0\r
-};\r
-\r
-void updateCRC16(unsigned short *crc, unsigned char data) {\r
-       *crc = CRC16_table[(*crc >> 8) & 0xFF] ^ (*crc << 8) ^ data;\r
-};\r
-\r
-\r
-/** file: CRC32.CPP\r
- *\r
- * CRC - Cyclic Redundancy Check (32-bit)\r
- *\r
- * A CRC-checksum is used to be sure, the data hasn't changed or is false.\r
- * To create a CRC-checksum, initialise a check-variable (unsigned long),\r
- * and set this to zero. Than call for every byte in the file (e.g.) the\r
- * procedure updateCRC32 with this check-variable as the first parameter,\r
- * and the byte as the second. At the end, the check-variable contains the\r
- * CRC-checksum.\r
- *\r
- * implemented by Michael Neumann, 14.06.1998\r
- *\r
- */\r
-const unsigned long CRC32_table[256] = {\r
-       0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,\r
-       0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,\r
-       0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,\r
-       0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,\r
-       0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,\r
-       0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,\r
-       0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,\r
-       0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,\r
-       0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,\r
-       0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,\r
-       0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,\r
-       0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,\r
-       0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,\r
-       0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,\r
-       0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,\r
-       0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,\r
-       0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,\r
-       0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,\r
-       0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,\r
-       0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,\r
-       0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,\r
-       0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,\r
-       0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,\r
-       0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,\r
-       0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,\r
-       0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,\r
-       0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,\r
-       0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,\r
-       0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,\r
-       0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,\r
-       0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,\r
-       0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,\r
-       0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,\r
-       0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,\r
-       0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,\r
-       0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,\r
-       0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,\r
-       0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,\r
-       0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,\r
-       0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,\r
-       0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,\r
-       0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,\r
-       0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d\r
-};\r
-\r
-void updateCRC32(unsigned long *crc, unsigned char data) {\r
-       *crc = CRC32_table[(unsigned char) *crc ^ data] ^ ((*crc >> 8) & 0x00FFFFFF);\r
-};\r
-\r
-#endif /* USE_JPWL */\r
diff --git a/jpwl/crc.h b/jpwl/crc.h
deleted file mode 100644 (file)
index 4ea2c4c..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (c) 2001-2003, David Janssens
- * Copyright (c) 2002-2003, Yannick Verschueren
- * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe
- * Copyright (c) 2005, Herve Drolon, FreeImage Team
- * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef USE_JPWL
-
-/**
-@file crc.h
-@brief Functions used to compute the 16- and 32-bit CRC of byte arrays
-
-*/
-
-#ifndef __CRC16_HEADER__
-#define __CRC16_HEADER__
-
-/** file: CRC16.HPP
- *
- * CRC - Cyclic Redundancy Check (16-bit)
- *
- * A CRC-checksum is used to be sure, the data hasn't changed or is false.
- * To create a CRC-checksum, initialise a check-variable (unsigned short),
- * and set this to zero. Than call for every byte in the file (e.g.) the
- * procedure updateCRC16 with this check-variable as the first parameter,
- * and the byte as the second. At the end, the check-variable contains the
- * CRC-checksum.
- *
- * implemented by Michael Neumann, 14.06.1998
- * 
- */
-void updateCRC16(unsigned short *, unsigned char);
-
-#endif /* __CRC16_HEADER__ */
-
-
-#ifndef __CRC32_HEADER__
-#define __CRC32_HEADER__
-
-/** file: CRC32.HPP
- *
- * CRC - Cyclic Redundancy Check (32-bit)
- *
- * A CRC-checksum is used to be sure, the data hasn't changed or is false.
- * To create a CRC-checksum, initialise a check-variable (unsigned short),
- * and set this to zero. Than call for every byte in the file (e.g.) the
- * procedure updateCRC32 with this check-variable as the first parameter,
- * and the byte as the second. At the end, the check-variable contains the
- * CRC-checksum.
- *
- * implemented by Michael Neumann, 14.06.1998
- *
- */
-void updateCRC32(unsigned long *, unsigned char);
-
-#endif /* __CRC32_HEADER__ */
-
-
-#endif /* USE_JPWL */
diff --git a/jpwl/jpwl.c b/jpwl/jpwl.c
deleted file mode 100644 (file)
index 42c8871..0000000
+++ /dev/null
@@ -1,1357 +0,0 @@
-/*\r
- * Copyright (c) 2001-2003, David Janssens\r
- * Copyright (c) 2002-2003, Yannick Verschueren\r
- * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe\r
- * Copyright (c) 2005, Herve Drolon, FreeImage Team\r
- * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium\r
- * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy\r
- * All rights reserved.\r
- *\r
- * Redistribution and use in source and binary forms, with or without\r
- * modification, are permitted provided that the following conditions\r
- * are met:\r
- * 1. Redistributions of source code must retain the above copyright\r
- *    notice, this list of conditions and the following disclaimer.\r
- * 2. Redistributions in binary form must reproduce the above copyright\r
- *    notice, this list of conditions and the following disclaimer in the\r
- *    documentation and/or other materials provided with the distribution.\r
- *\r
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
- * POSSIBILITY OF SUCH DAMAGE.\r
- */\r
-\r
-#include "../libopenjpeg/opj_includes.h"\r
-\r
-#ifdef USE_JPWL\r
-\r
-/** @defgroup JPWL JPWL - JPEG-2000 Part11 (JPWL) codestream manager */\r
-/*@{*/\r
-\r
-/** @name Local static variables */\r
-/*@{*/\r
-\r
-/** number of JPWL prepared markers */\r
-static int jwmarker_num;\r
-/** properties of JPWL markers to insert */\r
-static jpwl_marker_t jwmarker[JPWL_MAX_NO_MARKERS]; \r
-\r
-/*@}*/\r
-\r
-/*@}*/\r
-\r
-/** @name Local static functions */\r
-/*@{*/\r
-\r
-/** create an EPC marker segment\r
-@param j2k J2K compressor handle\r
-@param esd_on true if ESD is activated\r
-@param red_on true if RED is activated\r
-@param epb_on true if EPB is activated\r
-@param info_on true if informative techniques are activated\r
-@return returns the freshly created EPC\r
-*/\r
-jpwl_epc_ms_t *jpwl_epc_create(opj_j2k_t *j2k, bool esd_on, bool red_on, bool epb_on, bool info_on);\r
-\r
-/*@}*/\r
-\r
-/** create an EPC marker segment\r
-@param j2k J2K compressor handle\r
-@param comps considered component (-1=average, 0/1/2/...=component no.)\r
-@param addrm addressing mode (0=packet, 1=byte range, 2=packet range, 3=reserved)\r
-@param ad_size size of addresses (2/4 bytes)\r
-@param senst sensitivity type\r
-@param se_size sensitivity values size (1/2 bytes)\r
-@param tileno tile where this ESD lies (-1 means MH)\r
-@param svalnum number of sensitivity values (if 0, they will be automatically filled)\r
-@param sensval pointer to an array of sensitivity values (if NULL, they will be automatically filled)\r
-@return returns the freshly created ESD\r
-*/\r
-jpwl_esd_ms_t *jpwl_esd_create(opj_j2k_t *j2k, int comps, unsigned char addrm, unsigned char ad_size,\r
-                                                               unsigned char senst, int se_size, int tileno,\r
-                                                               unsigned long int svalnum, void *sensval);\r
-                       \r
-/** this function is used to compare two JPWL markers based on\r
-their relevant wishlist position\r
-@param arg1 pointer to first marker\r
-@param arg2 pointer to second marker\r
-@return 1 if arg1>arg2, 0 if arg1=arg2, -1 if arg1<arg2\r
-*/\r
-int jpwl_markcomp(const void *arg1, const void *arg2);\r
-\r
-/** write an EPB MS to a buffer\r
-@param j2k J2K compressor handle\r
-@param epbmark pointer to the EPB MS\r
-@param buf pointer to the memory buffer\r
-*/\r
-void jpwl_epb_write(opj_j2k_t *j2k, jpwl_epb_ms_t *epbmark, unsigned char *buf);\r
-\r
-/** write an EPC MS to a buffer\r
-@param j2k J2K compressor handle\r
-@param epcmark pointer to the EPC MS\r
-@param buf pointer to the memory buffer\r
-*/\r
-void jpwl_epc_write(opj_j2k_t *j2k, jpwl_epc_ms_t *epcmark, unsigned char *buf);\r
-\r
-/** write an ESD MS to a buffer\r
-@param j2k J2K compressor handle\r
-@param esdmark pointer to the ESD MS\r
-@param buf pointer to the memory buffer\r
-*/\r
-void jpwl_esd_write(opj_j2k_t *j2k, jpwl_esd_ms_t *esdmark, unsigned char *buf);\r
-\r
-/*-----------------------------------------------------------------*/\r
-\r
-void jpwl_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image) {\r
-\r
-       int mm;\r
-\r
-       /* let's reset some settings */\r
-\r
-       /* clear the existing markers */\r
-       for (mm = 0; mm < jwmarker_num; mm++) {\r
-\r
-               switch (jwmarker[mm].id) {\r
-\r
-               case J2K_MS_EPB:\r
-                       opj_free(jwmarker[mm].m.epbmark);\r
-                       break;\r
-\r
-               case J2K_MS_EPC:\r
-                       opj_free(jwmarker[mm].m.epcmark);\r
-                       break;\r
-\r
-               case J2K_MS_ESD:\r
-                       opj_free(jwmarker[mm].m.esdmark);\r
-                       break;\r
-\r
-               case J2K_MS_RED:\r
-                       opj_free(jwmarker[mm].m.redmark);\r
-                       break;\r
-\r
-               default:\r
-                       break;\r
-               }\r
-       }\r
-\r
-       /* clear the marker structure array */\r
-       memset(jwmarker, 0, sizeof(jpwl_marker_t) * JPWL_MAX_NO_MARKERS);\r
-\r
-       /* no more markers in the list */\r
-       jwmarker_num = 0;\r
-\r
-       /* let's begin creating a marker list, according to user wishes */\r
-       jpwl_prepare_marks(j2k, cio, image);\r
-\r
-       /* now we dump the JPWL markers on the codestream */\r
-       jpwl_dump_marks(j2k, cio, image);\r
-\r
-       /* do not know exactly what is this for,\r
-       but it gets called during index creation */\r
-       j2k->pos_correction = 0;\r
-\r
-}\r
-\r
-void j2k_add_marker(opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len) {\r
-\r
-       if (!cstr_info)\r
-               return;\r
-\r
-       /* expand the list? */\r
-       if ((cstr_info->marknum + 1) > cstr_info->maxmarknum) {\r
-               cstr_info->maxmarknum = 100 + (int) ((float) cstr_info->maxmarknum * 1.0F);\r
-               cstr_info->marker = opj_realloc(cstr_info->marker, cstr_info->maxmarknum);\r
-       }\r
-\r
-       /* add the marker */\r
-       cstr_info->marker[cstr_info->marknum].type = type;\r
-       cstr_info->marker[cstr_info->marknum].pos = pos;\r
-       cstr_info->marker[cstr_info->marknum].len = len;\r
-       cstr_info->marknum++;\r
-\r
-}\r
-\r
-void jpwl_prepare_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image) {\r
-\r
-       unsigned short int socsiz_len = 0;\r
-       int ciopos = cio_tell(cio), soc_pos = j2k->cstr_info->main_head_start;\r
-       unsigned char *socp = NULL;\r
-\r
-       int tileno, acc_tpno, tpno, tilespec, hprot, sens, pprot, packspec, lastileno, packno;\r
-\r
-       jpwl_epb_ms_t *epb_mark;\r
-       jpwl_epc_ms_t *epc_mark;\r
-       jpwl_esd_ms_t *esd_mark;\r
-\r
-       /* find (SOC + SIZ) length */\r
-       /* I assume SIZ is always the first marker after SOC */\r
-       cio_seek(cio, soc_pos + 4);\r
-       socsiz_len = (unsigned short int) cio_read(cio, 2) + 4; /* add the 2 marks length itself */\r
-       cio_seek(cio, soc_pos + 0);\r
-       socp = cio_getbp(cio); /* pointer to SOC */\r
-\r
-       /* \r
-        EPC MS for Main Header: if we are here it's required\r
-       */\r
-       /* create the EPC */\r
-       if ((epc_mark = jpwl_epc_create(\r
-                       j2k,\r
-                       j2k->cp->esd_on, /* is ESD present? */\r
-                       j2k->cp->red_on, /* is RED present? */\r
-                       j2k->cp->epb_on, /* is EPB present? */\r
-                       false /* are informative techniques present? */\r
-               ))) {\r
-\r
-               /* Add this marker to the 'insertanda' list */\r
-               if (epc_mark) {\r
-                       jwmarker[jwmarker_num].id = J2K_MS_EPC; /* its type */\r
-                       jwmarker[jwmarker_num].m.epcmark = epc_mark; /* the EPC */\r
-                       jwmarker[jwmarker_num].pos = soc_pos + socsiz_len; /* after SIZ */\r
-                       jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos + 0.1; /* not so first */\r
-                       jwmarker[jwmarker_num].len = epc_mark->Lepc; /* its length */\r
-                       jwmarker[jwmarker_num].len_ready = true; /* ready */\r
-                       jwmarker[jwmarker_num].pos_ready = true; /* ready */\r
-                       jwmarker[jwmarker_num].parms_ready = false; /* not ready */\r
-                       jwmarker[jwmarker_num].data_ready = true; /* ready */\r
-                       jwmarker_num++;\r
-               };\r
-\r
-               opj_event_msg(j2k->cinfo, EVT_INFO,\r
-                       "MH  EPC : setting %s%s%s\n",\r
-                       j2k->cp->esd_on ? "ESD, " : "",\r
-                       j2k->cp->red_on ? "RED, " : "",\r
-                       j2k->cp->epb_on ? "EPB, " : ""\r
-                       );\r
-\r
-       } else {\r
-               /* ooops, problems */\r
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create MH EPC\n");                              \r
-       };\r
-\r
-       /* \r
-        ESD MS for Main Header\r
-       */\r
-       /* first of all, must MH have an ESD MS? */\r
-       if (j2k->cp->esd_on && (j2k->cp->sens_MH >= 0)) {\r
-\r
-               /* Create the ESD */\r
-               if ((esd_mark = jpwl_esd_create(\r
-                       j2k, /* this encoder handle */\r
-                       -1, /* we are averaging over all components */\r
-                       (unsigned char) j2k->cp->sens_range, /* range method */\r
-                       (unsigned char) j2k->cp->sens_addr, /* sensitivity addressing */\r
-                       (unsigned char) j2k->cp->sens_MH, /* sensitivity method */\r
-                       j2k->cp->sens_size, /* sensitivity size */\r
-                       -1, /* this ESD is in main header */\r
-                       0 /*j2k->cstr_info->num*/, /* number of packets in codestream */\r
-                       NULL /*sensval*/ /* pointer to sensitivity data of packets */\r
-                       ))) {\r
-                       \r
-                       /* Add this marker to the 'insertanda' list */\r
-                       if (jwmarker_num < JPWL_MAX_NO_MARKERS) {\r
-                               jwmarker[jwmarker_num].id = J2K_MS_ESD; /* its type */\r
-                               jwmarker[jwmarker_num].m.esdmark = esd_mark; /* the EPB */\r
-                               jwmarker[jwmarker_num].pos = soc_pos + socsiz_len; /* we choose to place it after SIZ */\r
-                               jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos + 0.2; /* not first at all! */\r
-                               jwmarker[jwmarker_num].len = esd_mark->Lesd; /* its length */\r
-                               jwmarker[jwmarker_num].len_ready = true; /* not ready, yet */\r
-                               jwmarker[jwmarker_num].pos_ready = true; /* ready */\r
-                               jwmarker[jwmarker_num].parms_ready = true; /* not ready */\r
-                               jwmarker[jwmarker_num].data_ready = false; /* not ready */\r
-                               jwmarker_num++;\r
-                       }\r
-\r
-                       opj_event_msg(j2k->cinfo, EVT_INFO,\r
-                               "MH  ESDs: method %d\n",\r
-                               j2k->cp->sens_MH\r
-                               );\r
-\r
-               } else {\r
-                       /* ooops, problems */\r
-                       opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create MH ESD\n");                              \r
-               };\r
-\r
-       }\r
-\r
-       /* \r
-        ESD MSs for Tile Part Headers \r
-       */\r
-       /* cycle through tiles */\r
-       sens = -1; /* default spec: no ESD */\r
-       tilespec = 0; /* first tile spec */\r
-       acc_tpno = 0;\r
-       for (tileno = 0; tileno < j2k->cstr_info->tw * j2k->cstr_info->th; tileno++) {\r
-\r
-               opj_event_msg(j2k->cinfo, EVT_INFO,\r
-                       "Tile %d has %d tile part(s)\n",\r
-                       tileno, j2k->cstr_info->tile[tileno].num_tps\r
-                       );\r
-\r
-               /* for every tile part in the tile */\r
-               for (tpno = 0; tpno < j2k->cstr_info->tile[tileno].num_tps; tpno++, acc_tpno++) {\r
-       \r
-                       int sot_len, Psot, Psotp, mm;\r
-                       unsigned long sot_pos, post_sod_pos;\r
-\r
-                       unsigned long int left_THmarks_len;\r
-\r
-                       /******* sot_pos = j2k->cstr_info->tile[tileno].start_pos; */\r
-                       sot_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos;\r
-                       cio_seek(cio, sot_pos + 2); \r
-                       sot_len = cio_read(cio, 2); /* SOT Len */\r
-                       cio_skip(cio, 2);\r
-                       Psotp = cio_tell(cio);\r
-                       Psot = cio_read(cio, 4); /* tile length */\r
-\r
-                       /******* post_sod_pos = j2k->cstr_info->tile[tileno].end_header + 1; */\r
-                       post_sod_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_end_header + 1;\r
-                       left_THmarks_len = post_sod_pos - sot_pos;\r
-\r
-                       /* add all the lengths of the markers which are len-ready and stay within SOT and SOD */\r
-                       for (mm = 0; mm < jwmarker_num; mm++) {\r
-                               if ((jwmarker[mm].pos >= sot_pos) && (jwmarker[mm].pos < post_sod_pos)) {\r
-                                       if (jwmarker[mm].len_ready)\r
-                                               left_THmarks_len += jwmarker[mm].len + 2;\r
-                                       else {\r
-                                               opj_event_msg(j2k->cinfo, EVT_ERROR, "MS %x in %f is not len-ready: could not set up TH EPB\n",\r
-                                                       jwmarker[mm].id, jwmarker[mm].dpos);                            \r
-                                               exit(1);\r
-                                       }\r
-                               }\r
-                       }\r
-\r
-                       /******* if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->sens_TPH_tileno[tilespec] == tileno)) */\r
-                       if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->sens_TPH_tileno[tilespec] == acc_tpno))\r
-                               /* we got a specification from this tile onwards */\r
-                               sens = j2k->cp->sens_TPH[tilespec++];\r
-               \r
-                       /* must this TPH have an ESD MS? */\r
-                       if (j2k->cp->esd_on && (sens >= 0)) {\r
-\r
-                               /* Create the ESD */\r
-                               if ((esd_mark = jpwl_esd_create(\r
-                                       j2k, /* this encoder handle */\r
-                                       -1, /* we are averaging over all components */\r
-                                       (unsigned char) j2k->cp->sens_range, /* range method */\r
-                                       (unsigned char) j2k->cp->sens_addr, /* sensitivity addressing size */\r
-                                       (unsigned char) sens, /* sensitivity method */\r
-                                       j2k->cp->sens_size, /* sensitivity value size */\r
-                                       tileno, /* this ESD is in a tile */\r
-                                       0, /* number of packets in codestream */\r
-                                       NULL /* pointer to sensitivity data of packets */\r
-                                       ))) {\r
-                                       \r
-                                       /* Add this marker to the 'insertanda' list */\r
-                                       if (jwmarker_num < JPWL_MAX_NO_MARKERS) {\r
-                                               jwmarker[jwmarker_num].id = J2K_MS_ESD; /* its type */\r
-                                               jwmarker[jwmarker_num].m.esdmark = esd_mark; /* the EPB */\r
-                                               /****** jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].start_pos + sot_len + 2; */ /* after SOT */\r
-                                               jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2; /* after SOT */\r
-                                               jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos + 0.2; /* not first at all! */\r
-                                               jwmarker[jwmarker_num].len = esd_mark->Lesd; /* its length */\r
-                                               jwmarker[jwmarker_num].len_ready = true; /* ready, yet */\r
-                                               jwmarker[jwmarker_num].pos_ready = true; /* ready */\r
-                                               jwmarker[jwmarker_num].parms_ready = true; /* not ready */\r
-                                               jwmarker[jwmarker_num].data_ready = false; /* ready */\r
-                                               jwmarker_num++;\r
-                                       }\r
-\r
-                                       /* update Psot of the tile  */\r
-                                       cio_seek(cio, Psotp);\r
-                                       cio_write(cio, Psot + esd_mark->Lesd + 2, 4);\r
-\r
-                                       opj_event_msg(j2k->cinfo, EVT_INFO,\r
-                                               /******* "TPH ESDs: tile %02d, method %d\n", */\r
-                                               "TPH ESDs: tile %02d, part %02d, method %d\n",\r
-                                               /******* tileno, */\r
-                                               tileno, tpno,\r
-                                               sens\r
-                                               );\r
-\r
-                               } else {\r
-                                       /* ooops, problems */\r
-                                       /***** opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH ESD #%d\n", tileno); */\r
-                                       opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH ESD #%d,%d\n", tileno, tpno);\r
-                               };\r
-\r
-                       }\r
-                       \r
-               }\r
-       \r
-       };\r
-\r
-       /* \r
-        EPB MS for Main Header\r
-       */\r
-       /* first of all, must MH have an EPB MS? */\r
-       if (j2k->cp->epb_on && (j2k->cp->hprot_MH > 0)) {\r
-\r
-               int mm;\r
-\r
-               /* position of SOT */\r
-               unsigned int sot_pos = j2k->cstr_info->main_head_end + 1;\r
-\r
-               /* how much space is there between end of SIZ and beginning of SOT? */\r
-               int left_MHmarks_len = sot_pos - socsiz_len;\r
-\r
-               /* add all the lengths of the markers which are len-ready and stay within SOC and SOT */\r
-               for (mm = 0; mm < jwmarker_num; mm++) {\r
-                       if ((jwmarker[mm].pos >=0) && (jwmarker[mm].pos < sot_pos)) {\r
-                               if (jwmarker[mm].len_ready)\r
-                                       left_MHmarks_len += jwmarker[mm].len + 2;\r
-                               else {\r
-                                       opj_event_msg(j2k->cinfo, EVT_ERROR, "MS %x in %f is not len-ready: could not set up MH EPB\n",\r
-                                               jwmarker[mm].id, jwmarker[mm].dpos);                            \r
-                                       exit(1);\r
-                               }\r
-                       }\r
-               }\r
-\r
-               /* Create the EPB */\r
-               if ((epb_mark = jpwl_epb_create(\r
-                       j2k, /* this encoder handle */\r
-                       true, /* is it the latest? */\r
-                       true, /* is it packed? not for now */\r
-                       -1, /* we are in main header */\r
-                       0, /* its index is 0 (first) */\r
-                       j2k->cp->hprot_MH, /* protection type parameters of data */\r
-                       socsiz_len, /* pre-data: only SOC+SIZ */\r
-                       left_MHmarks_len /* post-data: from SOC to SOT, and all JPWL markers within */\r
-                       ))) {\r
-                       \r
-                       /* Add this marker to the 'insertanda' list */\r
-                       if (jwmarker_num < JPWL_MAX_NO_MARKERS) {\r
-                               jwmarker[jwmarker_num].id = J2K_MS_EPB; /* its type */\r
-                               jwmarker[jwmarker_num].m.epbmark = epb_mark; /* the EPB */\r
-                               jwmarker[jwmarker_num].pos = soc_pos + socsiz_len; /* after SIZ */\r
-                               jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos; /* first first first! */\r
-                               jwmarker[jwmarker_num].len = epb_mark->Lepb; /* its length */\r
-                               jwmarker[jwmarker_num].len_ready = true; /* ready */\r
-                               jwmarker[jwmarker_num].pos_ready = true; /* ready */\r
-                               jwmarker[jwmarker_num].parms_ready = true; /* ready */\r
-                               jwmarker[jwmarker_num].data_ready = false; /* not ready */\r
-                               jwmarker_num++;\r
-                       }\r
-\r
-                       opj_event_msg(j2k->cinfo, EVT_INFO,\r
-                               "MH  EPB : prot. %d\n",\r
-                               j2k->cp->hprot_MH\r
-                               );\r
-\r
-               } else {\r
-                       /* ooops, problems */\r
-                       opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create MH EPB\n");                              \r
-               };\r
-       }\r
-\r
-       /* \r
-        EPB MSs for Tile Parts\r
-       */\r
-       /* cycle through TPHs */\r
-       hprot = j2k->cp->hprot_MH; /* default spec */\r
-       tilespec = 0; /* first tile spec */\r
-       lastileno = 0;\r
-       packspec = 0;\r
-       pprot = -1;\r
-       acc_tpno = 0;\r
-       for (tileno = 0; tileno < j2k->cstr_info->tw * j2k->cstr_info->th; tileno++) {\r
-\r
-               opj_event_msg(j2k->cinfo, EVT_INFO,\r
-                       "Tile %d has %d tile part(s)\n",\r
-                       tileno, j2k->cstr_info->tile[tileno].num_tps\r
-                       );\r
-\r
-               /* for every tile part in the tile */\r
-               for (tpno = 0; tpno < j2k->cstr_info->tile[tileno].num_tps; tpno++, acc_tpno++) { \r
-               \r
-                       int sot_len, Psot, Psotp, mm, epb_index = 0, prot_len = 0;\r
-                       unsigned long sot_pos, post_sod_pos;\r
-                       unsigned long int left_THmarks_len/*, epbs_len = 0*/;\r
-                       int startpack = 0, stoppack = j2k->cstr_info->packno;\r
-                       int first_tp_pack, last_tp_pack;\r
-                       jpwl_epb_ms_t *tph_epb = NULL;\r
-\r
-                       /****** sot_pos = j2k->cstr_info->tile[tileno].start_pos; */\r
-                       sot_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos;\r
-                       cio_seek(cio, sot_pos + 2); \r
-                       sot_len = cio_read(cio, 2); /* SOT Len */\r
-                       cio_skip(cio, 2);\r
-                       Psotp = cio_tell(cio);\r
-                       Psot = cio_read(cio, 4); /* tile length */\r
-\r
-                       /* a-priori length of the data dwelling between SOT and SOD */\r
-                       /****** post_sod_pos = j2k->cstr_info->tile[tileno].end_header + 1; */\r
-                       post_sod_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_end_header + 1;\r
-                       left_THmarks_len = post_sod_pos - (sot_pos + sot_len + 2);\r
-\r
-                       /* add all the lengths of the JPWL markers which are len-ready and stay within SOT and SOD */\r
-                       for (mm = 0; mm < jwmarker_num; mm++) {\r
-                               if ((jwmarker[mm].pos >= sot_pos) && (jwmarker[mm].pos < post_sod_pos)) {\r
-                                       if (jwmarker[mm].len_ready)\r
-                                               left_THmarks_len += jwmarker[mm].len + 2;\r
-                                       else {\r
-                                               opj_event_msg(j2k->cinfo, EVT_ERROR, "MS %x in %f is not len-ready: could not set up TH EPB\n",\r
-                                                       jwmarker[mm].id, jwmarker[mm].dpos);                            \r
-                                               exit(1);\r
-                                       }\r
-                               }\r
-                       }\r
-\r
-                       /****** if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->hprot_TPH_tileno[tilespec] == tileno)) */\r
-                       if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->hprot_TPH_tileno[tilespec] == acc_tpno))\r
-                               /* we got a specification from this tile part onwards */\r
-                               hprot = j2k->cp->hprot_TPH[tilespec++];\r
-               \r
-                       /* must this TPH have an EPB MS? */\r
-                       if (j2k->cp->epb_on && (hprot > 0)) {\r
-\r
-                               /* Create the EPB */\r
-                               if ((epb_mark = jpwl_epb_create(\r
-                                       j2k, /* this encoder handle */\r
-                                       false, /* is it the latest? in TPH, no for now (if huge data size in TPH, we'd need more) */\r
-                                       true, /* is it packed? yes for now */\r
-                                       tileno, /* we are in TPH */\r
-                                       epb_index++, /* its index is 0 (first) */\r
-                                       hprot, /* protection type parameters of following data */\r
-                                       sot_len + 2, /* pre-data length: only SOT */\r
-                                       left_THmarks_len /* post-data length: from SOT end to SOD inclusive */\r
-                                       ))) {\r
-                                       \r
-                                       /* Add this marker to the 'insertanda' list */\r
-                                       if (jwmarker_num < JPWL_MAX_NO_MARKERS) {\r
-                                               jwmarker[jwmarker_num].id = J2K_MS_EPB; /* its type */\r
-                                               jwmarker[jwmarker_num].m.epbmark = epb_mark; /* the EPB */\r
-                                               /****** jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].start_pos + sot_len + 2; */ /* after SOT */\r
-                                               jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2; /* after SOT */\r
-                                               jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos; /* first first first! */\r
-                                               jwmarker[jwmarker_num].len = epb_mark->Lepb; /* its length */\r
-                                               jwmarker[jwmarker_num].len_ready = true; /* ready */\r
-                                               jwmarker[jwmarker_num].pos_ready = true; /* ready */\r
-                                               jwmarker[jwmarker_num].parms_ready = true; /* ready */\r
-                                               jwmarker[jwmarker_num].data_ready = false; /* not ready */\r
-                                               jwmarker_num++;\r
-                                       }\r
-\r
-                                       /* update Psot of the tile  */\r
-                                       Psot += epb_mark->Lepb + 2;\r
-\r
-                                       opj_event_msg(j2k->cinfo, EVT_INFO,\r
-                                               /***** "TPH EPB : tile %02d, prot. %d\n", */\r
-                                               "TPH EPB : tile %02d, part %02d, prot. %d\n",\r
-                                               /***** tileno, */\r
-                                               tileno, tpno,\r
-                                               hprot\r
-                                               );\r
-\r
-                                       /* save this TPH EPB address */\r
-                                       tph_epb = epb_mark;\r
-\r
-                               } else {\r
-                                       /* ooops, problems */\r
-                                       /****** opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH EPB #%d\n", tileno); */\r
-                                       opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH EPB in #%d,d\n", tileno, tpno);\r
-                               };\r
-\r
-                       }                               \r
-               \r
-                       startpack = 0;\r
-                       /* EPB MSs for UEP packet data protection in Tile Parts */\r
-                       /****** for (packno = 0; packno < j2k->cstr_info->num; packno++) { */\r
-                       /*first_tp_pack = (tpno > 0) ? (first_tp_pack + j2k->cstr_info->tile[tileno].tp[tpno - 1].tp_numpacks) : 0;*/\r
-                       first_tp_pack = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pack;\r
-                       last_tp_pack = first_tp_pack + j2k->cstr_info->tile[tileno].tp[tpno].tp_numpacks - 1;\r
-                       for (packno = 0; packno < j2k->cstr_info->tile[tileno].tp[tpno].tp_numpacks; packno++) {\r
-\r
-                               /******** if ((packspec < JPWL_MAX_NO_PACKSPECS) &&\r
-                                       (j2k->cp->pprot_tileno[packspec] == tileno) && (j2k->cp->pprot_packno[packspec] == packno)) { */\r
-                               if ((packspec < JPWL_MAX_NO_PACKSPECS) &&\r
-                                       (j2k->cp->pprot_tileno[packspec] == acc_tpno) && (j2k->cp->pprot_packno[packspec] == packno)) {\r
-\r
-                                       /* we got a specification from this tile and packet onwards */\r
-                                       /* print the previous spec */\r
-                                       if (packno > 0) {\r
-                                               stoppack = packno - 1;                          \r
-                                               opj_event_msg(j2k->cinfo, EVT_INFO,\r
-                                                       /***** "UEP EPBs: tile %02d, packs. %02d-%02d (B %d-%d), prot. %d\n", */\r
-                                                       "UEP EPBs: tile %02d, part %02d, packs. %02d-%02d (B %d-%d), prot. %d\n",\r
-                                                       /***** tileno, */\r
-                                                       tileno, tpno,\r
-                                                       startpack,\r
-                                                       stoppack,\r
-                                                       /***** j2k->cstr_info->tile[tileno].packet[startpack].start_pos, */\r
-                                                       j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos,\r
-                                                       /***** j2k->cstr_info->tile[tileno].packet[stoppack].end_pos, */\r
-                                                       j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos,\r
-                                                       pprot);\r
-\r
-                                               /***** prot_len = j2k->cstr_info->tile[tileno].packet[stoppack].end_pos + 1 -\r
-                                                       j2k->cstr_info->tile[tileno].packet[startpack].start_pos; */\r
-                                               prot_len = j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos + 1 -\r
-                                                       j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos;\r
-\r
-                                               /*\r
-                                                 particular case: if this is the last header and the last packet,\r
-                                                 then it is better to protect even the EOC marker\r
-                                               */\r
-                                               /****** if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) &&\r
-                                                       (stoppack == (j2k->cstr_info->num - 1))) */\r
-                                               if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) &&\r
-                                                       (tpno == (j2k->cstr_info->tile[tileno].num_tps - 1)) &&\r
-                                                       (stoppack == last_tp_pack))\r
-                                                       /* add the EOC len */\r
-                                                       prot_len += 2;\r
-\r
-                                               /* let's add the EPBs */\r
-                                               Psot += jpwl_epbs_add(\r
-                                                       j2k, /* J2K handle */\r
-                                                       jwmarker, /* pointer to JPWL markers list */\r
-                                                       &jwmarker_num, /* pointer to the number of current markers */\r
-                                                       false, /* latest */\r
-                                                       true, /* packed */\r
-                                                       false, /* inside MH */\r
-                                                       &epb_index, /* pointer to EPB index */\r
-                                                       pprot, /* protection type */\r
-                                                       /****** (double) (j2k->cstr_info->tile[tileno].start_pos + sot_len + 2) + 0.0001, */ /* position */\r
-                                                       (double) (j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2) + 0.0001, /* position */\r
-                                                       tileno, /* number of tile */\r
-                                                       0, /* length of pre-data */\r
-                                                       prot_len /*4000*/ /* length of post-data */\r
-                                                       );\r
-                                       }\r
-\r
-                                       startpack = packno;\r
-                                       pprot = j2k->cp->pprot[packspec++];\r
-                               }\r
-\r
-                               //printf("Tile %02d, pack %02d ==> %d\n", tileno, packno, pprot);\r
-               \r
-                       }\r
-\r
-                       /* we are at the end: print the remaining spec */\r
-                       stoppack = packno - 1;\r
-                       if (pprot >= 0) {\r
-\r
-                               opj_event_msg(j2k->cinfo, EVT_INFO,\r
-                                       /**** "UEP EPBs: tile %02d, packs. %02d-%02d (B %d-%d), prot. %d\n", */\r
-                                       "UEP EPBs: tile %02d, part %02d, packs. %02d-%02d (B %d-%d), prot. %d\n",\r
-                                       /**** tileno, */\r
-                                       tileno, tpno,\r
-                                       startpack,\r
-                                       stoppack,\r
-                                       /***** j2k->image_info->tile[tileno].packet[startpack].start_pos,\r
-                                       j2k->image_info->tile[tileno].packet[stoppack].end_pos, */\r
-                                       j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos,\r
-                                       j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos,\r
-                                       pprot);\r
-\r
-                               /***** prot_len = j2k->cstr_info->tile[tileno].packet[stoppack].end_pos + 1 -\r
-                                       j2k->cstr_info->tile[tileno].packet[startpack].start_pos; */\r
-                               prot_len = j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos + 1 -\r
-                                       j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos;\r
-\r
-                               /*\r
-                                 particular case: if this is the last header and the last packet,\r
-                                 then it is better to protect even the EOC marker\r
-                               */\r
-                               /***** if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) &&\r
-                                       (stoppack == (j2k->cstr_info->num - 1))) */\r
-                               if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) &&\r
-                                       (tpno == (j2k->cstr_info->tile[tileno].num_tps - 1)) &&\r
-                                       (stoppack == last_tp_pack))\r
-                                       /* add the EOC len */\r
-                                       prot_len += 2;\r
-\r
-                               /* let's add the EPBs */\r
-                               Psot += jpwl_epbs_add(\r
-                                                       j2k, /* J2K handle */\r
-                                                       jwmarker, /* pointer to JPWL markers list */\r
-                                                       &jwmarker_num, /* pointer to the number of current markers */\r
-                                                       true, /* latest */\r
-                                                       true, /* packed */\r
-                                                       false, /* inside MH */\r
-                                                       &epb_index, /* pointer to EPB index */\r
-                                                       pprot, /* protection type */\r
-                                                       /***** (double) (j2k->cstr_info->tile[tileno].start_pos + sot_len + 2) + 0.0001,*/ /* position */\r
-                                                       (double) (j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2) + 0.0001, /* position */\r
-                                                       tileno, /* number of tile */\r
-                                                       0, /* length of pre-data */\r
-                                                       prot_len /*4000*/ /* length of post-data */\r
-                                                       );\r
-                       }\r
-\r
-                       /* we can now check if the TPH EPB was really the last one */\r
-                       if (tph_epb && (epb_index == 1)) {\r
-                               /* set the TPH EPB to be the last one in current header */\r
-                               tph_epb->Depb |= (unsigned char) ((true & 0x0001) << 6);\r
-                               tph_epb = NULL;\r
-                       }\r
-\r
-                       /* write back Psot */\r
-                       cio_seek(cio, Psotp);\r
-                       cio_write(cio, Psot, 4);\r
-               \r
-               }\r
-\r
-       };\r
-\r
-       /* reset the position */\r
-       cio_seek(cio, ciopos);\r
-\r
-}\r
-\r
-void jpwl_dump_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image) {\r
-\r
-       int mm;\r
-       unsigned long int old_size = j2k->cstr_info->codestream_size;\r
-       unsigned long int new_size = old_size;\r
-       int /*ciopos = cio_tell(cio),*/ soc_pos = j2k->cstr_info->main_head_start;\r
-       unsigned char *jpwl_buf, *orig_buf;\r
-       unsigned long int orig_pos;\r
-       double epbcoding_time = 0.0, esdcoding_time = 0.0;\r
-\r
-       /* Order JPWL markers according to their wishlist position */\r
-       qsort((void *) jwmarker, (size_t) jwmarker_num, sizeof (jpwl_marker_t), jpwl_markcomp);\r
-\r
-       /* compute markers total size */ \r
-       for (mm = 0; mm < jwmarker_num; mm++) {\r
-               /*printf("%x, %d, %.10f, %d long\n", jwmarker[mm].id, jwmarker[mm].pos,\r
-                       jwmarker[mm].dpos, jwmarker[mm].len);*/\r
-               new_size += jwmarker[mm].len + 2;\r
-       }\r
-\r
-       /* allocate a new buffer of proper size */\r
-       if (!(jpwl_buf = (unsigned char *) opj_malloc((size_t) (new_size + soc_pos) * sizeof(unsigned char)))) {\r
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for JPWL codestream buffer\n");\r
-               exit(1);\r
-       };\r
-\r
-       /* copy the jp2 part, if any */\r
-       orig_buf = jpwl_buf;\r
-       memcpy(jpwl_buf, cio->buffer, soc_pos);\r
-       jpwl_buf += soc_pos;\r
-\r
-       /* cycle through markers */\r
-       orig_pos = soc_pos + 0; /* start from the beginning */\r
-       cio_seek(cio, soc_pos + 0); /* rewind the original */\r
-       for (mm = 0; mm < jwmarker_num; mm++) {\r
-\r
-               /*\r
-               need to copy a piece of the original codestream\r
-               if there is such\r
-               */\r
-               memcpy(jpwl_buf, cio_getbp(cio), jwmarker[mm].pos - orig_pos);\r
-               jpwl_buf += jwmarker[mm].pos - orig_pos;\r
-               orig_pos = jwmarker[mm].pos;\r
-               cio_seek(cio, orig_pos);\r
-\r
-               /*\r
-               then write down the marker\r
-               */\r
-               switch (jwmarker[mm].id) {\r
-\r
-               case J2K_MS_EPB:\r
-                       jpwl_epb_write(j2k, jwmarker[mm].m.epbmark, jpwl_buf);\r
-                       break;\r
-\r
-               case J2K_MS_EPC:\r
-                       jpwl_epc_write(j2k, jwmarker[mm].m.epcmark, jpwl_buf);\r
-                       break;\r
-\r
-               case J2K_MS_ESD:\r
-                       jpwl_esd_write(j2k, jwmarker[mm].m.esdmark, jpwl_buf);\r
-                       break;\r
-\r
-               case J2K_MS_RED:\r
-                       memset(jpwl_buf, 0, jwmarker[mm].len + 2); /* placeholder */\r
-                       break;\r
-\r
-               default:\r
-                       break;\r
-               };\r
-\r
-               /* we update the markers struct */\r
-               if (j2k->cstr_info)\r
-                       j2k->cstr_info->marker[j2k->cstr_info->marknum - 1].pos = (jpwl_buf - orig_buf);\r
-               \r
-               /* we set the marker dpos to the new position in the JPWL codestream */\r
-               jwmarker[mm].dpos = (double) (jpwl_buf - orig_buf);\r
-\r
-               /* advance JPWL buffer position */\r
-               jpwl_buf += jwmarker[mm].len + 2;\r
-\r
-       }\r
-\r
-       /* finish remaining original codestream */\r
-       memcpy(jpwl_buf, cio_getbp(cio), old_size - (orig_pos - soc_pos));\r
-       jpwl_buf += old_size - (orig_pos - soc_pos);\r
-       cio_seek(cio, soc_pos + old_size);\r
-       \r
-       /*\r
-       update info file based on added markers\r
-       */\r
-       if (!jpwl_update_info(j2k, jwmarker, jwmarker_num))\r
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not update OPJ cstr_info structure\n");\r
-\r
-       /* now we need to repass some markers and fill their data fields */\r
-       \r
-       /* first of all, DL and Pcrc in EPCs */ \r
-       for (mm = 0; mm < jwmarker_num; mm++) {\r
-\r
-               /* find the EPCs */\r
-               if (jwmarker[mm].id == J2K_MS_EPC) {\r
-\r
-                       int epc_pos = (int) jwmarker[mm].dpos, pp;\r
-                       unsigned short int mycrc = 0x0000;\r
-\r
-                       /* fix and fill the DL field */\r
-                       jwmarker[mm].m.epcmark->DL = new_size;\r
-                       orig_buf[epc_pos + 6] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 24);\r
-                       orig_buf[epc_pos + 7] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 16);\r
-                       orig_buf[epc_pos + 8] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 8);\r
-                       orig_buf[epc_pos + 9] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 0);\r
-\r
-                       /* compute the CRC field (excluding itself) */\r
-                       for (pp = 0; pp < 4; pp++)\r
-                               jpwl_updateCRC16(&mycrc, orig_buf[epc_pos + pp]);\r
-                       for (pp = 6; pp < (jwmarker[mm].len + 2); pp++)\r
-                               jpwl_updateCRC16(&mycrc, orig_buf[epc_pos + pp]);\r
-\r
-                       /* fix and fill the CRC */\r
-                       jwmarker[mm].m.epcmark->Pcrc = mycrc;\r
-                       orig_buf[epc_pos + 4] = (unsigned char) (jwmarker[mm].m.epcmark->Pcrc >> 8);\r
-                       orig_buf[epc_pos + 5] = (unsigned char) (jwmarker[mm].m.epcmark->Pcrc >> 0);\r
-\r
-               }\r
-       }\r
-\r
-       /* then, sensitivity data in ESDs */ \r
-       esdcoding_time = opj_clock();\r
-       for (mm = 0; mm < jwmarker_num; mm++) {\r
-\r
-               /* find the ESDs */\r
-               if (jwmarker[mm].id == J2K_MS_ESD) {\r
-\r
-                       /* remember that they are now in a new position (dpos) */\r
-                       int esd_pos = (int) jwmarker[mm].dpos;\r
-\r
-                       jpwl_esd_fill(j2k, jwmarker[mm].m.esdmark, &orig_buf[esd_pos]);\r
-               \r
-               }\r
-\r
-       }\r
-       esdcoding_time = opj_clock() - esdcoding_time;\r
-       if (j2k->cp->esd_on)\r
-               opj_event_msg(j2k->cinfo, EVT_INFO, "ESDs sensitivities computed in %f s\n", esdcoding_time);\r
-\r
-       /* finally, RS or CRC parity in EPBs */ \r
-       epbcoding_time = opj_clock();\r
-       for (mm = 0; mm < jwmarker_num; mm++) {\r
-\r
-               /* find the EPBs */\r
-               if (jwmarker[mm].id == J2K_MS_EPB) {\r
-\r
-                       /* remember that they are now in a new position (dpos) */\r
-                       int nn, accum_len;\r
-\r
-                       /* let's see how many EPBs are following this one, included itself */\r
-                       /* for this to work, we suppose that the markers are correctly ordered */\r
-                       /* and, overall, that they are in packed mode inside headers */\r
-                       accum_len = 0;\r
-                       for (nn = mm; (nn < jwmarker_num) && (jwmarker[nn].id == J2K_MS_EPB) &&\r
-                               (jwmarker[nn].pos == jwmarker[mm].pos); nn++)\r
-                               accum_len += jwmarker[nn].m.epbmark->Lepb + 2;\r
-\r
-                       /* fill the current (first) EPB with post-data starting from the computed position */\r
-                       jpwl_epb_fill(j2k, jwmarker[mm].m.epbmark, &orig_buf[(int) jwmarker[mm].dpos],\r
-                               &orig_buf[(int) jwmarker[mm].dpos + accum_len]);\r
-               \r
-                       /* fill the remaining EPBs in the header with post-data starting from the last position */\r
-                       for (nn = mm + 1; (nn < jwmarker_num) && (jwmarker[nn].id == J2K_MS_EPB) &&\r
-                               (jwmarker[nn].pos == jwmarker[mm].pos); nn++)\r
-                               jpwl_epb_fill(j2k, jwmarker[nn].m.epbmark, &orig_buf[(int) jwmarker[nn].dpos], NULL);\r
-\r
-                       /* skip all the processed EPBs */\r
-                       mm = nn - 1;\r
-               }\r
-\r
-       }\r
-       epbcoding_time = opj_clock() - epbcoding_time;\r
-       if (j2k->cp->epb_on)\r
-               opj_event_msg(j2k->cinfo, EVT_INFO, "EPBs redundancy computed in %f s\n", epbcoding_time);\r
-\r
-       /* free original cio buffer and set it to the JPWL one */\r
-       opj_free(cio->buffer);\r
-       cio->cinfo = cio->cinfo; /* no change */\r
-       cio->openmode = cio->openmode; /* no change */\r
-       cio->buffer = orig_buf;\r
-       cio->length = new_size + soc_pos;\r
-       cio->start = cio->buffer;\r
-       cio->end = cio->buffer + cio->length;\r
-       cio->bp = cio->buffer;\r
-       cio_seek(cio, soc_pos + new_size);\r
-\r
-}\r
-\r
-\r
-void j2k_read_epc(opj_j2k_t *j2k) {\r
-       unsigned long int DL, Lepcp, Pcrcp, l;\r
-       unsigned short int Lepc, Pcrc = 0x0000;\r
-       unsigned char Pepc;     \r
-       opj_cio_t *cio = j2k->cio;\r
-       char *ans1;\r
-\r
-       /* Simply read the EPC parameters */\r
-       Lepcp = cio_tell(cio);\r
-       Lepc = cio_read(cio, 2);\r
-       Pcrcp = cio_tell(cio);\r
-       cio_skip(cio, 2); /* Pcrc */\r
-       DL = cio_read(cio, 4);\r
-       Pepc = cio_read(cio, 1);\r
-\r
-       /* compute Pcrc */\r
-       cio_seek(cio, Lepcp - 2);\r
-\r
-               /* Marker */\r
-               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
-               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
-\r
-               /* Length */\r
-               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
-               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
-\r
-               /* skip Pcrc */\r
-               cio_skip(cio, 2);\r
-\r
-               /* read all remaining */\r
-               for (l = 4; l < Lepc; l++)\r
-                       jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
-\r
-               /* check Pcrc with the result */\r
-               cio_seek(cio, Pcrcp);\r
-               ans1 = (Pcrc == (unsigned short int) cio_read(cio, 2)) ? "crc-ok" : "crc-ko";\r
-\r
-       /* now we write them to screen */\r
-       opj_event_msg(j2k->cinfo, EVT_INFO, \r
-               "EPC(%u,%d): %s, DL=%d%s %s %s\n",\r
-               Lepcp - 2,\r
-               Lepc,\r
-               ans1,\r
-               DL, /* data length this EPC is referring to */\r
-               (Pepc & 0x10) ? ", esd" : "", /* ESD is present */\r
-               (Pepc & 0x20) ? ", red" : "", /* RED is present */\r
-               (Pepc & 0x40) ? ", epb" : ""); /* EPB is present */\r
-\r
-       cio_seek(cio, Lepcp + Lepc);  \r
-}\r
-\r
-void j2k_write_epc(opj_j2k_t *j2k) {\r
-\r
-       unsigned long int DL, Lepcp, Pcrcp, l;\r
-       unsigned short int Lepc, Pcrc;\r
-       unsigned char Pepc;     \r
-\r
-       opj_cio_t *cio = j2k->cio;\r
-\r
-       cio_write(cio, J2K_MS_EPC, 2);  /* EPC */\r
-       Lepcp = cio_tell(cio);\r
-       cio_skip(cio, 2);\r
-\r
-       /* CRC-16 word of the EPC */\r
-       Pcrc = 0x0000; /* initialize */\r
-       Pcrcp = cio_tell(cio);\r
-       cio_write(cio, Pcrc, 2); /* Pcrc placeholder*/\r
-\r
-       /* data length of the EPC protection domain */\r
-       DL = 0x00000000; /* we leave this set to 0, as if the information is not available */\r
-       cio_write(cio, DL, 4);   /* DL */\r
-\r
-       /* jpwl capabilities */\r
-       Pepc = 0x00;\r
-       cio_write(cio, Pepc, 1); /* Pepc */\r
-\r
-       /* ID section */\r
-       /* no ID's, as of now */\r
-\r
-       Lepc = (unsigned short) (cio_tell(cio) - Lepcp);\r
-       cio_seek(cio, Lepcp);\r
-       cio_write(cio, Lepc, 2); /* Lepc */\r
-\r
-       /* compute Pcrc */\r
-       cio_seek(cio, Lepcp - 2);\r
-\r
-               /* Marker */\r
-               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
-               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
-\r
-               /* Length */\r
-               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
-               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
-\r
-               /* skip Pcrc */\r
-               cio_skip(cio, 2);\r
-\r
-               /* read all remaining */\r
-               for (l = 4; l < Lepc; l++)\r
-                       jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
-\r
-               /* fill Pcrc with the result */\r
-               cio_seek(cio, Pcrcp);\r
-               cio_write(cio, Pcrc, 2);\r
-\r
-       cio_seek(cio, Lepcp + Lepc);\r
-\r
-       /* marker struct update */\r
-       j2k_add_marker(j2k->cstr_info, J2K_MS_EPC, Lepcp - 2, Lepc + 2);\r
-\r
-}\r
-\r
-void j2k_read_epb(opj_j2k_t *j2k) {\r
-       unsigned long int LDPepb, Pepb;\r
-       unsigned short int Lepb;\r
-       unsigned char Depb;\r
-       char str1[25] = "";\r
-       bool status;\r
-       static bool first_in_tph = true;\r
-       int type, pre_len, post_len;\r
-       static unsigned char *redund = NULL;\r
-       \r
-       opj_cio_t *cio = j2k->cio;\r
-\r
-       /* B/W = 45, RGB = 51 */\r
-       /*           SIZ   SIZ_FIELDS     SIZ_COMPS               FOLLOWING_MARKER */\r
-       int skipnum = 2  +     38     + 3 * j2k->cp->exp_comps  +         2;\r
-\r
-       if (j2k->cp->correct) {\r
-\r
-               /* go back to EPB marker value */\r
-               cio_seek(cio, cio_tell(cio) - 2);\r
-\r
-               /* we need to understand where we are */\r
-               if (j2k->state == J2K_STATE_MH) {\r
-                       /* we are in MH */\r
-                       type = 0; /* MH */\r
-                       pre_len = skipnum; /* SOC+SIZ */\r
-                       post_len = -1; /* auto */\r
-\r
-               } else if ((j2k->state == J2K_STATE_TPH) && first_in_tph) {\r
-                       /* we are in TPH */\r
-                       type = 1; /* TPH */\r
-                       pre_len = 12; /* SOC+SIZ */\r
-                       first_in_tph = false;\r
-                       post_len = -1; /* auto */\r
-\r
-               } else {\r
-                       /* we are elsewhere */\r
-                       type = 2; /* other */\r
-                       pre_len = 0; /* nada */\r
-                       post_len = -1; /* auto */\r
-\r
-               }\r
-\r
-               /* call EPB corrector */\r
-               /*printf("before %x, ", redund);*/\r
-               status = jpwl_epb_correct(j2k,      /* J2K decompressor handle */\r
-                                                                 cio->bp,  /* pointer to EPB in codestream buffer */\r
-                                                                 type,     /* EPB type: MH */\r
-                                                                 pre_len,  /* length of pre-data */\r
-                                                                 post_len, /* length of post-data: -1 means auto */\r
-                                                                 NULL,     /* do everything auto */\r
-                                                                 &redund\r
-                                                                );\r
-               /*printf("after %x\n", redund);*/\r
-\r
-               /* Read the (possibly corrected) EPB parameters */\r
-               cio_skip(cio, 2);\r
-               Lepb = cio_read(cio, 2);\r
-               Depb = cio_read(cio, 1);\r
-               LDPepb = cio_read(cio, 4);\r
-               Pepb = cio_read(cio, 4);\r
-\r
-               if (!status) {\r
-\r
-                       opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL correction could not be performed\n");\r
-\r
-                       /* advance to EPB endpoint */\r
-                       cio_skip(cio, Lepb + 2);  \r
-\r
-                       return;\r
-               }\r
-\r
-               /* last in current header? */\r
-               if (Depb & 0x40) {\r
-                       redund = NULL; /* reset the pointer to L4 buffer */\r
-                       first_in_tph = true;\r
-               }\r
-\r
-               /* advance to EPB endpoint */\r
-               cio_skip(cio, Lepb - 11);  \r
-\r
-       } else {\r
-\r
-               /* Simply read the EPB parameters */\r
-               Lepb = cio_read(cio, 2);\r
-               Depb = cio_read(cio, 1);\r
-               LDPepb = cio_read(cio, 4);\r
-               Pepb = cio_read(cio, 4);\r
-\r
-               /* What does Pepb tells us about the protection method? */\r
-               if (((Pepb & 0xF0000000) >> 28) == 0)\r
-                       sprintf(str1, "pred"); /* predefined */\r
-               else if (((Pepb & 0xF0000000) >> 28) == 1)\r
-                       sprintf(str1, "crc-%lu", 16 * ((Pepb & 0x00000001) + 1)); /* CRC mode */\r
-               else if (((Pepb & 0xF0000000) >> 28) == 2)\r
-                       sprintf(str1, "rs(%lu,32)", (Pepb & 0x0000FF00) >> 8); /* RS mode */\r
-               else if (Pepb == 0xFFFFFFFF)\r
-                       sprintf(str1, "nometh"); /* RS mode */\r
-               else\r
-                       sprintf(str1, "unknown"); /* unknown */\r
-\r
-               /* Now we write them to screen */\r
-               opj_event_msg(j2k->cinfo, EVT_INFO,\r
-                       "EPB(%d): (%sl, %sp, %u), %lu, %s\n",\r
-                       cio_tell(cio) - 13,\r
-                       (Depb & 0x40) ? "" : "n", /* latest EPB or not? */\r
-                       (Depb & 0x80) ? "" : "n", /* packed or unpacked EPB? */\r
-                       (Depb & 0x3F), /* EPB index value */\r
-                       LDPepb, /*length of the data protected by the EPB */\r
-                       str1); /* protection method */\r
-\r
-               cio_skip(cio, Lepb - 11);  \r
-       }\r
-}\r
-\r
-void j2k_write_epb(opj_j2k_t *j2k) {\r
-       unsigned long int LDPepb, Pepb, Lepbp;\r
-       unsigned short int Lepb;\r
-       unsigned char Depb;\r
-\r
-       opj_cio_t *cio = j2k->cio;\r
-\r
-       cio_write(cio, J2K_MS_EPB, 2);  /* EPB */\r
-       Lepbp = cio_tell(cio);\r
-       cio_skip(cio, 2);\r
-\r
-       /* EPB style */\r
-       Depb = 0x00; /* test */\r
-       cio_write(cio, Depb, 1);   /* Depb */\r
-\r
-       /* length of the data to be protected by this EPB */\r
-       LDPepb = 0x00000000; /* test */\r
-       cio_write(cio, LDPepb, 4);   /* LDPepb */\r
-\r
-       /* next error correction tool */\r
-       Pepb = 0x00000000; /* test */\r
-       cio_write(cio, Pepb, 4);   /* Pepb */\r
-\r
-       /* EPB data */\r
-       /* no data, as of now */\r
-\r
-       Lepb = (unsigned short) (cio_tell(cio) - Lepbp);\r
-       cio_seek(cio, Lepbp);\r
-       cio_write(cio, Lepb, 2);                /* Lepb */\r
-\r
-       cio_seek(cio, Lepbp + Lepb);\r
-\r
-       /* marker struct update */\r
-       j2k_add_marker(j2k->cstr_info, J2K_MS_EPB, Lepbp - 2, Lepb + 2);\r
-}\r
-\r
-void j2k_read_esd(opj_j2k_t *j2k) {\r
-       unsigned short int Lesd, Cesd;\r
-       unsigned char Pesd;\r
-\r
-       int cesdsize = (j2k->image->numcomps >= 257) ? 2 : 1;\r
-\r
-       char str1[4][4] = {"p", "br", "pr", "res"};\r
-       char str2[8][8] = {"res", "mse", "mse-r", "psnr", "psnr-i", "maxerr", "tse", "res"};\r
-       \r
-       opj_cio_t *cio = j2k->cio;\r
-\r
-       /* Simply read the ESD parameters */\r
-       Lesd = cio_read(cio, 2);\r
-       Cesd = cio_read(cio, cesdsize);\r
-       Pesd = cio_read(cio, 1);\r
-\r
-       /* Now we write them to screen */\r
-       opj_event_msg(j2k->cinfo, EVT_INFO,\r
-               "ESD(%d): c%d, %s, %s, %s, %s, %s\n",\r
-               cio_tell(cio) - (5 + cesdsize),\r
-               Cesd, /* component number for this ESD */\r
-               str1[(Pesd & (unsigned char) 0xC0) >> 6], /* addressing mode */\r
-               str2[(Pesd & (unsigned char) 0x38) >> 3], /* sensitivity type */\r
-               ((Pesd & (unsigned char) 0x04) >> 2) ? "2Bs" : "1Bs",\r
-               ((Pesd & (unsigned char) 0x02) >> 1) ? "4Ba" : "2Ba",\r
-               (Pesd & (unsigned char) 0x01) ? "avgc" : "");\r
-\r
-       cio_skip(cio, Lesd - (3 + cesdsize));  \r
-}\r
-\r
-void j2k_read_red(opj_j2k_t *j2k) {\r
-       unsigned short int Lred;\r
-       unsigned char Pred;\r
-       char str1[4][4] = {"p", "br", "pr", "res"};\r
-       \r
-       opj_cio_t *cio = j2k->cio;\r
-\r
-       /* Simply read the RED parameters */\r
-       Lred = cio_read(cio, 2);\r
-       Pred = cio_read(cio, 1);\r
-\r
-       /* Now we write them to screen */\r
-       opj_event_msg(j2k->cinfo, EVT_INFO,\r
-               "RED(%d): %s, %dc, %s, %s\n",\r
-               cio_tell(cio) - 5,\r
-               str1[(Pred & (unsigned char) 0xC0) >> 6], /* addressing mode */\r
-               (Pred & (unsigned char) 0x38) >> 3, /* corruption level */\r
-               ((Pred & (unsigned char) 0x02) >> 1) ? "4Ba" : "2Ba", /* address range */\r
-               (Pred & (unsigned char) 0x01) ? "errs" : "free"); /* error free? */\r
-\r
-       cio_skip(cio, Lred - 3);  \r
-}\r
-\r
-bool jpwl_check_tile(opj_j2k_t *j2k, opj_tcd_t *tcd, int tileno) {\r
-\r
-#ifdef oerhgierhgvhreit4u\r
-       /*\r
-          we navigate through the tile and find possible invalid parameters:\r
-       this saves a lot of crashes!!!!!\r
-        */\r
-       int compno, resno, precno, /*layno,*/ bandno, blockno;\r
-       int numprecincts, numblocks;\r
-\r
-       /* this is the selected tile */\r
-       opj_tcd_tile_t *tile = &(tcd->tcd_image->tiles[tileno]);\r
-\r
-       /* will keep the component */\r
-       opj_tcd_tilecomp_t *comp = NULL;\r
-\r
-       /* will keep the resolution */\r
-       opj_tcd_resolution_t *res;\r
-\r
-       /* will keep the subband */\r
-       opj_tcd_band_t *band; \r
-\r
-       /* will keep the precinct */\r
-       opj_tcd_precinct_t *prec; \r
-\r
-       /* will keep the codeblock */\r
-       opj_tcd_cblk_t *block;\r
-\r
-       /* check all tile components */\r
-       for (compno = 0; compno < tile->numcomps; compno++) {\r
-               comp = &(tile->comps[compno]);\r
-\r
-               /* check all component resolutions */\r
-               for (resno = 0; resno < comp->numresolutions; resno++) {\r
-                       res = &(comp->resolutions[resno]);\r
-                       numprecincts = res->pw * res->ph;\r
-\r
-                       /* check all the subbands */\r
-                       for (bandno = 0; bandno < res->numbands; bandno++) {\r
-                               band = &(res->bands[bandno]);\r
-\r
-                               /* check all the precincts */\r
-                               for (precno = 0; precno < numprecincts; precno++) {\r
-                                       prec = &(band->precincts[precno]);\r
-                                       numblocks = prec->ch * prec->cw;\r
-\r
-                                       /* check all the codeblocks */\r
-                                       for (blockno = 0; blockno < numblocks; blockno++) {\r
-                                               block = &(prec->cblks[blockno]);\r
-\r
-                                               /* x-origin is invalid */\r
-                                               if ((block->x0 < prec->x0) || (block->x0 > prec->x1)) {\r
-                                                       opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,\r
-                                                               "JPWL: wrong x-cord of block origin %d => x-prec is (%d, %d)\n",\r
-                                                               block->x0, prec->x0, prec->x1);\r
-                                                       if (!JPWL_ASSUME || JPWL_ASSUME)\r
-                                                               return false;\r
-                                               };\r
-                                       }\r
-                               }                               \r
-                       }\r
-               }\r
-       }\r
-\r
-#endif\r
-\r
-       return true;\r
-}\r
-\r
-/*@}*/\r
-\r
-#endif /* USE_JPWL */\r
-\r
-\r
-#ifdef USE_JPSEC\r
-\r
-/** @defgroup JPSEC JPSEC - JPEG-2000 Part 8 (JPSEC) codestream manager */\r
-/*@{*/\r
-\r
-\r
-/** @name Local static functions */\r
-/*@{*/\r
-\r
-void j2k_read_sec(opj_j2k_t *j2k) {\r
-       unsigned short int Lsec;\r
-       \r
-       opj_cio_t *cio = j2k->cio;\r
-\r
-       /* Simply read the SEC length */\r
-       Lsec = cio_read(cio, 2);\r
-\r
-       /* Now we write them to screen */\r
-       opj_event_msg(j2k->cinfo, EVT_INFO,\r
-               "SEC(%d)\n",\r
-               cio_tell(cio) - 2\r
-               );\r
-\r
-       cio_skip(cio, Lsec - 2);  \r
-}\r
-\r
-void j2k_write_sec(opj_j2k_t *j2k) {\r
-       unsigned short int Lsec = 24;\r
-       int i;\r
-\r
-       opj_cio_t *cio = j2k->cio;\r
-\r
-       cio_write(cio, J2K_MS_SEC, 2);  /* SEC */\r
-       cio_write(cio, Lsec, 2);\r
-\r
-       /* write dummy data */\r
-       for (i = 0; i < Lsec - 2; i++)\r
-               cio_write(cio, 0, 1);\r
-}\r
-\r
-void j2k_read_insec(opj_j2k_t *j2k) {\r
-       unsigned short int Linsec;\r
-       \r
-       opj_cio_t *cio = j2k->cio;\r
-\r
-       /* Simply read the INSEC length */\r
-       Linsec = cio_read(cio, 2);\r
-\r
-       /* Now we write them to screen */\r
-       opj_event_msg(j2k->cinfo, EVT_INFO,\r
-               "INSEC(%d)\n",\r
-               cio_tell(cio) - 2\r
-               );\r
-\r
-       cio_skip(cio, Linsec - 2);  \r
-}\r
-\r
-\r
-/*@}*/\r
-\r
-/*@}*/\r
-\r
-#endif /* USE_JPSEC */\r
-\r
diff --git a/jpwl/jpwl.h b/jpwl/jpwl.h
deleted file mode 100644 (file)
index d1d066c..0000000
+++ /dev/null
@@ -1,425 +0,0 @@
-/*
- * Copyright (c) 2001-2003, David Janssens
- * Copyright (c) 2002-2003, Yannick Verschueren
- * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe
- * Copyright (c) 2005, Herve Drolon, FreeImage Team
- * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef __JPWL_H
-#define __JPWL_H
-
-#ifdef USE_JPWL
-
-#include "crc.h"
-#include "rs.h"
-
-/**
-@file jpwl.h
-@brief The JPEG-2000 Part11 (JPWL) marker segments manager
-
-The functions in JPWL.C have for goal to read/write the markers added by JPWL.
-*/
-
-/** @defgroup JPWL JPWL - JPEG-2000 Part11 (JPWL) codestream manager */
-/*@{*/
-
-/**
-Assume a basic codestream structure, so you can resort better from uncorrected errors
-*/
-#define JPWL_ASSUME true
-
-/**
-EPB (Error Protection Block) Marker segment
-*/
-typedef struct jpwl_epb_ms {
-       /**@name Private fields set by epb_create */
-       /*@{*/
-       /** is the latest in header? */
-       bool latest;
-       /** is it in packed mode? */
-       bool packed;
-       /** TH where this marker has been placed (-1 means MH) */
-       int tileno;
-       /** index in current header (0-63) */
-       unsigned char index;
-       /** error protection method     [-1=absent 0=none 1=predefined 16=CRC-16 32=CRC-32 37-128=RS] */
-       int hprot;
-       /** message word length of pre-data */
-       int k_pre;
-       /** code word length of pre-data */
-       int n_pre;
-       /** length of pre-data */
-       int pre_len;
-       /** message word length of post-data */
-       int k_post;
-       /** code word length of post-data */
-       int n_post;
-       /** length of post-data */
-       int post_len;
-       /*@}*/
-       /**@name Marker segment fields */
-       /*@{*/
-       /** two bytes for the length of EPB MS, exluding the marker itself (11 to 65535 bytes) */
-       unsigned short int Lepb;
-       /** single byte for the style */
-       unsigned char Depb; 
-       /** four bytes, from 0 to 2^31-1 */
-       unsigned long int LDPepb;
-       /** four bytes, next error management method */
-       unsigned long int Pepb;
-       /** EPB data, variable size */
-       unsigned char *data;   
-       /*@}*/
-}      jpwl_epb_ms_t;
-
-/**
-EPC (Error Protection Capability) Marker segment
-*/
-typedef struct jpwl_epc_ms {
-       /** is ESD active? */
-       bool esd_on;
-       /** is RED active? */
-       bool red_on;
-       /** is EPB active? */
-       bool epb_on;
-       /** are informative techniques active? */
-       bool info_on;
-       /**@name Marker segment fields */
-       /*@{*/
-       /** two bytes for the length of EPC MS, exluding the marker itself (9 to 65535 bytes) */
-       unsigned short int Lepc;   
-       /** two bytes, CRC for the EPC, excluding Pcrc itself */
-       unsigned short int Pcrc;   
-       /** four bytes, the codestream length from SOC to EOC */
-       unsigned long int DL;     
-       /** one byte, signals JPWL techniques adoption */
-       unsigned char Pepc;     
-       /** EPC data, variable length */
-       unsigned char *data;    
-       /*@}*/
-}      jpwl_epc_ms_t;
-
-/**
-ESD (Error Sensitivity Descriptor) Marker segment
-*/
-typedef struct jpwl_esd_ms {
-       /** codestream addressing mode [0=packet, 1=byte range, 2=packet range, 3=reserved] */
-       unsigned char addrm;
-       /** size of codestream addresses [2/4 bytes] */
-       unsigned char ad_size;
-       /** type of sensitivity
-       [0=relative error, 1=MSE, 2=MSE reduction, 3=PSNR, 4=PSNR increment,
-       5=MAXERR (absolute peak error), 6=TSE (total squared error), 7=reserved */
-       unsigned char senst;
-       /** size of sensitivity data (1/2 bytes) */
-       unsigned char se_size;
-       /**@name Marker segment fields */
-       /*@{*/
-       /** two bytes for the length of ESD MS, exluding the marker itself (4 to 65535 bytes) */
-       unsigned short int Lesd;   
-       /** two bytes, component of error sensitivity */
-       unsigned short int Cesd;
-       /** one byte, signals JPWL techniques adoption */
-       unsigned char Pesd;     
-       /** ESD data, variable length */
-       unsigned char *data;    
-       /*@}*/
-       /**@name Fields set by esd_create (only internal use) */
-       /*@{*/
-       /** number of components in the image */
-       int numcomps;
-       /** tile where this marker has been placed (-1 means MH) */
-       int tileno;
-       /** number of sensitivity values */
-       unsigned long int svalnum;
-       /** size of a single sensitivity pair (address+value) */
-       size_t sensval_size;
-       /*@}*/
-}      jpwl_esd_ms_t;
-
-/**
-RED (Residual Error Descriptor) Marker segment
-*/
-typedef struct jpwl_red_ms {
-       /** two bytes for the length of RED MS, exluding the marker itself (3 to 65535 bytes) */
-       unsigned short int Lred;
-       /** one byte, signals JPWL techniques adoption */
-       unsigned char Pred;     
-       /** RED data, variable length */
-       unsigned char *data;    
-}      jpwl_red_ms_t;
-
-/**
-Structure used to store JPWL markers temporary position and readyness
-*/
-typedef struct jpwl_marker {
-       /** marker value (J2K_MS_EPC, etc.) */
-       int id;
-       /** union keeping the pointer to the real marker struct */
-       union jpwl_marks {
-               /** pointer to EPB marker */
-               jpwl_epb_ms_t *epbmark;
-               /** pointer to EPC marker */
-               jpwl_epc_ms_t *epcmark;
-               /** pointer to ESD marker */
-               jpwl_esd_ms_t *esdmark;
-               /** pointer to RED marker */
-               jpwl_red_ms_t *redmark;
-       } m;
-       /** position where the marker should go, in the pre-JPWL codestream */ 
-       unsigned long int pos;
-       /** same as before, only written as a double, so we can sort it better */
-       double dpos;
-       /** length of the marker segment (marker excluded) */
-       unsigned short int len;
-       /** the marker length is ready or not? */
-       bool len_ready;
-       /** the marker position is ready or not? */
-       bool pos_ready;
-       /** the marker parameters are ready or not? */
-       bool parms_ready;
-       /** are the written data ready or not */
-       bool data_ready;
-}      jpwl_marker_t;
-
-/**
-Encode according to JPWL specs
-@param j2k J2K handle
-@param cio codestream handle
-@param image image handle
-*/
-void jpwl_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image);
-
-/**
-Prepare the list of JPWL markers, after the Part 1 codestream
-has been finalized (index struct is full)
-@param j2k J2K handle
-@param cio codestream handle
-@param image image handle
-*/
-void jpwl_prepare_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image);
-
-/**
-Dump the list of JPWL markers, after it has been prepared
-@param j2k J2K handle
-@param cio codestream handle
-@param image image handle
-*/
-void jpwl_dump_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image);
-
-/**
-Read the EPC marker (Error Protection Capability)
-@param j2k J2K handle
-*/
-void j2k_read_epc(opj_j2k_t *j2k);
-
-/**
-Write the EPC marker (Error Protection Capability), BUT the DL field is always set to 0
-(this simplifies the management of EPBs and it is openly stated in the standard
-as a possible value, mening that the information is not available) and the informative techniques
-are not yet implemented
-@param j2k J2K handle
-*/
-void j2k_write_epc(opj_j2k_t *j2k);
-
-/**
-Read the EPB marker (Error Protection Block)
-@param j2k J2K handle
-*/
-void j2k_read_epb(opj_j2k_t *j2k);
-
-/**
-Write the EPB marker (Error Protection Block)
-@param j2k J2K handle
-*/
-void j2k_write_epb(opj_j2k_t *j2k);
-
-/**
-Read the ESD marker (Error Sensitivity Descriptor)
-@param j2k J2K handle
-*/
-void j2k_read_esd(opj_j2k_t *j2k);
-
-/**
-Read the RED marker (Residual Error Descriptor)
-@param j2k J2K handle
-*/
-void j2k_read_red(opj_j2k_t *j2k);
-
-/** create an EPB marker segment
-@param j2k J2K compressor handle
-@param latest it is the latest EPB in the header
-@param packed EPB is in packed style
-@param tileno tile number where the marker has been placed (-1 means MH)
-@param idx current EPB running index
-@param hprot applied protection type (-1/0,1,16,32,37-128)
-@param pre_len length of pre-protected data
-@param post_len length of post-protected data
-@return returns the freshly created EPB
-*/
-jpwl_epb_ms_t *jpwl_epb_create(opj_j2k_t *j2k, bool latest, bool packed, int tileno, int idx, int hprot,
-                                                          unsigned long int pre_len, unsigned long int post_len);
-
-/** add a number of EPB marker segments
-@param j2k J2K compressor handle
-@param jwmarker pointer to the JPWL markers list
-@param jwmarker_num pointer to the number of JPWL markers (gets updated)
-@param latest it is the latest group of EPBs in the header
-@param packed EPBs are in packed style
-@param insideMH it is in the MH
-@param idx pointer to the starting EPB running index (gets updated)
-@param hprot applied protection type (-1/0,1,16,32,37-128)
-@param place_pos place in original codestream where EPBs should go
-@param tileno tile number of these EPBs
-@param pre_len length of pre-protected data
-@param post_len length of post-protected data
-@return returns the length of all added markers
-*/
-int jpwl_epbs_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num,
-                                 bool latest, bool packed, bool insideMH, int *idx, int hprot,
-                                 double place_pos, int tileno,
-                                 unsigned long int pre_len, unsigned long int post_len);
-
-/** add a number of ESD marker segments
-@param j2k J2K compressor handle
-@param jwmarker pointer to the JPWL markers list
-@param jwmarker_num pointer to the number of JPWL markers (gets updated)
-@param comps considered component (-1=average, 0/1/2/...=component no.)
-@param addrm addressing mode (0=packet, 1=byte range, 2=packet range, 3=reserved)
-@param ad_size size of addresses (2/4 bytes)
-@param senst sensitivity type
-@param se_size sensitivity values size (1/2 bytes)
-@param place_pos place in original codestream where EPBs should go
-@param tileno tile number of these EPBs
-@return returns the length of all added markers
-*/
-int jpwl_esds_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num,
-                                 int comps, unsigned char addrm, unsigned char ad_size,
-                                 unsigned char senst, unsigned char se_size,
-                                 double place_pos, int tileno);
-       
-/** updates the information structure by modifying the positions and lengths
-@param j2k J2K compressor handle
-@param jwmarker pointer to JPWL markers list
-@param jwmarker_num number of JPWL markers
-@return returns true in case of success
-*/                       
-bool jpwl_update_info(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int jwmarker_num);
-
-
-bool jpwl_esd_fill(opj_j2k_t *j2k, jpwl_esd_ms_t *esdmark, unsigned char *buf);
-
-bool jpwl_epb_fill(opj_j2k_t *j2k, jpwl_epb_ms_t *epbmark, unsigned char *buf, unsigned char *post_buf);
-
-void j2k_add_marker(opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len);
-
-/** corrects the data in the JPWL codestream
-@param j2k J2K compressor handle
-@return true if correction is performed correctly
-*/
-bool jpwl_correct(opj_j2k_t *j2k);
-
-/** corrects the data protected by an EPB
-@param j2k J2K compressor handle
-@param buffer pointer to the EPB position
-@param type type of EPB: 0=MH, 1=TPH, 2=other, 3=auto
-@param pre_len length of pre-data
-@param post_len length of post_data
-@param conn is a pointer to the length of all connected (packed) EPBs
-@param L4_bufp is a pointer to the buffer pointer of redundancy data
-@return returns true if correction could be succesfully performed
-*/
-bool jpwl_epb_correct(opj_j2k_t *j2k, unsigned char *buffer, int type, int pre_len, int post_len, int *conn,
-                                         unsigned char **L4_bufp);
-
-/** check that a tile and its children have valid data
-@param j2k J2K decompressor handle
-@param tcd Tile decompressor handle
-@param tileno number of the tile to check
-*/
-bool jpwl_check_tile(opj_j2k_t *j2k, opj_tcd_t *tcd, int tileno);
-
-/** Macro functions for CRC computation */
-
-/**
-Computes the CRC-16, as stated in JPWL specs
-@param CRC two bytes containing the CRC value (must be initialized with 0x0000)
-@param DATA byte for which the CRC is computed; call this on every byte of the sequence
-and get the CRC at the end
-*/
-#define jpwl_updateCRC16(CRC, DATA) updateCRC16(CRC, DATA)
-
-/**
-Computes the CRC-32, as stated in JPWL specs
-@param CRC four bytes containing the CRC value (must be initialized with 0x00000000)
-@param DATA byte for which the CRC is computed; call this on every byte of the sequence
-and get the CRC at the end
-*/
-#define jpwl_updateCRC32(CRC, DATA) updateCRC32(CRC, DATA)
-
-/**
-Computes the minimum between two integers
-@param a first integer to compare
-@param b second integer to compare
-@return returns the minimum integer between a and b
-*/
-#ifndef min
-#define min(a,b)    (((a) < (b)) ? (a) : (b))
-#endif /* min */
-
-/*@}*/
-
-#endif /* USE_JPWL */
-
-#ifdef USE_JPSEC
-
-/** @defgroup JPSEC JPSEC - JPEG-2000 Part 8 (JPSEC) codestream manager */
-/*@{*/
-
-/**
-Read the SEC marker (SEcured Codestream)
-@param j2k J2K handle
-*/
-void j2k_read_sec(opj_j2k_t *j2k);
-
-/**
-Write the SEC marker (SEcured Codestream)
-@param j2k J2K handle
-*/
-void j2k_write_sec(opj_j2k_t *j2k);
-
-/**
-Read the INSEC marker (SEcured Codestream)
-@param j2k J2K handle
-*/
-void j2k_read_insec(opj_j2k_t *j2k);
-
-/*@}*/
-
-#endif /* USE_JPSEC */
-
-#endif /* __JPWL_H */
-
diff --git a/jpwl/jpwl_lib.c b/jpwl/jpwl_lib.c
deleted file mode 100644 (file)
index ea53c93..0000000
+++ /dev/null
@@ -1,1796 +0,0 @@
-/*
- * Copyright (c) 2001-2003, David Janssens
- * Copyright (c) 2002-2003, Yannick Verschueren
- * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe
- * Copyright (c) 2005, Herve Drolon, FreeImage Team
- * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef USE_JPWL
-
-#include "../libopenjpeg/opj_includes.h"
-#include <limits.h>
-
-/** Minimum and maximum values for the double->pfp conversion */
-#define MIN_V1 0.0
-#define MAX_V1 17293822569102704640.0
-#define MIN_V2 0.000030517578125
-#define MAX_V2 131040.0
-
-/** conversion between a double precision floating point
-number and the corresponding pseudo-floating point used 
-to represent sensitivity values
-@param V the double precision value
-@param bytes the number of bytes of the representation
-@return the pseudo-floating point value (cast accordingly)
-*/
-unsigned short int jpwl_double_to_pfp(double V, int bytes);
-
-/** conversion between a pseudo-floating point used 
-to represent sensitivity values and the corresponding
-double precision floating point number  
-@param em the pseudo-floating point value (cast accordingly)
-@param bytes the number of bytes of the representation
-@return the double precision value
-*/
-double jpwl_pfp_to_double(unsigned short int em, int bytes);
-
-       /*-------------------------------------------------------------*/
-
-int jpwl_markcomp(const void *arg1, const void *arg2)
-{
-   /* Compare the two markers' positions */
-   double diff = (((jpwl_marker_t *) arg1)->dpos - ((jpwl_marker_t *) arg2)->dpos);
-
-   if (diff == 0.0)
-          return (0);
-   else if (diff < 0)
-          return (-1);
-   else
-          return (+1);
-}
-
-int jpwl_epbs_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num,
-                                 bool latest, bool packed, bool insideMH, int *idx, int hprot,
-                                 double place_pos, int tileno,
-                                 unsigned long int pre_len, unsigned long int post_len) {
-
-       jpwl_epb_ms_t *epb_mark = NULL;
-
-       int k_pre, k_post, n_pre, n_post;
-       
-       unsigned long int L1, L2, dL4, max_postlen, epbs_len = 0;
-
-       /* We find RS(n,k) for EPB parms and pre-data, if any */
-       if (insideMH && (*idx == 0)) {
-               /* First EPB in MH */ 
-               k_pre = 64;
-               n_pre = 160;
-       } else if (!insideMH && (*idx == 0)) {
-               /* First EPB in TH */
-               k_pre = 25;
-               n_pre = 80;
-       } else {
-               /* Following EPBs in MH or TH */
-               k_pre = 13;
-               n_pre = 40;
-       };
-
-       /* Find lengths, Figs. B3 and B4 */
-       /* size of pre data: pre_buf(pre_len) + EPB(2) + Lepb(2) + Depb(1) + LDPepb(4) + Pepb(4) */
-       L1 = pre_len + 13;
-
-       /* size of pre-data redundancy */
-       /*   (redundancy per codeword)       *     (number of codewords, rounded up)   */
-       L2 = (n_pre - k_pre) * (unsigned long int) ceil((double) L1 / (double) k_pre);
-
-       /* Find protection type for post data and its associated redundancy field length*/
-       if ((hprot == 16) || (hprot == 32)) {
-               /* there is a CRC for post-data */
-               k_post = post_len;
-               n_post = post_len + (hprot >> 3);
-               /*L3 = hprot >> 3;*/ /* 2 (CRC-16) or 4 (CRC-32) bytes */
-
-       } else if ((hprot >= 37) && (hprot <= 128)) {
-               /* there is a RS for post-data */
-               k_post = 32;
-               n_post = hprot;
-
-       } else {
-               /* Use predefined codes */
-               n_post = n_pre;
-               k_post = k_pre;
-       };
-
-       /* Create the EPB(s) */
-       while (post_len > 0) {
-
-               /* maximum postlen in order to respect EPB size
-               (we use JPWL_MAXIMUM_EPB_ROOM instead of 65535 for keeping room for EPB parms)*/
-               /*      (message word size)    *            (number of containable parity words)  */
-               max_postlen = k_post * (unsigned long int) floor((double) JPWL_MAXIMUM_EPB_ROOM / (double) (n_post - k_post));
-
-               /* maximum postlen in order to respect EPB size */
-               if (*idx == 0)
-                       /* (we use (JPWL_MAXIMUM_EPB_ROOM - L2) instead of 65535 for keeping room for EPB parms + pre-data) */
-                       /*      (message word size)    *                   (number of containable parity words)  */
-                       max_postlen = k_post * (unsigned long int) floor((double) (JPWL_MAXIMUM_EPB_ROOM - L2) / (double) (n_post - k_post));
-
-               else
-                       /* (we use JPWL_MAXIMUM_EPB_ROOM instead of 65535 for keeping room for EPB parms) */
-                       /*      (message word size)    *            (number of containable parity words)  */
-                       max_postlen = k_post * (unsigned long int) floor((double) JPWL_MAXIMUM_EPB_ROOM / (double) (n_post - k_post));
-
-               /* null protection case */
-               /* the max post length can be as large as the LDPepb field can host */
-               if (hprot == 0)
-                       max_postlen = INT_MAX;
-               
-               /* length to use */
-               dL4 = min(max_postlen, post_len);
-
-               if ((epb_mark = jpwl_epb_create(
-                       j2k, /* this encoder handle */
-                       latest ? (dL4 < max_postlen) : false, /* is it the latest? */
-                       packed, /* is it packed? */
-                       tileno, /* we are in TPH */
-                       *idx, /* its index */
-                       hprot, /* protection type parameters of following data */
-                       0, /* pre-data: nothing for now */
-                       dL4 /* post-data: the stub computed previously */
-                       ))) {
-                       
-                       /* Add this marker to the 'insertanda' list */
-                       if (*jwmarker_num < JPWL_MAX_NO_MARKERS) {
-                               jwmarker[*jwmarker_num].id = J2K_MS_EPB; /* its type */
-                               jwmarker[*jwmarker_num].m.epbmark = epb_mark; /* the EPB */
-                               jwmarker[*jwmarker_num].pos = (int) place_pos; /* after SOT */
-                               jwmarker[*jwmarker_num].dpos = place_pos + 0.0000001 * (double)(*idx); /* not very first! */
-                               jwmarker[*jwmarker_num].len = epb_mark->Lepb; /* its length */
-                               jwmarker[*jwmarker_num].len_ready = true; /* ready */
-                               jwmarker[*jwmarker_num].pos_ready = true; /* ready */
-                               jwmarker[*jwmarker_num].parms_ready = true; /* ready */
-                               jwmarker[*jwmarker_num].data_ready = false; /* not ready */
-                               (*jwmarker_num)++;
-                       }
-
-                       /* increment epb index */
-                       (*idx)++;
-
-                       /* decrease postlen */
-                       post_len -= dL4;
-
-                       /* increase the total length of EPBs */
-                       epbs_len += epb_mark->Lepb + 2;
-
-               } else {
-                       /* ooops, problems */
-                       opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH EPB for UEP in tile %d\n", tileno);                          
-               };
-       }
-
-       return epbs_len;
-}
-
-
-jpwl_epb_ms_t *jpwl_epb_create(opj_j2k_t *j2k, bool latest, bool packed, int tileno, int idx, int hprot,
-                                                 unsigned long int pre_len, unsigned long int post_len) {
-
-       jpwl_epb_ms_t *epb = NULL;
-       /*unsigned short int data_len = 0;*/
-       unsigned short int L2, L3;
-       unsigned long int L1, L4;
-       /*unsigned char *predata_in = NULL;*/
-
-       bool insideMH = (tileno == -1);
-
-       /* Alloc space */
-       if (!(epb = (jpwl_epb_ms_t *) opj_malloc((size_t) 1 * sizeof (jpwl_epb_ms_t)))) {
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for one EPB MS\n");
-               return NULL;
-       };
-
-       /* We set RS(n,k) for EPB parms and pre-data, if any */
-       if (insideMH && (idx == 0)) {
-               /* First EPB in MH */ 
-               epb->k_pre = 64;
-               epb->n_pre = 160;
-       } else if (!insideMH && (idx == 0)) {
-               /* First EPB in TH */
-               epb->k_pre = 25;
-               epb->n_pre = 80;
-       } else {
-               /* Following EPBs in MH or TH */
-               epb->k_pre = 13;
-               epb->n_pre = 40;
-       };
-
-       /* Find lengths, Figs. B3 and B4 */
-       /* size of pre data: pre_buf(pre_len) + EPB(2) + Lepb(2) + Depb(1) + LDPepb(4) + Pepb(4) */
-       L1 = pre_len + 13;
-       epb->pre_len = pre_len;
-
-       /* size of pre-data redundancy */
-       /*   (redundancy per codeword)       *               (number of codewords, rounded up)   */
-       L2 = (epb->n_pre - epb->k_pre) * (unsigned short int) ceil((double) L1 / (double) epb->k_pre);
-
-       /* length of post-data */
-       L4 = post_len;
-       epb->post_len = post_len;
-
-       /* Find protection type for post data and its associated redundancy field length*/
-       if ((hprot == 16) || (hprot == 32)) {
-               /* there is a CRC for post-data */
-               epb->Pepb = 0x10000000 | ((unsigned long int) hprot >> 5); /* 0=CRC-16, 1=CRC-32 */
-               epb->k_post = post_len;
-               epb->n_post = post_len + (hprot >> 3);
-               /*L3 = hprot >> 3;*/ /* 2 (CRC-16) or 4 (CRC-32) bytes */
-
-       } else if ((hprot >= 37) && (hprot <= 128)) {
-               /* there is a RS for post-data */
-               epb->Pepb = 0x20000020 | (((unsigned long int) hprot & 0x000000FF) << 8);
-               epb->k_post = 32;
-               epb->n_post = hprot;
-
-       } else if (hprot == 1) {
-               /* Use predefined codes */
-               epb->Pepb = (unsigned long int) 0x00000000;
-               epb->n_post = epb->n_pre;
-               epb->k_post = epb->k_pre;
-       
-       } else if (hprot == 0) {
-               /* Placeholder EPB: only protects its parameters, no protection method */
-               epb->Pepb = (unsigned long int) 0xFFFFFFFF;
-               epb->n_post = 1;
-               epb->k_post = 1;
-       
-       } else {
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "Invalid protection value for EPB h = %d\n", hprot);                               
-               return NULL;
-       }
-
-       epb->hprot = hprot;
-
-       /*   (redundancy per codeword)          *                (number of codewords, rounded up) */
-       L3 = (epb->n_post - epb->k_post) * (unsigned short int) ceil((double) L4 / (double) epb->k_post);
-
-       /* private fields */
-       epb->tileno = tileno;
-
-       /* Fill some fields of the EPB */
-
-       /* total length of the EPB MS (less the EPB marker itself): */
-       /* Lepb(2) + Depb(1) + LDPepb(4) + Pepb(4) + pre_redundancy + post-redundancy */
-       epb->Lepb = 11 + L2 + L3;
-
-       /* EPB style */
-       epb->Depb = ((packed & 0x0001) << 7) | ((latest & 0x0001) << 6) | (idx & 0x003F);
-
-       /* length of data protected by EPB: */
-       epb->LDPepb = L1 + L4;
-
-       return epb;
-}
-
-void jpwl_epb_write(opj_j2k_t *j2k, jpwl_epb_ms_t *epb, unsigned char *buf) {
-
-       /* Marker */
-       *(buf++) = (unsigned char) (J2K_MS_EPB >> 8); 
-       *(buf++) = (unsigned char) (J2K_MS_EPB >> 0); 
-
-       /* Lepb */
-       *(buf++) = (unsigned char) (epb->Lepb >> 8); 
-       *(buf++) = (unsigned char) (epb->Lepb >> 0); 
-
-       /* Depb */
-       *(buf++) = (unsigned char) (epb->Depb >> 0); 
-
-       /* LDPepb */
-       *(buf++) = (unsigned char) (epb->LDPepb >> 24); 
-       *(buf++) = (unsigned char) (epb->LDPepb >> 16); 
-       *(buf++) = (unsigned char) (epb->LDPepb >> 8); 
-       *(buf++) = (unsigned char) (epb->LDPepb >> 0); 
-
-       /* Pepb */
-       *(buf++) = (unsigned char) (epb->Pepb >> 24); 
-       *(buf++) = (unsigned char) (epb->Pepb >> 16); 
-       *(buf++) = (unsigned char) (epb->Pepb >> 8); 
-       *(buf++) = (unsigned char) (epb->Pepb >> 0); 
-
-       /* Data */
-       /*memcpy(buf, epb->data, (size_t) epb->Lepb - 11);*/
-       memset(buf, 0, (size_t) epb->Lepb - 11);
-
-       /* update markers struct */
-       j2k_add_marker(j2k->cstr_info, J2K_MS_EPB, -1, epb->Lepb + 2);
-
-};
-
-
-jpwl_epc_ms_t *jpwl_epc_create(opj_j2k_t *j2k, bool esd_on, bool red_on, bool epb_on, bool info_on) {
-
-       jpwl_epc_ms_t *epc = NULL;
-
-       /* Alloc space */
-       if (!(epc = (jpwl_epc_ms_t *) opj_malloc((size_t) 1 * sizeof (jpwl_epc_ms_t)))) {
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for EPC MS\n");
-               return NULL;
-       };
-
-       /* Set the EPC parameters */
-       epc->esd_on = esd_on;
-       epc->epb_on = epb_on;
-       epc->red_on = red_on;
-       epc->info_on = info_on;
-
-       /* Fill the EPC fields with default values */
-       epc->Lepc = 9;
-       epc->Pcrc = 0x0000;
-       epc->DL = 0x00000000;
-       epc->Pepc = ((j2k->cp->esd_on & 0x0001) << 4) | ((j2k->cp->red_on & 0x0001) << 5) |
-               ((j2k->cp->epb_on & 0x0001) << 6) | ((j2k->cp->info_on & 0x0001) << 7);
-
-       return (epc);
-}
-
-bool jpwl_epb_fill(opj_j2k_t *j2k, jpwl_epb_ms_t *epb, unsigned char *buf, unsigned char *post_buf) {
-
-       unsigned long int L1, L2, L3, L4;
-       int remaining;
-       unsigned long int P, NN_P;
-
-       /* Operating buffer */
-       static unsigned char codeword[NN], *parityword;
-
-       unsigned char *L1_buf, *L2_buf;
-       /* these ones are static, since we need to keep memory of
-        the exact place from one call to the other */
-       static unsigned char *L3_buf, *L4_buf;
-
-       /* some consistency check */
-       if (!buf) {
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "There is no operating buffer for EPBs\n");
-               return false;
-       }
-
-       if (!post_buf && !L4_buf) {
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "There is no operating buffer for EPBs data\n");
-               return false;
-       }
-
-       /*
-        * Compute parity bytes on pre-data, ALWAYS present (at least only for EPB parms)
-        */
-
-       /* Initialize RS structures */
-       P = epb->n_pre - epb->k_pre;
-       NN_P = NN - P;
-       memset(codeword, 0, NN);
-       parityword = codeword + NN_P;
-       init_rs(NN_P);
-
-       /* pre-data begins pre_len bytes before of EPB buf */
-       L1_buf = buf - epb->pre_len;
-       L1 = epb->pre_len + 13;
-
-       /* redundancy for pre-data begins immediately after EPB parms */
-       L2_buf = buf + 13;
-       L2 = (epb->n_pre - epb->k_pre) * (unsigned short int) ceil((double) L1 / (double) epb->k_pre);
-
-       /* post-data
-          the position of L4 buffer can be:
-            1) passed as a parameter: in that case use it
-            2) null: in that case use the previous (static) one
-       */
-       if (post_buf)
-               L4_buf = post_buf;
-       L4 = epb->post_len;
-
-       /* post-data redundancy begins immediately after pre-data redundancy */
-       L3_buf = L2_buf + L2;
-       L3 = (epb->n_post - epb->k_post) * (unsigned short int) ceil((double) L4 / (double) epb->k_post);
-
-       /* let's check whether EPB length is sufficient to contain all these data */
-       if (epb->Lepb < (11 + L2 + L3))
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "There is no room in EPB data field for writing redundancy data\n");
-       /*printf("Env. %d, nec. %d (%d + %d)\n", epb->Lepb - 11, L2 + L3, L2, L3);*/
-
-       /* Compute redundancy of pre-data message words */
-       remaining = L1;
-       while (remaining) {
-
-               /* copy message data into codeword buffer */
-               if (remaining < epb->k_pre) {
-                       /* the last message word is zero-padded */
-                       memset(codeword, 0, NN);
-                       memcpy(codeword, L1_buf, remaining);
-                       L1_buf += remaining;
-                       remaining = 0;
-
-               } else {
-                       memcpy(codeword, L1_buf, epb->k_pre);
-                       L1_buf += epb->k_pre;
-                       remaining -= epb->k_pre;
-
-               }
-
-               /* Encode the buffer and obtain parity bytes */
-               if (encode_rs(codeword, parityword))
-                       opj_event_msg(j2k->cinfo, EVT_WARNING,
-                               "Possible encoding error in codeword @ position #%d\n", (L1_buf - buf) / epb->k_pre);
-
-               /* copy parity bytes only in redundancy buffer */
-               memcpy(L2_buf, parityword, P); 
-
-               /* advance parity buffer */
-               L2_buf += P;
-       }
-
-       /*
-        * Compute parity bytes on post-data, may be absent if there are no data
-        */
-       /*printf("Hprot is %d (tileno=%d, k_pre=%d, n_pre=%d, k_post=%d, n_post=%d, pre_len=%d, post_len=%d)\n",
-               epb->hprot, epb->tileno, epb->k_pre, epb->n_pre, epb->k_post, epb->n_post, epb->pre_len,
-               epb->post_len);*/
-       if (epb->hprot < 0) {
-
-               /* there should be no EPB */
-               
-       } else if (epb->hprot == 0) {
-
-               /* no protection for the data */
-               /* advance anyway */
-               L4_buf += epb->post_len;
-
-       } else if (epb->hprot == 16) {
-
-               /* CRC-16 */
-               unsigned short int mycrc = 0x0000;
-
-               /* compute the CRC field (excluding itself) */
-               remaining = L4;
-               while (remaining--)
-                       jpwl_updateCRC16(&mycrc, *(L4_buf++));
-
-               /* write the CRC field */
-               *(L3_buf++) = (unsigned char) (mycrc >> 8);
-               *(L3_buf++) = (unsigned char) (mycrc >> 0);
-
-       } else if (epb->hprot == 32) {
-
-               /* CRC-32 */
-               unsigned long int mycrc = 0x00000000;
-
-               /* compute the CRC field (excluding itself) */
-               remaining = L4;
-               while (remaining--)
-                       jpwl_updateCRC32(&mycrc, *(L4_buf++));
-
-               /* write the CRC field */
-               *(L3_buf++) = (unsigned char) (mycrc >> 24);
-               *(L3_buf++) = (unsigned char) (mycrc >> 16);
-               *(L3_buf++) = (unsigned char) (mycrc >> 8);
-               *(L3_buf++) = (unsigned char) (mycrc >> 0);
-
-       } else {
-
-               /* RS */
-
-               /* Initialize RS structures */
-               P = epb->n_post - epb->k_post;
-               NN_P = NN - P;
-               memset(codeword, 0, NN);
-               parityword = codeword + NN_P;
-               init_rs(NN_P);
-
-               /* Compute redundancy of post-data message words */
-               remaining = L4;
-               while (remaining) {
-
-                       /* copy message data into codeword buffer */
-                       if (remaining < epb->k_post) {
-                               /* the last message word is zero-padded */
-                               memset(codeword, 0, NN);
-                               memcpy(codeword, L4_buf, remaining);
-                               L4_buf += remaining;
-                               remaining = 0;
-
-                       } else {
-                               memcpy(codeword, L4_buf, epb->k_post);
-                               L4_buf += epb->k_post;
-                               remaining -= epb->k_post;
-
-                       }
-
-                       /* Encode the buffer and obtain parity bytes */
-                       if (encode_rs(codeword, parityword))
-                               opj_event_msg(j2k->cinfo, EVT_WARNING,
-                                       "Possible encoding error in codeword @ position #%d\n", (L4_buf - buf) / epb->k_post);
-
-                       /* copy parity bytes only in redundancy buffer */
-                       memcpy(L3_buf, parityword, P); 
-
-                       /* advance parity buffer */
-                       L3_buf += P;
-               }
-
-       }
-
-       return true;
-}
-
-
-bool jpwl_correct(opj_j2k_t *j2k) {
-
-       opj_cio_t *cio = j2k->cio;
-       bool status;
-       static bool mh_done = false;
-       int mark_pos, id, len, skips, sot_pos;
-       unsigned long int Psot = 0;
-
-       /* go back to marker position */
-       mark_pos = cio_tell(cio) - 2;
-       cio_seek(cio, mark_pos);
-
-       if ((j2k->state == J2K_STATE_MHSOC) && !mh_done) {
-
-               int mark_val = 0, skipnum = 0;
-
-               /*
-                 COLOR IMAGE
-                 first thing to do, if we are here, is to look whether
-                 51 (skipnum) positions ahead there is an EPB, in case of MH
-               */
-               /*
-                 B/W IMAGE
-                 first thing to do, if we are here, is to look whether
-                 45 (skipnum) positions ahead there is an EPB, in case of MH
-               */
-               /*       SIZ   SIZ_FIELDS     SIZ_COMPS               FOLLOWING_MARKER */
-               skipnum = 2  +     38     + 3 * j2k->cp->exp_comps  +         2;
-               if ((cio->bp + skipnum) < cio->end) {
-
-                       cio_skip(cio, skipnum);
-
-                       /* check that you are not going beyond the end of codestream */
-
-                       /* call EPB corrector */
-                       status = jpwl_epb_correct(j2k,     /* J2K decompressor handle */
-                                                                         cio->bp, /* pointer to EPB in codestream buffer */
-                                                                         0,       /* EPB type: MH */
-                                                                         skipnum,      /* length of pre-data */
-                                                                         -1,      /* length of post-data: -1 means auto */
-                                                                         NULL,
-                                                                         NULL
-                                                                        );
-
-                       /* read the marker value */
-                       mark_val = (*(cio->bp) << 8) | *(cio->bp + 1);
-
-                       if (status && (mark_val == J2K_MS_EPB)) {
-                               /* we found it! */
-                               mh_done = true;
-                               return true;
-                       }
-
-                       /* Disable correction in case of missing or bad head EPB */
-                       /* We can't do better! */
-                       /* PATCHED: 2008-01-25 */
-                       /* MOVED UP: 2008-02-01 */
-                       if (!status) {
-                               j2k->cp->correct = false;
-                               opj_event_msg(j2k->cinfo, EVT_WARNING, "Couldn't find the MH EPB: disabling JPWL\n");
-                       }
-
-               }
-
-       }
-
-       if (true /*(j2k->state == J2K_STATE_TPHSOT) || (j2k->state == J2K_STATE_TPH)*/) {
-               /* else, look if 12 positions ahead there is an EPB, in case of TPH */
-               cio_seek(cio, mark_pos);
-               if ((cio->bp + 12) < cio->end) {
-
-                       cio_skip(cio, 12);
-
-                       /* call EPB corrector */
-                       status = jpwl_epb_correct(j2k,     /* J2K decompressor handle */
-                                                                         cio->bp, /* pointer to EPB in codestream buffer */
-                                                                         1,       /* EPB type: TPH */
-                                                                         12,      /* length of pre-data */
-                                                                         -1,      /* length of post-data: -1 means auto */
-                                                                         NULL,
-                                                                         NULL
-                                                                        );
-                       if (status)
-                               /* we found it! */
-                               return true;
-               }
-       }
-
-       return false;
-
-       /* for now, don't use this code */
-
-       /* else, look if here is an EPB, in case of other */
-       if (mark_pos > 64) {
-               /* it cannot stay before the first MH EPB */
-               cio_seek(cio, mark_pos);
-               cio_skip(cio, 0);
-
-               /* call EPB corrector */
-               status = jpwl_epb_correct(j2k,     /* J2K decompressor handle */
-                                                                 cio->bp, /* pointer to EPB in codestream buffer */
-                                                                 2,       /* EPB type: TPH */
-                                                                 0,       /* length of pre-data */
-                                                                 -1,      /* length of post-data: -1 means auto */
-                                                                 NULL,
-                                                                 NULL
-                                                                );
-               if (status)
-                       /* we found it! */
-                       return true;
-       }
-
-       /* nope, no EPBs probably, or they are so damaged that we can give up */
-       return false;
-       
-       return true;
-
-       /* AN ATTEMPT OF PARSER */
-       /* NOT USED ACTUALLY    */
-
-       /* go to the beginning of the file */
-       cio_seek(cio, 0);
-
-       /* let's begin */
-       j2k->state = J2K_STATE_MHSOC;
-
-       /* cycle all over the markers */
-       while (cio_tell(cio) < cio->length) {
-
-               /* read the marker */
-               mark_pos = cio_tell(cio);
-               id = cio_read(cio, 2);
-
-               /* details */
-               printf("Marker@%d: %X\n", cio_tell(cio) - 2, id);
-
-               /* do an action in response to the read marker */
-               switch (id) {
-
-               /* short markers */
-
-                       /* SOC */
-               case J2K_MS_SOC:
-                       j2k->state = J2K_STATE_MHSIZ;
-                       len = 0;
-                       skips = 0;
-                       break;
-
-                       /* EOC */
-               case J2K_MS_EOC:
-                       j2k->state = J2K_STATE_MT;
-                       len = 0;
-                       skips = 0;
-                       break;
-
-                       /* particular case of SOD */
-               case J2K_MS_SOD:
-                       len = Psot - (mark_pos - sot_pos) - 2;
-                       skips = len;
-                       break;
-
-               /* long markers */
-
-                       /* SOT */
-               case J2K_MS_SOT:
-                       j2k->state = J2K_STATE_TPH;
-                       sot_pos = mark_pos; /* position of SOT */
-                       len = cio_read(cio, 2); /* read the length field */
-                       cio_skip(cio, 2); /* this field is unnecessary */
-                       Psot = cio_read(cio, 4); /* tile length */
-                       skips = len - 8;
-                       break;
-
-                       /* remaining */
-               case J2K_MS_SIZ:
-                       j2k->state = J2K_STATE_MH;
-                       /* read the length field */
-                       len = cio_read(cio, 2);
-                       skips = len - 2;
-                       break;
-
-                       /* remaining */
-               default:
-                       /* read the length field */
-                       len = cio_read(cio, 2);
-                       skips = len - 2;
-                       break;
-
-               }
-
-               /* skip to marker's end */
-               cio_skip(cio, skips);   
-
-       }
-
-
-}
-
-bool jpwl_epb_correct(opj_j2k_t *j2k, unsigned char *buffer, int type, int pre_len, int post_len, int *conn,
-                                         unsigned char **L4_bufp) {
-
-       /* Operating buffer */
-       unsigned char codeword[NN], *parityword;
-
-       unsigned long int P, NN_P;
-       unsigned long int L1, L4;
-       int remaining, n_pre, k_pre, n_post, k_post;
-
-       int status, tt;
-
-       int orig_pos = cio_tell(j2k->cio);
-
-       unsigned char *L1_buf, *L2_buf;
-       unsigned char *L3_buf, *L4_buf;
-
-       unsigned long int LDPepb, Pepb;
-       unsigned short int Lepb;
-       unsigned char Depb;
-       char str1[25] = "";
-       int myconn, errnum = 0;
-       bool errflag = false;
-       
-       opj_cio_t *cio = j2k->cio;
-
-       /* check for common errors */
-       if (!buffer) {
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "The EPB pointer is a NULL buffer\n");
-               return false;
-       }
-       
-       /* set bignesses */
-       L1 = pre_len + 13;
-
-       /* pre-data correction */
-       switch (type) {
-
-       case 0:
-               /* MH EPB */
-               k_pre = 64;
-               n_pre = 160;
-               break;
-
-       case 1:
-               /* TPH EPB */
-               k_pre = 25;
-               n_pre = 80;
-               break;
-
-       case 2:
-               /* other EPBs */
-               k_pre = 13;
-               n_pre = 40;
-               break;
-
-       case 3:
-               /* automatic setup */
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "Auto. setup not yet implemented\n");
-               return false;
-               break;
-
-       default:
-               /* unknown type */
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "Unknown expected EPB type\n");
-               return false;
-               break;
-
-       }
-
-       /* Initialize RS structures */
-       P = n_pre - k_pre;
-       NN_P = NN - P;
-       tt = (int) floor((float) P / 2.0F); /* correction capability of the code */
-       memset(codeword, 0, NN);
-       parityword = codeword + NN_P;
-       init_rs(NN_P);
-
-       /* Correct pre-data message words */
-       L1_buf = buffer - pre_len;
-       L2_buf = buffer + 13;
-       remaining = L1;
-       while (remaining) {
-               /* always zero-pad codewords */
-               /* (this is required, since after decoding the zeros in the long codeword
-                   could change, and keep unchanged in subsequent calls) */
-               memset(codeword, 0, NN);
-
-               /* copy codeword buffer into message bytes */
-               if (remaining < k_pre)
-                       memcpy(codeword, L1_buf, remaining);
-               else
-                       memcpy(codeword, L1_buf, k_pre);
-
-               /* copy redundancy buffer in parity bytes */
-               memcpy(parityword, L2_buf, P); 
-
-               /* Decode the buffer and possibly obtain corrected bytes */
-               status = eras_dec_rs(codeword, NULL, 0);
-               if (status == -1) {
-                       /*if (conn == NULL)
-                               opj_event_msg(j2k->cinfo, EVT_WARNING,
-                                       "Possible decoding error in codeword @ position #%d\n", (L1_buf - buffer) / k_pre);*/
-                       errflag = true;
-                       /* we can try to safely get out from the function:
-                         if we are here, either this is not an EPB or the first codeword
-                         is too damaged to be helpful */
-                       /*return false;*/
-
-               } else if (status == 0) {
-                       /*if (conn == NULL)
-                               opj_event_msg(j2k->cinfo, EVT_INFO, "codeword is correctly decoded\n");*/
-
-               } else if (status <= tt) {
-                       /* it has corrected 0 <= errs <= tt */
-                       /*if (conn == NULL)
-                               opj_event_msg(j2k->cinfo, EVT_WARNING, "%d errors corrected in codeword\n", status);*/
-                       errnum += status;
-
-               } else {
-                       /*if (conn == NULL)
-                               opj_event_msg(j2k->cinfo, EVT_WARNING, "EPB correction capability exceeded\n");
-                       return false;*/
-                       errflag = true;
-               }
-
-
-               /* advance parity buffer */
-               if ((status >= 0) && (status <= tt))
-                       /* copy back corrected parity only if all is OK */
-                       memcpy(L2_buf, parityword, P);
-               L2_buf += P;
-
-               /* advance message buffer */
-               if (remaining < k_pre) {
-                       if ((status >= 0) && (status <= tt))
-                               /* copy back corrected data only if all is OK */
-                               memcpy(L1_buf, codeword, remaining);
-                       L1_buf += remaining;
-                       remaining = 0;
-
-               } else {
-                       if ((status >= 0) && (status <= tt))
-                               /* copy back corrected data only if all is OK */
-                               memcpy(L1_buf, codeword, k_pre);
-                       L1_buf += k_pre;
-                       remaining -= k_pre;
-
-               }
-       }
-
-       /* print summary */
-       if (!conn) {
-
-               /*if (errnum)
-                       opj_event_msg(j2k->cinfo, EVT_INFO, "+ %d symbol errors corrected (Ps=%.1e)\n", errnum,
-                               (float) errnum / ((float) n_pre * (float) L1 / (float) k_pre));*/
-               if (errflag) {
-                       /*opj_event_msg(j2k->cinfo, EVT_INFO, "+ there were unrecoverable errors\n");*/
-                       return false;
-               }
-
-       }
-
-       /* presumably, now, EPB parameters are correct */
-       /* let's get them */
-
-       /* Simply read the EPB parameters */
-       if (conn)
-               cio->bp = buffer;
-       cio_skip(cio, 2); /* the marker */
-       Lepb = cio_read(cio, 2);
-       Depb = cio_read(cio, 1);
-       LDPepb = cio_read(cio, 4);
-       Pepb = cio_read(cio, 4);
-
-       /* What does Pepb tells us about the protection method? */
-       if (((Pepb & 0xF0000000) >> 28) == 0)
-               sprintf(str1, "pred"); /* predefined */
-       else if (((Pepb & 0xF0000000) >> 28) == 1)
-               sprintf(str1, "crc-%lu", 16 * ((Pepb & 0x00000001) + 1)); /* CRC mode */
-       else if (((Pepb & 0xF0000000) >> 28) == 2)
-               sprintf(str1, "rs(%lu,32)", (Pepb & 0x0000FF00) >> 8); /* RS mode */
-       else if (Pepb == 0xFFFFFFFF)
-               sprintf(str1, "nometh"); /* RS mode */
-       else
-               sprintf(str1, "unknown"); /* unknown */
-
-       /* Now we write them to screen */
-       if (!conn && post_len)
-               opj_event_msg(j2k->cinfo, EVT_INFO,
-                       "EPB(%d): (%sl, %sp, %u), %lu, %s\n",
-                       cio_tell(cio) - 13,
-                       (Depb & 0x40) ? "" : "n", /* latest EPB or not? */
-                       (Depb & 0x80) ? "" : "n", /* packed or unpacked EPB? */
-                       (Depb & 0x3F), /* EPB index value */
-                       LDPepb, /*length of the data protected by the EPB */
-                       str1); /* protection method */
-
-
-       /* well, we need to investigate how long is the connected length of packed EPBs */
-       myconn = Lepb + 2;
-       if ((Depb & 0x40) == 0) /* not latest in header */
-               jpwl_epb_correct(j2k,      /* J2K decompressor handle */
-                                            buffer + Lepb + 2,   /* pointer to next EPB in codestream buffer */
-                                            2,     /* EPB type: should be of other type */
-                                            0,  /* only EPB fields */
-                                            0, /* do not look after */
-                                                &myconn,
-                                                NULL
-                                            );
-       if (conn)
-               *conn += myconn;
-
-       /*if (!conn)
-               printf("connected = %d\n", myconn);*/
-
-       /*cio_seek(j2k->cio, orig_pos);
-       return true;*/
-
-       /* post-data
-          the position of L4 buffer is at the end of currently connected EPBs
-       */
-       if (!(L4_bufp))
-               L4_buf = buffer + myconn;
-       else if (!(*L4_bufp))
-               L4_buf = buffer + myconn;
-       else
-               L4_buf = *L4_bufp;
-       if (post_len == -1) 
-               L4 = LDPepb - pre_len - 13;
-       else if (post_len == 0)
-               L4 = 0;
-       else
-               L4 = post_len;
-
-       L3_buf = L2_buf;
-
-       /* Do a further check here on the read parameters */
-       if (L4 > (unsigned long) cio_numbytesleft(j2k->cio))
-               /* overflow */
-               return false;
-
-       /* we are ready for decoding the remaining data */
-       if (((Pepb & 0xF0000000) >> 28) == 1) {
-               /* CRC here */
-               if ((16 * ((Pepb & 0x00000001) + 1)) == 16) {
-
-                       /* CRC-16 */
-                       unsigned short int mycrc = 0x0000, filecrc = 0x0000;
-
-                       /* compute the CRC field */
-                       remaining = L4;
-                       while (remaining--)
-                               jpwl_updateCRC16(&mycrc, *(L4_buf++));
-
-                       /* read the CRC field */
-                       filecrc = *(L3_buf++) << 8;
-                       filecrc |= *(L3_buf++);
-
-                       /* check the CRC field */
-                       if (mycrc == filecrc) {
-                               if (conn == NULL)
-                                       opj_event_msg(j2k->cinfo, EVT_INFO, "- CRC is OK\n");
-                       } else {
-                               if (conn == NULL)
-                                       opj_event_msg(j2k->cinfo, EVT_WARNING, "- CRC is KO (r=%d, c=%d)\n", filecrc, mycrc);
-                               errflag = true;
-                       }       
-               }
-
-               if ((16 * ((Pepb & 0x00000001) + 1)) == 32) {
-
-                       /* CRC-32 */
-                       unsigned long int mycrc = 0x00000000, filecrc = 0x00000000;
-
-                       /* compute the CRC field */
-                       remaining = L4;
-                       while (remaining--)
-                               jpwl_updateCRC32(&mycrc, *(L4_buf++));
-
-                       /* read the CRC field */
-                       filecrc = *(L3_buf++) << 24;
-                       filecrc |= *(L3_buf++) << 16;
-                       filecrc |= *(L3_buf++) << 8;
-                       filecrc |= *(L3_buf++);
-
-                       /* check the CRC field */
-                       if (mycrc == filecrc) {
-                               if (conn == NULL)
-                                       opj_event_msg(j2k->cinfo, EVT_INFO, "- CRC is OK\n");
-                       } else {
-                               if (conn == NULL)
-                                       opj_event_msg(j2k->cinfo, EVT_WARNING, "- CRC is KO (r=%d, c=%d)\n", filecrc, mycrc);
-                               errflag = true;
-                       }
-               }
-
-       } else if (Pepb == 0xFFFFFFFF) {
-               /* no method */
-
-               /* advance without doing anything */
-               remaining = L4;
-               while (remaining--)
-                       L4_buf++;
-
-       } else if ((((Pepb & 0xF0000000) >> 28) == 2) || (((Pepb & 0xF0000000) >> 28) == 0)) {
-               /* RS coding here */
-
-               if (((Pepb & 0xF0000000) >> 28) == 0) {
-
-                       k_post = k_pre;
-                       n_post = n_pre;
-
-               } else {
-
-                       k_post = 32;
-                       n_post = (Pepb & 0x0000FF00) >> 8;
-               }
-
-               /* Initialize RS structures */
-               P = n_post - k_post;
-               NN_P = NN - P;
-               tt = (int) floor((float) P / 2.0F); /* again, correction capability */
-               memset(codeword, 0, NN);
-               parityword = codeword + NN_P;
-               init_rs(NN_P);
-
-               /* Correct post-data message words */
-               /*L4_buf = buffer + Lepb + 2;*/
-               L3_buf = L2_buf;
-               remaining = L4;
-               while (remaining) {
-                       /* always zero-pad codewords */
-                       /* (this is required, since after decoding the zeros in the long codeword
-                               could change, and keep unchanged in subsequent calls) */
-                       memset(codeword, 0, NN);
-
-                       /* copy codeword buffer into message bytes */
-                       if (remaining < k_post)
-                               memcpy(codeword, L4_buf, remaining);
-                       else
-                               memcpy(codeword, L4_buf, k_post);
-
-                       /* copy redundancy buffer in parity bytes */
-                       memcpy(parityword, L3_buf, P); 
-
-                       /* Decode the buffer and possibly obtain corrected bytes */
-                       status = eras_dec_rs(codeword, NULL, 0);
-                       if (status == -1) {
-                               /*if (conn == NULL)
-                                       opj_event_msg(j2k->cinfo, EVT_WARNING,
-                                               "Possible decoding error in codeword @ position #%d\n", (L4_buf - (buffer + Lepb + 2)) / k_post);*/
-                               errflag = true;
-
-                       } else if (status == 0) {
-                               /*if (conn == NULL)
-                                       opj_event_msg(j2k->cinfo, EVT_INFO, "codeword is correctly decoded\n");*/
-
-                       } else if (status <= tt) {
-                               /*if (conn == NULL)
-                                       opj_event_msg(j2k->cinfo, EVT_WARNING, "%d errors corrected in codeword\n", status);*/
-                               errnum += status;
-
-                       } else {
-                               /*if (conn == NULL)
-                                       opj_event_msg(j2k->cinfo, EVT_WARNING, "EPB correction capability exceeded\n");
-                               return false;*/
-                               errflag = true;
-                       }
-
-
-                       /* advance parity buffer */
-                       if ((status >= 0) && (status <= tt))
-                               /* copy back corrected data only if all is OK */
-                               memcpy(L3_buf, parityword, P);
-                       L3_buf += P;
-
-                       /* advance message buffer */
-                       if (remaining < k_post) {
-                               if ((status >= 0) && (status <= tt))
-                                       /* copy back corrected data only if all is OK */
-                                       memcpy(L4_buf, codeword, remaining);
-                               L4_buf += remaining;
-                               remaining = 0;
-
-                       } else {
-                               if ((status >= 0) && (status <= tt))
-                                       /* copy back corrected data only if all is OK */
-                                       memcpy(L4_buf, codeword, k_post);
-                               L4_buf += k_post;
-                               remaining -= k_post;
-
-                       }
-               }
-       }
-
-       /* give back the L4_buf address */
-       if (L4_bufp)
-               *L4_bufp = L4_buf;
-
-       /* print summary */
-       if (!conn) {
-
-               if (errnum)
-                       opj_event_msg(j2k->cinfo, EVT_INFO, "- %d symbol errors corrected (Ps=%.1e)\n", errnum,
-                               (float) errnum / (float) LDPepb);
-               if (errflag)
-                       opj_event_msg(j2k->cinfo, EVT_INFO, "- there were unrecoverable errors\n");
-
-       }
-
-       cio_seek(j2k->cio, orig_pos);
-
-       return true;
-}
-
-void jpwl_epc_write(opj_j2k_t *j2k, jpwl_epc_ms_t *epc, unsigned char *buf) {
-
-       /* Marker */
-       *(buf++) = (unsigned char) (J2K_MS_EPC >> 8); 
-       *(buf++) = (unsigned char) (J2K_MS_EPC >> 0); 
-
-       /* Lepc */
-       *(buf++) = (unsigned char) (epc->Lepc >> 8); 
-       *(buf++) = (unsigned char) (epc->Lepc >> 0); 
-
-       /* Pcrc */
-       *(buf++) = (unsigned char) (epc->Pcrc >> 8); 
-       *(buf++) = (unsigned char) (epc->Pcrc >> 0);
-
-       /* DL */
-       *(buf++) = (unsigned char) (epc->DL >> 24); 
-       *(buf++) = (unsigned char) (epc->DL >> 16); 
-       *(buf++) = (unsigned char) (epc->DL >> 8); 
-       *(buf++) = (unsigned char) (epc->DL >> 0); 
-
-       /* Pepc */
-       *(buf++) = (unsigned char) (epc->Pepc >> 0); 
-
-       /* Data */
-       /*memcpy(buf, epc->data, (size_t) epc->Lepc - 9);*/
-       memset(buf, 0, (size_t) epc->Lepc - 9);
-
-       /* update markers struct */
-       j2k_add_marker(j2k->cstr_info, J2K_MS_EPC, -1, epc->Lepc + 2);
-
-};
-
-int jpwl_esds_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num,
-                                 int comps, unsigned char addrm, unsigned char ad_size,
-                                 unsigned char senst, unsigned char se_size,
-                                 double place_pos, int tileno) {
-
-       return 0;
-}
-
-jpwl_esd_ms_t *jpwl_esd_create(opj_j2k_t *j2k, int comp, unsigned char addrm, unsigned char ad_size,
-                                                               unsigned char senst, unsigned char se_size, int tileno,
-                                                               unsigned long int svalnum, void *sensval) {
-
-       jpwl_esd_ms_t *esd = NULL;
-
-       /* Alloc space */
-       if (!(esd = (jpwl_esd_ms_t *) opj_malloc((size_t) 1 * sizeof (jpwl_esd_ms_t)))) {
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for ESD MS\n");
-               return NULL;
-       };
-
-       /* if relative sensitivity, activate byte range mode */
-       if (senst == 0)
-               addrm = 1;
-
-       /* size of sensval's ... */
-       if ((ad_size != 0) && (ad_size != 2) && (ad_size != 4)) {
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "Address size %d for ESD MS is forbidden\n", ad_size);
-               return NULL;
-       }
-       if ((se_size != 1) && (se_size != 2)) {
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "Sensitivity size %d for ESD MS is forbidden\n", se_size);
-               return NULL;
-       }
-       
-       /* ... depends on the addressing mode */
-       switch (addrm) {
-
-       /* packet mode */
-       case (0):
-               ad_size = 0; /* as per the standard */
-               esd->sensval_size = se_size; 
-               break;
-
-       /* byte range */
-       case (1):
-               /* auto sense address size */
-               if (ad_size == 0)
-                       /* if there are more than 66% of (2^16 - 1) bytes, switch to 4 bytes
-                        (we keep space for possible EPBs being inserted) */
-                       ad_size = (j2k->cstr_info->codestream_size > (1 * 65535 / 3)) ? 4 : 2;
-               esd->sensval_size = ad_size + ad_size + se_size; 
-               break;
-
-       /* packet range */
-       case (2):
-               /* auto sense address size */
-               if (ad_size == 0)
-                       /* if there are more than 2^16 - 1 packets, switch to 4 bytes */
-                       ad_size = (j2k->cstr_info->packno > 65535) ? 4 : 2;
-               esd->sensval_size = ad_size + ad_size + se_size; 
-               break;
-
-       case (3):
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "Address mode %d for ESD MS is unimplemented\n", addrm);
-               return NULL;
-
-       default:
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "Address mode %d for ESD MS is forbidden\n", addrm);
-               return NULL;
-       }
-
-       /* set or unset sensitivity values */
-       if (svalnum <= 0) {
-
-               switch (senst) {
-
-               /* just based on the portions of a codestream */
-               case (0):
-                       /* MH + no. of THs + no. of packets */
-                       svalnum = 1 + (j2k->cstr_info->tw * j2k->cstr_info->th) * (1 + j2k->cstr_info->packno);
-                       break;
-
-               /* all the ones that are based on the packets */
-               default:
-                       if (tileno < 0)
-                               /* MH: all the packets and all the tiles info is written */
-                               svalnum = j2k->cstr_info->tw * j2k->cstr_info->th * j2k->cstr_info->packno;
-                       else
-                               /* TPH: only that tile info is written */
-                               svalnum = j2k->cstr_info->packno;
-                       break;
-
-               }
-       }               
-
-       /* fill private fields */
-       esd->senst = senst;
-       esd->ad_size = ad_size;
-       esd->se_size = se_size;
-       esd->addrm = addrm;
-       esd->svalnum = svalnum;
-       esd->numcomps = j2k->image->numcomps;
-       esd->tileno = tileno;
-       
-       /* Set the ESD parameters */
-       /* length, excluding data field */
-       if (esd->numcomps < 257)
-               esd->Lesd = 4 + (unsigned short int) (esd->svalnum * esd->sensval_size);
-       else
-               esd->Lesd = 5 + (unsigned short int) (esd->svalnum * esd->sensval_size);
-
-       /* component data field */
-       if (comp >= 0)
-               esd->Cesd = comp;
-       else
-               /* we are averaging */
-               esd->Cesd = 0;
-
-       /* Pesd field */
-       esd->Pesd = 0x00;
-       esd->Pesd |= (esd->addrm & 0x03) << 6; /* addressing mode */
-       esd->Pesd |= (esd->senst & 0x07) << 3; /* sensitivity type */
-       esd->Pesd |= ((esd->se_size >> 1) & 0x01) << 2; /* sensitivity size */
-       esd->Pesd |= ((esd->ad_size >> 2) & 0x01) << 1; /* addressing size */
-       esd->Pesd |= (comp < 0) ? 0x01 : 0x00; /* averaging components */
-
-       /* if pointer to sensval is NULL, we can fill data field by ourselves */
-       if (!sensval) {
-
-               /* old code moved to jpwl_esd_fill() */
-               esd->data = NULL;
-
-       } else {
-                       /* we set the data field as the sensitivity values poinnter passed to the function */
-                       esd->data = (unsigned char *) sensval;
-       }
-
-       return (esd);
-}
-
-bool jpwl_esd_fill(opj_j2k_t *j2k, jpwl_esd_ms_t *esd, unsigned char *buf) {
-
-       int i;
-       unsigned long int vv;
-       unsigned long int addr1 = 0L, addr2 = 0L;
-       double dvalue = 0.0, Omax2, tmp, TSE = 0.0, MSE, oldMSE = 0.0, PSNR, oldPSNR = 0.0;
-       unsigned short int pfpvalue;
-       unsigned long int addrmask = 0x00000000;
-       bool doneMH = false, doneTPH = false;
-
-       /* sensitivity values in image info are as follows:
-               - for each tile, distotile is the starting distortion for that tile, sum of all components
-               - for each packet in a tile, disto is the distortion reduction caused by that packet to that tile
-               - the TSE for a single tile should be given by   distotile - sum(disto)  , for all components
-               - the MSE for a single tile is given by     TSE / nbpix    , for all components
-               - the PSNR for a single tile is given by   10*log10( Omax^2 / MSE)    , for all components
-                 (Omax is given by    2^bpp - 1    for unsigned images and by    2^(bpp - 1) - 1    for signed images
-       */
-
-       /* browse all components and find Omax */
-       Omax2 = 0.0;
-       for (i = 0; i < j2k->image->numcomps; i++) {
-               tmp = pow(2.0, (double) (j2k->image->comps[i].sgnd ?
-                       (j2k->image->comps[i].bpp - 1) : (j2k->image->comps[i].bpp))) - 1;
-               if (tmp > Omax2)
-                       Omax2 = tmp;
-       }
-       Omax2 = Omax2 * Omax2;
-
-       /* if pointer of esd->data is not null, simply write down all the values byte by byte */
-       if (esd->data) {
-               for (i = 0; i < (int) esd->svalnum; i++)
-                       *(buf++) = esd->data[i]; 
-               return true;
-       }
-
-       /* addressing mask */
-       if (esd->ad_size == 2)
-               addrmask = 0x0000FFFF; /* two bytes */
-       else
-               addrmask = 0xFFFFFFFF; /* four bytes */
-
-       /* set on precise point where sensitivity starts */
-       if (esd->numcomps < 257)
-               buf += 6;
-       else
-               buf += 7;
-
-       /* let's fill the data fields */
-       for (vv = (esd->tileno < 0) ? 0 : (j2k->cstr_info->packno * esd->tileno); vv < esd->svalnum; vv++) {
-
-               int thistile = vv / j2k->cstr_info->packno, thispacket = vv % j2k->cstr_info->packno;
-
-               /* skip for the hack some lines below */
-               if (thistile == j2k->cstr_info->tw * j2k->cstr_info->th)
-                       break;
-
-               /* starting tile distortion */
-               if (thispacket == 0) {
-                       TSE = j2k->cstr_info->tile[thistile].distotile;
-                       oldMSE = TSE / j2k->cstr_info->tile[thistile].numpix;
-                       oldPSNR = 10.0 * log10(Omax2 / oldMSE);
-               }
-
-               /* TSE */
-               TSE -= j2k->cstr_info->tile[thistile].packet[thispacket].disto;
-
-               /* MSE */
-               MSE = TSE / j2k->cstr_info->tile[thistile].numpix;
-
-               /* PSNR */
-               PSNR = 10.0 * log10(Omax2 / MSE);
-
-               /* fill the address range */
-               switch (esd->addrm) {
-
-               /* packet mode */
-               case (0):
-                       /* nothing, there is none */
-                       break;
-
-               /* byte range */
-               case (1):
-                       /* start address of packet */
-                       addr1 = (j2k->cstr_info->tile[thistile].packet[thispacket].start_pos) & addrmask;
-                       /* end address of packet */
-                       addr2 = (j2k->cstr_info->tile[thistile].packet[thispacket].end_pos) & addrmask;
-                       break;
-
-               /* packet range */
-               case (2):
-                       /* not implemented here */
-                       opj_event_msg(j2k->cinfo, EVT_WARNING, "Addressing mode packet_range is not implemented\n");
-                       break;
-
-               /* unknown addressing method */
-               default:
-                       /* not implemented here */
-                       opj_event_msg(j2k->cinfo, EVT_WARNING, "Unknown addressing mode\n");
-                       break;
-
-               }
-
-               /* hack for writing relative sensitivity of MH and TPHs */
-               if ((esd->senst == 0) && (thispacket == 0)) {
-
-                       /* possible MH */
-                       if ((thistile == 0) && !doneMH) {
-                               /* we have to manage MH addresses */
-                               addr1 = 0; /* start of MH */
-                               addr2 = j2k->cstr_info->main_head_end; /* end of MH */
-                               /* set special dvalue for this MH */
-                               dvalue = -10.0;
-                               doneMH = true; /* don't come here anymore */
-                               vv--; /* wrap back loop counter */
-
-                       } else if (!doneTPH) {
-                               /* we have to manage TPH addresses */
-                               addr1 = j2k->cstr_info->tile[thistile].start_pos;
-                               addr2 = j2k->cstr_info->tile[thistile].end_header;
-                               /* set special dvalue for this TPH */
-                               dvalue = -1.0;
-                               doneTPH = true; /* don't come here till the next tile */
-                               vv--; /* wrap back loop counter */
-                       }
-
-               } else
-                       doneTPH = false; /* reset TPH counter */
-
-               /* write the addresses to the buffer */
-               switch (esd->ad_size) {
-
-               case (0):
-                       /* do nothing */
-                       break;
-
-               case (2):
-                       /* two bytes */
-                       *(buf++) = (unsigned char) (addr1 >> 8); 
-                       *(buf++) = (unsigned char) (addr1 >> 0); 
-                       *(buf++) = (unsigned char) (addr2 >> 8); 
-                       *(buf++) = (unsigned char) (addr2 >> 0); 
-                       break;
-
-               case (4):
-                       /* four bytes */
-                       *(buf++) = (unsigned char) (addr1 >> 24); 
-                       *(buf++) = (unsigned char) (addr1 >> 16); 
-                       *(buf++) = (unsigned char) (addr1 >> 8); 
-                       *(buf++) = (unsigned char) (addr1 >> 0); 
-                       *(buf++) = (unsigned char) (addr2 >> 24); 
-                       *(buf++) = (unsigned char) (addr2 >> 16); 
-                       *(buf++) = (unsigned char) (addr2 >> 8); 
-                       *(buf++) = (unsigned char) (addr2 >> 0); 
-                       break;
-
-               default:
-                       /* do nothing */
-                       break;
-               }
-
-
-               /* let's fill the value field */
-               switch (esd->senst) {
-
-               /* relative sensitivity */
-               case (0):
-                       /* we just write down the packet ordering */
-                       if (dvalue == -10)
-                               /* MH */
-                               dvalue = MAX_V1 + 1000.0; /* this will cause pfpvalue set to 0xFFFF */
-                       else if (dvalue == -1)
-                               /* TPH */
-                               dvalue = MAX_V1 + 1000.0; /* this will cause pfpvalue set to 0xFFFF */
-                       else
-                               /* packet: first is most important, and then in decreasing order
-                               down to the last, which counts for 1 */
-                               dvalue = jpwl_pfp_to_double((unsigned short) (j2k->cstr_info->packno - thispacket), esd->se_size);
-                       break;
-
-               /* MSE */
-               case (1):
-                       /* !!! WRONG: let's put here disto field of packets !!! */
-                       dvalue = MSE;
-                       break;
-
-               /* MSE reduction */
-               case (2):
-                       dvalue = oldMSE - MSE;
-                       oldMSE = MSE;
-                       break;
-
-               /* PSNR */
-               case (3):
-                       dvalue = PSNR;
-                       break;
-
-               /* PSNR increase */
-               case (4):
-                       dvalue = PSNR - oldPSNR;
-                       oldPSNR = PSNR;
-                       break;
-
-               /* MAXERR */
-               case (5):
-                       dvalue = 0.0;
-                       opj_event_msg(j2k->cinfo, EVT_WARNING, "MAXERR sensitivity mode is not implemented\n");
-                       break;
-
-               /* TSE */
-               case (6):
-                       dvalue = TSE;
-                       break;
-
-               /* reserved */
-               case (7):
-                       dvalue = 0.0;
-                       opj_event_msg(j2k->cinfo, EVT_WARNING, "Reserved sensitivity mode is not implemented\n");
-                       break;
-
-               default:
-                       dvalue = 0.0;
-                       break;
-               }
-
-               /* compute the pseudo-floating point value */
-               pfpvalue = jpwl_double_to_pfp(dvalue, esd->se_size);
-
-               /* write the pfp value to the buffer */
-               switch (esd->se_size) {
-
-               case (1):
-                       /* one byte */
-                       *(buf++) = (unsigned char) (pfpvalue >> 0); 
-                       break;
-
-               case (2):
-                       /* two bytes */
-                       *(buf++) = (unsigned char) (pfpvalue >> 8); 
-                       *(buf++) = (unsigned char) (pfpvalue >> 0); 
-                       break;
-               }
-
-       }
-
-       return true;
-}
-
-void jpwl_esd_write(opj_j2k_t *j2k, jpwl_esd_ms_t *esd, unsigned char *buf) {
-
-       /* Marker */
-       *(buf++) = (unsigned char) (J2K_MS_ESD >> 8); 
-       *(buf++) = (unsigned char) (J2K_MS_ESD >> 0); 
-
-       /* Lesd */
-       *(buf++) = (unsigned char) (esd->Lesd >> 8); 
-       *(buf++) = (unsigned char) (esd->Lesd >> 0); 
-
-       /* Cesd */
-       if (esd->numcomps >= 257)
-               *(buf++) = (unsigned char) (esd->Cesd >> 8); 
-       *(buf++) = (unsigned char) (esd->Cesd >> 0); 
-
-       /* Pesd */
-       *(buf++) = (unsigned char) (esd->Pesd >> 0); 
-
-       /* Data */
-       if (esd->numcomps < 257)
-               memset(buf, 0xAA, (size_t) esd->Lesd - 4);
-               /*memcpy(buf, esd->data, (size_t) esd->Lesd - 4);*/
-       else
-               memset(buf, 0xAA, (size_t) esd->Lesd - 5);
-               /*memcpy(buf, esd->data, (size_t) esd->Lesd - 5);*/
-
-       /* update markers struct */
-       j2k_add_marker(j2k->cstr_info, J2K_MS_ESD, -1, esd->Lesd + 2);
-
-}
-
-unsigned short int jpwl_double_to_pfp(double V, int bytes) {
-
-       unsigned short int em, e, m;
-
-       switch (bytes) {
-
-       case (1):
-
-               if (V < MIN_V1) {
-                       e = 0x0000;
-                       m = 0x0000;
-               } else if (V > MAX_V1) {
-                       e = 0x000F;
-                       m = 0x000F;
-               } else {
-                       e = (unsigned short int) (floor(log(V) * 1.44269504088896) / 4.0);
-                       m = (unsigned short int) (0.5 + (V / (pow(2.0, (double) (4 * e)))));
-               }
-               em = ((e & 0x000F) << 4) + (m & 0x000F);                
-               break;
-
-       case (2):
-
-               if (V < MIN_V2) {
-                       e = 0x0000;
-                       m = 0x0000;
-               } else if (V > MAX_V2) {
-                       e = 0x001F;
-                       m = 0x07FF;
-               } else {
-                       e = (unsigned short int) floor(log(V) * 1.44269504088896) + 15;
-                       m = (unsigned short int) (0.5 + 2048.0 * ((V / (pow(2.0, (double) e - 15.0))) - 1.0));
-               }
-               em = ((e & 0x001F) << 11) + (m & 0x07FF);
-               break;
-
-       default:
-
-               em = 0x0000;
-               break;
-       };
-
-       return em;
-}
-
-double jpwl_pfp_to_double(unsigned short int em, int bytes) {
-
-       double V;
-
-       switch (bytes) {
-
-       case 1:
-               V = (double) (em & 0x0F) * pow(2.0, (double) (em & 0xF0));
-               break;
-
-       case 2:
-
-               V = pow(2.0, (double) ((em & 0xF800) >> 11) - 15.0) * (1.0 + (double) (em & 0x07FF) / 2048.0);
-               break;
-
-       default:
-               V = 0.0;
-               break;
-
-       }
-
-       return V;
-
-}
-
-bool jpwl_update_info(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int jwmarker_num) {
-
-       int mm;
-       unsigned long int addlen;
-
-       opj_codestream_info_t *info = j2k->cstr_info;
-       int tileno, tpno, packno, numtiles = info->th * info->tw, numpacks = info->packno;
-
-       if (!j2k || !jwmarker ) {
-               opj_event_msg(j2k->cinfo, EVT_ERROR, "J2K handle or JPWL markers list badly allocated\n");
-               return false;
-       }
-
-       /* main_head_end: how many markers are there before? */
-       addlen = 0;
-       for (mm = 0; mm < jwmarker_num; mm++)
-               if (jwmarker[mm].pos < (unsigned long int) info->main_head_end)
-                       addlen += jwmarker[mm].len + 2;
-       info->main_head_end += addlen;
-
-       /* codestream_size: always increment with all markers */
-       addlen = 0;
-       for (mm = 0; mm < jwmarker_num; mm++)
-               addlen += jwmarker[mm].len + 2;
-       info->codestream_size += addlen;
-
-       /* navigate through all the tiles */
-       for (tileno = 0; tileno < numtiles; tileno++) {
-
-               /* start_pos: increment with markers before SOT */
-               addlen = 0;
-               for (mm = 0; mm < jwmarker_num; mm++)
-                       if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].start_pos)
-                               addlen += jwmarker[mm].len + 2;
-               info->tile[tileno].start_pos += addlen;
-
-               /* end_header: increment with markers before of it */
-               addlen = 0;
-               for (mm = 0; mm < jwmarker_num; mm++)
-                       if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].end_header)
-                               addlen += jwmarker[mm].len + 2;
-               info->tile[tileno].end_header += addlen;
-
-               /* end_pos: increment with markers before the end of this tile */
-               /* code is disabled, since according to JPWL no markers can be beyond TPH */
-               addlen = 0;
-               for (mm = 0; mm < jwmarker_num; mm++)
-                       if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].end_pos)
-                               addlen += jwmarker[mm].len + 2;
-               info->tile[tileno].end_pos += addlen;
-
-               /* navigate through all the tile parts */
-               for (tpno = 0; tpno < info->tile[tileno].num_tps; tpno++) {
-
-                       /* start_pos: increment with markers before SOT */
-                       addlen = 0;
-                       for (mm = 0; mm < jwmarker_num; mm++)
-                               if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].tp[tpno].tp_start_pos)
-                                       addlen += jwmarker[mm].len + 2;
-                       info->tile[tileno].tp[tpno].tp_start_pos += addlen;
-
-                       /* end_header: increment with markers before of it */
-                       addlen = 0;
-                       for (mm = 0; mm < jwmarker_num; mm++)
-                               if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].tp[tpno].tp_end_header)
-                                       addlen += jwmarker[mm].len + 2;
-                       info->tile[tileno].tp[tpno].tp_end_header += addlen;
-
-                       /* end_pos: increment with markers before the end of this tile part */
-                       addlen = 0;
-                       for (mm = 0; mm < jwmarker_num; mm++)
-                               if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].tp[tpno].tp_end_pos)
-                                       addlen += jwmarker[mm].len + 2;
-                       info->tile[tileno].tp[tpno].tp_end_pos += addlen;
-
-               }
-
-               /* navigate through all the packets in this tile */
-               for (packno = 0; packno < numpacks; packno++) {
-                       
-                       /* start_pos: increment with markers before the packet */
-                       /* disabled for the same reason as before */
-                       addlen = 0;
-                       for (mm = 0; mm < jwmarker_num; mm++)
-                               if (jwmarker[mm].pos <= (unsigned long int) info->tile[tileno].packet[packno].start_pos)
-                                       addlen += jwmarker[mm].len + 2;
-                       info->tile[tileno].packet[packno].start_pos += addlen;
-
-                       /* end_ph_pos: increment with markers before the packet */
-                       /* disabled for the same reason as before */
-                       /*addlen = 0;
-                       for (mm = 0; mm < jwmarker_num; mm++)
-                               if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].packet[packno].end_ph_pos)
-                                       addlen += jwmarker[mm].len + 2;*/
-                       info->tile[tileno].packet[packno].end_ph_pos += addlen;
-
-                       /* end_pos: increment if marker is before the end of packet */
-                       /* disabled for the same reason as before */
-                       /*addlen = 0;
-                       for (mm = 0; mm < jwmarker_num; mm++)
-                               if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].packet[packno].end_pos)
-                                       addlen += jwmarker[mm].len + 2;*/
-                       info->tile[tileno].packet[packno].end_pos += addlen;
-
-               }
-       }
-
-       /* reorder the markers list */
-
-       return true;
-}
-
-#endif /* USE_JPWL */
diff --git a/jpwl/rs.c b/jpwl/rs.c
deleted file mode 100644 (file)
index 0841c63..0000000
--- a/jpwl/rs.c
+++ /dev/null
@@ -1,597 +0,0 @@
- /*
- * Copyright (c) 2001-2003, David Janssens
- * Copyright (c) 2002-2003, Yannick Verschueren
- * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe
- * Copyright (c) 2005, Herve Drolon, FreeImage Team
- * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef USE_JPWL
-
-/**
-@file rs.c
-@brief Functions used to compute the Reed-Solomon parity and check of byte arrays
-
-*/
-
-/**
- * Reed-Solomon coding and decoding
- * Phil Karn (karn@ka9q.ampr.org) September 1996
- * 
- * This file is derived from the program "new_rs_erasures.c" by Robert
- * Morelos-Zaragoza (robert@spectra.eng.hawaii.edu) and Hari Thirumoorthy
- * (harit@spectra.eng.hawaii.edu), Aug 1995
- *
- * I've made changes to improve performance, clean up the code and make it
- * easier to follow. Data is now passed to the encoding and decoding functions
- * through arguments rather than in global arrays. The decode function returns
- * the number of corrected symbols, or -1 if the word is uncorrectable.
- *
- * This code supports a symbol size from 2 bits up to 16 bits,
- * implying a block size of 3 2-bit symbols (6 bits) up to 65535
- * 16-bit symbols (1,048,560 bits). The code parameters are set in rs.h.
- *
- * Note that if symbols larger than 8 bits are used, the type of each
- * data array element switches from unsigned char to unsigned int. The
- * caller must ensure that elements larger than the symbol range are
- * not passed to the encoder or decoder.
- *
- */
-#include <stdio.h>
-#include <stdlib.h>
-#include "rs.h"
-
-/* This defines the type used to store an element of the Galois Field
- * used by the code. Make sure this is something larger than a char if
- * if anything larger than GF(256) is used.
- *
- * Note: unsigned char will work up to GF(256) but int seems to run
- * faster on the Pentium.
- */
-typedef int gf;
-
-/* KK = number of information symbols */
-static int     KK;
-
-/* Primitive polynomials - see Lin & Costello, Appendix A,
- * and  Lee & Messerschmitt, p. 453.
- */
-#if(MM == 2)/* Admittedly silly */
-int Pp[MM+1] = { 1, 1, 1 };
-
-#elif(MM == 3)
-/* 1 + x + x^3 */
-int Pp[MM+1] = { 1, 1, 0, 1 };
-
-#elif(MM == 4)
-/* 1 + x + x^4 */
-int Pp[MM+1] = { 1, 1, 0, 0, 1 };
-
-#elif(MM == 5)
-/* 1 + x^2 + x^5 */
-int Pp[MM+1] = { 1, 0, 1, 0, 0, 1 };
-
-#elif(MM == 6)
-/* 1 + x + x^6 */
-int Pp[MM+1] = { 1, 1, 0, 0, 0, 0, 1 };
-
-#elif(MM == 7)
-/* 1 + x^3 + x^7 */
-int Pp[MM+1] = { 1, 0, 0, 1, 0, 0, 0, 1 };
-
-#elif(MM == 8)
-/* 1+x^2+x^3+x^4+x^8 */
-int Pp[MM+1] = { 1, 0, 1, 1, 1, 0, 0, 0, 1 };
-
-#elif(MM == 9)
-/* 1+x^4+x^9 */
-int Pp[MM+1] = { 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
-
-#elif(MM == 10)
-/* 1+x^3+x^10 */
-int Pp[MM+1] = { 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 };
-
-#elif(MM == 11)
-/* 1+x^2+x^11 */
-int Pp[MM+1] = { 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
-
-#elif(MM == 12)
-/* 1+x+x^4+x^6+x^12 */
-int Pp[MM+1] = { 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1 };
-
-#elif(MM == 13)
-/* 1+x+x^3+x^4+x^13 */
-int Pp[MM+1] = { 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
-
-#elif(MM == 14)
-/* 1+x+x^6+x^10+x^14 */
-int Pp[MM+1] = { 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 };
-
-#elif(MM == 15)
-/* 1+x+x^15 */
-int Pp[MM+1] = { 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
-
-#elif(MM == 16)
-/* 1+x+x^3+x^12+x^16 */
-int Pp[MM+1] = { 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1 };
-
-#else
-#error "MM must be in range 2-16"
-#endif
-
-/* Alpha exponent for the first root of the generator polynomial */
-#define B0     0  /* Different from the default 1 */
-
-/* index->polynomial form conversion table */
-gf Alpha_to[NN + 1];
-
-/* Polynomial->index form conversion table */
-gf Index_of[NN + 1];
-
-/* No legal value in index form represents zero, so
- * we need a special value for this purpose
- */
-#define A0     (NN)
-
-/* Generator polynomial g(x)
- * Degree of g(x) = 2*TT
- * has roots @**B0, @**(B0+1), ... ,@^(B0+2*TT-1)
- */
-/*gf Gg[NN - KK + 1];*/
-gf             Gg[NN - 1];
-
-/* Compute x % NN, where NN is 2**MM - 1,
- * without a slow divide
- */
-static /*inline*/ gf
-modnn(int x)
-{
-       while (x >= NN) {
-               x -= NN;
-               x = (x >> MM) + (x & NN);
-       }
-       return x;
-}
-
-/*#define      min(a,b)        ((a) < (b) ? (a) : (b))*/
-
-#define        CLEAR(a,n) {\
-       int ci;\
-       for(ci=(n)-1;ci >=0;ci--)\
-               (a)[ci] = 0;\
-       }
-
-#define        COPY(a,b,n) {\
-       int ci;\
-       for(ci=(n)-1;ci >=0;ci--)\
-               (a)[ci] = (b)[ci];\
-       }
-#define        COPYDOWN(a,b,n) {\
-       int ci;\
-       for(ci=(n)-1;ci >=0;ci--)\
-               (a)[ci] = (b)[ci];\
-       }
-
-void init_rs(int k)
-{
-       KK = k;
-       if (KK >= NN) {
-               printf("KK must be less than 2**MM - 1\n");
-               exit(1);
-       }
-       
-       generate_gf();
-       gen_poly();
-}
-
-/* generate GF(2**m) from the irreducible polynomial p(X) in p[0]..p[m]
-   lookup tables:  index->polynomial form   alpha_to[] contains j=alpha**i;
-                   polynomial form -> index form  index_of[j=alpha**i] = i
-   alpha=2 is the primitive element of GF(2**m)
-   HARI's COMMENT: (4/13/94) alpha_to[] can be used as follows:
-        Let @ represent the primitive element commonly called "alpha" that
-   is the root of the primitive polynomial p(x). Then in GF(2^m), for any
-   0 <= i <= 2^m-2,
-        @^i = a(0) + a(1) @ + a(2) @^2 + ... + a(m-1) @^(m-1)
-   where the binary vector (a(0),a(1),a(2),...,a(m-1)) is the representation
-   of the integer "alpha_to[i]" with a(0) being the LSB and a(m-1) the MSB. Thus for
-   example the polynomial representation of @^5 would be given by the binary
-   representation of the integer "alpha_to[5]".
-                   Similarily, index_of[] can be used as follows:
-        As above, let @ represent the primitive element of GF(2^m) that is
-   the root of the primitive polynomial p(x). In order to find the power
-   of @ (alpha) that has the polynomial representation
-        a(0) + a(1) @ + a(2) @^2 + ... + a(m-1) @^(m-1)
-   we consider the integer "i" whose binary representation with a(0) being LSB
-   and a(m-1) MSB is (a(0),a(1),...,a(m-1)) and locate the entry
-   "index_of[i]". Now, @^index_of[i] is that element whose polynomial 
-    representation is (a(0),a(1),a(2),...,a(m-1)).
-   NOTE:
-        The element alpha_to[2^m-1] = 0 always signifying that the
-   representation of "@^infinity" = 0 is (0,0,0,...,0).
-        Similarily, the element index_of[0] = A0 always signifying
-   that the power of alpha which has the polynomial representation
-   (0,0,...,0) is "infinity".
-*/
-
-void
-generate_gf(void)
-{
-       register int i, mask;
-
-       mask = 1;
-       Alpha_to[MM] = 0;
-       for (i = 0; i < MM; i++) {
-               Alpha_to[i] = mask;
-               Index_of[Alpha_to[i]] = i;
-               /* If Pp[i] == 1 then, term @^i occurs in poly-repr of @^MM */
-               if (Pp[i] != 0)
-                       Alpha_to[MM] ^= mask;   /* Bit-wise EXOR operation */
-               mask <<= 1;     /* single left-shift */
-       }
-       Index_of[Alpha_to[MM]] = MM;
-       /*
-        * Have obtained poly-repr of @^MM. Poly-repr of @^(i+1) is given by
-        * poly-repr of @^i shifted left one-bit and accounting for any @^MM
-        * term that may occur when poly-repr of @^i is shifted.
-        */
-       mask >>= 1;
-       for (i = MM + 1; i < NN; i++) {
-               if (Alpha_to[i - 1] >= mask)
-                       Alpha_to[i] = Alpha_to[MM] ^ ((Alpha_to[i - 1] ^ mask) << 1);
-               else
-                       Alpha_to[i] = Alpha_to[i - 1] << 1;
-               Index_of[Alpha_to[i]] = i;
-       }
-       Index_of[0] = A0;
-       Alpha_to[NN] = 0;
-}
-
-
-/*
- * Obtain the generator polynomial of the TT-error correcting, length
- * NN=(2**MM -1) Reed Solomon code from the product of (X+@**(B0+i)), i = 0,
- * ... ,(2*TT-1)
- *
- * Examples:
- *
- * If B0 = 1, TT = 1. deg(g(x)) = 2*TT = 2.
- * g(x) = (x+@) (x+@**2)
- *
- * If B0 = 0, TT = 2. deg(g(x)) = 2*TT = 4.
- * g(x) = (x+1) (x+@) (x+@**2) (x+@**3)
- */
-void
-gen_poly(void)
-{
-       register int i, j;
-
-       Gg[0] = Alpha_to[B0];
-       Gg[1] = 1;              /* g(x) = (X+@**B0) initially */
-       for (i = 2; i <= NN - KK; i++) {
-               Gg[i] = 1;
-               /*
-                * Below multiply (Gg[0]+Gg[1]*x + ... +Gg[i]x^i) by
-                * (@**(B0+i-1) + x)
-                */
-               for (j = i - 1; j > 0; j--)
-                       if (Gg[j] != 0)
-                               Gg[j] = Gg[j - 1] ^ Alpha_to[modnn((Index_of[Gg[j]]) + B0 + i - 1)];
-                       else
-                               Gg[j] = Gg[j - 1];
-               /* Gg[0] can never be zero */
-               Gg[0] = Alpha_to[modnn((Index_of[Gg[0]]) + B0 + i - 1)];
-       }
-       /* convert Gg[] to index form for quicker encoding */
-       for (i = 0; i <= NN - KK; i++)
-               Gg[i] = Index_of[Gg[i]];
-}
-
-
-/*
- * take the string of symbols in data[i], i=0..(k-1) and encode
- * systematically to produce NN-KK parity symbols in bb[0]..bb[NN-KK-1] data[]
- * is input and bb[] is output in polynomial form. Encoding is done by using
- * a feedback shift register with appropriate connections specified by the
- * elements of Gg[], which was generated above. Codeword is   c(X) =
- * data(X)*X**(NN-KK)+ b(X)
- */
-int
-encode_rs(dtype *data, dtype *bb)
-{
-       register int i, j;
-       gf feedback;
-
-       CLEAR(bb,NN-KK);
-       for (i = KK - 1; i >= 0; i--) {
-#if (MM != 8)
-               if(data[i] > NN)
-                       return -1;      /* Illegal symbol */
-#endif
-               feedback = Index_of[data[i] ^ bb[NN - KK - 1]];
-               if (feedback != A0) {   /* feedback term is non-zero */
-                       for (j = NN - KK - 1; j > 0; j--)
-                               if (Gg[j] != A0)
-                                       bb[j] = bb[j - 1] ^ Alpha_to[modnn(Gg[j] + feedback)];
-                               else
-                                       bb[j] = bb[j - 1];
-                       bb[0] = Alpha_to[modnn(Gg[0] + feedback)];
-               } else {        /* feedback term is zero. encoder becomes a
-                                * single-byte shifter */
-                       for (j = NN - KK - 1; j > 0; j--)
-                               bb[j] = bb[j - 1];
-                       bb[0] = 0;
-               }
-       }
-       return 0;
-}
-
-/*
- * Performs ERRORS+ERASURES decoding of RS codes. If decoding is successful,
- * writes the codeword into data[] itself. Otherwise data[] is unaltered.
- *
- * Return number of symbols corrected, or -1 if codeword is illegal
- * or uncorrectable.
- * 
- * First "no_eras" erasures are declared by the calling program. Then, the
- * maximum # of errors correctable is t_after_eras = floor((NN-KK-no_eras)/2).
- * If the number of channel errors is not greater than "t_after_eras" the
- * transmitted codeword will be recovered. Details of algorithm can be found
- * in R. Blahut's "Theory ... of Error-Correcting Codes".
- */
-int
-eras_dec_rs(dtype *data, int *eras_pos, int no_eras)
-{
-       int deg_lambda, el, deg_omega;
-       int i, j, r;
-       gf u,q,tmp,num1,num2,den,discr_r;
-       gf recd[NN];
-       /* Err+Eras Locator poly and syndrome poly */
-       /*gf lambda[NN-KK + 1], s[NN-KK + 1];   
-       gf b[NN-KK + 1], t[NN-KK + 1], omega[NN-KK + 1];
-       gf root[NN-KK], reg[NN-KK + 1], loc[NN-KK];*/
-       gf lambda[NN + 1], s[NN + 1];   
-       gf b[NN + 1], t[NN + 1], omega[NN + 1];
-       gf root[NN], reg[NN + 1], loc[NN];
-       int syn_error, count;
-
-       /* data[] is in polynomial form, copy and convert to index form */
-       for (i = NN-1; i >= 0; i--){
-#if (MM != 8)
-               if(data[i] > NN)
-                       return -1;      /* Illegal symbol */
-#endif
-               recd[i] = Index_of[data[i]];
-       }
-       /* first form the syndromes; i.e., evaluate recd(x) at roots of g(x)
-        * namely @**(B0+i), i = 0, ... ,(NN-KK-1)
-        */
-       syn_error = 0;
-       for (i = 1; i <= NN-KK; i++) {
-               tmp = 0;
-               for (j = 0; j < NN; j++)
-                       if (recd[j] != A0)      /* recd[j] in index form */
-                               tmp ^= Alpha_to[modnn(recd[j] + (B0+i-1)*j)];
-               syn_error |= tmp;       /* set flag if non-zero syndrome =>
-                                        * error */
-               /* store syndrome in index form  */
-               s[i] = Index_of[tmp];
-       }
-       if (!syn_error) {
-               /*
-                * if syndrome is zero, data[] is a codeword and there are no
-                * errors to correct. So return data[] unmodified
-                */
-               return 0;
-       }
-       CLEAR(&lambda[1],NN-KK);
-       lambda[0] = 1;
-       if (no_eras > 0) {
-               /* Init lambda to be the erasure locator polynomial */
-               lambda[1] = Alpha_to[eras_pos[0]];
-               for (i = 1; i < no_eras; i++) {
-                       u = eras_pos[i];
-                       for (j = i+1; j > 0; j--) {
-                               tmp = Index_of[lambda[j - 1]];
-                               if(tmp != A0)
-                                       lambda[j] ^= Alpha_to[modnn(u + tmp)];
-                       }
-               }
-#ifdef ERASURE_DEBUG
-               /* find roots of the erasure location polynomial */
-               for(i=1;i<=no_eras;i++)
-                       reg[i] = Index_of[lambda[i]];
-               count = 0;
-               for (i = 1; i <= NN; i++) {
-                       q = 1;
-                       for (j = 1; j <= no_eras; j++)
-                               if (reg[j] != A0) {
-                                       reg[j] = modnn(reg[j] + j);
-                                       q ^= Alpha_to[reg[j]];
-                               }
-                       if (!q) {
-                               /* store root and error location
-                                * number indices
-                                */
-                               root[count] = i;
-                               loc[count] = NN - i;
-                               count++;
-                       }
-               }
-               if (count != no_eras) {
-                       printf("\n lambda(x) is WRONG\n");
-                       return -1;
-               }
-#ifndef NO_PRINT
-               printf("\n Erasure positions as determined by roots of Eras Loc Poly:\n");
-               for (i = 0; i < count; i++)
-                       printf("%d ", loc[i]);
-               printf("\n");
-#endif
-#endif
-       }
-       for(i=0;i<NN-KK+1;i++)
-               b[i] = Index_of[lambda[i]];
-
-       /*
-        * Begin Berlekamp-Massey algorithm to determine error+erasure
-        * locator polynomial
-        */
-       r = no_eras;
-       el = no_eras;
-       while (++r <= NN-KK) {  /* r is the step number */
-               /* Compute discrepancy at the r-th step in poly-form */
-               discr_r = 0;
-               for (i = 0; i < r; i++){
-                       if ((lambda[i] != 0) && (s[r - i] != A0)) {
-                               discr_r ^= Alpha_to[modnn(Index_of[lambda[i]] + s[r - i])];
-                       }
-               }
-               discr_r = Index_of[discr_r];    /* Index form */
-               if (discr_r == A0) {
-                       /* 2 lines below: B(x) <-- x*B(x) */
-                       COPYDOWN(&b[1],b,NN-KK);
-                       b[0] = A0;
-               } else {
-                       /* 7 lines below: T(x) <-- lambda(x) - discr_r*x*b(x) */
-                       t[0] = lambda[0];
-                       for (i = 0 ; i < NN-KK; i++) {
-                               if(b[i] != A0)
-                                       t[i+1] = lambda[i+1] ^ Alpha_to[modnn(discr_r + b[i])];
-                               else
-                                       t[i+1] = lambda[i+1];
-                       }
-                       if (2 * el <= r + no_eras - 1) {
-                               el = r + no_eras - el;
-                               /*
-                                * 2 lines below: B(x) <-- inv(discr_r) *
-                                * lambda(x)
-                                */
-                               for (i = 0; i <= NN-KK; i++)
-                                       b[i] = (lambda[i] == 0) ? A0 : modnn(Index_of[lambda[i]] - discr_r + NN);
-                       } else {
-                               /* 2 lines below: B(x) <-- x*B(x) */
-                               COPYDOWN(&b[1],b,NN-KK);
-                               b[0] = A0;
-                       }
-                       COPY(lambda,t,NN-KK+1);
-               }
-       }
-
-       /* Convert lambda to index form and compute deg(lambda(x)) */
-       deg_lambda = 0;
-       for(i=0;i<NN-KK+1;i++){
-               lambda[i] = Index_of[lambda[i]];
-               if(lambda[i] != A0)
-                       deg_lambda = i;
-       }
-       /*
-        * Find roots of the error+erasure locator polynomial. By Chien
-        * Search
-        */
-       COPY(&reg[1],&lambda[1],NN-KK);
-       count = 0;              /* Number of roots of lambda(x) */
-       for (i = 1; i <= NN; i++) {
-               q = 1;
-               for (j = deg_lambda; j > 0; j--)
-                       if (reg[j] != A0) {
-                               reg[j] = modnn(reg[j] + j);
-                               q ^= Alpha_to[reg[j]];
-                       }
-               if (!q) {
-                       /* store root (index-form) and error location number */
-                       root[count] = i;
-                       loc[count] = NN - i;
-                       count++;
-               }
-       }
-
-#ifdef DEBUG
-       printf("\n Final error positions:\t");
-       for (i = 0; i < count; i++)
-               printf("%d ", loc[i]);
-       printf("\n");
-#endif
-       if (deg_lambda != count) {
-               /*
-                * deg(lambda) unequal to number of roots => uncorrectable
-                * error detected
-                */
-               return -1;
-       }
-       /*
-        * Compute err+eras evaluator poly omega(x) = s(x)*lambda(x) (modulo
-        * x**(NN-KK)). in index form. Also find deg(omega).
-        */
-       deg_omega = 0;
-       for (i = 0; i < NN-KK;i++){
-               tmp = 0;
-               j = (deg_lambda < i) ? deg_lambda : i;
-               for(;j >= 0; j--){
-                       if ((s[i + 1 - j] != A0) && (lambda[j] != A0))
-                               tmp ^= Alpha_to[modnn(s[i + 1 - j] + lambda[j])];
-               }
-               if(tmp != 0)
-                       deg_omega = i;
-               omega[i] = Index_of[tmp];
-       }
-       omega[NN-KK] = A0;
-
-       /*
-        * Compute error values in poly-form. num1 = omega(inv(X(l))), num2 =
-        * inv(X(l))**(B0-1) and den = lambda_pr(inv(X(l))) all in poly-form
-        */
-       for (j = count-1; j >=0; j--) {
-               num1 = 0;
-               for (i = deg_omega; i >= 0; i--) {
-                       if (omega[i] != A0)
-                               num1  ^= Alpha_to[modnn(omega[i] + i * root[j])];
-               }
-               num2 = Alpha_to[modnn(root[j] * (B0 - 1) + NN)];
-               den = 0;
-
-               /* lambda[i+1] for i even is the formal derivative lambda_pr of lambda[i] */
-               for (i = min(deg_lambda,NN-KK-1) & ~1; i >= 0; i -=2) {
-                       if(lambda[i+1] != A0)
-                               den ^= Alpha_to[modnn(lambda[i+1] + i * root[j])];
-               }
-               if (den == 0) {
-#ifdef DEBUG
-                       printf("\n ERROR: denominator = 0\n");
-#endif
-                       return -1;
-               }
-               /* Apply error to data */
-               if (num1 != 0) {
-                       data[loc[j]] ^= Alpha_to[modnn(Index_of[num1] + Index_of[num2] + NN - Index_of[den])];
-               }
-       }
-       return count;
-}
-
-
-#endif /* USE_JPWL */
diff --git a/jpwl/rs.h b/jpwl/rs.h
deleted file mode 100644 (file)
index 7d02a47..0000000
--- a/jpwl/rs.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (c) 2001-2003, David Janssens
- * Copyright (c) 2002-2003, Yannick Verschueren
- * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe
- * Copyright (c) 2005, Herve Drolon, FreeImage Team
- * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
- * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef USE_JPWL
-
-/**
-@file rs.h
-@brief Functions used to compute Reed-Solomon parity and check of byte arrays
-
-*/
-
-#ifndef __RS_HEADER__
-#define __RS_HEADER__
-
-/** Global definitions for Reed-Solomon encoder/decoder
- * Phil Karn KA9Q, September 1996
- *
- * The parameters MM and KK specify the Reed-Solomon code parameters.
- *
- * Set MM to be the size of each code symbol in bits. The Reed-Solomon
- * block size will then be NN = 2**M - 1 symbols. Supported values are
- * defined in rs.c.
- *
- * Set KK to be the number of data symbols in each block, which must be
- * less than the block size. The code will then be able to correct up
- * to NN-KK erasures or (NN-KK)/2 errors, or combinations thereof with
- * each error counting as two erasures.
- */
-#define MM  8          /* RS code over GF(2**MM) - change to suit */
-
-/* KK defined in rs.c */
-
-#define        NN ((1 << MM) - 1)
-
-#if (MM <= 8)
-typedef unsigned char dtype;
-#else
-typedef unsigned int dtype;
-#endif
-
-/** Initialization function */
-void init_rs(int);
-
-/** These two functions *must* be called in this order (e.g.,
- * by init_rs()) before any encoding/decoding
- */
-void generate_gf(void);        /* Generate Galois Field */
-void gen_poly(void);   /* Generate generator polynomial */
-
-/** Reed-Solomon encoding
- * data[] is the input block, parity symbols are placed in bb[]
- * bb[] may lie past the end of the data, e.g., for (255,223):
- *     encode_rs(&data[0],&data[223]);
- */
-int encode_rs(dtype data[], dtype bb[]);
-
-/** Reed-Solomon erasures-and-errors decoding
- * The received block goes into data[], and a list of zero-origin
- * erasure positions, if any, goes in eras_pos[] with a count in no_eras.
- *
- * The decoder corrects the symbols in place, if possible and returns
- * the number of corrected symbols. If the codeword is illegal or
- * uncorrectible, the data array is unchanged and -1 is returned
- */
-int eras_dec_rs(dtype data[], int eras_pos[], int no_eras);
-
-/**
-Computes the minimum between two integers
-@param a first integer to compare
-@param b second integer to compare
-@return returns the minimum integer between a and b
-*/
-#ifndef min
-#define min(a,b)    (((a) < (b)) ? (a) : (b))
-#endif /* min */
-
-#endif /* __RS_HEADER__ */
-
-
-#endif /* USE_JPWL */
diff --git a/libopenjpeg/jpwl/CMakeLists.txt b/libopenjpeg/jpwl/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..7dbb3d6
--- /dev/null
@@ -0,0 +1,93 @@
+# Makefile for the main JPWL OpenJPEG codecs: JPWL_ j2k_to_image and JPWL_image_to_j2k
+
+ADD_DEFINITIONS(-DUSE_JPWL)
+
+SET(OPJ_SRCS
+../libopenjpeg/bio.c
+../libopenjpeg/cio.c
+../libopenjpeg/dwt.c
+../libopenjpeg/event.c
+../libopenjpeg/image.c
+../libopenjpeg/j2k.c
+../libopenjpeg/j2k_lib.c
+../libopenjpeg/jp2.c
+../libopenjpeg/jpt.c
+../libopenjpeg/mct.c
+../libopenjpeg/mqc.c
+../libopenjpeg/openjpeg.c
+../libopenjpeg/pi.c
+../libopenjpeg/raw.c
+../libopenjpeg/t1.c
+../libopenjpeg/t2.c
+../libopenjpeg/tcd.c
+../libopenjpeg/tgt.c
+)
+SET(JPWL_SRCS crc.c jpwl.c jpwl_lib.c rs.c)
+
+SET(common_SRCS "")
+# If not getopt was found then add it to the lib:
+IF(DONT_HAVE_GETOPT)
+  SET(common_SRCS ${OPENJPEG_SOURCE_DIR}/common/getopt.c)
+ENDIF(DONT_HAVE_GETOPT)
+
+# Build the library
+IF(WIN32)
+  IF(BUILD_SHARED_LIBS)
+    ADD_DEFINITIONS(-DOPJ_EXPORTS)
+  ELSE(BUILD_SHARED_LIBS)
+    ADD_DEFINITIONS(-DOPJ_STATIC)
+  ENDIF(BUILD_SHARED_LIBS)
+ENDIF(WIN32)
+ADD_LIBRARY(${OPENJPEG_LIBRARY_NAME}_JPWL ${JPWL_SRCS} ${OPJ_SRCS})
+SET_TARGET_PROPERTIES(${OPENJPEG_LIBRARY_NAME}_JPWL 
+  PROPERTIES ${OPENJPEG_LIBRARY_PROPERTIES})
+
+# Install library
+INSTALL(TARGETS ${OPENJPEG_LIBRARY_NAME}_JPWL
+  DESTINATION ${OPENJPEG_INSTALL_LIB_DIR} COMPONENT Libraries
+)
+
+# Build executables
+
+INCLUDE_DIRECTORIES(
+  ${OPENJPEG_SOURCE_DIR}/libopenjpeg
+  ${OPENJPEG_SOURCE_DIR}/common
+  ${ZLIB_INCLUDE_DIRNAME}
+  ${LCMS_INCLUDE_DIRNAME}
+  ${PNG_INCLUDE_DIRNAME}
+  ${TIFF_INCLUDE_DIRNAME}
+  )
+
+ADD_EXECUTABLE(JPWL_j2k_to_image
+../codec/j2k_to_image.c
+../codec/convert.c
+../codec/index.c
+${OPENJPEG_SOURCE_DIR}/common/color.c
+${common_SRCS}
+)
+
+TARGET_LINK_LIBRARIES(JPWL_j2k_to_image ${OPENJPEG_LIBRARY_NAME}_JPWL
+  ${LCMS_LIBNAME} ${Z_LIBNAME} ${PNG_LIBNAME} ${TIFF_LIBNAME})
+#
+IF(UNIX)
+  TARGET_LINK_LIBRARIES(JPWL_j2k_to_image m)
+ENDIF(UNIX)
+
+
+ADD_EXECUTABLE(JPWL_image_to_j2k
+../codec/convert.c
+../codec/index.c
+../codec/image_to_j2k.c
+${common_SRCS}
+)
+
+TARGET_LINK_LIBRARIES(JPWL_image_to_j2k ${OPENJPEG_LIBRARY_NAME}_JPWL 
+       ${LCMS_LIBNAME} ${Z_LIBNAME} ${PNG_LIBNAME} ${TIFF_LIBNAME})
+#
+IF(UNIX)
+  TARGET_LINK_LIBRARIES(JPWL_image_to_j2k m)
+ENDIF(UNIX)
+
+INSTALL(TARGETS JPWL_image_to_j2k JPWL_j2k_to_image
+  DESTINATION ${OPENJPEG_INSTALL_BIN_DIR} COMPONENT Binaries
+)
diff --git a/libopenjpeg/jpwl/Makefile.am b/libopenjpeg/jpwl/Makefile.am
new file mode 100644 (file)
index 0000000..3bbce01
--- /dev/null
@@ -0,0 +1,116 @@
+MAINTAINERCLEANFILES = Makefile.in
+
+lib_LTLIBRARIES = libopenjpeg_JPWL.la
+
+OPJ_SRC = \
+../libopenjpeg/bio.c \
+../libopenjpeg/cio.c \
+../libopenjpeg/dwt.c \
+../libopenjpeg/event.c \
+../libopenjpeg/image.c \
+../libopenjpeg/j2k.c \
+../libopenjpeg/j2k_lib.c \
+../libopenjpeg/jp2.c \
+../libopenjpeg/jpt.c \
+../libopenjpeg/mct.c \
+../libopenjpeg/mqc.c \
+../libopenjpeg/openjpeg.c \
+../libopenjpeg/pi.c \
+../libopenjpeg/raw.c \
+../libopenjpeg/t1.c \
+../libopenjpeg/t2.c \
+../libopenjpeg/tcd.c \
+../libopenjpeg/tgt.c
+
+libopenjpeg_JPWL_la_CPPFLAGS = \
+-I. \
+-I$(top_srcdir)/libopenjpeg \
+-I$(top_builddir)/libopenjpeg \
+-I$(top_srcdir)/jpwl \
+-I$(top_builddir)/jpwl \
+-DUSE_JPWL
+libopenjpeg_JPWL_la_CFLAGS =
+libopenjpeg_JPWL_la_LIBADD = -lm
+libopenjpeg_JPWL_la_LDFLAGS = -no-undefined -version-info @lt_version@
+libopenjpeg_JPWL_la_SOURCES = \
+$(OPJ_SRC) \
+crc.c \
+jpwl.c \
+jpwl_lib.c \
+rs.c \
+jpwl.h \
+crc.h \
+rs.h
+
+bin_PROGRAMS = JPWL_j2k_to_image JPWL_image_to_j2k
+
+JPWL_j2k_to_image_CPPFLAGS = \
+-I. \
+-I$(top_srcdir)/common \
+-I$(top_builddir)/common \
+-I$(top_srcdir)/libopenjpeg \
+-I$(top_builddir)/libopenjpeg \
+-I$(top_srcdir)/jpwl \
+-I$(top_builddir)/jpwl \
+-DUSE_JPWL \
+@TIFF_CFLAGS@ \
+@PNG_CFLAGS@ \
+@LCMS1_CFLAGS@ \
+@LCMS2_CFLAGS@
+JPWL_j2k_to_image_CFLAGS =
+JPWL_j2k_to_image_LDADD = $(top_builddir)/jpwl/libopenjpeg_JPWL.la  @LCMS1_LIBS@ @LCMS2_LIBS@ @TIFF_LIBS@ @PNG_LIBS@
+JPWL_j2k_to_image_SOURCES = \
+$(top_builddir)/common/color.c \
+$(top_builddir)/common/getopt.c \
+$(top_builddir)/codec/index.c \
+$(top_builddir)/codec/convert.c \
+$(top_builddir)/codec/j2k_to_image.c
+
+JPWL_image_to_j2k_CPPFLAGS = \
+-I. \
+-I$(top_srcdir)/common \
+-I$(top_builddir)/common \
+-I$(top_srcdir)/libopenjpeg \
+-I$(top_builddir)/libopenjpeg \
+-I$(top_srcdir)/jpwl \
+-I$(top_builddir)/jpwl \
+-DUSE_JPWL \
+@TIFF_CFLAGS@ \
+@PNG_CFLAGS@
+JPWL_image_to_j2k_CFLAGS =
+JPWL_image_to_j2k_LDADD = $(top_builddir)/jpwl/libopenjpeg_JPWL.la @TIFF_LIBS@ @PNG_LIBS@
+
+JPWL_image_to_j2k_SOURCES = \
+$(top_builddir)/common/getopt.c \
+$(top_builddir)/codec/index.c \
+$(top_builddir)/codec/convert.c \
+$(top_builddir)/codec/image_to_j2k.c
+
+EXTRA_DIST = \
+CMakeLists.txt
+
+install-data-hook:
+       @echo -e " (B)\t$(bindir)/JPWL_j2k_to_image$(EXEEXT)" >> $(top_builddir)/report.txt
+       @echo -e " (B)\t$(bindir)/JPWL_image_to_j2k$(EXEEXT)" >> $(top_builddir)/report.txt
+       @echo -e " (LA)\t$(libdir)/libopenjpeg_JPWL.la" >> $(top_builddir)/report.txt
+       @( $(call solist) ) >> $(top_builddir)/report.txt
+       @echo -e " (A)\t$(base)/$(a)" >> $(top_builddir)/report.txt
+
+solist    = $(foreach f, $(dll) $(so), echo -e ' $(SO_PREFIX)\t$(base)/$(f)' ;)
+get_tok   = $(shell grep -E "^$(1)=" $(lib_LTLIBRARIES) | cut -d "'" -f 2)
+base      = $(call get_tok,libdir)
+so        = $(call get_tok,library_names)
+a         = $(call get_tok,old_library)
+
+if HAVE_WIN32
+SO_PREFIX = (DLL)
+dll       = $(call get_tok,dlname)
+else
+if HAVE_DARWIN
+SO_PREFIX = (DY)
+dll       =
+else
+SO_PREFIX = (SO)
+dll       =
+endif
+endif
diff --git a/libopenjpeg/jpwl/Makefile.nix b/libopenjpeg/jpwl/Makefile.nix
new file mode 100644 (file)
index 0000000..a266cd1
--- /dev/null
@@ -0,0 +1,152 @@
+#jpwl Makefile
+include ../config.nix
+
+TARGET  = openjpeg_JPWL
+COMPILERFLAGS = -Wall -ffast-math -std=c99 -fPIC
+USERLIBS =
+
+JPWL_SRCS = ./crc.c ./jpwl.c ./jpwl_lib.c ./rs.c
+
+SRCS = ../libopenjpeg/bio.c ../libopenjpeg/cio.c ../libopenjpeg/dwt.c \
+  ../libopenjpeg/event.c ../libopenjpeg/image.c ../libopenjpeg/j2k.c \
+  ../libopenjpeg/j2k_lib.c ../libopenjpeg/jp2.c ../libopenjpeg/jpt.c \
+  ../libopenjpeg/mct.c ../libopenjpeg/mqc.c ../libopenjpeg/openjpeg.c \
+  ../libopenjpeg/pi.c ../libopenjpeg/raw.c ../libopenjpeg/t1.c \
+  ../libopenjpeg/t2.c ../libopenjpeg/tcd.c ../libopenjpeg/tgt.c \
+  $(JPWL_SRCS)
+
+INCLS = ../libopenjpeg/bio.h ../libopenjpeg/cio.h ../libopenjpeg/dwt.h \
+  ../libopenjpeg/event.h ../libopenjpeg/fix.h ../libopenjpeg/image.h \
+  ../libopenjpeg/int.h ../libopenjpeg/j2k.h ../libopenjpeg/j2k_lib.h \
+  ../libopenjpeg/jp2.h ../libopenjpeg/jpt.h ../libopenjpeg/mct.h \
+  ../libopenjpeg/mqc.h ../libopenjpeg/openjpeg.h ../libopenjpeg/pi.h \
+  ../libopenjpeg/raw.h ../libopenjpeg/t1.h ../libopenjpeg/t2.h \
+  ../libopenjpeg/tcd.h ../libopenjpeg/tgt.h ../libopenjpeg/opj_malloc.h \
+  ../libopenjpeg/opj_includes.h
+
+INCLUDE = -I.. -I. -I../libopenjpeg -I../common
+
+INSTALL_LIBDIR = $(prefix)/lib
+INSTALL_BIN = $(prefix)/bin
+
+# Converts cr/lf to just lf
+DOS2UNIX = dos2unix
+
+
+LIBRARIES = -lstdc++
+
+ifeq ($(WITH_TIFF),yes)
+INCLUDE += $(TIFF_INCLUDE)
+USERLIBS += $(TIFF_LIB)
+endif
+
+ifeq ($(WITH_PNG),yes)
+INCLUDE += $(PNG_INCLUDE)
+USERLIBS += $(PNG_LIB)
+endif
+
+ifeq ($(WITH_LCMS2),yes)
+INCLUDE += $(LCMS2_INCLUDE)
+USERLIBS += $(LCMS2_LIB)
+endif
+
+ifeq ($(WITH_LCMS1),yes)
+INCLUDE += $(LCMS1_INCLUDE)
+USERLIBS += $(LCMS1_LIB)
+endif
+
+USERLIBS += -lm
+
+MODULES = $(SRCS:.c=.o)
+
+CFLAGS = $(COMPILERFLAGS) $(INCLUDE) -DUSE_JPWL
+
+LIBNAME = lib$(TARGET)
+
+ifeq ($(ENABLE_SHARED),yes)
+SHAREDLIB = $(LIBNAME).so.$(MAJOR).$(MINOR).$(BUILD)
+else
+STATICLIB = $(LIBNAME).a
+endif
+
+default: all
+
+all: OpenJPEG_JPWL JPWL_image_to_j2k JPWL_j2k_to_image
+       install -d ../bin
+ifeq ($(ENABLE_SHARED),yes)
+       install -m 755 $(SHAREDLIB) ../bin
+       (cd ../bin && ln -sf $(SHAREDLIB) $(LIBNAME).so.$(MAJOR).$(MINOR))
+       (cd ../bin && ln -sf $(LIBNAME).so.$(MAJOR).$(MINOR) $(LIBNAME).so)
+else
+       install -m 644 $(STATICLIB) ../bin
+endif
+       install JPWL_image_to_j2k JPWL_j2k_to_image ../bin
+
+dos2unix:
+       @$(DOS2UNIX) $(SRCS) $(INCLS)
+
+OpenJPEG_JPWL: $(STATICLIB) $(SHAREDLIB)
+
+JPWL_codec: JPWL_j2k_to_image JPWL_image_to_j2k $(STATICLIB)
+
+.c.o:
+       $(CC) $(CFLAGS) -c $< -o $@
+
+ifeq ($(ENABLE_SHARED),yes)
+$(SHAREDLIB): $(MODULES)
+       $(CC) -shared -Wl,-soname,$(LIBNAME) -o $@ $(MODULES) $(LIBRARIES)
+else
+$(STATICLIB): $(MODULES)
+       $(AR) r $@ $(MODULES)
+endif
+
+ifeq ($(ENABLE_SHARED),yes)
+ELIB = $(SHAREDLIB)
+else
+ELIB = $(STATICLIB)
+endif
+
+JPWL_j2k_to_image: ../codec/j2k_to_image.c
+       $(CC) $(CFLAGS) ../common/getopt.c ../codec/index.c \
+       ../codec/convert.c ../common/color.c ../codec/j2k_to_image.c \
+       -o JPWL_j2k_to_image $(ELIB) $(USERLIBS)
+
+JPWL_image_to_j2k: ../codec/image_to_j2k.c
+       $(CC) $(CFLAGS) ../common/getopt.c ../codec/index.c \
+       ../codec/convert.c ../codec/image_to_j2k.c \
+       -o JPWL_image_to_j2k $(ELIB) $(USERLIBS)
+
+install: OpenJPEG_JPWL
+       install -d $(DESTDIR)$(INSTALL_LIBDIR)
+ifeq ($(ENABLE_SHARED),yes)
+       install -m 755 -o root -g root $(SHAREDLIB) $(DESTDIR)$(INSTALL_LIBDIR)
+       (cd $(DESTDIR)$(INSTALL_LIBDIR) && \
+       ln -sf $(SHAREDLIB) $(LIBNAME).so.$(MAJOR).$(MINOR) )
+       (cd $(DESTDIR)$(INSTALL_LIBDIR) && \
+       ln -sf $(LIBNAME).so.$(MAJOR).$(MINOR) $(LIBNAME).so )
+else
+       install -m 644 -o root -g root $(STATICLIB) $(DESTDIR)$(INSTALL_LIBDIR)
+       (cd $(DESTDIR)$(INSTALL_LIBDIR) && ranlib $(STATICLIB))
+endif
+       install -d $(DESTDIR)$(INSTALL_BIN)
+       install -m 755 -o root -g root JPWL_j2k_to_image $(DESTDIR)$(INSTALL_BIN)
+       install -m 755 -o root -g root JPWL_image_to_j2k $(DESTDIR)$(INSTALL_BIN)
+       
+cleanlib:
+       rm -f core u2dtmp* $(MODULES) $(STATICLIB) $(SHAREDLIB)
+
+cleancodec:
+       rm -f JPWL_j2k_to_image JPWL_image_to_j2k JPWL_j2k_to_image.o \
+       JPWL_image_to_j2k.o
+
+clean: cleanlib cleancodec
+
+uninstall:
+ifeq ($(ENABLE_SHARED),yes)
+       (cd $(DESTDIR)$(INSTALL_LIBDIR) && \
+       rm -f $(LIBNAME).so $(LIBNAME).so.$(MAJOR).$(MINOR) $(SHAREDLIB))
+else
+       rm -f $(DESTDIR)$(INSTALL_LIBDIR)/$(STATICLIB)
+endif
+       rm -f $(DESTDIR)$(INSTALL_BIN)/JPWL_j2k_to_image
+       rm -f $(DESTDIR)$(INSTALL_BIN)/JPWL_image_to_j2k
diff --git a/libopenjpeg/jpwl/README.txt b/libopenjpeg/jpwl/README.txt
new file mode 100644 (file)
index 0000000..66e9d5b
--- /dev/null
@@ -0,0 +1,136 @@
+===============================================================================
+       JPEG2000 Part 11 (ISO/IEC 15444-11 JPWL) Software
+
+\r
+\r
+               Version 20061213
+===============================================================================
+
+
+\r
+\r
+\r
+1. Scope\r
+=============\r
+\r
+This document describes the installation and use of the JPWL module in the framework of OpenJPEG library.\r
+\r
+This implementation has been developed from OpenJPEG implementation of JPEG2000 standard, and for this reason it is written in C language.\r
+\r
+If you find some bugs or if you have problems using the encoder/decoder, please send an e-mail to jpwl@diei.unipg.it
+\r
+\r
+2. Installing the code\r
+==========================\r
+\r
+The JPWL code is integrated with the standard OpenJPEG library and codecs: it is activated by setting the macro USE_JPWL to defined in the preprocessor configuration options of your preferred C compiler.\r
+\r
+2.1. Compiling the source code in Windows\r
+-------------------------------------------\r
+\r
+The "jpwl" directory is already populated with a couple of Visual C++ 6.0 workspaces\r
+\r
+ * JPWL_image_to_j2k.dsw - Creates the encoder with JPWL functionalities\r
+ * JPWL_j2k_to_image.dsw - Creates the decoder with JPWL functionalities\r
+\r
+2.2. Compiling the source code in Unix-like systems\r
+-----------------------------------------------------\r
+\r
+Under linux, enter the jpwl directory and type "make clean" and "make".\r
+\r
+\r
+3. Running the JPWL software\r
+=========================\r
+\r
+The options available at the command line are exactly the same of the base OpenJPEG codecs. In addition, there is a "-W" switch that activates JPWL functionalities.\r
+\r
+3.1. JPWL Encoder\r
+-------------------\r
+\r
+-W           : adoption of JPWL (Part 11) capabilities (-W params)\r
+               The parameters can be written and repeated in any order:\r
+               [h<tile><=type>,s<tile><=method>,a=<addr>,z=<size>,g=<range>,...\r
+                ...,p<tile:pack><=type>]\r
+\r
+                 h selects the header error protection (EPB): 'type' can be\r
+                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\r
+                   if 'tile' is absent, it applies to main and tile headers\r
+                   if 'tile' is present, it applies from that tile\r
+                     onwards, up to the next h<tile> spec, or to the last tile\r
+                     in the codestream (max. 16 specs)\r
+\r
+                 p selects the packet error protection (EEP/UEP with EPBs)\r
+                  to be applied to raw data: 'type' can be\r
+                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\r
+                   if 'tile:pack' is absent, it starts from tile 0, packet 0\r
+                   if 'tile:pack' is present, it applies from that tile\r
+                     and that packet onwards, up to the next packet spec\r
+                     or to the last packet in the last tile in the codestream\r
+                     (max. 16 specs)\r
+\r
+                 s enables sensitivity data insertion (ESD): 'method' can be\r
+                   [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR\r
+                    4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED]\r
+                   if 'tile' is absent, it applies to main header only\r
+                   if 'tile' is present, it applies from that tile\r
+                     onwards, up to the next s<tile> spec, or to the last tile\r
+                     in the codestream (max. 16 specs)\r
+\r
+                 g determines the addressing mode: <range> can be\r
+                   [0=PACKET 1=BYTE RANGE 2=PACKET RANGE]\r
+\r
+                 a determines the size of data addressing: <addr> can be\r
+                   2/4 bytes (small/large codestreams). If not set, auto-mode\r
+\r
+                 z determines the size of sensitivity values: <size> can be\r
+                   1/2 bytes, for the transformed pseudo-floating point value\r
+\r
+                 ex.:\r
+ h,h0=64,h3=16,h5=32,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,s0=6,s3=-1,a=0,g=1,z=1\r
+                 means\r
+                   predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2,\r
+                   CRC-16 in TPH 3 and TPH 4, CRC-32 in remaining TPHs,\r
+                   UEP rs(78,32) for packets 0 to 23 of tile 0,\r
+                   UEP rs(56,32) for packets 24 to the last of tile 0,\r
+                   UEP rs default for packets of tile 1,\r
+                   no UEP for packets 0 to 19 of tile 3,\r
+                   UEP CRC-32 for packets 20 of tile 3 to last tile,\r
+                   relative sensitivity ESD for MH,\r
+                   TSE ESD from TPH 0 to TPH 2, byte range with automatic\r
+                   size of addresses and 1 byte for each sensitivity value\r
+\r
+                 ex.:\r
+                       h,s,p\r
+                 means\r
+                   default protection to headers (MH and TPHs) as well as\r
+                   data packets, one ESD in MH\r
+\r
+                 N.B.: use the following recommendations when specifying\r
+                       the JPWL parameters list\r
+                   - when you use UEP, always pair the 'p' option with 'h'\r
+\r
+3.2. JPWL Decoder\r
+-------------------\r
+\r
+  -W <options>\r
+    Activates the JPWL correction capability, if the codestream complies.\r
+    Options can be a comma separated list of <param=val> tokens:\r
+    c, c=numcomps\r
+       numcomps is the number of expected components in the codestream\r
+       (search of first EPB rely upon this, default is 3)\r
+\r
+\r
+4. Known bugs and limitations\r
+===============================\r
+\r
+4.1. Bugs\r
+-----------\r
+\r
+* It is not possible to save a JPWL encoded codestream using the wrapped file format (i.e. JP2): only raw file format (i.e. J2K) is working\r
+\r
+4.2. Limitations\r
+------------------\r
+\r
+* When specifying an UEP protection, you need to activate even TPH protection for those tiles where there is a protection of the packets\r
+* RED insertion is not currently implemented at the decoder\r
+* JPWL at entropy coding level is not implemented\r
diff --git a/libopenjpeg/jpwl/crc.c b/libopenjpeg/jpwl/crc.c
new file mode 100644 (file)
index 0000000..f65e4e1
--- /dev/null
@@ -0,0 +1,160 @@
+/*\r
+ * Copyright (c) 2001-2003, David Janssens\r
+ * Copyright (c) 2002-2003, Yannick Verschueren\r
+ * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe\r
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team\r
+ * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium\r
+ * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+\r
+#ifdef USE_JPWL\r
+\r
+#include "crc.h"\r
+\r
+/**\r
+@file crc.c\r
+@brief Functions used to compute the 16- and 32-bit CRC of byte arrays\r
+\r
+*/\r
+\r
+/** file: CRC16.CPP\r
+ *\r
+ * CRC - Cyclic Redundancy Check (16-bit)\r
+ *\r
+ * A CRC-checksum is used to be sure, the data hasn't changed or is false.\r
+ * To create a CRC-checksum, initialise a check-variable (unsigned short),\r
+ * and set this to zero. Than call for every byte in the file (e.g.) the\r
+ * procedure updateCRC16 with this check-variable as the first parameter,\r
+ * and the byte as the second. At the end, the check-variable contains the\r
+ * CRC-checksum.\r
+ *\r
+ * implemented by Michael Neumann, 14.06.1998\r
+ * \r
+ */\r
+const unsigned short CRC16_table[256] = {\r
+       0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, \r
+       0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, \r
+       0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, \r
+       0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,\r
+       0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, \r
+       0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, \r
+       0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, \r
+       0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, \r
+       0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, \r
+       0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, \r
+       0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, \r
+       0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,\r
+       0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, \r
+       0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, \r
+       0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, \r
+       0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, \r
+       0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, \r
+       0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,\r
+       0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, \r
+       0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, \r
+       0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,\r
+       0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, \r
+       0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, \r
+       0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, \r
+       0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, \r
+       0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, \r
+       0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, \r
+       0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, \r
+       0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, \r
+       0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, \r
+       0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, \r
+       0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0\r
+};\r
+\r
+void updateCRC16(unsigned short *crc, unsigned char data) {\r
+       *crc = CRC16_table[(*crc >> 8) & 0xFF] ^ (*crc << 8) ^ data;\r
+};\r
+\r
+\r
+/** file: CRC32.CPP\r
+ *\r
+ * CRC - Cyclic Redundancy Check (32-bit)\r
+ *\r
+ * A CRC-checksum is used to be sure, the data hasn't changed or is false.\r
+ * To create a CRC-checksum, initialise a check-variable (unsigned long),\r
+ * and set this to zero. Than call for every byte in the file (e.g.) the\r
+ * procedure updateCRC32 with this check-variable as the first parameter,\r
+ * and the byte as the second. At the end, the check-variable contains the\r
+ * CRC-checksum.\r
+ *\r
+ * implemented by Michael Neumann, 14.06.1998\r
+ *\r
+ */\r
+const unsigned long CRC32_table[256] = {\r
+       0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,\r
+       0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,\r
+       0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,\r
+       0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,\r
+       0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,\r
+       0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,\r
+       0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,\r
+       0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,\r
+       0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,\r
+       0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,\r
+       0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,\r
+       0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,\r
+       0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,\r
+       0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,\r
+       0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,\r
+       0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,\r
+       0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,\r
+       0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,\r
+       0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,\r
+       0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,\r
+       0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,\r
+       0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,\r
+       0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,\r
+       0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,\r
+       0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,\r
+       0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,\r
+       0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,\r
+       0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,\r
+       0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,\r
+       0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,\r
+       0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,\r
+       0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,\r
+       0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,\r
+       0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,\r
+       0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,\r
+       0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,\r
+       0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,\r
+       0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,\r
+       0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,\r
+       0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,\r
+       0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,\r
+       0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,\r
+       0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d\r
+};\r
+\r
+void updateCRC32(unsigned long *crc, unsigned char data) {\r
+       *crc = CRC32_table[(unsigned char) *crc ^ data] ^ ((*crc >> 8) & 0x00FFFFFF);\r
+};\r
+\r
+#endif /* USE_JPWL */\r
diff --git a/libopenjpeg/jpwl/crc.h b/libopenjpeg/jpwl/crc.h
new file mode 100644 (file)
index 0000000..4ea2c4c
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifdef USE_JPWL
+
+/**
+@file crc.h
+@brief Functions used to compute the 16- and 32-bit CRC of byte arrays
+
+*/
+
+#ifndef __CRC16_HEADER__
+#define __CRC16_HEADER__
+
+/** file: CRC16.HPP
+ *
+ * CRC - Cyclic Redundancy Check (16-bit)
+ *
+ * A CRC-checksum is used to be sure, the data hasn't changed or is false.
+ * To create a CRC-checksum, initialise a check-variable (unsigned short),
+ * and set this to zero. Than call for every byte in the file (e.g.) the
+ * procedure updateCRC16 with this check-variable as the first parameter,
+ * and the byte as the second. At the end, the check-variable contains the
+ * CRC-checksum.
+ *
+ * implemented by Michael Neumann, 14.06.1998
+ * 
+ */
+void updateCRC16(unsigned short *, unsigned char);
+
+#endif /* __CRC16_HEADER__ */
+
+
+#ifndef __CRC32_HEADER__
+#define __CRC32_HEADER__
+
+/** file: CRC32.HPP
+ *
+ * CRC - Cyclic Redundancy Check (32-bit)
+ *
+ * A CRC-checksum is used to be sure, the data hasn't changed or is false.
+ * To create a CRC-checksum, initialise a check-variable (unsigned short),
+ * and set this to zero. Than call for every byte in the file (e.g.) the
+ * procedure updateCRC32 with this check-variable as the first parameter,
+ * and the byte as the second. At the end, the check-variable contains the
+ * CRC-checksum.
+ *
+ * implemented by Michael Neumann, 14.06.1998
+ *
+ */
+void updateCRC32(unsigned long *, unsigned char);
+
+#endif /* __CRC32_HEADER__ */
+
+
+#endif /* USE_JPWL */
diff --git a/libopenjpeg/jpwl/jpwl.c b/libopenjpeg/jpwl/jpwl.c
new file mode 100644 (file)
index 0000000..42c8871
--- /dev/null
@@ -0,0 +1,1357 @@
+/*\r
+ * Copyright (c) 2001-2003, David Janssens\r
+ * Copyright (c) 2002-2003, Yannick Verschueren\r
+ * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe\r
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team\r
+ * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium\r
+ * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy\r
+ * All rights reserved.\r
+ *\r
+ * Redistribution and use in source and binary forms, with or without\r
+ * modification, are permitted provided that the following conditions\r
+ * are met:\r
+ * 1. Redistributions of source code must retain the above copyright\r
+ *    notice, this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright\r
+ *    notice, this list of conditions and the following disclaimer in the\r
+ *    documentation and/or other materials provided with the distribution.\r
+ *\r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+ * POSSIBILITY OF SUCH DAMAGE.\r
+ */\r
+\r
+#include "../libopenjpeg/opj_includes.h"\r
+\r
+#ifdef USE_JPWL\r
+\r
+/** @defgroup JPWL JPWL - JPEG-2000 Part11 (JPWL) codestream manager */\r
+/*@{*/\r
+\r
+/** @name Local static variables */\r
+/*@{*/\r
+\r
+/** number of JPWL prepared markers */\r
+static int jwmarker_num;\r
+/** properties of JPWL markers to insert */\r
+static jpwl_marker_t jwmarker[JPWL_MAX_NO_MARKERS]; \r
+\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+/** @name Local static functions */\r
+/*@{*/\r
+\r
+/** create an EPC marker segment\r
+@param j2k J2K compressor handle\r
+@param esd_on true if ESD is activated\r
+@param red_on true if RED is activated\r
+@param epb_on true if EPB is activated\r
+@param info_on true if informative techniques are activated\r
+@return returns the freshly created EPC\r
+*/\r
+jpwl_epc_ms_t *jpwl_epc_create(opj_j2k_t *j2k, bool esd_on, bool red_on, bool epb_on, bool info_on);\r
+\r
+/*@}*/\r
+\r
+/** create an EPC marker segment\r
+@param j2k J2K compressor handle\r
+@param comps considered component (-1=average, 0/1/2/...=component no.)\r
+@param addrm addressing mode (0=packet, 1=byte range, 2=packet range, 3=reserved)\r
+@param ad_size size of addresses (2/4 bytes)\r
+@param senst sensitivity type\r
+@param se_size sensitivity values size (1/2 bytes)\r
+@param tileno tile where this ESD lies (-1 means MH)\r
+@param svalnum number of sensitivity values (if 0, they will be automatically filled)\r
+@param sensval pointer to an array of sensitivity values (if NULL, they will be automatically filled)\r
+@return returns the freshly created ESD\r
+*/\r
+jpwl_esd_ms_t *jpwl_esd_create(opj_j2k_t *j2k, int comps, unsigned char addrm, unsigned char ad_size,\r
+                                                               unsigned char senst, int se_size, int tileno,\r
+                                                               unsigned long int svalnum, void *sensval);\r
+                       \r
+/** this function is used to compare two JPWL markers based on\r
+their relevant wishlist position\r
+@param arg1 pointer to first marker\r
+@param arg2 pointer to second marker\r
+@return 1 if arg1>arg2, 0 if arg1=arg2, -1 if arg1<arg2\r
+*/\r
+int jpwl_markcomp(const void *arg1, const void *arg2);\r
+\r
+/** write an EPB MS to a buffer\r
+@param j2k J2K compressor handle\r
+@param epbmark pointer to the EPB MS\r
+@param buf pointer to the memory buffer\r
+*/\r
+void jpwl_epb_write(opj_j2k_t *j2k, jpwl_epb_ms_t *epbmark, unsigned char *buf);\r
+\r
+/** write an EPC MS to a buffer\r
+@param j2k J2K compressor handle\r
+@param epcmark pointer to the EPC MS\r
+@param buf pointer to the memory buffer\r
+*/\r
+void jpwl_epc_write(opj_j2k_t *j2k, jpwl_epc_ms_t *epcmark, unsigned char *buf);\r
+\r
+/** write an ESD MS to a buffer\r
+@param j2k J2K compressor handle\r
+@param esdmark pointer to the ESD MS\r
+@param buf pointer to the memory buffer\r
+*/\r
+void jpwl_esd_write(opj_j2k_t *j2k, jpwl_esd_ms_t *esdmark, unsigned char *buf);\r
+\r
+/*-----------------------------------------------------------------*/\r
+\r
+void jpwl_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image) {\r
+\r
+       int mm;\r
+\r
+       /* let's reset some settings */\r
+\r
+       /* clear the existing markers */\r
+       for (mm = 0; mm < jwmarker_num; mm++) {\r
+\r
+               switch (jwmarker[mm].id) {\r
+\r
+               case J2K_MS_EPB:\r
+                       opj_free(jwmarker[mm].m.epbmark);\r
+                       break;\r
+\r
+               case J2K_MS_EPC:\r
+                       opj_free(jwmarker[mm].m.epcmark);\r
+                       break;\r
+\r
+               case J2K_MS_ESD:\r
+                       opj_free(jwmarker[mm].m.esdmark);\r
+                       break;\r
+\r
+               case J2K_MS_RED:\r
+                       opj_free(jwmarker[mm].m.redmark);\r
+                       break;\r
+\r
+               default:\r
+                       break;\r
+               }\r
+       }\r
+\r
+       /* clear the marker structure array */\r
+       memset(jwmarker, 0, sizeof(jpwl_marker_t) * JPWL_MAX_NO_MARKERS);\r
+\r
+       /* no more markers in the list */\r
+       jwmarker_num = 0;\r
+\r
+       /* let's begin creating a marker list, according to user wishes */\r
+       jpwl_prepare_marks(j2k, cio, image);\r
+\r
+       /* now we dump the JPWL markers on the codestream */\r
+       jpwl_dump_marks(j2k, cio, image);\r
+\r
+       /* do not know exactly what is this for,\r
+       but it gets called during index creation */\r
+       j2k->pos_correction = 0;\r
+\r
+}\r
+\r
+void j2k_add_marker(opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len) {\r
+\r
+       if (!cstr_info)\r
+               return;\r
+\r
+       /* expand the list? */\r
+       if ((cstr_info->marknum + 1) > cstr_info->maxmarknum) {\r
+               cstr_info->maxmarknum = 100 + (int) ((float) cstr_info->maxmarknum * 1.0F);\r
+               cstr_info->marker = opj_realloc(cstr_info->marker, cstr_info->maxmarknum);\r
+       }\r
+\r
+       /* add the marker */\r
+       cstr_info->marker[cstr_info->marknum].type = type;\r
+       cstr_info->marker[cstr_info->marknum].pos = pos;\r
+       cstr_info->marker[cstr_info->marknum].len = len;\r
+       cstr_info->marknum++;\r
+\r
+}\r
+\r
+void jpwl_prepare_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image) {\r
+\r
+       unsigned short int socsiz_len = 0;\r
+       int ciopos = cio_tell(cio), soc_pos = j2k->cstr_info->main_head_start;\r
+       unsigned char *socp = NULL;\r
+\r
+       int tileno, acc_tpno, tpno, tilespec, hprot, sens, pprot, packspec, lastileno, packno;\r
+\r
+       jpwl_epb_ms_t *epb_mark;\r
+       jpwl_epc_ms_t *epc_mark;\r
+       jpwl_esd_ms_t *esd_mark;\r
+\r
+       /* find (SOC + SIZ) length */\r
+       /* I assume SIZ is always the first marker after SOC */\r
+       cio_seek(cio, soc_pos + 4);\r
+       socsiz_len = (unsigned short int) cio_read(cio, 2) + 4; /* add the 2 marks length itself */\r
+       cio_seek(cio, soc_pos + 0);\r
+       socp = cio_getbp(cio); /* pointer to SOC */\r
+\r
+       /* \r
+        EPC MS for Main Header: if we are here it's required\r
+       */\r
+       /* create the EPC */\r
+       if ((epc_mark = jpwl_epc_create(\r
+                       j2k,\r
+                       j2k->cp->esd_on, /* is ESD present? */\r
+                       j2k->cp->red_on, /* is RED present? */\r
+                       j2k->cp->epb_on, /* is EPB present? */\r
+                       false /* are informative techniques present? */\r
+               ))) {\r
+\r
+               /* Add this marker to the 'insertanda' list */\r
+               if (epc_mark) {\r
+                       jwmarker[jwmarker_num].id = J2K_MS_EPC; /* its type */\r
+                       jwmarker[jwmarker_num].m.epcmark = epc_mark; /* the EPC */\r
+                       jwmarker[jwmarker_num].pos = soc_pos + socsiz_len; /* after SIZ */\r
+                       jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos + 0.1; /* not so first */\r
+                       jwmarker[jwmarker_num].len = epc_mark->Lepc; /* its length */\r
+                       jwmarker[jwmarker_num].len_ready = true; /* ready */\r
+                       jwmarker[jwmarker_num].pos_ready = true; /* ready */\r
+                       jwmarker[jwmarker_num].parms_ready = false; /* not ready */\r
+                       jwmarker[jwmarker_num].data_ready = true; /* ready */\r
+                       jwmarker_num++;\r
+               };\r
+\r
+               opj_event_msg(j2k->cinfo, EVT_INFO,\r
+                       "MH  EPC : setting %s%s%s\n",\r
+                       j2k->cp->esd_on ? "ESD, " : "",\r
+                       j2k->cp->red_on ? "RED, " : "",\r
+                       j2k->cp->epb_on ? "EPB, " : ""\r
+                       );\r
+\r
+       } else {\r
+               /* ooops, problems */\r
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create MH EPC\n");                              \r
+       };\r
+\r
+       /* \r
+        ESD MS for Main Header\r
+       */\r
+       /* first of all, must MH have an ESD MS? */\r
+       if (j2k->cp->esd_on && (j2k->cp->sens_MH >= 0)) {\r
+\r
+               /* Create the ESD */\r
+               if ((esd_mark = jpwl_esd_create(\r
+                       j2k, /* this encoder handle */\r
+                       -1, /* we are averaging over all components */\r
+                       (unsigned char) j2k->cp->sens_range, /* range method */\r
+                       (unsigned char) j2k->cp->sens_addr, /* sensitivity addressing */\r
+                       (unsigned char) j2k->cp->sens_MH, /* sensitivity method */\r
+                       j2k->cp->sens_size, /* sensitivity size */\r
+                       -1, /* this ESD is in main header */\r
+                       0 /*j2k->cstr_info->num*/, /* number of packets in codestream */\r
+                       NULL /*sensval*/ /* pointer to sensitivity data of packets */\r
+                       ))) {\r
+                       \r
+                       /* Add this marker to the 'insertanda' list */\r
+                       if (jwmarker_num < JPWL_MAX_NO_MARKERS) {\r
+                               jwmarker[jwmarker_num].id = J2K_MS_ESD; /* its type */\r
+                               jwmarker[jwmarker_num].m.esdmark = esd_mark; /* the EPB */\r
+                               jwmarker[jwmarker_num].pos = soc_pos + socsiz_len; /* we choose to place it after SIZ */\r
+                               jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos + 0.2; /* not first at all! */\r
+                               jwmarker[jwmarker_num].len = esd_mark->Lesd; /* its length */\r
+                               jwmarker[jwmarker_num].len_ready = true; /* not ready, yet */\r
+                               jwmarker[jwmarker_num].pos_ready = true; /* ready */\r
+                               jwmarker[jwmarker_num].parms_ready = true; /* not ready */\r
+                               jwmarker[jwmarker_num].data_ready = false; /* not ready */\r
+                               jwmarker_num++;\r
+                       }\r
+\r
+                       opj_event_msg(j2k->cinfo, EVT_INFO,\r
+                               "MH  ESDs: method %d\n",\r
+                               j2k->cp->sens_MH\r
+                               );\r
+\r
+               } else {\r
+                       /* ooops, problems */\r
+                       opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create MH ESD\n");                              \r
+               };\r
+\r
+       }\r
+\r
+       /* \r
+        ESD MSs for Tile Part Headers \r
+       */\r
+       /* cycle through tiles */\r
+       sens = -1; /* default spec: no ESD */\r
+       tilespec = 0; /* first tile spec */\r
+       acc_tpno = 0;\r
+       for (tileno = 0; tileno < j2k->cstr_info->tw * j2k->cstr_info->th; tileno++) {\r
+\r
+               opj_event_msg(j2k->cinfo, EVT_INFO,\r
+                       "Tile %d has %d tile part(s)\n",\r
+                       tileno, j2k->cstr_info->tile[tileno].num_tps\r
+                       );\r
+\r
+               /* for every tile part in the tile */\r
+               for (tpno = 0; tpno < j2k->cstr_info->tile[tileno].num_tps; tpno++, acc_tpno++) {\r
+       \r
+                       int sot_len, Psot, Psotp, mm;\r
+                       unsigned long sot_pos, post_sod_pos;\r
+\r
+                       unsigned long int left_THmarks_len;\r
+\r
+                       /******* sot_pos = j2k->cstr_info->tile[tileno].start_pos; */\r
+                       sot_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos;\r
+                       cio_seek(cio, sot_pos + 2); \r
+                       sot_len = cio_read(cio, 2); /* SOT Len */\r
+                       cio_skip(cio, 2);\r
+                       Psotp = cio_tell(cio);\r
+                       Psot = cio_read(cio, 4); /* tile length */\r
+\r
+                       /******* post_sod_pos = j2k->cstr_info->tile[tileno].end_header + 1; */\r
+                       post_sod_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_end_header + 1;\r
+                       left_THmarks_len = post_sod_pos - sot_pos;\r
+\r
+                       /* add all the lengths of the markers which are len-ready and stay within SOT and SOD */\r
+                       for (mm = 0; mm < jwmarker_num; mm++) {\r
+                               if ((jwmarker[mm].pos >= sot_pos) && (jwmarker[mm].pos < post_sod_pos)) {\r
+                                       if (jwmarker[mm].len_ready)\r
+                                               left_THmarks_len += jwmarker[mm].len + 2;\r
+                                       else {\r
+                                               opj_event_msg(j2k->cinfo, EVT_ERROR, "MS %x in %f is not len-ready: could not set up TH EPB\n",\r
+                                                       jwmarker[mm].id, jwmarker[mm].dpos);                            \r
+                                               exit(1);\r
+                                       }\r
+                               }\r
+                       }\r
+\r
+                       /******* if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->sens_TPH_tileno[tilespec] == tileno)) */\r
+                       if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->sens_TPH_tileno[tilespec] == acc_tpno))\r
+                               /* we got a specification from this tile onwards */\r
+                               sens = j2k->cp->sens_TPH[tilespec++];\r
+               \r
+                       /* must this TPH have an ESD MS? */\r
+                       if (j2k->cp->esd_on && (sens >= 0)) {\r
+\r
+                               /* Create the ESD */\r
+                               if ((esd_mark = jpwl_esd_create(\r
+                                       j2k, /* this encoder handle */\r
+                                       -1, /* we are averaging over all components */\r
+                                       (unsigned char) j2k->cp->sens_range, /* range method */\r
+                                       (unsigned char) j2k->cp->sens_addr, /* sensitivity addressing size */\r
+                                       (unsigned char) sens, /* sensitivity method */\r
+                                       j2k->cp->sens_size, /* sensitivity value size */\r
+                                       tileno, /* this ESD is in a tile */\r
+                                       0, /* number of packets in codestream */\r
+                                       NULL /* pointer to sensitivity data of packets */\r
+                                       ))) {\r
+                                       \r
+                                       /* Add this marker to the 'insertanda' list */\r
+                                       if (jwmarker_num < JPWL_MAX_NO_MARKERS) {\r
+                                               jwmarker[jwmarker_num].id = J2K_MS_ESD; /* its type */\r
+                                               jwmarker[jwmarker_num].m.esdmark = esd_mark; /* the EPB */\r
+                                               /****** jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].start_pos + sot_len + 2; */ /* after SOT */\r
+                                               jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2; /* after SOT */\r
+                                               jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos + 0.2; /* not first at all! */\r
+                                               jwmarker[jwmarker_num].len = esd_mark->Lesd; /* its length */\r
+                                               jwmarker[jwmarker_num].len_ready = true; /* ready, yet */\r
+                                               jwmarker[jwmarker_num].pos_ready = true; /* ready */\r
+                                               jwmarker[jwmarker_num].parms_ready = true; /* not ready */\r
+                                               jwmarker[jwmarker_num].data_ready = false; /* ready */\r
+                                               jwmarker_num++;\r
+                                       }\r
+\r
+                                       /* update Psot of the tile  */\r
+                                       cio_seek(cio, Psotp);\r
+                                       cio_write(cio, Psot + esd_mark->Lesd + 2, 4);\r
+\r
+                                       opj_event_msg(j2k->cinfo, EVT_INFO,\r
+                                               /******* "TPH ESDs: tile %02d, method %d\n", */\r
+                                               "TPH ESDs: tile %02d, part %02d, method %d\n",\r
+                                               /******* tileno, */\r
+                                               tileno, tpno,\r
+                                               sens\r
+                                               );\r
+\r
+                               } else {\r
+                                       /* ooops, problems */\r
+                                       /***** opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH ESD #%d\n", tileno); */\r
+                                       opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH ESD #%d,%d\n", tileno, tpno);\r
+                               };\r
+\r
+                       }\r
+                       \r
+               }\r
+       \r
+       };\r
+\r
+       /* \r
+        EPB MS for Main Header\r
+       */\r
+       /* first of all, must MH have an EPB MS? */\r
+       if (j2k->cp->epb_on && (j2k->cp->hprot_MH > 0)) {\r
+\r
+               int mm;\r
+\r
+               /* position of SOT */\r
+               unsigned int sot_pos = j2k->cstr_info->main_head_end + 1;\r
+\r
+               /* how much space is there between end of SIZ and beginning of SOT? */\r
+               int left_MHmarks_len = sot_pos - socsiz_len;\r
+\r
+               /* add all the lengths of the markers which are len-ready and stay within SOC and SOT */\r
+               for (mm = 0; mm < jwmarker_num; mm++) {\r
+                       if ((jwmarker[mm].pos >=0) && (jwmarker[mm].pos < sot_pos)) {\r
+                               if (jwmarker[mm].len_ready)\r
+                                       left_MHmarks_len += jwmarker[mm].len + 2;\r
+                               else {\r
+                                       opj_event_msg(j2k->cinfo, EVT_ERROR, "MS %x in %f is not len-ready: could not set up MH EPB\n",\r
+                                               jwmarker[mm].id, jwmarker[mm].dpos);                            \r
+                                       exit(1);\r
+                               }\r
+                       }\r
+               }\r
+\r
+               /* Create the EPB */\r
+               if ((epb_mark = jpwl_epb_create(\r
+                       j2k, /* this encoder handle */\r
+                       true, /* is it the latest? */\r
+                       true, /* is it packed? not for now */\r
+                       -1, /* we are in main header */\r
+                       0, /* its index is 0 (first) */\r
+                       j2k->cp->hprot_MH, /* protection type parameters of data */\r
+                       socsiz_len, /* pre-data: only SOC+SIZ */\r
+                       left_MHmarks_len /* post-data: from SOC to SOT, and all JPWL markers within */\r
+                       ))) {\r
+                       \r
+                       /* Add this marker to the 'insertanda' list */\r
+                       if (jwmarker_num < JPWL_MAX_NO_MARKERS) {\r
+                               jwmarker[jwmarker_num].id = J2K_MS_EPB; /* its type */\r
+                               jwmarker[jwmarker_num].m.epbmark = epb_mark; /* the EPB */\r
+                               jwmarker[jwmarker_num].pos = soc_pos + socsiz_len; /* after SIZ */\r
+                               jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos; /* first first first! */\r
+                               jwmarker[jwmarker_num].len = epb_mark->Lepb; /* its length */\r
+                               jwmarker[jwmarker_num].len_ready = true; /* ready */\r
+                               jwmarker[jwmarker_num].pos_ready = true; /* ready */\r
+                               jwmarker[jwmarker_num].parms_ready = true; /* ready */\r
+                               jwmarker[jwmarker_num].data_ready = false; /* not ready */\r
+                               jwmarker_num++;\r
+                       }\r
+\r
+                       opj_event_msg(j2k->cinfo, EVT_INFO,\r
+                               "MH  EPB : prot. %d\n",\r
+                               j2k->cp->hprot_MH\r
+                               );\r
+\r
+               } else {\r
+                       /* ooops, problems */\r
+                       opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create MH EPB\n");                              \r
+               };\r
+       }\r
+\r
+       /* \r
+        EPB MSs for Tile Parts\r
+       */\r
+       /* cycle through TPHs */\r
+       hprot = j2k->cp->hprot_MH; /* default spec */\r
+       tilespec = 0; /* first tile spec */\r
+       lastileno = 0;\r
+       packspec = 0;\r
+       pprot = -1;\r
+       acc_tpno = 0;\r
+       for (tileno = 0; tileno < j2k->cstr_info->tw * j2k->cstr_info->th; tileno++) {\r
+\r
+               opj_event_msg(j2k->cinfo, EVT_INFO,\r
+                       "Tile %d has %d tile part(s)\n",\r
+                       tileno, j2k->cstr_info->tile[tileno].num_tps\r
+                       );\r
+\r
+               /* for every tile part in the tile */\r
+               for (tpno = 0; tpno < j2k->cstr_info->tile[tileno].num_tps; tpno++, acc_tpno++) { \r
+               \r
+                       int sot_len, Psot, Psotp, mm, epb_index = 0, prot_len = 0;\r
+                       unsigned long sot_pos, post_sod_pos;\r
+                       unsigned long int left_THmarks_len/*, epbs_len = 0*/;\r
+                       int startpack = 0, stoppack = j2k->cstr_info->packno;\r
+                       int first_tp_pack, last_tp_pack;\r
+                       jpwl_epb_ms_t *tph_epb = NULL;\r
+\r
+                       /****** sot_pos = j2k->cstr_info->tile[tileno].start_pos; */\r
+                       sot_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos;\r
+                       cio_seek(cio, sot_pos + 2); \r
+                       sot_len = cio_read(cio, 2); /* SOT Len */\r
+                       cio_skip(cio, 2);\r
+                       Psotp = cio_tell(cio);\r
+                       Psot = cio_read(cio, 4); /* tile length */\r
+\r
+                       /* a-priori length of the data dwelling between SOT and SOD */\r
+                       /****** post_sod_pos = j2k->cstr_info->tile[tileno].end_header + 1; */\r
+                       post_sod_pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_end_header + 1;\r
+                       left_THmarks_len = post_sod_pos - (sot_pos + sot_len + 2);\r
+\r
+                       /* add all the lengths of the JPWL markers which are len-ready and stay within SOT and SOD */\r
+                       for (mm = 0; mm < jwmarker_num; mm++) {\r
+                               if ((jwmarker[mm].pos >= sot_pos) && (jwmarker[mm].pos < post_sod_pos)) {\r
+                                       if (jwmarker[mm].len_ready)\r
+                                               left_THmarks_len += jwmarker[mm].len + 2;\r
+                                       else {\r
+                                               opj_event_msg(j2k->cinfo, EVT_ERROR, "MS %x in %f is not len-ready: could not set up TH EPB\n",\r
+                                                       jwmarker[mm].id, jwmarker[mm].dpos);                            \r
+                                               exit(1);\r
+                                       }\r
+                               }\r
+                       }\r
+\r
+                       /****** if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->hprot_TPH_tileno[tilespec] == tileno)) */\r
+                       if ((tilespec < JPWL_MAX_NO_TILESPECS) && (j2k->cp->hprot_TPH_tileno[tilespec] == acc_tpno))\r
+                               /* we got a specification from this tile part onwards */\r
+                               hprot = j2k->cp->hprot_TPH[tilespec++];\r
+               \r
+                       /* must this TPH have an EPB MS? */\r
+                       if (j2k->cp->epb_on && (hprot > 0)) {\r
+\r
+                               /* Create the EPB */\r
+                               if ((epb_mark = jpwl_epb_create(\r
+                                       j2k, /* this encoder handle */\r
+                                       false, /* is it the latest? in TPH, no for now (if huge data size in TPH, we'd need more) */\r
+                                       true, /* is it packed? yes for now */\r
+                                       tileno, /* we are in TPH */\r
+                                       epb_index++, /* its index is 0 (first) */\r
+                                       hprot, /* protection type parameters of following data */\r
+                                       sot_len + 2, /* pre-data length: only SOT */\r
+                                       left_THmarks_len /* post-data length: from SOT end to SOD inclusive */\r
+                                       ))) {\r
+                                       \r
+                                       /* Add this marker to the 'insertanda' list */\r
+                                       if (jwmarker_num < JPWL_MAX_NO_MARKERS) {\r
+                                               jwmarker[jwmarker_num].id = J2K_MS_EPB; /* its type */\r
+                                               jwmarker[jwmarker_num].m.epbmark = epb_mark; /* the EPB */\r
+                                               /****** jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].start_pos + sot_len + 2; */ /* after SOT */\r
+                                               jwmarker[jwmarker_num].pos = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2; /* after SOT */\r
+                                               jwmarker[jwmarker_num].dpos = (double) jwmarker[jwmarker_num].pos; /* first first first! */\r
+                                               jwmarker[jwmarker_num].len = epb_mark->Lepb; /* its length */\r
+                                               jwmarker[jwmarker_num].len_ready = true; /* ready */\r
+                                               jwmarker[jwmarker_num].pos_ready = true; /* ready */\r
+                                               jwmarker[jwmarker_num].parms_ready = true; /* ready */\r
+                                               jwmarker[jwmarker_num].data_ready = false; /* not ready */\r
+                                               jwmarker_num++;\r
+                                       }\r
+\r
+                                       /* update Psot of the tile  */\r
+                                       Psot += epb_mark->Lepb + 2;\r
+\r
+                                       opj_event_msg(j2k->cinfo, EVT_INFO,\r
+                                               /***** "TPH EPB : tile %02d, prot. %d\n", */\r
+                                               "TPH EPB : tile %02d, part %02d, prot. %d\n",\r
+                                               /***** tileno, */\r
+                                               tileno, tpno,\r
+                                               hprot\r
+                                               );\r
+\r
+                                       /* save this TPH EPB address */\r
+                                       tph_epb = epb_mark;\r
+\r
+                               } else {\r
+                                       /* ooops, problems */\r
+                                       /****** opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH EPB #%d\n", tileno); */\r
+                                       opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH EPB in #%d,d\n", tileno, tpno);\r
+                               };\r
+\r
+                       }                               \r
+               \r
+                       startpack = 0;\r
+                       /* EPB MSs for UEP packet data protection in Tile Parts */\r
+                       /****** for (packno = 0; packno < j2k->cstr_info->num; packno++) { */\r
+                       /*first_tp_pack = (tpno > 0) ? (first_tp_pack + j2k->cstr_info->tile[tileno].tp[tpno - 1].tp_numpacks) : 0;*/\r
+                       first_tp_pack = j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pack;\r
+                       last_tp_pack = first_tp_pack + j2k->cstr_info->tile[tileno].tp[tpno].tp_numpacks - 1;\r
+                       for (packno = 0; packno < j2k->cstr_info->tile[tileno].tp[tpno].tp_numpacks; packno++) {\r
+\r
+                               /******** if ((packspec < JPWL_MAX_NO_PACKSPECS) &&\r
+                                       (j2k->cp->pprot_tileno[packspec] == tileno) && (j2k->cp->pprot_packno[packspec] == packno)) { */\r
+                               if ((packspec < JPWL_MAX_NO_PACKSPECS) &&\r
+                                       (j2k->cp->pprot_tileno[packspec] == acc_tpno) && (j2k->cp->pprot_packno[packspec] == packno)) {\r
+\r
+                                       /* we got a specification from this tile and packet onwards */\r
+                                       /* print the previous spec */\r
+                                       if (packno > 0) {\r
+                                               stoppack = packno - 1;                          \r
+                                               opj_event_msg(j2k->cinfo, EVT_INFO,\r
+                                                       /***** "UEP EPBs: tile %02d, packs. %02d-%02d (B %d-%d), prot. %d\n", */\r
+                                                       "UEP EPBs: tile %02d, part %02d, packs. %02d-%02d (B %d-%d), prot. %d\n",\r
+                                                       /***** tileno, */\r
+                                                       tileno, tpno,\r
+                                                       startpack,\r
+                                                       stoppack,\r
+                                                       /***** j2k->cstr_info->tile[tileno].packet[startpack].start_pos, */\r
+                                                       j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos,\r
+                                                       /***** j2k->cstr_info->tile[tileno].packet[stoppack].end_pos, */\r
+                                                       j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos,\r
+                                                       pprot);\r
+\r
+                                               /***** prot_len = j2k->cstr_info->tile[tileno].packet[stoppack].end_pos + 1 -\r
+                                                       j2k->cstr_info->tile[tileno].packet[startpack].start_pos; */\r
+                                               prot_len = j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos + 1 -\r
+                                                       j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos;\r
+\r
+                                               /*\r
+                                                 particular case: if this is the last header and the last packet,\r
+                                                 then it is better to protect even the EOC marker\r
+                                               */\r
+                                               /****** if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) &&\r
+                                                       (stoppack == (j2k->cstr_info->num - 1))) */\r
+                                               if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) &&\r
+                                                       (tpno == (j2k->cstr_info->tile[tileno].num_tps - 1)) &&\r
+                                                       (stoppack == last_tp_pack))\r
+                                                       /* add the EOC len */\r
+                                                       prot_len += 2;\r
+\r
+                                               /* let's add the EPBs */\r
+                                               Psot += jpwl_epbs_add(\r
+                                                       j2k, /* J2K handle */\r
+                                                       jwmarker, /* pointer to JPWL markers list */\r
+                                                       &jwmarker_num, /* pointer to the number of current markers */\r
+                                                       false, /* latest */\r
+                                                       true, /* packed */\r
+                                                       false, /* inside MH */\r
+                                                       &epb_index, /* pointer to EPB index */\r
+                                                       pprot, /* protection type */\r
+                                                       /****** (double) (j2k->cstr_info->tile[tileno].start_pos + sot_len + 2) + 0.0001, */ /* position */\r
+                                                       (double) (j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2) + 0.0001, /* position */\r
+                                                       tileno, /* number of tile */\r
+                                                       0, /* length of pre-data */\r
+                                                       prot_len /*4000*/ /* length of post-data */\r
+                                                       );\r
+                                       }\r
+\r
+                                       startpack = packno;\r
+                                       pprot = j2k->cp->pprot[packspec++];\r
+                               }\r
+\r
+                               //printf("Tile %02d, pack %02d ==> %d\n", tileno, packno, pprot);\r
+               \r
+                       }\r
+\r
+                       /* we are at the end: print the remaining spec */\r
+                       stoppack = packno - 1;\r
+                       if (pprot >= 0) {\r
+\r
+                               opj_event_msg(j2k->cinfo, EVT_INFO,\r
+                                       /**** "UEP EPBs: tile %02d, packs. %02d-%02d (B %d-%d), prot. %d\n", */\r
+                                       "UEP EPBs: tile %02d, part %02d, packs. %02d-%02d (B %d-%d), prot. %d\n",\r
+                                       /**** tileno, */\r
+                                       tileno, tpno,\r
+                                       startpack,\r
+                                       stoppack,\r
+                                       /***** j2k->image_info->tile[tileno].packet[startpack].start_pos,\r
+                                       j2k->image_info->tile[tileno].packet[stoppack].end_pos, */\r
+                                       j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos,\r
+                                       j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos,\r
+                                       pprot);\r
+\r
+                               /***** prot_len = j2k->cstr_info->tile[tileno].packet[stoppack].end_pos + 1 -\r
+                                       j2k->cstr_info->tile[tileno].packet[startpack].start_pos; */\r
+                               prot_len = j2k->cstr_info->tile[tileno].packet[first_tp_pack + stoppack].end_pos + 1 -\r
+                                       j2k->cstr_info->tile[tileno].packet[first_tp_pack + startpack].start_pos;\r
+\r
+                               /*\r
+                                 particular case: if this is the last header and the last packet,\r
+                                 then it is better to protect even the EOC marker\r
+                               */\r
+                               /***** if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) &&\r
+                                       (stoppack == (j2k->cstr_info->num - 1))) */\r
+                               if ((tileno == ((j2k->cstr_info->tw * j2k->cstr_info->th) - 1)) &&\r
+                                       (tpno == (j2k->cstr_info->tile[tileno].num_tps - 1)) &&\r
+                                       (stoppack == last_tp_pack))\r
+                                       /* add the EOC len */\r
+                                       prot_len += 2;\r
+\r
+                               /* let's add the EPBs */\r
+                               Psot += jpwl_epbs_add(\r
+                                                       j2k, /* J2K handle */\r
+                                                       jwmarker, /* pointer to JPWL markers list */\r
+                                                       &jwmarker_num, /* pointer to the number of current markers */\r
+                                                       true, /* latest */\r
+                                                       true, /* packed */\r
+                                                       false, /* inside MH */\r
+                                                       &epb_index, /* pointer to EPB index */\r
+                                                       pprot, /* protection type */\r
+                                                       /***** (double) (j2k->cstr_info->tile[tileno].start_pos + sot_len + 2) + 0.0001,*/ /* position */\r
+                                                       (double) (j2k->cstr_info->tile[tileno].tp[tpno].tp_start_pos + sot_len + 2) + 0.0001, /* position */\r
+                                                       tileno, /* number of tile */\r
+                                                       0, /* length of pre-data */\r
+                                                       prot_len /*4000*/ /* length of post-data */\r
+                                                       );\r
+                       }\r
+\r
+                       /* we can now check if the TPH EPB was really the last one */\r
+                       if (tph_epb && (epb_index == 1)) {\r
+                               /* set the TPH EPB to be the last one in current header */\r
+                               tph_epb->Depb |= (unsigned char) ((true & 0x0001) << 6);\r
+                               tph_epb = NULL;\r
+                       }\r
+\r
+                       /* write back Psot */\r
+                       cio_seek(cio, Psotp);\r
+                       cio_write(cio, Psot, 4);\r
+               \r
+               }\r
+\r
+       };\r
+\r
+       /* reset the position */\r
+       cio_seek(cio, ciopos);\r
+\r
+}\r
+\r
+void jpwl_dump_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image) {\r
+\r
+       int mm;\r
+       unsigned long int old_size = j2k->cstr_info->codestream_size;\r
+       unsigned long int new_size = old_size;\r
+       int /*ciopos = cio_tell(cio),*/ soc_pos = j2k->cstr_info->main_head_start;\r
+       unsigned char *jpwl_buf, *orig_buf;\r
+       unsigned long int orig_pos;\r
+       double epbcoding_time = 0.0, esdcoding_time = 0.0;\r
+\r
+       /* Order JPWL markers according to their wishlist position */\r
+       qsort((void *) jwmarker, (size_t) jwmarker_num, sizeof (jpwl_marker_t), jpwl_markcomp);\r
+\r
+       /* compute markers total size */ \r
+       for (mm = 0; mm < jwmarker_num; mm++) {\r
+               /*printf("%x, %d, %.10f, %d long\n", jwmarker[mm].id, jwmarker[mm].pos,\r
+                       jwmarker[mm].dpos, jwmarker[mm].len);*/\r
+               new_size += jwmarker[mm].len + 2;\r
+       }\r
+\r
+       /* allocate a new buffer of proper size */\r
+       if (!(jpwl_buf = (unsigned char *) opj_malloc((size_t) (new_size + soc_pos) * sizeof(unsigned char)))) {\r
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for JPWL codestream buffer\n");\r
+               exit(1);\r
+       };\r
+\r
+       /* copy the jp2 part, if any */\r
+       orig_buf = jpwl_buf;\r
+       memcpy(jpwl_buf, cio->buffer, soc_pos);\r
+       jpwl_buf += soc_pos;\r
+\r
+       /* cycle through markers */\r
+       orig_pos = soc_pos + 0; /* start from the beginning */\r
+       cio_seek(cio, soc_pos + 0); /* rewind the original */\r
+       for (mm = 0; mm < jwmarker_num; mm++) {\r
+\r
+               /*\r
+               need to copy a piece of the original codestream\r
+               if there is such\r
+               */\r
+               memcpy(jpwl_buf, cio_getbp(cio), jwmarker[mm].pos - orig_pos);\r
+               jpwl_buf += jwmarker[mm].pos - orig_pos;\r
+               orig_pos = jwmarker[mm].pos;\r
+               cio_seek(cio, orig_pos);\r
+\r
+               /*\r
+               then write down the marker\r
+               */\r
+               switch (jwmarker[mm].id) {\r
+\r
+               case J2K_MS_EPB:\r
+                       jpwl_epb_write(j2k, jwmarker[mm].m.epbmark, jpwl_buf);\r
+                       break;\r
+\r
+               case J2K_MS_EPC:\r
+                       jpwl_epc_write(j2k, jwmarker[mm].m.epcmark, jpwl_buf);\r
+                       break;\r
+\r
+               case J2K_MS_ESD:\r
+                       jpwl_esd_write(j2k, jwmarker[mm].m.esdmark, jpwl_buf);\r
+                       break;\r
+\r
+               case J2K_MS_RED:\r
+                       memset(jpwl_buf, 0, jwmarker[mm].len + 2); /* placeholder */\r
+                       break;\r
+\r
+               default:\r
+                       break;\r
+               };\r
+\r
+               /* we update the markers struct */\r
+               if (j2k->cstr_info)\r
+                       j2k->cstr_info->marker[j2k->cstr_info->marknum - 1].pos = (jpwl_buf - orig_buf);\r
+               \r
+               /* we set the marker dpos to the new position in the JPWL codestream */\r
+               jwmarker[mm].dpos = (double) (jpwl_buf - orig_buf);\r
+\r
+               /* advance JPWL buffer position */\r
+               jpwl_buf += jwmarker[mm].len + 2;\r
+\r
+       }\r
+\r
+       /* finish remaining original codestream */\r
+       memcpy(jpwl_buf, cio_getbp(cio), old_size - (orig_pos - soc_pos));\r
+       jpwl_buf += old_size - (orig_pos - soc_pos);\r
+       cio_seek(cio, soc_pos + old_size);\r
+       \r
+       /*\r
+       update info file based on added markers\r
+       */\r
+       if (!jpwl_update_info(j2k, jwmarker, jwmarker_num))\r
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not update OPJ cstr_info structure\n");\r
+\r
+       /* now we need to repass some markers and fill their data fields */\r
+       \r
+       /* first of all, DL and Pcrc in EPCs */ \r
+       for (mm = 0; mm < jwmarker_num; mm++) {\r
+\r
+               /* find the EPCs */\r
+               if (jwmarker[mm].id == J2K_MS_EPC) {\r
+\r
+                       int epc_pos = (int) jwmarker[mm].dpos, pp;\r
+                       unsigned short int mycrc = 0x0000;\r
+\r
+                       /* fix and fill the DL field */\r
+                       jwmarker[mm].m.epcmark->DL = new_size;\r
+                       orig_buf[epc_pos + 6] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 24);\r
+                       orig_buf[epc_pos + 7] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 16);\r
+                       orig_buf[epc_pos + 8] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 8);\r
+                       orig_buf[epc_pos + 9] = (unsigned char) (jwmarker[mm].m.epcmark->DL >> 0);\r
+\r
+                       /* compute the CRC field (excluding itself) */\r
+                       for (pp = 0; pp < 4; pp++)\r
+                               jpwl_updateCRC16(&mycrc, orig_buf[epc_pos + pp]);\r
+                       for (pp = 6; pp < (jwmarker[mm].len + 2); pp++)\r
+                               jpwl_updateCRC16(&mycrc, orig_buf[epc_pos + pp]);\r
+\r
+                       /* fix and fill the CRC */\r
+                       jwmarker[mm].m.epcmark->Pcrc = mycrc;\r
+                       orig_buf[epc_pos + 4] = (unsigned char) (jwmarker[mm].m.epcmark->Pcrc >> 8);\r
+                       orig_buf[epc_pos + 5] = (unsigned char) (jwmarker[mm].m.epcmark->Pcrc >> 0);\r
+\r
+               }\r
+       }\r
+\r
+       /* then, sensitivity data in ESDs */ \r
+       esdcoding_time = opj_clock();\r
+       for (mm = 0; mm < jwmarker_num; mm++) {\r
+\r
+               /* find the ESDs */\r
+               if (jwmarker[mm].id == J2K_MS_ESD) {\r
+\r
+                       /* remember that they are now in a new position (dpos) */\r
+                       int esd_pos = (int) jwmarker[mm].dpos;\r
+\r
+                       jpwl_esd_fill(j2k, jwmarker[mm].m.esdmark, &orig_buf[esd_pos]);\r
+               \r
+               }\r
+\r
+       }\r
+       esdcoding_time = opj_clock() - esdcoding_time;\r
+       if (j2k->cp->esd_on)\r
+               opj_event_msg(j2k->cinfo, EVT_INFO, "ESDs sensitivities computed in %f s\n", esdcoding_time);\r
+\r
+       /* finally, RS or CRC parity in EPBs */ \r
+       epbcoding_time = opj_clock();\r
+       for (mm = 0; mm < jwmarker_num; mm++) {\r
+\r
+               /* find the EPBs */\r
+               if (jwmarker[mm].id == J2K_MS_EPB) {\r
+\r
+                       /* remember that they are now in a new position (dpos) */\r
+                       int nn, accum_len;\r
+\r
+                       /* let's see how many EPBs are following this one, included itself */\r
+                       /* for this to work, we suppose that the markers are correctly ordered */\r
+                       /* and, overall, that they are in packed mode inside headers */\r
+                       accum_len = 0;\r
+                       for (nn = mm; (nn < jwmarker_num) && (jwmarker[nn].id == J2K_MS_EPB) &&\r
+                               (jwmarker[nn].pos == jwmarker[mm].pos); nn++)\r
+                               accum_len += jwmarker[nn].m.epbmark->Lepb + 2;\r
+\r
+                       /* fill the current (first) EPB with post-data starting from the computed position */\r
+                       jpwl_epb_fill(j2k, jwmarker[mm].m.epbmark, &orig_buf[(int) jwmarker[mm].dpos],\r
+                               &orig_buf[(int) jwmarker[mm].dpos + accum_len]);\r
+               \r
+                       /* fill the remaining EPBs in the header with post-data starting from the last position */\r
+                       for (nn = mm + 1; (nn < jwmarker_num) && (jwmarker[nn].id == J2K_MS_EPB) &&\r
+                               (jwmarker[nn].pos == jwmarker[mm].pos); nn++)\r
+                               jpwl_epb_fill(j2k, jwmarker[nn].m.epbmark, &orig_buf[(int) jwmarker[nn].dpos], NULL);\r
+\r
+                       /* skip all the processed EPBs */\r
+                       mm = nn - 1;\r
+               }\r
+\r
+       }\r
+       epbcoding_time = opj_clock() - epbcoding_time;\r
+       if (j2k->cp->epb_on)\r
+               opj_event_msg(j2k->cinfo, EVT_INFO, "EPBs redundancy computed in %f s\n", epbcoding_time);\r
+\r
+       /* free original cio buffer and set it to the JPWL one */\r
+       opj_free(cio->buffer);\r
+       cio->cinfo = cio->cinfo; /* no change */\r
+       cio->openmode = cio->openmode; /* no change */\r
+       cio->buffer = orig_buf;\r
+       cio->length = new_size + soc_pos;\r
+       cio->start = cio->buffer;\r
+       cio->end = cio->buffer + cio->length;\r
+       cio->bp = cio->buffer;\r
+       cio_seek(cio, soc_pos + new_size);\r
+\r
+}\r
+\r
+\r
+void j2k_read_epc(opj_j2k_t *j2k) {\r
+       unsigned long int DL, Lepcp, Pcrcp, l;\r
+       unsigned short int Lepc, Pcrc = 0x0000;\r
+       unsigned char Pepc;     \r
+       opj_cio_t *cio = j2k->cio;\r
+       char *ans1;\r
+\r
+       /* Simply read the EPC parameters */\r
+       Lepcp = cio_tell(cio);\r
+       Lepc = cio_read(cio, 2);\r
+       Pcrcp = cio_tell(cio);\r
+       cio_skip(cio, 2); /* Pcrc */\r
+       DL = cio_read(cio, 4);\r
+       Pepc = cio_read(cio, 1);\r
+\r
+       /* compute Pcrc */\r
+       cio_seek(cio, Lepcp - 2);\r
+\r
+               /* Marker */\r
+               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
+               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
+\r
+               /* Length */\r
+               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
+               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
+\r
+               /* skip Pcrc */\r
+               cio_skip(cio, 2);\r
+\r
+               /* read all remaining */\r
+               for (l = 4; l < Lepc; l++)\r
+                       jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
+\r
+               /* check Pcrc with the result */\r
+               cio_seek(cio, Pcrcp);\r
+               ans1 = (Pcrc == (unsigned short int) cio_read(cio, 2)) ? "crc-ok" : "crc-ko";\r
+\r
+       /* now we write them to screen */\r
+       opj_event_msg(j2k->cinfo, EVT_INFO, \r
+               "EPC(%u,%d): %s, DL=%d%s %s %s\n",\r
+               Lepcp - 2,\r
+               Lepc,\r
+               ans1,\r
+               DL, /* data length this EPC is referring to */\r
+               (Pepc & 0x10) ? ", esd" : "", /* ESD is present */\r
+               (Pepc & 0x20) ? ", red" : "", /* RED is present */\r
+               (Pepc & 0x40) ? ", epb" : ""); /* EPB is present */\r
+\r
+       cio_seek(cio, Lepcp + Lepc);  \r
+}\r
+\r
+void j2k_write_epc(opj_j2k_t *j2k) {\r
+\r
+       unsigned long int DL, Lepcp, Pcrcp, l;\r
+       unsigned short int Lepc, Pcrc;\r
+       unsigned char Pepc;     \r
+\r
+       opj_cio_t *cio = j2k->cio;\r
+\r
+       cio_write(cio, J2K_MS_EPC, 2);  /* EPC */\r
+       Lepcp = cio_tell(cio);\r
+       cio_skip(cio, 2);\r
+\r
+       /* CRC-16 word of the EPC */\r
+       Pcrc = 0x0000; /* initialize */\r
+       Pcrcp = cio_tell(cio);\r
+       cio_write(cio, Pcrc, 2); /* Pcrc placeholder*/\r
+\r
+       /* data length of the EPC protection domain */\r
+       DL = 0x00000000; /* we leave this set to 0, as if the information is not available */\r
+       cio_write(cio, DL, 4);   /* DL */\r
+\r
+       /* jpwl capabilities */\r
+       Pepc = 0x00;\r
+       cio_write(cio, Pepc, 1); /* Pepc */\r
+\r
+       /* ID section */\r
+       /* no ID's, as of now */\r
+\r
+       Lepc = (unsigned short) (cio_tell(cio) - Lepcp);\r
+       cio_seek(cio, Lepcp);\r
+       cio_write(cio, Lepc, 2); /* Lepc */\r
+\r
+       /* compute Pcrc */\r
+       cio_seek(cio, Lepcp - 2);\r
+\r
+               /* Marker */\r
+               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
+               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
+\r
+               /* Length */\r
+               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
+               jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
+\r
+               /* skip Pcrc */\r
+               cio_skip(cio, 2);\r
+\r
+               /* read all remaining */\r
+               for (l = 4; l < Lepc; l++)\r
+                       jpwl_updateCRC16(&Pcrc, (unsigned char) cio_read(cio, 1)); \r
+\r
+               /* fill Pcrc with the result */\r
+               cio_seek(cio, Pcrcp);\r
+               cio_write(cio, Pcrc, 2);\r
+\r
+       cio_seek(cio, Lepcp + Lepc);\r
+\r
+       /* marker struct update */\r
+       j2k_add_marker(j2k->cstr_info, J2K_MS_EPC, Lepcp - 2, Lepc + 2);\r
+\r
+}\r
+\r
+void j2k_read_epb(opj_j2k_t *j2k) {\r
+       unsigned long int LDPepb, Pepb;\r
+       unsigned short int Lepb;\r
+       unsigned char Depb;\r
+       char str1[25] = "";\r
+       bool status;\r
+       static bool first_in_tph = true;\r
+       int type, pre_len, post_len;\r
+       static unsigned char *redund = NULL;\r
+       \r
+       opj_cio_t *cio = j2k->cio;\r
+\r
+       /* B/W = 45, RGB = 51 */\r
+       /*           SIZ   SIZ_FIELDS     SIZ_COMPS               FOLLOWING_MARKER */\r
+       int skipnum = 2  +     38     + 3 * j2k->cp->exp_comps  +         2;\r
+\r
+       if (j2k->cp->correct) {\r
+\r
+               /* go back to EPB marker value */\r
+               cio_seek(cio, cio_tell(cio) - 2);\r
+\r
+               /* we need to understand where we are */\r
+               if (j2k->state == J2K_STATE_MH) {\r
+                       /* we are in MH */\r
+                       type = 0; /* MH */\r
+                       pre_len = skipnum; /* SOC+SIZ */\r
+                       post_len = -1; /* auto */\r
+\r
+               } else if ((j2k->state == J2K_STATE_TPH) && first_in_tph) {\r
+                       /* we are in TPH */\r
+                       type = 1; /* TPH */\r
+                       pre_len = 12; /* SOC+SIZ */\r
+                       first_in_tph = false;\r
+                       post_len = -1; /* auto */\r
+\r
+               } else {\r
+                       /* we are elsewhere */\r
+                       type = 2; /* other */\r
+                       pre_len = 0; /* nada */\r
+                       post_len = -1; /* auto */\r
+\r
+               }\r
+\r
+               /* call EPB corrector */\r
+               /*printf("before %x, ", redund);*/\r
+               status = jpwl_epb_correct(j2k,      /* J2K decompressor handle */\r
+                                                                 cio->bp,  /* pointer to EPB in codestream buffer */\r
+                                                                 type,     /* EPB type: MH */\r
+                                                                 pre_len,  /* length of pre-data */\r
+                                                                 post_len, /* length of post-data: -1 means auto */\r
+                                                                 NULL,     /* do everything auto */\r
+                                                                 &redund\r
+                                                                );\r
+               /*printf("after %x\n", redund);*/\r
+\r
+               /* Read the (possibly corrected) EPB parameters */\r
+               cio_skip(cio, 2);\r
+               Lepb = cio_read(cio, 2);\r
+               Depb = cio_read(cio, 1);\r
+               LDPepb = cio_read(cio, 4);\r
+               Pepb = cio_read(cio, 4);\r
+\r
+               if (!status) {\r
+\r
+                       opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL correction could not be performed\n");\r
+\r
+                       /* advance to EPB endpoint */\r
+                       cio_skip(cio, Lepb + 2);  \r
+\r
+                       return;\r
+               }\r
+\r
+               /* last in current header? */\r
+               if (Depb & 0x40) {\r
+                       redund = NULL; /* reset the pointer to L4 buffer */\r
+                       first_in_tph = true;\r
+               }\r
+\r
+               /* advance to EPB endpoint */\r
+               cio_skip(cio, Lepb - 11);  \r
+\r
+       } else {\r
+\r
+               /* Simply read the EPB parameters */\r
+               Lepb = cio_read(cio, 2);\r
+               Depb = cio_read(cio, 1);\r
+               LDPepb = cio_read(cio, 4);\r
+               Pepb = cio_read(cio, 4);\r
+\r
+               /* What does Pepb tells us about the protection method? */\r
+               if (((Pepb & 0xF0000000) >> 28) == 0)\r
+                       sprintf(str1, "pred"); /* predefined */\r
+               else if (((Pepb & 0xF0000000) >> 28) == 1)\r
+                       sprintf(str1, "crc-%lu", 16 * ((Pepb & 0x00000001) + 1)); /* CRC mode */\r
+               else if (((Pepb & 0xF0000000) >> 28) == 2)\r
+                       sprintf(str1, "rs(%lu,32)", (Pepb & 0x0000FF00) >> 8); /* RS mode */\r
+               else if (Pepb == 0xFFFFFFFF)\r
+                       sprintf(str1, "nometh"); /* RS mode */\r
+               else\r
+                       sprintf(str1, "unknown"); /* unknown */\r
+\r
+               /* Now we write them to screen */\r
+               opj_event_msg(j2k->cinfo, EVT_INFO,\r
+                       "EPB(%d): (%sl, %sp, %u), %lu, %s\n",\r
+                       cio_tell(cio) - 13,\r
+                       (Depb & 0x40) ? "" : "n", /* latest EPB or not? */\r
+                       (Depb & 0x80) ? "" : "n", /* packed or unpacked EPB? */\r
+                       (Depb & 0x3F), /* EPB index value */\r
+                       LDPepb, /*length of the data protected by the EPB */\r
+                       str1); /* protection method */\r
+\r
+               cio_skip(cio, Lepb - 11);  \r
+       }\r
+}\r
+\r
+void j2k_write_epb(opj_j2k_t *j2k) {\r
+       unsigned long int LDPepb, Pepb, Lepbp;\r
+       unsigned short int Lepb;\r
+       unsigned char Depb;\r
+\r
+       opj_cio_t *cio = j2k->cio;\r
+\r
+       cio_write(cio, J2K_MS_EPB, 2);  /* EPB */\r
+       Lepbp = cio_tell(cio);\r
+       cio_skip(cio, 2);\r
+\r
+       /* EPB style */\r
+       Depb = 0x00; /* test */\r
+       cio_write(cio, Depb, 1);   /* Depb */\r
+\r
+       /* length of the data to be protected by this EPB */\r
+       LDPepb = 0x00000000; /* test */\r
+       cio_write(cio, LDPepb, 4);   /* LDPepb */\r
+\r
+       /* next error correction tool */\r
+       Pepb = 0x00000000; /* test */\r
+       cio_write(cio, Pepb, 4);   /* Pepb */\r
+\r
+       /* EPB data */\r
+       /* no data, as of now */\r
+\r
+       Lepb = (unsigned short) (cio_tell(cio) - Lepbp);\r
+       cio_seek(cio, Lepbp);\r
+       cio_write(cio, Lepb, 2);                /* Lepb */\r
+\r
+       cio_seek(cio, Lepbp + Lepb);\r
+\r
+       /* marker struct update */\r
+       j2k_add_marker(j2k->cstr_info, J2K_MS_EPB, Lepbp - 2, Lepb + 2);\r
+}\r
+\r
+void j2k_read_esd(opj_j2k_t *j2k) {\r
+       unsigned short int Lesd, Cesd;\r
+       unsigned char Pesd;\r
+\r
+       int cesdsize = (j2k->image->numcomps >= 257) ? 2 : 1;\r
+\r
+       char str1[4][4] = {"p", "br", "pr", "res"};\r
+       char str2[8][8] = {"res", "mse", "mse-r", "psnr", "psnr-i", "maxerr", "tse", "res"};\r
+       \r
+       opj_cio_t *cio = j2k->cio;\r
+\r
+       /* Simply read the ESD parameters */\r
+       Lesd = cio_read(cio, 2);\r
+       Cesd = cio_read(cio, cesdsize);\r
+       Pesd = cio_read(cio, 1);\r
+\r
+       /* Now we write them to screen */\r
+       opj_event_msg(j2k->cinfo, EVT_INFO,\r
+               "ESD(%d): c%d, %s, %s, %s, %s, %s\n",\r
+               cio_tell(cio) - (5 + cesdsize),\r
+               Cesd, /* component number for this ESD */\r
+               str1[(Pesd & (unsigned char) 0xC0) >> 6], /* addressing mode */\r
+               str2[(Pesd & (unsigned char) 0x38) >> 3], /* sensitivity type */\r
+               ((Pesd & (unsigned char) 0x04) >> 2) ? "2Bs" : "1Bs",\r
+               ((Pesd & (unsigned char) 0x02) >> 1) ? "4Ba" : "2Ba",\r
+               (Pesd & (unsigned char) 0x01) ? "avgc" : "");\r
+\r
+       cio_skip(cio, Lesd - (3 + cesdsize));  \r
+}\r
+\r
+void j2k_read_red(opj_j2k_t *j2k) {\r
+       unsigned short int Lred;\r
+       unsigned char Pred;\r
+       char str1[4][4] = {"p", "br", "pr", "res"};\r
+       \r
+       opj_cio_t *cio = j2k->cio;\r
+\r
+       /* Simply read the RED parameters */\r
+       Lred = cio_read(cio, 2);\r
+       Pred = cio_read(cio, 1);\r
+\r
+       /* Now we write them to screen */\r
+       opj_event_msg(j2k->cinfo, EVT_INFO,\r
+               "RED(%d): %s, %dc, %s, %s\n",\r
+               cio_tell(cio) - 5,\r
+               str1[(Pred & (unsigned char) 0xC0) >> 6], /* addressing mode */\r
+               (Pred & (unsigned char) 0x38) >> 3, /* corruption level */\r
+               ((Pred & (unsigned char) 0x02) >> 1) ? "4Ba" : "2Ba", /* address range */\r
+               (Pred & (unsigned char) 0x01) ? "errs" : "free"); /* error free? */\r
+\r
+       cio_skip(cio, Lred - 3);  \r
+}\r
+\r
+bool jpwl_check_tile(opj_j2k_t *j2k, opj_tcd_t *tcd, int tileno) {\r
+\r
+#ifdef oerhgierhgvhreit4u\r
+       /*\r
+          we navigate through the tile and find possible invalid parameters:\r
+       this saves a lot of crashes!!!!!\r
+        */\r
+       int compno, resno, precno, /*layno,*/ bandno, blockno;\r
+       int numprecincts, numblocks;\r
+\r
+       /* this is the selected tile */\r
+       opj_tcd_tile_t *tile = &(tcd->tcd_image->tiles[tileno]);\r
+\r
+       /* will keep the component */\r
+       opj_tcd_tilecomp_t *comp = NULL;\r
+\r
+       /* will keep the resolution */\r
+       opj_tcd_resolution_t *res;\r
+\r
+       /* will keep the subband */\r
+       opj_tcd_band_t *band; \r
+\r
+       /* will keep the precinct */\r
+       opj_tcd_precinct_t *prec; \r
+\r
+       /* will keep the codeblock */\r
+       opj_tcd_cblk_t *block;\r
+\r
+       /* check all tile components */\r
+       for (compno = 0; compno < tile->numcomps; compno++) {\r
+               comp = &(tile->comps[compno]);\r
+\r
+               /* check all component resolutions */\r
+               for (resno = 0; resno < comp->numresolutions; resno++) {\r
+                       res = &(comp->resolutions[resno]);\r
+                       numprecincts = res->pw * res->ph;\r
+\r
+                       /* check all the subbands */\r
+                       for (bandno = 0; bandno < res->numbands; bandno++) {\r
+                               band = &(res->bands[bandno]);\r
+\r
+                               /* check all the precincts */\r
+                               for (precno = 0; precno < numprecincts; precno++) {\r
+                                       prec = &(band->precincts[precno]);\r
+                                       numblocks = prec->ch * prec->cw;\r
+\r
+                                       /* check all the codeblocks */\r
+                                       for (blockno = 0; blockno < numblocks; blockno++) {\r
+                                               block = &(prec->cblks[blockno]);\r
+\r
+                                               /* x-origin is invalid */\r
+                                               if ((block->x0 < prec->x0) || (block->x0 > prec->x1)) {\r
+                                                       opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,\r
+                                                               "JPWL: wrong x-cord of block origin %d => x-prec is (%d, %d)\n",\r
+                                                               block->x0, prec->x0, prec->x1);\r
+                                                       if (!JPWL_ASSUME || JPWL_ASSUME)\r
+                                                               return false;\r
+                                               };\r
+                                       }\r
+                               }                               \r
+                       }\r
+               }\r
+       }\r
+\r
+#endif\r
+\r
+       return true;\r
+}\r
+\r
+/*@}*/\r
+\r
+#endif /* USE_JPWL */\r
+\r
+\r
+#ifdef USE_JPSEC\r
+\r
+/** @defgroup JPSEC JPSEC - JPEG-2000 Part 8 (JPSEC) codestream manager */\r
+/*@{*/\r
+\r
+\r
+/** @name Local static functions */\r
+/*@{*/\r
+\r
+void j2k_read_sec(opj_j2k_t *j2k) {\r
+       unsigned short int Lsec;\r
+       \r
+       opj_cio_t *cio = j2k->cio;\r
+\r
+       /* Simply read the SEC length */\r
+       Lsec = cio_read(cio, 2);\r
+\r
+       /* Now we write them to screen */\r
+       opj_event_msg(j2k->cinfo, EVT_INFO,\r
+               "SEC(%d)\n",\r
+               cio_tell(cio) - 2\r
+               );\r
+\r
+       cio_skip(cio, Lsec - 2);  \r
+}\r
+\r
+void j2k_write_sec(opj_j2k_t *j2k) {\r
+       unsigned short int Lsec = 24;\r
+       int i;\r
+\r
+       opj_cio_t *cio = j2k->cio;\r
+\r
+       cio_write(cio, J2K_MS_SEC, 2);  /* SEC */\r
+       cio_write(cio, Lsec, 2);\r
+\r
+       /* write dummy data */\r
+       for (i = 0; i < Lsec - 2; i++)\r
+               cio_write(cio, 0, 1);\r
+}\r
+\r
+void j2k_read_insec(opj_j2k_t *j2k) {\r
+       unsigned short int Linsec;\r
+       \r
+       opj_cio_t *cio = j2k->cio;\r
+\r
+       /* Simply read the INSEC length */\r
+       Linsec = cio_read(cio, 2);\r
+\r
+       /* Now we write them to screen */\r
+       opj_event_msg(j2k->cinfo, EVT_INFO,\r
+               "INSEC(%d)\n",\r
+               cio_tell(cio) - 2\r
+               );\r
+\r
+       cio_skip(cio, Linsec - 2);  \r
+}\r
+\r
+\r
+/*@}*/\r
+\r
+/*@}*/\r
+\r
+#endif /* USE_JPSEC */\r
+\r
diff --git a/libopenjpeg/jpwl/jpwl.h b/libopenjpeg/jpwl/jpwl.h
new file mode 100644 (file)
index 0000000..d1d066c
--- /dev/null
@@ -0,0 +1,425 @@
+/*
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef __JPWL_H
+#define __JPWL_H
+
+#ifdef USE_JPWL
+
+#include "crc.h"
+#include "rs.h"
+
+/**
+@file jpwl.h
+@brief The JPEG-2000 Part11 (JPWL) marker segments manager
+
+The functions in JPWL.C have for goal to read/write the markers added by JPWL.
+*/
+
+/** @defgroup JPWL JPWL - JPEG-2000 Part11 (JPWL) codestream manager */
+/*@{*/
+
+/**
+Assume a basic codestream structure, so you can resort better from uncorrected errors
+*/
+#define JPWL_ASSUME true
+
+/**
+EPB (Error Protection Block) Marker segment
+*/
+typedef struct jpwl_epb_ms {
+       /**@name Private fields set by epb_create */
+       /*@{*/
+       /** is the latest in header? */
+       bool latest;
+       /** is it in packed mode? */
+       bool packed;
+       /** TH where this marker has been placed (-1 means MH) */
+       int tileno;
+       /** index in current header (0-63) */
+       unsigned char index;
+       /** error protection method     [-1=absent 0=none 1=predefined 16=CRC-16 32=CRC-32 37-128=RS] */
+       int hprot;
+       /** message word length of pre-data */
+       int k_pre;
+       /** code word length of pre-data */
+       int n_pre;
+       /** length of pre-data */
+       int pre_len;
+       /** message word length of post-data */
+       int k_post;
+       /** code word length of post-data */
+       int n_post;
+       /** length of post-data */
+       int post_len;
+       /*@}*/
+       /**@name Marker segment fields */
+       /*@{*/
+       /** two bytes for the length of EPB MS, exluding the marker itself (11 to 65535 bytes) */
+       unsigned short int Lepb;
+       /** single byte for the style */
+       unsigned char Depb; 
+       /** four bytes, from 0 to 2^31-1 */
+       unsigned long int LDPepb;
+       /** four bytes, next error management method */
+       unsigned long int Pepb;
+       /** EPB data, variable size */
+       unsigned char *data;   
+       /*@}*/
+}      jpwl_epb_ms_t;
+
+/**
+EPC (Error Protection Capability) Marker segment
+*/
+typedef struct jpwl_epc_ms {
+       /** is ESD active? */
+       bool esd_on;
+       /** is RED active? */
+       bool red_on;
+       /** is EPB active? */
+       bool epb_on;
+       /** are informative techniques active? */
+       bool info_on;
+       /**@name Marker segment fields */
+       /*@{*/
+       /** two bytes for the length of EPC MS, exluding the marker itself (9 to 65535 bytes) */
+       unsigned short int Lepc;   
+       /** two bytes, CRC for the EPC, excluding Pcrc itself */
+       unsigned short int Pcrc;   
+       /** four bytes, the codestream length from SOC to EOC */
+       unsigned long int DL;     
+       /** one byte, signals JPWL techniques adoption */
+       unsigned char Pepc;     
+       /** EPC data, variable length */
+       unsigned char *data;    
+       /*@}*/
+}      jpwl_epc_ms_t;
+
+/**
+ESD (Error Sensitivity Descriptor) Marker segment
+*/
+typedef struct jpwl_esd_ms {
+       /** codestream addressing mode [0=packet, 1=byte range, 2=packet range, 3=reserved] */
+       unsigned char addrm;
+       /** size of codestream addresses [2/4 bytes] */
+       unsigned char ad_size;
+       /** type of sensitivity
+       [0=relative error, 1=MSE, 2=MSE reduction, 3=PSNR, 4=PSNR increment,
+       5=MAXERR (absolute peak error), 6=TSE (total squared error), 7=reserved */
+       unsigned char senst;
+       /** size of sensitivity data (1/2 bytes) */
+       unsigned char se_size;
+       /**@name Marker segment fields */
+       /*@{*/
+       /** two bytes for the length of ESD MS, exluding the marker itself (4 to 65535 bytes) */
+       unsigned short int Lesd;   
+       /** two bytes, component of error sensitivity */
+       unsigned short int Cesd;
+       /** one byte, signals JPWL techniques adoption */
+       unsigned char Pesd;     
+       /** ESD data, variable length */
+       unsigned char *data;    
+       /*@}*/
+       /**@name Fields set by esd_create (only internal use) */
+       /*@{*/
+       /** number of components in the image */
+       int numcomps;
+       /** tile where this marker has been placed (-1 means MH) */
+       int tileno;
+       /** number of sensitivity values */
+       unsigned long int svalnum;
+       /** size of a single sensitivity pair (address+value) */
+       size_t sensval_size;
+       /*@}*/
+}      jpwl_esd_ms_t;
+
+/**
+RED (Residual Error Descriptor) Marker segment
+*/
+typedef struct jpwl_red_ms {
+       /** two bytes for the length of RED MS, exluding the marker itself (3 to 65535 bytes) */
+       unsigned short int Lred;
+       /** one byte, signals JPWL techniques adoption */
+       unsigned char Pred;     
+       /** RED data, variable length */
+       unsigned char *data;    
+}      jpwl_red_ms_t;
+
+/**
+Structure used to store JPWL markers temporary position and readyness
+*/
+typedef struct jpwl_marker {
+       /** marker value (J2K_MS_EPC, etc.) */
+       int id;
+       /** union keeping the pointer to the real marker struct */
+       union jpwl_marks {
+               /** pointer to EPB marker */
+               jpwl_epb_ms_t *epbmark;
+               /** pointer to EPC marker */
+               jpwl_epc_ms_t *epcmark;
+               /** pointer to ESD marker */
+               jpwl_esd_ms_t *esdmark;
+               /** pointer to RED marker */
+               jpwl_red_ms_t *redmark;
+       } m;
+       /** position where the marker should go, in the pre-JPWL codestream */ 
+       unsigned long int pos;
+       /** same as before, only written as a double, so we can sort it better */
+       double dpos;
+       /** length of the marker segment (marker excluded) */
+       unsigned short int len;
+       /** the marker length is ready or not? */
+       bool len_ready;
+       /** the marker position is ready or not? */
+       bool pos_ready;
+       /** the marker parameters are ready or not? */
+       bool parms_ready;
+       /** are the written data ready or not */
+       bool data_ready;
+}      jpwl_marker_t;
+
+/**
+Encode according to JPWL specs
+@param j2k J2K handle
+@param cio codestream handle
+@param image image handle
+*/
+void jpwl_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image);
+
+/**
+Prepare the list of JPWL markers, after the Part 1 codestream
+has been finalized (index struct is full)
+@param j2k J2K handle
+@param cio codestream handle
+@param image image handle
+*/
+void jpwl_prepare_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image);
+
+/**
+Dump the list of JPWL markers, after it has been prepared
+@param j2k J2K handle
+@param cio codestream handle
+@param image image handle
+*/
+void jpwl_dump_marks(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image);
+
+/**
+Read the EPC marker (Error Protection Capability)
+@param j2k J2K handle
+*/
+void j2k_read_epc(opj_j2k_t *j2k);
+
+/**
+Write the EPC marker (Error Protection Capability), BUT the DL field is always set to 0
+(this simplifies the management of EPBs and it is openly stated in the standard
+as a possible value, mening that the information is not available) and the informative techniques
+are not yet implemented
+@param j2k J2K handle
+*/
+void j2k_write_epc(opj_j2k_t *j2k);
+
+/**
+Read the EPB marker (Error Protection Block)
+@param j2k J2K handle
+*/
+void j2k_read_epb(opj_j2k_t *j2k);
+
+/**
+Write the EPB marker (Error Protection Block)
+@param j2k J2K handle
+*/
+void j2k_write_epb(opj_j2k_t *j2k);
+
+/**
+Read the ESD marker (Error Sensitivity Descriptor)
+@param j2k J2K handle
+*/
+void j2k_read_esd(opj_j2k_t *j2k);
+
+/**
+Read the RED marker (Residual Error Descriptor)
+@param j2k J2K handle
+*/
+void j2k_read_red(opj_j2k_t *j2k);
+
+/** create an EPB marker segment
+@param j2k J2K compressor handle
+@param latest it is the latest EPB in the header
+@param packed EPB is in packed style
+@param tileno tile number where the marker has been placed (-1 means MH)
+@param idx current EPB running index
+@param hprot applied protection type (-1/0,1,16,32,37-128)
+@param pre_len length of pre-protected data
+@param post_len length of post-protected data
+@return returns the freshly created EPB
+*/
+jpwl_epb_ms_t *jpwl_epb_create(opj_j2k_t *j2k, bool latest, bool packed, int tileno, int idx, int hprot,
+                                                          unsigned long int pre_len, unsigned long int post_len);
+
+/** add a number of EPB marker segments
+@param j2k J2K compressor handle
+@param jwmarker pointer to the JPWL markers list
+@param jwmarker_num pointer to the number of JPWL markers (gets updated)
+@param latest it is the latest group of EPBs in the header
+@param packed EPBs are in packed style
+@param insideMH it is in the MH
+@param idx pointer to the starting EPB running index (gets updated)
+@param hprot applied protection type (-1/0,1,16,32,37-128)
+@param place_pos place in original codestream where EPBs should go
+@param tileno tile number of these EPBs
+@param pre_len length of pre-protected data
+@param post_len length of post-protected data
+@return returns the length of all added markers
+*/
+int jpwl_epbs_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num,
+                                 bool latest, bool packed, bool insideMH, int *idx, int hprot,
+                                 double place_pos, int tileno,
+                                 unsigned long int pre_len, unsigned long int post_len);
+
+/** add a number of ESD marker segments
+@param j2k J2K compressor handle
+@param jwmarker pointer to the JPWL markers list
+@param jwmarker_num pointer to the number of JPWL markers (gets updated)
+@param comps considered component (-1=average, 0/1/2/...=component no.)
+@param addrm addressing mode (0=packet, 1=byte range, 2=packet range, 3=reserved)
+@param ad_size size of addresses (2/4 bytes)
+@param senst sensitivity type
+@param se_size sensitivity values size (1/2 bytes)
+@param place_pos place in original codestream where EPBs should go
+@param tileno tile number of these EPBs
+@return returns the length of all added markers
+*/
+int jpwl_esds_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num,
+                                 int comps, unsigned char addrm, unsigned char ad_size,
+                                 unsigned char senst, unsigned char se_size,
+                                 double place_pos, int tileno);
+       
+/** updates the information structure by modifying the positions and lengths
+@param j2k J2K compressor handle
+@param jwmarker pointer to JPWL markers list
+@param jwmarker_num number of JPWL markers
+@return returns true in case of success
+*/                       
+bool jpwl_update_info(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int jwmarker_num);
+
+
+bool jpwl_esd_fill(opj_j2k_t *j2k, jpwl_esd_ms_t *esdmark, unsigned char *buf);
+
+bool jpwl_epb_fill(opj_j2k_t *j2k, jpwl_epb_ms_t *epbmark, unsigned char *buf, unsigned char *post_buf);
+
+void j2k_add_marker(opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len);
+
+/** corrects the data in the JPWL codestream
+@param j2k J2K compressor handle
+@return true if correction is performed correctly
+*/
+bool jpwl_correct(opj_j2k_t *j2k);
+
+/** corrects the data protected by an EPB
+@param j2k J2K compressor handle
+@param buffer pointer to the EPB position
+@param type type of EPB: 0=MH, 1=TPH, 2=other, 3=auto
+@param pre_len length of pre-data
+@param post_len length of post_data
+@param conn is a pointer to the length of all connected (packed) EPBs
+@param L4_bufp is a pointer to the buffer pointer of redundancy data
+@return returns true if correction could be succesfully performed
+*/
+bool jpwl_epb_correct(opj_j2k_t *j2k, unsigned char *buffer, int type, int pre_len, int post_len, int *conn,
+                                         unsigned char **L4_bufp);
+
+/** check that a tile and its children have valid data
+@param j2k J2K decompressor handle
+@param tcd Tile decompressor handle
+@param tileno number of the tile to check
+*/
+bool jpwl_check_tile(opj_j2k_t *j2k, opj_tcd_t *tcd, int tileno);
+
+/** Macro functions for CRC computation */
+
+/**
+Computes the CRC-16, as stated in JPWL specs
+@param CRC two bytes containing the CRC value (must be initialized with 0x0000)
+@param DATA byte for which the CRC is computed; call this on every byte of the sequence
+and get the CRC at the end
+*/
+#define jpwl_updateCRC16(CRC, DATA) updateCRC16(CRC, DATA)
+
+/**
+Computes the CRC-32, as stated in JPWL specs
+@param CRC four bytes containing the CRC value (must be initialized with 0x00000000)
+@param DATA byte for which the CRC is computed; call this on every byte of the sequence
+and get the CRC at the end
+*/
+#define jpwl_updateCRC32(CRC, DATA) updateCRC32(CRC, DATA)
+
+/**
+Computes the minimum between two integers
+@param a first integer to compare
+@param b second integer to compare
+@return returns the minimum integer between a and b
+*/
+#ifndef min
+#define min(a,b)    (((a) < (b)) ? (a) : (b))
+#endif /* min */
+
+/*@}*/
+
+#endif /* USE_JPWL */
+
+#ifdef USE_JPSEC
+
+/** @defgroup JPSEC JPSEC - JPEG-2000 Part 8 (JPSEC) codestream manager */
+/*@{*/
+
+/**
+Read the SEC marker (SEcured Codestream)
+@param j2k J2K handle
+*/
+void j2k_read_sec(opj_j2k_t *j2k);
+
+/**
+Write the SEC marker (SEcured Codestream)
+@param j2k J2K handle
+*/
+void j2k_write_sec(opj_j2k_t *j2k);
+
+/**
+Read the INSEC marker (SEcured Codestream)
+@param j2k J2K handle
+*/
+void j2k_read_insec(opj_j2k_t *j2k);
+
+/*@}*/
+
+#endif /* USE_JPSEC */
+
+#endif /* __JPWL_H */
+
diff --git a/libopenjpeg/jpwl/jpwl_lib.c b/libopenjpeg/jpwl/jpwl_lib.c
new file mode 100644 (file)
index 0000000..ea53c93
--- /dev/null
@@ -0,0 +1,1796 @@
+/*
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifdef USE_JPWL
+
+#include "../libopenjpeg/opj_includes.h"
+#include <limits.h>
+
+/** Minimum and maximum values for the double->pfp conversion */
+#define MIN_V1 0.0
+#define MAX_V1 17293822569102704640.0
+#define MIN_V2 0.000030517578125
+#define MAX_V2 131040.0
+
+/** conversion between a double precision floating point
+number and the corresponding pseudo-floating point used 
+to represent sensitivity values
+@param V the double precision value
+@param bytes the number of bytes of the representation
+@return the pseudo-floating point value (cast accordingly)
+*/
+unsigned short int jpwl_double_to_pfp(double V, int bytes);
+
+/** conversion between a pseudo-floating point used 
+to represent sensitivity values and the corresponding
+double precision floating point number  
+@param em the pseudo-floating point value (cast accordingly)
+@param bytes the number of bytes of the representation
+@return the double precision value
+*/
+double jpwl_pfp_to_double(unsigned short int em, int bytes);
+
+       /*-------------------------------------------------------------*/
+
+int jpwl_markcomp(const void *arg1, const void *arg2)
+{
+   /* Compare the two markers' positions */
+   double diff = (((jpwl_marker_t *) arg1)->dpos - ((jpwl_marker_t *) arg2)->dpos);
+
+   if (diff == 0.0)
+          return (0);
+   else if (diff < 0)
+          return (-1);
+   else
+          return (+1);
+}
+
+int jpwl_epbs_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num,
+                                 bool latest, bool packed, bool insideMH, int *idx, int hprot,
+                                 double place_pos, int tileno,
+                                 unsigned long int pre_len, unsigned long int post_len) {
+
+       jpwl_epb_ms_t *epb_mark = NULL;
+
+       int k_pre, k_post, n_pre, n_post;
+       
+       unsigned long int L1, L2, dL4, max_postlen, epbs_len = 0;
+
+       /* We find RS(n,k) for EPB parms and pre-data, if any */
+       if (insideMH && (*idx == 0)) {
+               /* First EPB in MH */ 
+               k_pre = 64;
+               n_pre = 160;
+       } else if (!insideMH && (*idx == 0)) {
+               /* First EPB in TH */
+               k_pre = 25;
+               n_pre = 80;
+       } else {
+               /* Following EPBs in MH or TH */
+               k_pre = 13;
+               n_pre = 40;
+       };
+
+       /* Find lengths, Figs. B3 and B4 */
+       /* size of pre data: pre_buf(pre_len) + EPB(2) + Lepb(2) + Depb(1) + LDPepb(4) + Pepb(4) */
+       L1 = pre_len + 13;
+
+       /* size of pre-data redundancy */
+       /*   (redundancy per codeword)       *     (number of codewords, rounded up)   */
+       L2 = (n_pre - k_pre) * (unsigned long int) ceil((double) L1 / (double) k_pre);
+
+       /* Find protection type for post data and its associated redundancy field length*/
+       if ((hprot == 16) || (hprot == 32)) {
+               /* there is a CRC for post-data */
+               k_post = post_len;
+               n_post = post_len + (hprot >> 3);
+               /*L3 = hprot >> 3;*/ /* 2 (CRC-16) or 4 (CRC-32) bytes */
+
+       } else if ((hprot >= 37) && (hprot <= 128)) {
+               /* there is a RS for post-data */
+               k_post = 32;
+               n_post = hprot;
+
+       } else {
+               /* Use predefined codes */
+               n_post = n_pre;
+               k_post = k_pre;
+       };
+
+       /* Create the EPB(s) */
+       while (post_len > 0) {
+
+               /* maximum postlen in order to respect EPB size
+               (we use JPWL_MAXIMUM_EPB_ROOM instead of 65535 for keeping room for EPB parms)*/
+               /*      (message word size)    *            (number of containable parity words)  */
+               max_postlen = k_post * (unsigned long int) floor((double) JPWL_MAXIMUM_EPB_ROOM / (double) (n_post - k_post));
+
+               /* maximum postlen in order to respect EPB size */
+               if (*idx == 0)
+                       /* (we use (JPWL_MAXIMUM_EPB_ROOM - L2) instead of 65535 for keeping room for EPB parms + pre-data) */
+                       /*      (message word size)    *                   (number of containable parity words)  */
+                       max_postlen = k_post * (unsigned long int) floor((double) (JPWL_MAXIMUM_EPB_ROOM - L2) / (double) (n_post - k_post));
+
+               else
+                       /* (we use JPWL_MAXIMUM_EPB_ROOM instead of 65535 for keeping room for EPB parms) */
+                       /*      (message word size)    *            (number of containable parity words)  */
+                       max_postlen = k_post * (unsigned long int) floor((double) JPWL_MAXIMUM_EPB_ROOM / (double) (n_post - k_post));
+
+               /* null protection case */
+               /* the max post length can be as large as the LDPepb field can host */
+               if (hprot == 0)
+                       max_postlen = INT_MAX;
+               
+               /* length to use */
+               dL4 = min(max_postlen, post_len);
+
+               if ((epb_mark = jpwl_epb_create(
+                       j2k, /* this encoder handle */
+                       latest ? (dL4 < max_postlen) : false, /* is it the latest? */
+                       packed, /* is it packed? */
+                       tileno, /* we are in TPH */
+                       *idx, /* its index */
+                       hprot, /* protection type parameters of following data */
+                       0, /* pre-data: nothing for now */
+                       dL4 /* post-data: the stub computed previously */
+                       ))) {
+                       
+                       /* Add this marker to the 'insertanda' list */
+                       if (*jwmarker_num < JPWL_MAX_NO_MARKERS) {
+                               jwmarker[*jwmarker_num].id = J2K_MS_EPB; /* its type */
+                               jwmarker[*jwmarker_num].m.epbmark = epb_mark; /* the EPB */
+                               jwmarker[*jwmarker_num].pos = (int) place_pos; /* after SOT */
+                               jwmarker[*jwmarker_num].dpos = place_pos + 0.0000001 * (double)(*idx); /* not very first! */
+                               jwmarker[*jwmarker_num].len = epb_mark->Lepb; /* its length */
+                               jwmarker[*jwmarker_num].len_ready = true; /* ready */
+                               jwmarker[*jwmarker_num].pos_ready = true; /* ready */
+                               jwmarker[*jwmarker_num].parms_ready = true; /* ready */
+                               jwmarker[*jwmarker_num].data_ready = false; /* not ready */
+                               (*jwmarker_num)++;
+                       }
+
+                       /* increment epb index */
+                       (*idx)++;
+
+                       /* decrease postlen */
+                       post_len -= dL4;
+
+                       /* increase the total length of EPBs */
+                       epbs_len += epb_mark->Lepb + 2;
+
+               } else {
+                       /* ooops, problems */
+                       opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not create TPH EPB for UEP in tile %d\n", tileno);                          
+               };
+       }
+
+       return epbs_len;
+}
+
+
+jpwl_epb_ms_t *jpwl_epb_create(opj_j2k_t *j2k, bool latest, bool packed, int tileno, int idx, int hprot,
+                                                 unsigned long int pre_len, unsigned long int post_len) {
+
+       jpwl_epb_ms_t *epb = NULL;
+       /*unsigned short int data_len = 0;*/
+       unsigned short int L2, L3;
+       unsigned long int L1, L4;
+       /*unsigned char *predata_in = NULL;*/
+
+       bool insideMH = (tileno == -1);
+
+       /* Alloc space */
+       if (!(epb = (jpwl_epb_ms_t *) opj_malloc((size_t) 1 * sizeof (jpwl_epb_ms_t)))) {
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for one EPB MS\n");
+               return NULL;
+       };
+
+       /* We set RS(n,k) for EPB parms and pre-data, if any */
+       if (insideMH && (idx == 0)) {
+               /* First EPB in MH */ 
+               epb->k_pre = 64;
+               epb->n_pre = 160;
+       } else if (!insideMH && (idx == 0)) {
+               /* First EPB in TH */
+               epb->k_pre = 25;
+               epb->n_pre = 80;
+       } else {
+               /* Following EPBs in MH or TH */
+               epb->k_pre = 13;
+               epb->n_pre = 40;
+       };
+
+       /* Find lengths, Figs. B3 and B4 */
+       /* size of pre data: pre_buf(pre_len) + EPB(2) + Lepb(2) + Depb(1) + LDPepb(4) + Pepb(4) */
+       L1 = pre_len + 13;
+       epb->pre_len = pre_len;
+
+       /* size of pre-data redundancy */
+       /*   (redundancy per codeword)       *               (number of codewords, rounded up)   */
+       L2 = (epb->n_pre - epb->k_pre) * (unsigned short int) ceil((double) L1 / (double) epb->k_pre);
+
+       /* length of post-data */
+       L4 = post_len;
+       epb->post_len = post_len;
+
+       /* Find protection type for post data and its associated redundancy field length*/
+       if ((hprot == 16) || (hprot == 32)) {
+               /* there is a CRC for post-data */
+               epb->Pepb = 0x10000000 | ((unsigned long int) hprot >> 5); /* 0=CRC-16, 1=CRC-32 */
+               epb->k_post = post_len;
+               epb->n_post = post_len + (hprot >> 3);
+               /*L3 = hprot >> 3;*/ /* 2 (CRC-16) or 4 (CRC-32) bytes */
+
+       } else if ((hprot >= 37) && (hprot <= 128)) {
+               /* there is a RS for post-data */
+               epb->Pepb = 0x20000020 | (((unsigned long int) hprot & 0x000000FF) << 8);
+               epb->k_post = 32;
+               epb->n_post = hprot;
+
+       } else if (hprot == 1) {
+               /* Use predefined codes */
+               epb->Pepb = (unsigned long int) 0x00000000;
+               epb->n_post = epb->n_pre;
+               epb->k_post = epb->k_pre;
+       
+       } else if (hprot == 0) {
+               /* Placeholder EPB: only protects its parameters, no protection method */
+               epb->Pepb = (unsigned long int) 0xFFFFFFFF;
+               epb->n_post = 1;
+               epb->k_post = 1;
+       
+       } else {
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Invalid protection value for EPB h = %d\n", hprot);                               
+               return NULL;
+       }
+
+       epb->hprot = hprot;
+
+       /*   (redundancy per codeword)          *                (number of codewords, rounded up) */
+       L3 = (epb->n_post - epb->k_post) * (unsigned short int) ceil((double) L4 / (double) epb->k_post);
+
+       /* private fields */
+       epb->tileno = tileno;
+
+       /* Fill some fields of the EPB */
+
+       /* total length of the EPB MS (less the EPB marker itself): */
+       /* Lepb(2) + Depb(1) + LDPepb(4) + Pepb(4) + pre_redundancy + post-redundancy */
+       epb->Lepb = 11 + L2 + L3;
+
+       /* EPB style */
+       epb->Depb = ((packed & 0x0001) << 7) | ((latest & 0x0001) << 6) | (idx & 0x003F);
+
+       /* length of data protected by EPB: */
+       epb->LDPepb = L1 + L4;
+
+       return epb;
+}
+
+void jpwl_epb_write(opj_j2k_t *j2k, jpwl_epb_ms_t *epb, unsigned char *buf) {
+
+       /* Marker */
+       *(buf++) = (unsigned char) (J2K_MS_EPB >> 8); 
+       *(buf++) = (unsigned char) (J2K_MS_EPB >> 0); 
+
+       /* Lepb */
+       *(buf++) = (unsigned char) (epb->Lepb >> 8); 
+       *(buf++) = (unsigned char) (epb->Lepb >> 0); 
+
+       /* Depb */
+       *(buf++) = (unsigned char) (epb->Depb >> 0); 
+
+       /* LDPepb */
+       *(buf++) = (unsigned char) (epb->LDPepb >> 24); 
+       *(buf++) = (unsigned char) (epb->LDPepb >> 16); 
+       *(buf++) = (unsigned char) (epb->LDPepb >> 8); 
+       *(buf++) = (unsigned char) (epb->LDPepb >> 0); 
+
+       /* Pepb */
+       *(buf++) = (unsigned char) (epb->Pepb >> 24); 
+       *(buf++) = (unsigned char) (epb->Pepb >> 16); 
+       *(buf++) = (unsigned char) (epb->Pepb >> 8); 
+       *(buf++) = (unsigned char) (epb->Pepb >> 0); 
+
+       /* Data */
+       /*memcpy(buf, epb->data, (size_t) epb->Lepb - 11);*/
+       memset(buf, 0, (size_t) epb->Lepb - 11);
+
+       /* update markers struct */
+       j2k_add_marker(j2k->cstr_info, J2K_MS_EPB, -1, epb->Lepb + 2);
+
+};
+
+
+jpwl_epc_ms_t *jpwl_epc_create(opj_j2k_t *j2k, bool esd_on, bool red_on, bool epb_on, bool info_on) {
+
+       jpwl_epc_ms_t *epc = NULL;
+
+       /* Alloc space */
+       if (!(epc = (jpwl_epc_ms_t *) opj_malloc((size_t) 1 * sizeof (jpwl_epc_ms_t)))) {
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for EPC MS\n");
+               return NULL;
+       };
+
+       /* Set the EPC parameters */
+       epc->esd_on = esd_on;
+       epc->epb_on = epb_on;
+       epc->red_on = red_on;
+       epc->info_on = info_on;
+
+       /* Fill the EPC fields with default values */
+       epc->Lepc = 9;
+       epc->Pcrc = 0x0000;
+       epc->DL = 0x00000000;
+       epc->Pepc = ((j2k->cp->esd_on & 0x0001) << 4) | ((j2k->cp->red_on & 0x0001) << 5) |
+               ((j2k->cp->epb_on & 0x0001) << 6) | ((j2k->cp->info_on & 0x0001) << 7);
+
+       return (epc);
+}
+
+bool jpwl_epb_fill(opj_j2k_t *j2k, jpwl_epb_ms_t *epb, unsigned char *buf, unsigned char *post_buf) {
+
+       unsigned long int L1, L2, L3, L4;
+       int remaining;
+       unsigned long int P, NN_P;
+
+       /* Operating buffer */
+       static unsigned char codeword[NN], *parityword;
+
+       unsigned char *L1_buf, *L2_buf;
+       /* these ones are static, since we need to keep memory of
+        the exact place from one call to the other */
+       static unsigned char *L3_buf, *L4_buf;
+
+       /* some consistency check */
+       if (!buf) {
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "There is no operating buffer for EPBs\n");
+               return false;
+       }
+
+       if (!post_buf && !L4_buf) {
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "There is no operating buffer for EPBs data\n");
+               return false;
+       }
+
+       /*
+        * Compute parity bytes on pre-data, ALWAYS present (at least only for EPB parms)
+        */
+
+       /* Initialize RS structures */
+       P = epb->n_pre - epb->k_pre;
+       NN_P = NN - P;
+       memset(codeword, 0, NN);
+       parityword = codeword + NN_P;
+       init_rs(NN_P);
+
+       /* pre-data begins pre_len bytes before of EPB buf */
+       L1_buf = buf - epb->pre_len;
+       L1 = epb->pre_len + 13;
+
+       /* redundancy for pre-data begins immediately after EPB parms */
+       L2_buf = buf + 13;
+       L2 = (epb->n_pre - epb->k_pre) * (unsigned short int) ceil((double) L1 / (double) epb->k_pre);
+
+       /* post-data
+          the position of L4 buffer can be:
+            1) passed as a parameter: in that case use it
+            2) null: in that case use the previous (static) one
+       */
+       if (post_buf)
+               L4_buf = post_buf;
+       L4 = epb->post_len;
+
+       /* post-data redundancy begins immediately after pre-data redundancy */
+       L3_buf = L2_buf + L2;
+       L3 = (epb->n_post - epb->k_post) * (unsigned short int) ceil((double) L4 / (double) epb->k_post);
+
+       /* let's check whether EPB length is sufficient to contain all these data */
+       if (epb->Lepb < (11 + L2 + L3))
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "There is no room in EPB data field for writing redundancy data\n");
+       /*printf("Env. %d, nec. %d (%d + %d)\n", epb->Lepb - 11, L2 + L3, L2, L3);*/
+
+       /* Compute redundancy of pre-data message words */
+       remaining = L1;
+       while (remaining) {
+
+               /* copy message data into codeword buffer */
+               if (remaining < epb->k_pre) {
+                       /* the last message word is zero-padded */
+                       memset(codeword, 0, NN);
+                       memcpy(codeword, L1_buf, remaining);
+                       L1_buf += remaining;
+                       remaining = 0;
+
+               } else {
+                       memcpy(codeword, L1_buf, epb->k_pre);
+                       L1_buf += epb->k_pre;
+                       remaining -= epb->k_pre;
+
+               }
+
+               /* Encode the buffer and obtain parity bytes */
+               if (encode_rs(codeword, parityword))
+                       opj_event_msg(j2k->cinfo, EVT_WARNING,
+                               "Possible encoding error in codeword @ position #%d\n", (L1_buf - buf) / epb->k_pre);
+
+               /* copy parity bytes only in redundancy buffer */
+               memcpy(L2_buf, parityword, P); 
+
+               /* advance parity buffer */
+               L2_buf += P;
+       }
+
+       /*
+        * Compute parity bytes on post-data, may be absent if there are no data
+        */
+       /*printf("Hprot is %d (tileno=%d, k_pre=%d, n_pre=%d, k_post=%d, n_post=%d, pre_len=%d, post_len=%d)\n",
+               epb->hprot, epb->tileno, epb->k_pre, epb->n_pre, epb->k_post, epb->n_post, epb->pre_len,
+               epb->post_len);*/
+       if (epb->hprot < 0) {
+
+               /* there should be no EPB */
+               
+       } else if (epb->hprot == 0) {
+
+               /* no protection for the data */
+               /* advance anyway */
+               L4_buf += epb->post_len;
+
+       } else if (epb->hprot == 16) {
+
+               /* CRC-16 */
+               unsigned short int mycrc = 0x0000;
+
+               /* compute the CRC field (excluding itself) */
+               remaining = L4;
+               while (remaining--)
+                       jpwl_updateCRC16(&mycrc, *(L4_buf++));
+
+               /* write the CRC field */
+               *(L3_buf++) = (unsigned char) (mycrc >> 8);
+               *(L3_buf++) = (unsigned char) (mycrc >> 0);
+
+       } else if (epb->hprot == 32) {
+
+               /* CRC-32 */
+               unsigned long int mycrc = 0x00000000;
+
+               /* compute the CRC field (excluding itself) */
+               remaining = L4;
+               while (remaining--)
+                       jpwl_updateCRC32(&mycrc, *(L4_buf++));
+
+               /* write the CRC field */
+               *(L3_buf++) = (unsigned char) (mycrc >> 24);
+               *(L3_buf++) = (unsigned char) (mycrc >> 16);
+               *(L3_buf++) = (unsigned char) (mycrc >> 8);
+               *(L3_buf++) = (unsigned char) (mycrc >> 0);
+
+       } else {
+
+               /* RS */
+
+               /* Initialize RS structures */
+               P = epb->n_post - epb->k_post;
+               NN_P = NN - P;
+               memset(codeword, 0, NN);
+               parityword = codeword + NN_P;
+               init_rs(NN_P);
+
+               /* Compute redundancy of post-data message words */
+               remaining = L4;
+               while (remaining) {
+
+                       /* copy message data into codeword buffer */
+                       if (remaining < epb->k_post) {
+                               /* the last message word is zero-padded */
+                               memset(codeword, 0, NN);
+                               memcpy(codeword, L4_buf, remaining);
+                               L4_buf += remaining;
+                               remaining = 0;
+
+                       } else {
+                               memcpy(codeword, L4_buf, epb->k_post);
+                               L4_buf += epb->k_post;
+                               remaining -= epb->k_post;
+
+                       }
+
+                       /* Encode the buffer and obtain parity bytes */
+                       if (encode_rs(codeword, parityword))
+                               opj_event_msg(j2k->cinfo, EVT_WARNING,
+                                       "Possible encoding error in codeword @ position #%d\n", (L4_buf - buf) / epb->k_post);
+
+                       /* copy parity bytes only in redundancy buffer */
+                       memcpy(L3_buf, parityword, P); 
+
+                       /* advance parity buffer */
+                       L3_buf += P;
+               }
+
+       }
+
+       return true;
+}
+
+
+bool jpwl_correct(opj_j2k_t *j2k) {
+
+       opj_cio_t *cio = j2k->cio;
+       bool status;
+       static bool mh_done = false;
+       int mark_pos, id, len, skips, sot_pos;
+       unsigned long int Psot = 0;
+
+       /* go back to marker position */
+       mark_pos = cio_tell(cio) - 2;
+       cio_seek(cio, mark_pos);
+
+       if ((j2k->state == J2K_STATE_MHSOC) && !mh_done) {
+
+               int mark_val = 0, skipnum = 0;
+
+               /*
+                 COLOR IMAGE
+                 first thing to do, if we are here, is to look whether
+                 51 (skipnum) positions ahead there is an EPB, in case of MH
+               */
+               /*
+                 B/W IMAGE
+                 first thing to do, if we are here, is to look whether
+                 45 (skipnum) positions ahead there is an EPB, in case of MH
+               */
+               /*       SIZ   SIZ_FIELDS     SIZ_COMPS               FOLLOWING_MARKER */
+               skipnum = 2  +     38     + 3 * j2k->cp->exp_comps  +         2;
+               if ((cio->bp + skipnum) < cio->end) {
+
+                       cio_skip(cio, skipnum);
+
+                       /* check that you are not going beyond the end of codestream */
+
+                       /* call EPB corrector */
+                       status = jpwl_epb_correct(j2k,     /* J2K decompressor handle */
+                                                                         cio->bp, /* pointer to EPB in codestream buffer */
+                                                                         0,       /* EPB type: MH */
+                                                                         skipnum,      /* length of pre-data */
+                                                                         -1,      /* length of post-data: -1 means auto */
+                                                                         NULL,
+                                                                         NULL
+                                                                        );
+
+                       /* read the marker value */
+                       mark_val = (*(cio->bp) << 8) | *(cio->bp + 1);
+
+                       if (status && (mark_val == J2K_MS_EPB)) {
+                               /* we found it! */
+                               mh_done = true;
+                               return true;
+                       }
+
+                       /* Disable correction in case of missing or bad head EPB */
+                       /* We can't do better! */
+                       /* PATCHED: 2008-01-25 */
+                       /* MOVED UP: 2008-02-01 */
+                       if (!status) {
+                               j2k->cp->correct = false;
+                               opj_event_msg(j2k->cinfo, EVT_WARNING, "Couldn't find the MH EPB: disabling JPWL\n");
+                       }
+
+               }
+
+       }
+
+       if (true /*(j2k->state == J2K_STATE_TPHSOT) || (j2k->state == J2K_STATE_TPH)*/) {
+               /* else, look if 12 positions ahead there is an EPB, in case of TPH */
+               cio_seek(cio, mark_pos);
+               if ((cio->bp + 12) < cio->end) {
+
+                       cio_skip(cio, 12);
+
+                       /* call EPB corrector */
+                       status = jpwl_epb_correct(j2k,     /* J2K decompressor handle */
+                                                                         cio->bp, /* pointer to EPB in codestream buffer */
+                                                                         1,       /* EPB type: TPH */
+                                                                         12,      /* length of pre-data */
+                                                                         -1,      /* length of post-data: -1 means auto */
+                                                                         NULL,
+                                                                         NULL
+                                                                        );
+                       if (status)
+                               /* we found it! */
+                               return true;
+               }
+       }
+
+       return false;
+
+       /* for now, don't use this code */
+
+       /* else, look if here is an EPB, in case of other */
+       if (mark_pos > 64) {
+               /* it cannot stay before the first MH EPB */
+               cio_seek(cio, mark_pos);
+               cio_skip(cio, 0);
+
+               /* call EPB corrector */
+               status = jpwl_epb_correct(j2k,     /* J2K decompressor handle */
+                                                                 cio->bp, /* pointer to EPB in codestream buffer */
+                                                                 2,       /* EPB type: TPH */
+                                                                 0,       /* length of pre-data */
+                                                                 -1,      /* length of post-data: -1 means auto */
+                                                                 NULL,
+                                                                 NULL
+                                                                );
+               if (status)
+                       /* we found it! */
+                       return true;
+       }
+
+       /* nope, no EPBs probably, or they are so damaged that we can give up */
+       return false;
+       
+       return true;
+
+       /* AN ATTEMPT OF PARSER */
+       /* NOT USED ACTUALLY    */
+
+       /* go to the beginning of the file */
+       cio_seek(cio, 0);
+
+       /* let's begin */
+       j2k->state = J2K_STATE_MHSOC;
+
+       /* cycle all over the markers */
+       while (cio_tell(cio) < cio->length) {
+
+               /* read the marker */
+               mark_pos = cio_tell(cio);
+               id = cio_read(cio, 2);
+
+               /* details */
+               printf("Marker@%d: %X\n", cio_tell(cio) - 2, id);
+
+               /* do an action in response to the read marker */
+               switch (id) {
+
+               /* short markers */
+
+                       /* SOC */
+               case J2K_MS_SOC:
+                       j2k->state = J2K_STATE_MHSIZ;
+                       len = 0;
+                       skips = 0;
+                       break;
+
+                       /* EOC */
+               case J2K_MS_EOC:
+                       j2k->state = J2K_STATE_MT;
+                       len = 0;
+                       skips = 0;
+                       break;
+
+                       /* particular case of SOD */
+               case J2K_MS_SOD:
+                       len = Psot - (mark_pos - sot_pos) - 2;
+                       skips = len;
+                       break;
+
+               /* long markers */
+
+                       /* SOT */
+               case J2K_MS_SOT:
+                       j2k->state = J2K_STATE_TPH;
+                       sot_pos = mark_pos; /* position of SOT */
+                       len = cio_read(cio, 2); /* read the length field */
+                       cio_skip(cio, 2); /* this field is unnecessary */
+                       Psot = cio_read(cio, 4); /* tile length */
+                       skips = len - 8;
+                       break;
+
+                       /* remaining */
+               case J2K_MS_SIZ:
+                       j2k->state = J2K_STATE_MH;
+                       /* read the length field */
+                       len = cio_read(cio, 2);
+                       skips = len - 2;
+                       break;
+
+                       /* remaining */
+               default:
+                       /* read the length field */
+                       len = cio_read(cio, 2);
+                       skips = len - 2;
+                       break;
+
+               }
+
+               /* skip to marker's end */
+               cio_skip(cio, skips);   
+
+       }
+
+
+}
+
+bool jpwl_epb_correct(opj_j2k_t *j2k, unsigned char *buffer, int type, int pre_len, int post_len, int *conn,
+                                         unsigned char **L4_bufp) {
+
+       /* Operating buffer */
+       unsigned char codeword[NN], *parityword;
+
+       unsigned long int P, NN_P;
+       unsigned long int L1, L4;
+       int remaining, n_pre, k_pre, n_post, k_post;
+
+       int status, tt;
+
+       int orig_pos = cio_tell(j2k->cio);
+
+       unsigned char *L1_buf, *L2_buf;
+       unsigned char *L3_buf, *L4_buf;
+
+       unsigned long int LDPepb, Pepb;
+       unsigned short int Lepb;
+       unsigned char Depb;
+       char str1[25] = "";
+       int myconn, errnum = 0;
+       bool errflag = false;
+       
+       opj_cio_t *cio = j2k->cio;
+
+       /* check for common errors */
+       if (!buffer) {
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "The EPB pointer is a NULL buffer\n");
+               return false;
+       }
+       
+       /* set bignesses */
+       L1 = pre_len + 13;
+
+       /* pre-data correction */
+       switch (type) {
+
+       case 0:
+               /* MH EPB */
+               k_pre = 64;
+               n_pre = 160;
+               break;
+
+       case 1:
+               /* TPH EPB */
+               k_pre = 25;
+               n_pre = 80;
+               break;
+
+       case 2:
+               /* other EPBs */
+               k_pre = 13;
+               n_pre = 40;
+               break;
+
+       case 3:
+               /* automatic setup */
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Auto. setup not yet implemented\n");
+               return false;
+               break;
+
+       default:
+               /* unknown type */
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Unknown expected EPB type\n");
+               return false;
+               break;
+
+       }
+
+       /* Initialize RS structures */
+       P = n_pre - k_pre;
+       NN_P = NN - P;
+       tt = (int) floor((float) P / 2.0F); /* correction capability of the code */
+       memset(codeword, 0, NN);
+       parityword = codeword + NN_P;
+       init_rs(NN_P);
+
+       /* Correct pre-data message words */
+       L1_buf = buffer - pre_len;
+       L2_buf = buffer + 13;
+       remaining = L1;
+       while (remaining) {
+               /* always zero-pad codewords */
+               /* (this is required, since after decoding the zeros in the long codeword
+                   could change, and keep unchanged in subsequent calls) */
+               memset(codeword, 0, NN);
+
+               /* copy codeword buffer into message bytes */
+               if (remaining < k_pre)
+                       memcpy(codeword, L1_buf, remaining);
+               else
+                       memcpy(codeword, L1_buf, k_pre);
+
+               /* copy redundancy buffer in parity bytes */
+               memcpy(parityword, L2_buf, P); 
+
+               /* Decode the buffer and possibly obtain corrected bytes */
+               status = eras_dec_rs(codeword, NULL, 0);
+               if (status == -1) {
+                       /*if (conn == NULL)
+                               opj_event_msg(j2k->cinfo, EVT_WARNING,
+                                       "Possible decoding error in codeword @ position #%d\n", (L1_buf - buffer) / k_pre);*/
+                       errflag = true;
+                       /* we can try to safely get out from the function:
+                         if we are here, either this is not an EPB or the first codeword
+                         is too damaged to be helpful */
+                       /*return false;*/
+
+               } else if (status == 0) {
+                       /*if (conn == NULL)
+                               opj_event_msg(j2k->cinfo, EVT_INFO, "codeword is correctly decoded\n");*/
+
+               } else if (status <= tt) {
+                       /* it has corrected 0 <= errs <= tt */
+                       /*if (conn == NULL)
+                               opj_event_msg(j2k->cinfo, EVT_WARNING, "%d errors corrected in codeword\n", status);*/
+                       errnum += status;
+
+               } else {
+                       /*if (conn == NULL)
+                               opj_event_msg(j2k->cinfo, EVT_WARNING, "EPB correction capability exceeded\n");
+                       return false;*/
+                       errflag = true;
+               }
+
+
+               /* advance parity buffer */
+               if ((status >= 0) && (status <= tt))
+                       /* copy back corrected parity only if all is OK */
+                       memcpy(L2_buf, parityword, P);
+               L2_buf += P;
+
+               /* advance message buffer */
+               if (remaining < k_pre) {
+                       if ((status >= 0) && (status <= tt))
+                               /* copy back corrected data only if all is OK */
+                               memcpy(L1_buf, codeword, remaining);
+                       L1_buf += remaining;
+                       remaining = 0;
+
+               } else {
+                       if ((status >= 0) && (status <= tt))
+                               /* copy back corrected data only if all is OK */
+                               memcpy(L1_buf, codeword, k_pre);
+                       L1_buf += k_pre;
+                       remaining -= k_pre;
+
+               }
+       }
+
+       /* print summary */
+       if (!conn) {
+
+               /*if (errnum)
+                       opj_event_msg(j2k->cinfo, EVT_INFO, "+ %d symbol errors corrected (Ps=%.1e)\n", errnum,
+                               (float) errnum / ((float) n_pre * (float) L1 / (float) k_pre));*/
+               if (errflag) {
+                       /*opj_event_msg(j2k->cinfo, EVT_INFO, "+ there were unrecoverable errors\n");*/
+                       return false;
+               }
+
+       }
+
+       /* presumably, now, EPB parameters are correct */
+       /* let's get them */
+
+       /* Simply read the EPB parameters */
+       if (conn)
+               cio->bp = buffer;
+       cio_skip(cio, 2); /* the marker */
+       Lepb = cio_read(cio, 2);
+       Depb = cio_read(cio, 1);
+       LDPepb = cio_read(cio, 4);
+       Pepb = cio_read(cio, 4);
+
+       /* What does Pepb tells us about the protection method? */
+       if (((Pepb & 0xF0000000) >> 28) == 0)
+               sprintf(str1, "pred"); /* predefined */
+       else if (((Pepb & 0xF0000000) >> 28) == 1)
+               sprintf(str1, "crc-%lu", 16 * ((Pepb & 0x00000001) + 1)); /* CRC mode */
+       else if (((Pepb & 0xF0000000) >> 28) == 2)
+               sprintf(str1, "rs(%lu,32)", (Pepb & 0x0000FF00) >> 8); /* RS mode */
+       else if (Pepb == 0xFFFFFFFF)
+               sprintf(str1, "nometh"); /* RS mode */
+       else
+               sprintf(str1, "unknown"); /* unknown */
+
+       /* Now we write them to screen */
+       if (!conn && post_len)
+               opj_event_msg(j2k->cinfo, EVT_INFO,
+                       "EPB(%d): (%sl, %sp, %u), %lu, %s\n",
+                       cio_tell(cio) - 13,
+                       (Depb & 0x40) ? "" : "n", /* latest EPB or not? */
+                       (Depb & 0x80) ? "" : "n", /* packed or unpacked EPB? */
+                       (Depb & 0x3F), /* EPB index value */
+                       LDPepb, /*length of the data protected by the EPB */
+                       str1); /* protection method */
+
+
+       /* well, we need to investigate how long is the connected length of packed EPBs */
+       myconn = Lepb + 2;
+       if ((Depb & 0x40) == 0) /* not latest in header */
+               jpwl_epb_correct(j2k,      /* J2K decompressor handle */
+                                            buffer + Lepb + 2,   /* pointer to next EPB in codestream buffer */
+                                            2,     /* EPB type: should be of other type */
+                                            0,  /* only EPB fields */
+                                            0, /* do not look after */
+                                                &myconn,
+                                                NULL
+                                            );
+       if (conn)
+               *conn += myconn;
+
+       /*if (!conn)
+               printf("connected = %d\n", myconn);*/
+
+       /*cio_seek(j2k->cio, orig_pos);
+       return true;*/
+
+       /* post-data
+          the position of L4 buffer is at the end of currently connected EPBs
+       */
+       if (!(L4_bufp))
+               L4_buf = buffer + myconn;
+       else if (!(*L4_bufp))
+               L4_buf = buffer + myconn;
+       else
+               L4_buf = *L4_bufp;
+       if (post_len == -1) 
+               L4 = LDPepb - pre_len - 13;
+       else if (post_len == 0)
+               L4 = 0;
+       else
+               L4 = post_len;
+
+       L3_buf = L2_buf;
+
+       /* Do a further check here on the read parameters */
+       if (L4 > (unsigned long) cio_numbytesleft(j2k->cio))
+               /* overflow */
+               return false;
+
+       /* we are ready for decoding the remaining data */
+       if (((Pepb & 0xF0000000) >> 28) == 1) {
+               /* CRC here */
+               if ((16 * ((Pepb & 0x00000001) + 1)) == 16) {
+
+                       /* CRC-16 */
+                       unsigned short int mycrc = 0x0000, filecrc = 0x0000;
+
+                       /* compute the CRC field */
+                       remaining = L4;
+                       while (remaining--)
+                               jpwl_updateCRC16(&mycrc, *(L4_buf++));
+
+                       /* read the CRC field */
+                       filecrc = *(L3_buf++) << 8;
+                       filecrc |= *(L3_buf++);
+
+                       /* check the CRC field */
+                       if (mycrc == filecrc) {
+                               if (conn == NULL)
+                                       opj_event_msg(j2k->cinfo, EVT_INFO, "- CRC is OK\n");
+                       } else {
+                               if (conn == NULL)
+                                       opj_event_msg(j2k->cinfo, EVT_WARNING, "- CRC is KO (r=%d, c=%d)\n", filecrc, mycrc);
+                               errflag = true;
+                       }       
+               }
+
+               if ((16 * ((Pepb & 0x00000001) + 1)) == 32) {
+
+                       /* CRC-32 */
+                       unsigned long int mycrc = 0x00000000, filecrc = 0x00000000;
+
+                       /* compute the CRC field */
+                       remaining = L4;
+                       while (remaining--)
+                               jpwl_updateCRC32(&mycrc, *(L4_buf++));
+
+                       /* read the CRC field */
+                       filecrc = *(L3_buf++) << 24;
+                       filecrc |= *(L3_buf++) << 16;
+                       filecrc |= *(L3_buf++) << 8;
+                       filecrc |= *(L3_buf++);
+
+                       /* check the CRC field */
+                       if (mycrc == filecrc) {
+                               if (conn == NULL)
+                                       opj_event_msg(j2k->cinfo, EVT_INFO, "- CRC is OK\n");
+                       } else {
+                               if (conn == NULL)
+                                       opj_event_msg(j2k->cinfo, EVT_WARNING, "- CRC is KO (r=%d, c=%d)\n", filecrc, mycrc);
+                               errflag = true;
+                       }
+               }
+
+       } else if (Pepb == 0xFFFFFFFF) {
+               /* no method */
+
+               /* advance without doing anything */
+               remaining = L4;
+               while (remaining--)
+                       L4_buf++;
+
+       } else if ((((Pepb & 0xF0000000) >> 28) == 2) || (((Pepb & 0xF0000000) >> 28) == 0)) {
+               /* RS coding here */
+
+               if (((Pepb & 0xF0000000) >> 28) == 0) {
+
+                       k_post = k_pre;
+                       n_post = n_pre;
+
+               } else {
+
+                       k_post = 32;
+                       n_post = (Pepb & 0x0000FF00) >> 8;
+               }
+
+               /* Initialize RS structures */
+               P = n_post - k_post;
+               NN_P = NN - P;
+               tt = (int) floor((float) P / 2.0F); /* again, correction capability */
+               memset(codeword, 0, NN);
+               parityword = codeword + NN_P;
+               init_rs(NN_P);
+
+               /* Correct post-data message words */
+               /*L4_buf = buffer + Lepb + 2;*/
+               L3_buf = L2_buf;
+               remaining = L4;
+               while (remaining) {
+                       /* always zero-pad codewords */
+                       /* (this is required, since after decoding the zeros in the long codeword
+                               could change, and keep unchanged in subsequent calls) */
+                       memset(codeword, 0, NN);
+
+                       /* copy codeword buffer into message bytes */
+                       if (remaining < k_post)
+                               memcpy(codeword, L4_buf, remaining);
+                       else
+                               memcpy(codeword, L4_buf, k_post);
+
+                       /* copy redundancy buffer in parity bytes */
+                       memcpy(parityword, L3_buf, P); 
+
+                       /* Decode the buffer and possibly obtain corrected bytes */
+                       status = eras_dec_rs(codeword, NULL, 0);
+                       if (status == -1) {
+                               /*if (conn == NULL)
+                                       opj_event_msg(j2k->cinfo, EVT_WARNING,
+                                               "Possible decoding error in codeword @ position #%d\n", (L4_buf - (buffer + Lepb + 2)) / k_post);*/
+                               errflag = true;
+
+                       } else if (status == 0) {
+                               /*if (conn == NULL)
+                                       opj_event_msg(j2k->cinfo, EVT_INFO, "codeword is correctly decoded\n");*/
+
+                       } else if (status <= tt) {
+                               /*if (conn == NULL)
+                                       opj_event_msg(j2k->cinfo, EVT_WARNING, "%d errors corrected in codeword\n", status);*/
+                               errnum += status;
+
+                       } else {
+                               /*if (conn == NULL)
+                                       opj_event_msg(j2k->cinfo, EVT_WARNING, "EPB correction capability exceeded\n");
+                               return false;*/
+                               errflag = true;
+                       }
+
+
+                       /* advance parity buffer */
+                       if ((status >= 0) && (status <= tt))
+                               /* copy back corrected data only if all is OK */
+                               memcpy(L3_buf, parityword, P);
+                       L3_buf += P;
+
+                       /* advance message buffer */
+                       if (remaining < k_post) {
+                               if ((status >= 0) && (status <= tt))
+                                       /* copy back corrected data only if all is OK */
+                                       memcpy(L4_buf, codeword, remaining);
+                               L4_buf += remaining;
+                               remaining = 0;
+
+                       } else {
+                               if ((status >= 0) && (status <= tt))
+                                       /* copy back corrected data only if all is OK */
+                                       memcpy(L4_buf, codeword, k_post);
+                               L4_buf += k_post;
+                               remaining -= k_post;
+
+                       }
+               }
+       }
+
+       /* give back the L4_buf address */
+       if (L4_bufp)
+               *L4_bufp = L4_buf;
+
+       /* print summary */
+       if (!conn) {
+
+               if (errnum)
+                       opj_event_msg(j2k->cinfo, EVT_INFO, "- %d symbol errors corrected (Ps=%.1e)\n", errnum,
+                               (float) errnum / (float) LDPepb);
+               if (errflag)
+                       opj_event_msg(j2k->cinfo, EVT_INFO, "- there were unrecoverable errors\n");
+
+       }
+
+       cio_seek(j2k->cio, orig_pos);
+
+       return true;
+}
+
+void jpwl_epc_write(opj_j2k_t *j2k, jpwl_epc_ms_t *epc, unsigned char *buf) {
+
+       /* Marker */
+       *(buf++) = (unsigned char) (J2K_MS_EPC >> 8); 
+       *(buf++) = (unsigned char) (J2K_MS_EPC >> 0); 
+
+       /* Lepc */
+       *(buf++) = (unsigned char) (epc->Lepc >> 8); 
+       *(buf++) = (unsigned char) (epc->Lepc >> 0); 
+
+       /* Pcrc */
+       *(buf++) = (unsigned char) (epc->Pcrc >> 8); 
+       *(buf++) = (unsigned char) (epc->Pcrc >> 0);
+
+       /* DL */
+       *(buf++) = (unsigned char) (epc->DL >> 24); 
+       *(buf++) = (unsigned char) (epc->DL >> 16); 
+       *(buf++) = (unsigned char) (epc->DL >> 8); 
+       *(buf++) = (unsigned char) (epc->DL >> 0); 
+
+       /* Pepc */
+       *(buf++) = (unsigned char) (epc->Pepc >> 0); 
+
+       /* Data */
+       /*memcpy(buf, epc->data, (size_t) epc->Lepc - 9);*/
+       memset(buf, 0, (size_t) epc->Lepc - 9);
+
+       /* update markers struct */
+       j2k_add_marker(j2k->cstr_info, J2K_MS_EPC, -1, epc->Lepc + 2);
+
+};
+
+int jpwl_esds_add(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int *jwmarker_num,
+                                 int comps, unsigned char addrm, unsigned char ad_size,
+                                 unsigned char senst, unsigned char se_size,
+                                 double place_pos, int tileno) {
+
+       return 0;
+}
+
+jpwl_esd_ms_t *jpwl_esd_create(opj_j2k_t *j2k, int comp, unsigned char addrm, unsigned char ad_size,
+                                                               unsigned char senst, unsigned char se_size, int tileno,
+                                                               unsigned long int svalnum, void *sensval) {
+
+       jpwl_esd_ms_t *esd = NULL;
+
+       /* Alloc space */
+       if (!(esd = (jpwl_esd_ms_t *) opj_malloc((size_t) 1 * sizeof (jpwl_esd_ms_t)))) {
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not allocate room for ESD MS\n");
+               return NULL;
+       };
+
+       /* if relative sensitivity, activate byte range mode */
+       if (senst == 0)
+               addrm = 1;
+
+       /* size of sensval's ... */
+       if ((ad_size != 0) && (ad_size != 2) && (ad_size != 4)) {
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Address size %d for ESD MS is forbidden\n", ad_size);
+               return NULL;
+       }
+       if ((se_size != 1) && (se_size != 2)) {
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Sensitivity size %d for ESD MS is forbidden\n", se_size);
+               return NULL;
+       }
+       
+       /* ... depends on the addressing mode */
+       switch (addrm) {
+
+       /* packet mode */
+       case (0):
+               ad_size = 0; /* as per the standard */
+               esd->sensval_size = se_size; 
+               break;
+
+       /* byte range */
+       case (1):
+               /* auto sense address size */
+               if (ad_size == 0)
+                       /* if there are more than 66% of (2^16 - 1) bytes, switch to 4 bytes
+                        (we keep space for possible EPBs being inserted) */
+                       ad_size = (j2k->cstr_info->codestream_size > (1 * 65535 / 3)) ? 4 : 2;
+               esd->sensval_size = ad_size + ad_size + se_size; 
+               break;
+
+       /* packet range */
+       case (2):
+               /* auto sense address size */
+               if (ad_size == 0)
+                       /* if there are more than 2^16 - 1 packets, switch to 4 bytes */
+                       ad_size = (j2k->cstr_info->packno > 65535) ? 4 : 2;
+               esd->sensval_size = ad_size + ad_size + se_size; 
+               break;
+
+       case (3):
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Address mode %d for ESD MS is unimplemented\n", addrm);
+               return NULL;
+
+       default:
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "Address mode %d for ESD MS is forbidden\n", addrm);
+               return NULL;
+       }
+
+       /* set or unset sensitivity values */
+       if (svalnum <= 0) {
+
+               switch (senst) {
+
+               /* just based on the portions of a codestream */
+               case (0):
+                       /* MH + no. of THs + no. of packets */
+                       svalnum = 1 + (j2k->cstr_info->tw * j2k->cstr_info->th) * (1 + j2k->cstr_info->packno);
+                       break;
+
+               /* all the ones that are based on the packets */
+               default:
+                       if (tileno < 0)
+                               /* MH: all the packets and all the tiles info is written */
+                               svalnum = j2k->cstr_info->tw * j2k->cstr_info->th * j2k->cstr_info->packno;
+                       else
+                               /* TPH: only that tile info is written */
+                               svalnum = j2k->cstr_info->packno;
+                       break;
+
+               }
+       }               
+
+       /* fill private fields */
+       esd->senst = senst;
+       esd->ad_size = ad_size;
+       esd->se_size = se_size;
+       esd->addrm = addrm;
+       esd->svalnum = svalnum;
+       esd->numcomps = j2k->image->numcomps;
+       esd->tileno = tileno;
+       
+       /* Set the ESD parameters */
+       /* length, excluding data field */
+       if (esd->numcomps < 257)
+               esd->Lesd = 4 + (unsigned short int) (esd->svalnum * esd->sensval_size);
+       else
+               esd->Lesd = 5 + (unsigned short int) (esd->svalnum * esd->sensval_size);
+
+       /* component data field */
+       if (comp >= 0)
+               esd->Cesd = comp;
+       else
+               /* we are averaging */
+               esd->Cesd = 0;
+
+       /* Pesd field */
+       esd->Pesd = 0x00;
+       esd->Pesd |= (esd->addrm & 0x03) << 6; /* addressing mode */
+       esd->Pesd |= (esd->senst & 0x07) << 3; /* sensitivity type */
+       esd->Pesd |= ((esd->se_size >> 1) & 0x01) << 2; /* sensitivity size */
+       esd->Pesd |= ((esd->ad_size >> 2) & 0x01) << 1; /* addressing size */
+       esd->Pesd |= (comp < 0) ? 0x01 : 0x00; /* averaging components */
+
+       /* if pointer to sensval is NULL, we can fill data field by ourselves */
+       if (!sensval) {
+
+               /* old code moved to jpwl_esd_fill() */
+               esd->data = NULL;
+
+       } else {
+                       /* we set the data field as the sensitivity values poinnter passed to the function */
+                       esd->data = (unsigned char *) sensval;
+       }
+
+       return (esd);
+}
+
+bool jpwl_esd_fill(opj_j2k_t *j2k, jpwl_esd_ms_t *esd, unsigned char *buf) {
+
+       int i;
+       unsigned long int vv;
+       unsigned long int addr1 = 0L, addr2 = 0L;
+       double dvalue = 0.0, Omax2, tmp, TSE = 0.0, MSE, oldMSE = 0.0, PSNR, oldPSNR = 0.0;
+       unsigned short int pfpvalue;
+       unsigned long int addrmask = 0x00000000;
+       bool doneMH = false, doneTPH = false;
+
+       /* sensitivity values in image info are as follows:
+               - for each tile, distotile is the starting distortion for that tile, sum of all components
+               - for each packet in a tile, disto is the distortion reduction caused by that packet to that tile
+               - the TSE for a single tile should be given by   distotile - sum(disto)  , for all components
+               - the MSE for a single tile is given by     TSE / nbpix    , for all components
+               - the PSNR for a single tile is given by   10*log10( Omax^2 / MSE)    , for all components
+                 (Omax is given by    2^bpp - 1    for unsigned images and by    2^(bpp - 1) - 1    for signed images
+       */
+
+       /* browse all components and find Omax */
+       Omax2 = 0.0;
+       for (i = 0; i < j2k->image->numcomps; i++) {
+               tmp = pow(2.0, (double) (j2k->image->comps[i].sgnd ?
+                       (j2k->image->comps[i].bpp - 1) : (j2k->image->comps[i].bpp))) - 1;
+               if (tmp > Omax2)
+                       Omax2 = tmp;
+       }
+       Omax2 = Omax2 * Omax2;
+
+       /* if pointer of esd->data is not null, simply write down all the values byte by byte */
+       if (esd->data) {
+               for (i = 0; i < (int) esd->svalnum; i++)
+                       *(buf++) = esd->data[i]; 
+               return true;
+       }
+
+       /* addressing mask */
+       if (esd->ad_size == 2)
+               addrmask = 0x0000FFFF; /* two bytes */
+       else
+               addrmask = 0xFFFFFFFF; /* four bytes */
+
+       /* set on precise point where sensitivity starts */
+       if (esd->numcomps < 257)
+               buf += 6;
+       else
+               buf += 7;
+
+       /* let's fill the data fields */
+       for (vv = (esd->tileno < 0) ? 0 : (j2k->cstr_info->packno * esd->tileno); vv < esd->svalnum; vv++) {
+
+               int thistile = vv / j2k->cstr_info->packno, thispacket = vv % j2k->cstr_info->packno;
+
+               /* skip for the hack some lines below */
+               if (thistile == j2k->cstr_info->tw * j2k->cstr_info->th)
+                       break;
+
+               /* starting tile distortion */
+               if (thispacket == 0) {
+                       TSE = j2k->cstr_info->tile[thistile].distotile;
+                       oldMSE = TSE / j2k->cstr_info->tile[thistile].numpix;
+                       oldPSNR = 10.0 * log10(Omax2 / oldMSE);
+               }
+
+               /* TSE */
+               TSE -= j2k->cstr_info->tile[thistile].packet[thispacket].disto;
+
+               /* MSE */
+               MSE = TSE / j2k->cstr_info->tile[thistile].numpix;
+
+               /* PSNR */
+               PSNR = 10.0 * log10(Omax2 / MSE);
+
+               /* fill the address range */
+               switch (esd->addrm) {
+
+               /* packet mode */
+               case (0):
+                       /* nothing, there is none */
+                       break;
+
+               /* byte range */
+               case (1):
+                       /* start address of packet */
+                       addr1 = (j2k->cstr_info->tile[thistile].packet[thispacket].start_pos) & addrmask;
+                       /* end address of packet */
+                       addr2 = (j2k->cstr_info->tile[thistile].packet[thispacket].end_pos) & addrmask;
+                       break;
+
+               /* packet range */
+               case (2):
+                       /* not implemented here */
+                       opj_event_msg(j2k->cinfo, EVT_WARNING, "Addressing mode packet_range is not implemented\n");
+                       break;
+
+               /* unknown addressing method */
+               default:
+                       /* not implemented here */
+                       opj_event_msg(j2k->cinfo, EVT_WARNING, "Unknown addressing mode\n");
+                       break;
+
+               }
+
+               /* hack for writing relative sensitivity of MH and TPHs */
+               if ((esd->senst == 0) && (thispacket == 0)) {
+
+                       /* possible MH */
+                       if ((thistile == 0) && !doneMH) {
+                               /* we have to manage MH addresses */
+                               addr1 = 0; /* start of MH */
+                               addr2 = j2k->cstr_info->main_head_end; /* end of MH */
+                               /* set special dvalue for this MH */
+                               dvalue = -10.0;
+                               doneMH = true; /* don't come here anymore */
+                               vv--; /* wrap back loop counter */
+
+                       } else if (!doneTPH) {
+                               /* we have to manage TPH addresses */
+                               addr1 = j2k->cstr_info->tile[thistile].start_pos;
+                               addr2 = j2k->cstr_info->tile[thistile].end_header;
+                               /* set special dvalue for this TPH */
+                               dvalue = -1.0;
+                               doneTPH = true; /* don't come here till the next tile */
+                               vv--; /* wrap back loop counter */
+                       }
+
+               } else
+                       doneTPH = false; /* reset TPH counter */
+
+               /* write the addresses to the buffer */
+               switch (esd->ad_size) {
+
+               case (0):
+                       /* do nothing */
+                       break;
+
+               case (2):
+                       /* two bytes */
+                       *(buf++) = (unsigned char) (addr1 >> 8); 
+                       *(buf++) = (unsigned char) (addr1 >> 0); 
+                       *(buf++) = (unsigned char) (addr2 >> 8); 
+                       *(buf++) = (unsigned char) (addr2 >> 0); 
+                       break;
+
+               case (4):
+                       /* four bytes */
+                       *(buf++) = (unsigned char) (addr1 >> 24); 
+                       *(buf++) = (unsigned char) (addr1 >> 16); 
+                       *(buf++) = (unsigned char) (addr1 >> 8); 
+                       *(buf++) = (unsigned char) (addr1 >> 0); 
+                       *(buf++) = (unsigned char) (addr2 >> 24); 
+                       *(buf++) = (unsigned char) (addr2 >> 16); 
+                       *(buf++) = (unsigned char) (addr2 >> 8); 
+                       *(buf++) = (unsigned char) (addr2 >> 0); 
+                       break;
+
+               default:
+                       /* do nothing */
+                       break;
+               }
+
+
+               /* let's fill the value field */
+               switch (esd->senst) {
+
+               /* relative sensitivity */
+               case (0):
+                       /* we just write down the packet ordering */
+                       if (dvalue == -10)
+                               /* MH */
+                               dvalue = MAX_V1 + 1000.0; /* this will cause pfpvalue set to 0xFFFF */
+                       else if (dvalue == -1)
+                               /* TPH */
+                               dvalue = MAX_V1 + 1000.0; /* this will cause pfpvalue set to 0xFFFF */
+                       else
+                               /* packet: first is most important, and then in decreasing order
+                               down to the last, which counts for 1 */
+                               dvalue = jpwl_pfp_to_double((unsigned short) (j2k->cstr_info->packno - thispacket), esd->se_size);
+                       break;
+
+               /* MSE */
+               case (1):
+                       /* !!! WRONG: let's put here disto field of packets !!! */
+                       dvalue = MSE;
+                       break;
+
+               /* MSE reduction */
+               case (2):
+                       dvalue = oldMSE - MSE;
+                       oldMSE = MSE;
+                       break;
+
+               /* PSNR */
+               case (3):
+                       dvalue = PSNR;
+                       break;
+
+               /* PSNR increase */
+               case (4):
+                       dvalue = PSNR - oldPSNR;
+                       oldPSNR = PSNR;
+                       break;
+
+               /* MAXERR */
+               case (5):
+                       dvalue = 0.0;
+                       opj_event_msg(j2k->cinfo, EVT_WARNING, "MAXERR sensitivity mode is not implemented\n");
+                       break;
+
+               /* TSE */
+               case (6):
+                       dvalue = TSE;
+                       break;
+
+               /* reserved */
+               case (7):
+                       dvalue = 0.0;
+                       opj_event_msg(j2k->cinfo, EVT_WARNING, "Reserved sensitivity mode is not implemented\n");
+                       break;
+
+               default:
+                       dvalue = 0.0;
+                       break;
+               }
+
+               /* compute the pseudo-floating point value */
+               pfpvalue = jpwl_double_to_pfp(dvalue, esd->se_size);
+
+               /* write the pfp value to the buffer */
+               switch (esd->se_size) {
+
+               case (1):
+                       /* one byte */
+                       *(buf++) = (unsigned char) (pfpvalue >> 0); 
+                       break;
+
+               case (2):
+                       /* two bytes */
+                       *(buf++) = (unsigned char) (pfpvalue >> 8); 
+                       *(buf++) = (unsigned char) (pfpvalue >> 0); 
+                       break;
+               }
+
+       }
+
+       return true;
+}
+
+void jpwl_esd_write(opj_j2k_t *j2k, jpwl_esd_ms_t *esd, unsigned char *buf) {
+
+       /* Marker */
+       *(buf++) = (unsigned char) (J2K_MS_ESD >> 8); 
+       *(buf++) = (unsigned char) (J2K_MS_ESD >> 0); 
+
+       /* Lesd */
+       *(buf++) = (unsigned char) (esd->Lesd >> 8); 
+       *(buf++) = (unsigned char) (esd->Lesd >> 0); 
+
+       /* Cesd */
+       if (esd->numcomps >= 257)
+               *(buf++) = (unsigned char) (esd->Cesd >> 8); 
+       *(buf++) = (unsigned char) (esd->Cesd >> 0); 
+
+       /* Pesd */
+       *(buf++) = (unsigned char) (esd->Pesd >> 0); 
+
+       /* Data */
+       if (esd->numcomps < 257)
+               memset(buf, 0xAA, (size_t) esd->Lesd - 4);
+               /*memcpy(buf, esd->data, (size_t) esd->Lesd - 4);*/
+       else
+               memset(buf, 0xAA, (size_t) esd->Lesd - 5);
+               /*memcpy(buf, esd->data, (size_t) esd->Lesd - 5);*/
+
+       /* update markers struct */
+       j2k_add_marker(j2k->cstr_info, J2K_MS_ESD, -1, esd->Lesd + 2);
+
+}
+
+unsigned short int jpwl_double_to_pfp(double V, int bytes) {
+
+       unsigned short int em, e, m;
+
+       switch (bytes) {
+
+       case (1):
+
+               if (V < MIN_V1) {
+                       e = 0x0000;
+                       m = 0x0000;
+               } else if (V > MAX_V1) {
+                       e = 0x000F;
+                       m = 0x000F;
+               } else {
+                       e = (unsigned short int) (floor(log(V) * 1.44269504088896) / 4.0);
+                       m = (unsigned short int) (0.5 + (V / (pow(2.0, (double) (4 * e)))));
+               }
+               em = ((e & 0x000F) << 4) + (m & 0x000F);                
+               break;
+
+       case (2):
+
+               if (V < MIN_V2) {
+                       e = 0x0000;
+                       m = 0x0000;
+               } else if (V > MAX_V2) {
+                       e = 0x001F;
+                       m = 0x07FF;
+               } else {
+                       e = (unsigned short int) floor(log(V) * 1.44269504088896) + 15;
+                       m = (unsigned short int) (0.5 + 2048.0 * ((V / (pow(2.0, (double) e - 15.0))) - 1.0));
+               }
+               em = ((e & 0x001F) << 11) + (m & 0x07FF);
+               break;
+
+       default:
+
+               em = 0x0000;
+               break;
+       };
+
+       return em;
+}
+
+double jpwl_pfp_to_double(unsigned short int em, int bytes) {
+
+       double V;
+
+       switch (bytes) {
+
+       case 1:
+               V = (double) (em & 0x0F) * pow(2.0, (double) (em & 0xF0));
+               break;
+
+       case 2:
+
+               V = pow(2.0, (double) ((em & 0xF800) >> 11) - 15.0) * (1.0 + (double) (em & 0x07FF) / 2048.0);
+               break;
+
+       default:
+               V = 0.0;
+               break;
+
+       }
+
+       return V;
+
+}
+
+bool jpwl_update_info(opj_j2k_t *j2k, jpwl_marker_t *jwmarker, int jwmarker_num) {
+
+       int mm;
+       unsigned long int addlen;
+
+       opj_codestream_info_t *info = j2k->cstr_info;
+       int tileno, tpno, packno, numtiles = info->th * info->tw, numpacks = info->packno;
+
+       if (!j2k || !jwmarker ) {
+               opj_event_msg(j2k->cinfo, EVT_ERROR, "J2K handle or JPWL markers list badly allocated\n");
+               return false;
+       }
+
+       /* main_head_end: how many markers are there before? */
+       addlen = 0;
+       for (mm = 0; mm < jwmarker_num; mm++)
+               if (jwmarker[mm].pos < (unsigned long int) info->main_head_end)
+                       addlen += jwmarker[mm].len + 2;
+       info->main_head_end += addlen;
+
+       /* codestream_size: always increment with all markers */
+       addlen = 0;
+       for (mm = 0; mm < jwmarker_num; mm++)
+               addlen += jwmarker[mm].len + 2;
+       info->codestream_size += addlen;
+
+       /* navigate through all the tiles */
+       for (tileno = 0; tileno < numtiles; tileno++) {
+
+               /* start_pos: increment with markers before SOT */
+               addlen = 0;
+               for (mm = 0; mm < jwmarker_num; mm++)
+                       if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].start_pos)
+                               addlen += jwmarker[mm].len + 2;
+               info->tile[tileno].start_pos += addlen;
+
+               /* end_header: increment with markers before of it */
+               addlen = 0;
+               for (mm = 0; mm < jwmarker_num; mm++)
+                       if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].end_header)
+                               addlen += jwmarker[mm].len + 2;
+               info->tile[tileno].end_header += addlen;
+
+               /* end_pos: increment with markers before the end of this tile */
+               /* code is disabled, since according to JPWL no markers can be beyond TPH */
+               addlen = 0;
+               for (mm = 0; mm < jwmarker_num; mm++)
+                       if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].end_pos)
+                               addlen += jwmarker[mm].len + 2;
+               info->tile[tileno].end_pos += addlen;
+
+               /* navigate through all the tile parts */
+               for (tpno = 0; tpno < info->tile[tileno].num_tps; tpno++) {
+
+                       /* start_pos: increment with markers before SOT */
+                       addlen = 0;
+                       for (mm = 0; mm < jwmarker_num; mm++)
+                               if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].tp[tpno].tp_start_pos)
+                                       addlen += jwmarker[mm].len + 2;
+                       info->tile[tileno].tp[tpno].tp_start_pos += addlen;
+
+                       /* end_header: increment with markers before of it */
+                       addlen = 0;
+                       for (mm = 0; mm < jwmarker_num; mm++)
+                               if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].tp[tpno].tp_end_header)
+                                       addlen += jwmarker[mm].len + 2;
+                       info->tile[tileno].tp[tpno].tp_end_header += addlen;
+
+                       /* end_pos: increment with markers before the end of this tile part */
+                       addlen = 0;
+                       for (mm = 0; mm < jwmarker_num; mm++)
+                               if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].tp[tpno].tp_end_pos)
+                                       addlen += jwmarker[mm].len + 2;
+                       info->tile[tileno].tp[tpno].tp_end_pos += addlen;
+
+               }
+
+               /* navigate through all the packets in this tile */
+               for (packno = 0; packno < numpacks; packno++) {
+                       
+                       /* start_pos: increment with markers before the packet */
+                       /* disabled for the same reason as before */
+                       addlen = 0;
+                       for (mm = 0; mm < jwmarker_num; mm++)
+                               if (jwmarker[mm].pos <= (unsigned long int) info->tile[tileno].packet[packno].start_pos)
+                                       addlen += jwmarker[mm].len + 2;
+                       info->tile[tileno].packet[packno].start_pos += addlen;
+
+                       /* end_ph_pos: increment with markers before the packet */
+                       /* disabled for the same reason as before */
+                       /*addlen = 0;
+                       for (mm = 0; mm < jwmarker_num; mm++)
+                               if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].packet[packno].end_ph_pos)
+                                       addlen += jwmarker[mm].len + 2;*/
+                       info->tile[tileno].packet[packno].end_ph_pos += addlen;
+
+                       /* end_pos: increment if marker is before the end of packet */
+                       /* disabled for the same reason as before */
+                       /*addlen = 0;
+                       for (mm = 0; mm < jwmarker_num; mm++)
+                               if (jwmarker[mm].pos < (unsigned long int) info->tile[tileno].packet[packno].end_pos)
+                                       addlen += jwmarker[mm].len + 2;*/
+                       info->tile[tileno].packet[packno].end_pos += addlen;
+
+               }
+       }
+
+       /* reorder the markers list */
+
+       return true;
+}
+
+#endif /* USE_JPWL */
diff --git a/libopenjpeg/jpwl/rs.c b/libopenjpeg/jpwl/rs.c
new file mode 100644 (file)
index 0000000..0841c63
--- /dev/null
@@ -0,0 +1,597 @@
+ /*
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifdef USE_JPWL
+
+/**
+@file rs.c
+@brief Functions used to compute the Reed-Solomon parity and check of byte arrays
+
+*/
+
+/**
+ * Reed-Solomon coding and decoding
+ * Phil Karn (karn@ka9q.ampr.org) September 1996
+ * 
+ * This file is derived from the program "new_rs_erasures.c" by Robert
+ * Morelos-Zaragoza (robert@spectra.eng.hawaii.edu) and Hari Thirumoorthy
+ * (harit@spectra.eng.hawaii.edu), Aug 1995
+ *
+ * I've made changes to improve performance, clean up the code and make it
+ * easier to follow. Data is now passed to the encoding and decoding functions
+ * through arguments rather than in global arrays. The decode function returns
+ * the number of corrected symbols, or -1 if the word is uncorrectable.
+ *
+ * This code supports a symbol size from 2 bits up to 16 bits,
+ * implying a block size of 3 2-bit symbols (6 bits) up to 65535
+ * 16-bit symbols (1,048,560 bits). The code parameters are set in rs.h.
+ *
+ * Note that if symbols larger than 8 bits are used, the type of each
+ * data array element switches from unsigned char to unsigned int. The
+ * caller must ensure that elements larger than the symbol range are
+ * not passed to the encoder or decoder.
+ *
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include "rs.h"
+
+/* This defines the type used to store an element of the Galois Field
+ * used by the code. Make sure this is something larger than a char if
+ * if anything larger than GF(256) is used.
+ *
+ * Note: unsigned char will work up to GF(256) but int seems to run
+ * faster on the Pentium.
+ */
+typedef int gf;
+
+/* KK = number of information symbols */
+static int     KK;
+
+/* Primitive polynomials - see Lin & Costello, Appendix A,
+ * and  Lee & Messerschmitt, p. 453.
+ */
+#if(MM == 2)/* Admittedly silly */
+int Pp[MM+1] = { 1, 1, 1 };
+
+#elif(MM == 3)
+/* 1 + x + x^3 */
+int Pp[MM+1] = { 1, 1, 0, 1 };
+
+#elif(MM == 4)
+/* 1 + x + x^4 */
+int Pp[MM+1] = { 1, 1, 0, 0, 1 };
+
+#elif(MM == 5)
+/* 1 + x^2 + x^5 */
+int Pp[MM+1] = { 1, 0, 1, 0, 0, 1 };
+
+#elif(MM == 6)
+/* 1 + x + x^6 */
+int Pp[MM+1] = { 1, 1, 0, 0, 0, 0, 1 };
+
+#elif(MM == 7)
+/* 1 + x^3 + x^7 */
+int Pp[MM+1] = { 1, 0, 0, 1, 0, 0, 0, 1 };
+
+#elif(MM == 8)
+/* 1+x^2+x^3+x^4+x^8 */
+int Pp[MM+1] = { 1, 0, 1, 1, 1, 0, 0, 0, 1 };
+
+#elif(MM == 9)
+/* 1+x^4+x^9 */
+int Pp[MM+1] = { 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
+
+#elif(MM == 10)
+/* 1+x^3+x^10 */
+int Pp[MM+1] = { 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 };
+
+#elif(MM == 11)
+/* 1+x^2+x^11 */
+int Pp[MM+1] = { 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
+
+#elif(MM == 12)
+/* 1+x+x^4+x^6+x^12 */
+int Pp[MM+1] = { 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1 };
+
+#elif(MM == 13)
+/* 1+x+x^3+x^4+x^13 */
+int Pp[MM+1] = { 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
+
+#elif(MM == 14)
+/* 1+x+x^6+x^10+x^14 */
+int Pp[MM+1] = { 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 };
+
+#elif(MM == 15)
+/* 1+x+x^15 */
+int Pp[MM+1] = { 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
+
+#elif(MM == 16)
+/* 1+x+x^3+x^12+x^16 */
+int Pp[MM+1] = { 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1 };
+
+#else
+#error "MM must be in range 2-16"
+#endif
+
+/* Alpha exponent for the first root of the generator polynomial */
+#define B0     0  /* Different from the default 1 */
+
+/* index->polynomial form conversion table */
+gf Alpha_to[NN + 1];
+
+/* Polynomial->index form conversion table */
+gf Index_of[NN + 1];
+
+/* No legal value in index form represents zero, so
+ * we need a special value for this purpose
+ */
+#define A0     (NN)
+
+/* Generator polynomial g(x)
+ * Degree of g(x) = 2*TT
+ * has roots @**B0, @**(B0+1), ... ,@^(B0+2*TT-1)
+ */
+/*gf Gg[NN - KK + 1];*/
+gf             Gg[NN - 1];
+
+/* Compute x % NN, where NN is 2**MM - 1,
+ * without a slow divide
+ */
+static /*inline*/ gf
+modnn(int x)
+{
+       while (x >= NN) {
+               x -= NN;
+               x = (x >> MM) + (x & NN);
+       }
+       return x;
+}
+
+/*#define      min(a,b)        ((a) < (b) ? (a) : (b))*/
+
+#define        CLEAR(a,n) {\
+       int ci;\
+       for(ci=(n)-1;ci >=0;ci--)\
+               (a)[ci] = 0;\
+       }
+
+#define        COPY(a,b,n) {\
+       int ci;\
+       for(ci=(n)-1;ci >=0;ci--)\
+               (a)[ci] = (b)[ci];\
+       }
+#define        COPYDOWN(a,b,n) {\
+       int ci;\
+       for(ci=(n)-1;ci >=0;ci--)\
+               (a)[ci] = (b)[ci];\
+       }
+
+void init_rs(int k)
+{
+       KK = k;
+       if (KK >= NN) {
+               printf("KK must be less than 2**MM - 1\n");
+               exit(1);
+       }
+       
+       generate_gf();
+       gen_poly();
+}
+
+/* generate GF(2**m) from the irreducible polynomial p(X) in p[0]..p[m]
+   lookup tables:  index->polynomial form   alpha_to[] contains j=alpha**i;
+                   polynomial form -> index form  index_of[j=alpha**i] = i
+   alpha=2 is the primitive element of GF(2**m)
+   HARI's COMMENT: (4/13/94) alpha_to[] can be used as follows:
+        Let @ represent the primitive element commonly called "alpha" that
+   is the root of the primitive polynomial p(x). Then in GF(2^m), for any
+   0 <= i <= 2^m-2,
+        @^i = a(0) + a(1) @ + a(2) @^2 + ... + a(m-1) @^(m-1)
+   where the binary vector (a(0),a(1),a(2),...,a(m-1)) is the representation
+   of the integer "alpha_to[i]" with a(0) being the LSB and a(m-1) the MSB. Thus for
+   example the polynomial representation of @^5 would be given by the binary
+   representation of the integer "alpha_to[5]".
+                   Similarily, index_of[] can be used as follows:
+        As above, let @ represent the primitive element of GF(2^m) that is
+   the root of the primitive polynomial p(x). In order to find the power
+   of @ (alpha) that has the polynomial representation
+        a(0) + a(1) @ + a(2) @^2 + ... + a(m-1) @^(m-1)
+   we consider the integer "i" whose binary representation with a(0) being LSB
+   and a(m-1) MSB is (a(0),a(1),...,a(m-1)) and locate the entry
+   "index_of[i]". Now, @^index_of[i] is that element whose polynomial 
+    representation is (a(0),a(1),a(2),...,a(m-1)).
+   NOTE:
+        The element alpha_to[2^m-1] = 0 always signifying that the
+   representation of "@^infinity" = 0 is (0,0,0,...,0).
+        Similarily, the element index_of[0] = A0 always signifying
+   that the power of alpha which has the polynomial representation
+   (0,0,...,0) is "infinity".
+*/
+
+void
+generate_gf(void)
+{
+       register int i, mask;
+
+       mask = 1;
+       Alpha_to[MM] = 0;
+       for (i = 0; i < MM; i++) {
+               Alpha_to[i] = mask;
+               Index_of[Alpha_to[i]] = i;
+               /* If Pp[i] == 1 then, term @^i occurs in poly-repr of @^MM */
+               if (Pp[i] != 0)
+                       Alpha_to[MM] ^= mask;   /* Bit-wise EXOR operation */
+               mask <<= 1;     /* single left-shift */
+       }
+       Index_of[Alpha_to[MM]] = MM;
+       /*
+        * Have obtained poly-repr of @^MM. Poly-repr of @^(i+1) is given by
+        * poly-repr of @^i shifted left one-bit and accounting for any @^MM
+        * term that may occur when poly-repr of @^i is shifted.
+        */
+       mask >>= 1;
+       for (i = MM + 1; i < NN; i++) {
+               if (Alpha_to[i - 1] >= mask)
+                       Alpha_to[i] = Alpha_to[MM] ^ ((Alpha_to[i - 1] ^ mask) << 1);
+               else
+                       Alpha_to[i] = Alpha_to[i - 1] << 1;
+               Index_of[Alpha_to[i]] = i;
+       }
+       Index_of[0] = A0;
+       Alpha_to[NN] = 0;
+}
+
+
+/*
+ * Obtain the generator polynomial of the TT-error correcting, length
+ * NN=(2**MM -1) Reed Solomon code from the product of (X+@**(B0+i)), i = 0,
+ * ... ,(2*TT-1)
+ *
+ * Examples:
+ *
+ * If B0 = 1, TT = 1. deg(g(x)) = 2*TT = 2.
+ * g(x) = (x+@) (x+@**2)
+ *
+ * If B0 = 0, TT = 2. deg(g(x)) = 2*TT = 4.
+ * g(x) = (x+1) (x+@) (x+@**2) (x+@**3)
+ */
+void
+gen_poly(void)
+{
+       register int i, j;
+
+       Gg[0] = Alpha_to[B0];
+       Gg[1] = 1;              /* g(x) = (X+@**B0) initially */
+       for (i = 2; i <= NN - KK; i++) {
+               Gg[i] = 1;
+               /*
+                * Below multiply (Gg[0]+Gg[1]*x + ... +Gg[i]x^i) by
+                * (@**(B0+i-1) + x)
+                */
+               for (j = i - 1; j > 0; j--)
+                       if (Gg[j] != 0)
+                               Gg[j] = Gg[j - 1] ^ Alpha_to[modnn((Index_of[Gg[j]]) + B0 + i - 1)];
+                       else
+                               Gg[j] = Gg[j - 1];
+               /* Gg[0] can never be zero */
+               Gg[0] = Alpha_to[modnn((Index_of[Gg[0]]) + B0 + i - 1)];
+       }
+       /* convert Gg[] to index form for quicker encoding */
+       for (i = 0; i <= NN - KK; i++)
+               Gg[i] = Index_of[Gg[i]];
+}
+
+
+/*
+ * take the string of symbols in data[i], i=0..(k-1) and encode
+ * systematically to produce NN-KK parity symbols in bb[0]..bb[NN-KK-1] data[]
+ * is input and bb[] is output in polynomial form. Encoding is done by using
+ * a feedback shift register with appropriate connections specified by the
+ * elements of Gg[], which was generated above. Codeword is   c(X) =
+ * data(X)*X**(NN-KK)+ b(X)
+ */
+int
+encode_rs(dtype *data, dtype *bb)
+{
+       register int i, j;
+       gf feedback;
+
+       CLEAR(bb,NN-KK);
+       for (i = KK - 1; i >= 0; i--) {
+#if (MM != 8)
+               if(data[i] > NN)
+                       return -1;      /* Illegal symbol */
+#endif
+               feedback = Index_of[data[i] ^ bb[NN - KK - 1]];
+               if (feedback != A0) {   /* feedback term is non-zero */
+                       for (j = NN - KK - 1; j > 0; j--)
+                               if (Gg[j] != A0)
+                                       bb[j] = bb[j - 1] ^ Alpha_to[modnn(Gg[j] + feedback)];
+                               else
+                                       bb[j] = bb[j - 1];
+                       bb[0] = Alpha_to[modnn(Gg[0] + feedback)];
+               } else {        /* feedback term is zero. encoder becomes a
+                                * single-byte shifter */
+                       for (j = NN - KK - 1; j > 0; j--)
+                               bb[j] = bb[j - 1];
+                       bb[0] = 0;
+               }
+       }
+       return 0;
+}
+
+/*
+ * Performs ERRORS+ERASURES decoding of RS codes. If decoding is successful,
+ * writes the codeword into data[] itself. Otherwise data[] is unaltered.
+ *
+ * Return number of symbols corrected, or -1 if codeword is illegal
+ * or uncorrectable.
+ * 
+ * First "no_eras" erasures are declared by the calling program. Then, the
+ * maximum # of errors correctable is t_after_eras = floor((NN-KK-no_eras)/2).
+ * If the number of channel errors is not greater than "t_after_eras" the
+ * transmitted codeword will be recovered. Details of algorithm can be found
+ * in R. Blahut's "Theory ... of Error-Correcting Codes".
+ */
+int
+eras_dec_rs(dtype *data, int *eras_pos, int no_eras)
+{
+       int deg_lambda, el, deg_omega;
+       int i, j, r;
+       gf u,q,tmp,num1,num2,den,discr_r;
+       gf recd[NN];
+       /* Err+Eras Locator poly and syndrome poly */
+       /*gf lambda[NN-KK + 1], s[NN-KK + 1];   
+       gf b[NN-KK + 1], t[NN-KK + 1], omega[NN-KK + 1];
+       gf root[NN-KK], reg[NN-KK + 1], loc[NN-KK];*/
+       gf lambda[NN + 1], s[NN + 1];   
+       gf b[NN + 1], t[NN + 1], omega[NN + 1];
+       gf root[NN], reg[NN + 1], loc[NN];
+       int syn_error, count;
+
+       /* data[] is in polynomial form, copy and convert to index form */
+       for (i = NN-1; i >= 0; i--){
+#if (MM != 8)
+               if(data[i] > NN)
+                       return -1;      /* Illegal symbol */
+#endif
+               recd[i] = Index_of[data[i]];
+       }
+       /* first form the syndromes; i.e., evaluate recd(x) at roots of g(x)
+        * namely @**(B0+i), i = 0, ... ,(NN-KK-1)
+        */
+       syn_error = 0;
+       for (i = 1; i <= NN-KK; i++) {
+               tmp = 0;
+               for (j = 0; j < NN; j++)
+                       if (recd[j] != A0)      /* recd[j] in index form */
+                               tmp ^= Alpha_to[modnn(recd[j] + (B0+i-1)*j)];
+               syn_error |= tmp;       /* set flag if non-zero syndrome =>
+                                        * error */
+               /* store syndrome in index form  */
+               s[i] = Index_of[tmp];
+       }
+       if (!syn_error) {
+               /*
+                * if syndrome is zero, data[] is a codeword and there are no
+                * errors to correct. So return data[] unmodified
+                */
+               return 0;
+       }
+       CLEAR(&lambda[1],NN-KK);
+       lambda[0] = 1;
+       if (no_eras > 0) {
+               /* Init lambda to be the erasure locator polynomial */
+               lambda[1] = Alpha_to[eras_pos[0]];
+               for (i = 1; i < no_eras; i++) {
+                       u = eras_pos[i];
+                       for (j = i+1; j > 0; j--) {
+                               tmp = Index_of[lambda[j - 1]];
+                               if(tmp != A0)
+                                       lambda[j] ^= Alpha_to[modnn(u + tmp)];
+                       }
+               }
+#ifdef ERASURE_DEBUG
+               /* find roots of the erasure location polynomial */
+               for(i=1;i<=no_eras;i++)
+                       reg[i] = Index_of[lambda[i]];
+               count = 0;
+               for (i = 1; i <= NN; i++) {
+                       q = 1;
+                       for (j = 1; j <= no_eras; j++)
+                               if (reg[j] != A0) {
+                                       reg[j] = modnn(reg[j] + j);
+                                       q ^= Alpha_to[reg[j]];
+                               }
+                       if (!q) {
+                               /* store root and error location
+                                * number indices
+                                */
+                               root[count] = i;
+                               loc[count] = NN - i;
+                               count++;
+                       }
+               }
+               if (count != no_eras) {
+                       printf("\n lambda(x) is WRONG\n");
+                       return -1;
+               }
+#ifndef NO_PRINT
+               printf("\n Erasure positions as determined by roots of Eras Loc Poly:\n");
+               for (i = 0; i < count; i++)
+                       printf("%d ", loc[i]);
+               printf("\n");
+#endif
+#endif
+       }
+       for(i=0;i<NN-KK+1;i++)
+               b[i] = Index_of[lambda[i]];
+
+       /*
+        * Begin Berlekamp-Massey algorithm to determine error+erasure
+        * locator polynomial
+        */
+       r = no_eras;
+       el = no_eras;
+       while (++r <= NN-KK) {  /* r is the step number */
+               /* Compute discrepancy at the r-th step in poly-form */
+               discr_r = 0;
+               for (i = 0; i < r; i++){
+                       if ((lambda[i] != 0) && (s[r - i] != A0)) {
+                               discr_r ^= Alpha_to[modnn(Index_of[lambda[i]] + s[r - i])];
+                       }
+               }
+               discr_r = Index_of[discr_r];    /* Index form */
+               if (discr_r == A0) {
+                       /* 2 lines below: B(x) <-- x*B(x) */
+                       COPYDOWN(&b[1],b,NN-KK);
+                       b[0] = A0;
+               } else {
+                       /* 7 lines below: T(x) <-- lambda(x) - discr_r*x*b(x) */
+                       t[0] = lambda[0];
+                       for (i = 0 ; i < NN-KK; i++) {
+                               if(b[i] != A0)
+                                       t[i+1] = lambda[i+1] ^ Alpha_to[modnn(discr_r + b[i])];
+                               else
+                                       t[i+1] = lambda[i+1];
+                       }
+                       if (2 * el <= r + no_eras - 1) {
+                               el = r + no_eras - el;
+                               /*
+                                * 2 lines below: B(x) <-- inv(discr_r) *
+                                * lambda(x)
+                                */
+                               for (i = 0; i <= NN-KK; i++)
+                                       b[i] = (lambda[i] == 0) ? A0 : modnn(Index_of[lambda[i]] - discr_r + NN);
+                       } else {
+                               /* 2 lines below: B(x) <-- x*B(x) */
+                               COPYDOWN(&b[1],b,NN-KK);
+                               b[0] = A0;
+                       }
+                       COPY(lambda,t,NN-KK+1);
+               }
+       }
+
+       /* Convert lambda to index form and compute deg(lambda(x)) */
+       deg_lambda = 0;
+       for(i=0;i<NN-KK+1;i++){
+               lambda[i] = Index_of[lambda[i]];
+               if(lambda[i] != A0)
+                       deg_lambda = i;
+       }
+       /*
+        * Find roots of the error+erasure locator polynomial. By Chien
+        * Search
+        */
+       COPY(&reg[1],&lambda[1],NN-KK);
+       count = 0;              /* Number of roots of lambda(x) */
+       for (i = 1; i <= NN; i++) {
+               q = 1;
+               for (j = deg_lambda; j > 0; j--)
+                       if (reg[j] != A0) {
+                               reg[j] = modnn(reg[j] + j);
+                               q ^= Alpha_to[reg[j]];
+                       }
+               if (!q) {
+                       /* store root (index-form) and error location number */
+                       root[count] = i;
+                       loc[count] = NN - i;
+                       count++;
+               }
+       }
+
+#ifdef DEBUG
+       printf("\n Final error positions:\t");
+       for (i = 0; i < count; i++)
+               printf("%d ", loc[i]);
+       printf("\n");
+#endif
+       if (deg_lambda != count) {
+               /*
+                * deg(lambda) unequal to number of roots => uncorrectable
+                * error detected
+                */
+               return -1;
+       }
+       /*
+        * Compute err+eras evaluator poly omega(x) = s(x)*lambda(x) (modulo
+        * x**(NN-KK)). in index form. Also find deg(omega).
+        */
+       deg_omega = 0;
+       for (i = 0; i < NN-KK;i++){
+               tmp = 0;
+               j = (deg_lambda < i) ? deg_lambda : i;
+               for(;j >= 0; j--){
+                       if ((s[i + 1 - j] != A0) && (lambda[j] != A0))
+                               tmp ^= Alpha_to[modnn(s[i + 1 - j] + lambda[j])];
+               }
+               if(tmp != 0)
+                       deg_omega = i;
+               omega[i] = Index_of[tmp];
+       }
+       omega[NN-KK] = A0;
+
+       /*
+        * Compute error values in poly-form. num1 = omega(inv(X(l))), num2 =
+        * inv(X(l))**(B0-1) and den = lambda_pr(inv(X(l))) all in poly-form
+        */
+       for (j = count-1; j >=0; j--) {
+               num1 = 0;
+               for (i = deg_omega; i >= 0; i--) {
+                       if (omega[i] != A0)
+                               num1  ^= Alpha_to[modnn(omega[i] + i * root[j])];
+               }
+               num2 = Alpha_to[modnn(root[j] * (B0 - 1) + NN)];
+               den = 0;
+
+               /* lambda[i+1] for i even is the formal derivative lambda_pr of lambda[i] */
+               for (i = min(deg_lambda,NN-KK-1) & ~1; i >= 0; i -=2) {
+                       if(lambda[i+1] != A0)
+                               den ^= Alpha_to[modnn(lambda[i+1] + i * root[j])];
+               }
+               if (den == 0) {
+#ifdef DEBUG
+                       printf("\n ERROR: denominator = 0\n");
+#endif
+                       return -1;
+               }
+               /* Apply error to data */
+               if (num1 != 0) {
+                       data[loc[j]] ^= Alpha_to[modnn(Index_of[num1] + Index_of[num2] + NN - Index_of[den])];
+               }
+       }
+       return count;
+}
+
+
+#endif /* USE_JPWL */
diff --git a/libopenjpeg/jpwl/rs.h b/libopenjpeg/jpwl/rs.h
new file mode 100644 (file)
index 0000000..7d02a47
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2003-2005, Francois Devaux and Antonin Descampe
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * Copyright (c) 2002-2005, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
+ * Copyright (c) 2005-2006, Dept. of Electronic and Information Engineering, Universita' degli Studi di Perugia, Italy
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifdef USE_JPWL
+
+/**
+@file rs.h
+@brief Functions used to compute Reed-Solomon parity and check of byte arrays
+
+*/
+
+#ifndef __RS_HEADER__
+#define __RS_HEADER__
+
+/** Global definitions for Reed-Solomon encoder/decoder
+ * Phil Karn KA9Q, September 1996
+ *
+ * The parameters MM and KK specify the Reed-Solomon code parameters.
+ *
+ * Set MM to be the size of each code symbol in bits. The Reed-Solomon
+ * block size will then be NN = 2**M - 1 symbols. Supported values are
+ * defined in rs.c.
+ *
+ * Set KK to be the number of data symbols in each block, which must be
+ * less than the block size. The code will then be able to correct up
+ * to NN-KK erasures or (NN-KK)/2 errors, or combinations thereof with
+ * each error counting as two erasures.
+ */
+#define MM  8          /* RS code over GF(2**MM) - change to suit */
+
+/* KK defined in rs.c */
+
+#define        NN ((1 << MM) - 1)
+
+#if (MM <= 8)
+typedef unsigned char dtype;
+#else
+typedef unsigned int dtype;
+#endif
+
+/** Initialization function */
+void init_rs(int);
+
+/** These two functions *must* be called in this order (e.g.,
+ * by init_rs()) before any encoding/decoding
+ */
+void generate_gf(void);        /* Generate Galois Field */
+void gen_poly(void);   /* Generate generator polynomial */
+
+/** Reed-Solomon encoding
+ * data[] is the input block, parity symbols are placed in bb[]
+ * bb[] may lie past the end of the data, e.g., for (255,223):
+ *     encode_rs(&data[0],&data[223]);
+ */
+int encode_rs(dtype data[], dtype bb[]);
+
+/** Reed-Solomon erasures-and-errors decoding
+ * The received block goes into data[], and a list of zero-origin
+ * erasure positions, if any, goes in eras_pos[] with a count in no_eras.
+ *
+ * The decoder corrects the symbols in place, if possible and returns
+ * the number of corrected symbols. If the codeword is illegal or
+ * uncorrectible, the data array is unchanged and -1 is returned
+ */
+int eras_dec_rs(dtype data[], int eras_pos[], int no_eras);
+
+/**
+Computes the minimum between two integers
+@param a first integer to compare
+@param b second integer to compare
+@return returns the minimum integer between a and b
+*/
+#ifndef min
+#define min(a,b)    (((a) < (b)) ? (a) : (b))
+#endif /* min */
+
+#endif /* __RS_HEADER__ */
+
+
+#endif /* USE_JPWL */
diff --git a/mj2/CMakeLists.txt b/mj2/CMakeLists.txt
deleted file mode 100644 (file)
index 6fd63dd..0000000
+++ /dev/null
@@ -1,95 +0,0 @@
-# Makefile for the MJ2 codecs of the OpenJPEG library: frames_to_mj2, mj2_to_frames, extract_j2k_from_mj2 and wrap_j2k_in_mj2
-
-SET(common_SRCS "")
-IF(DONT_HAVE_GETOPT)
-  SET(common_SRCS ${OPENJPEG_SOURCE_DIR}/common/getopt.c)
-ENDIF(DONT_HAVE_GETOPT)
-
-# While mj2 executables do not use the API correctly, we do not link with the library but rather compile the sources files.
-SET(OPJ_SRCS
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/bio.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/cio.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/dwt.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/event.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/image.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/j2k.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/j2k_lib.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/jp2.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/jpt.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/mct.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/mqc.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/openjpeg.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/pi.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/raw.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/t1.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/t2.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/tcd.c
-${OPENJPEG_SOURCE_DIR}/libopenjpeg/tgt.c
-)
-
-SET(MJ2_SRCS mj2.c mj2_convert.c)
-
-IF(WIN32)
-  ADD_DEFINITIONS(-DOPJ_STATIC)
-ENDIF(WIN32)
-
-# Headers file are located here:
-INCLUDE_DIRECTORIES(
-  ${OPENJPEG_SOURCE_DIR}/libopenjpeg
-  ${OPENJPEG_SOURCE_DIR}/common
-  ${LCMS_INCLUDE_DIRNAME}
-  )
-
-ADD_EXECUTABLE(frames_to_mj2
-  frames_to_mj2.c
-  ${common_SRCS}
-  ${OPJ_SRCS}
-  ${MJ2_SRCS}
-  )
-IF(LCMS_FOUND OR LCMS2_FOUND)
-  TARGET_LINK_LIBRARIES(frames_to_mj2 ${LCMS_LIBNAME})
-ENDIF(LCMS_FOUND OR LCMS2_FOUND)
-IF(UNIX)
-  TARGET_LINK_LIBRARIES(frames_to_mj2 m)
-ENDIF(UNIX)
-
-ADD_EXECUTABLE(mj2_to_frames
-    mj2_to_frames.c
-    ${common_SRCS}
-    ${OPJ_SRCS}
-    ${MJ2_SRCS}
-    ${OPENJPEG_SOURCE_DIR}/common/color.c
-    )
-IF(LCMS_FOUND OR LCMS2_FOUND)
-  TARGET_LINK_LIBRARIES(mj2_to_frames ${LCMS_LIBNAME})
-ENDIF(LCMS_FOUND OR LCMS2_FOUND)
-IF(UNIX)
-  TARGET_LINK_LIBRARIES(mj2_to_frames m)
-ENDIF(UNIX)
-
-ADD_EXECUTABLE(extract_j2k_from_mj2
-    extract_j2k_from_mj2.c
-    ${OPJ_SRCS}
-    ${MJ2_SRCS}
-    )
-IF(LCMS_FOUND OR LCMS2_FOUND)
-  TARGET_LINK_LIBRARIES(extract_j2k_from_mj2 ${LCMS_LIBNAME})
-ENDIF(LCMS_FOUND OR LCMS2_FOUND)
-IF(UNIX)
-  TARGET_LINK_LIBRARIES(extract_j2k_from_mj2 m)
-ENDIF(UNIX)
-
-ADD_EXECUTABLE(wrap_j2k_in_mj2
-    wrap_j2k_in_mj2.c
-    ${OPJ_SRCS}
-    ${MJ2_SRCS}
-    )
-IF(LCMS_FOUND OR LCMS2_FOUND)
-  TARGET_LINK_LIBRARIES(wrap_j2k_in_mj2 ${LCMS_LIBNAME})
-ENDIF(LCMS_FOUND OR LCMS2_FOUND)
-IF(UNIX)
-  TARGET_LINK_LIBRARIES(wrap_j2k_in_mj2 m)
-ENDIF(UNIX)
-
-INSTALL(TARGETS frames_to_mj2 mj2_to_frames extract_j2k_from_mj2 wrap_j2k_in_mj2
-       DESTINATION bin)
diff --git a/mj2/Makefile.am b/mj2/Makefile.am
deleted file mode 100644 (file)
index c96bd97..0000000
+++ /dev/null
@@ -1,113 +0,0 @@
-MAINTAINERCLEANFILES = Makefile.in
-
-OPJ_SRC = \
-../libopenjpeg/bio.c \
-../libopenjpeg/cio.c \
-../libopenjpeg/dwt.c \
-../libopenjpeg/event.c \
-../libopenjpeg/image.c \
-../libopenjpeg/j2k.c \
-../libopenjpeg/j2k_lib.c \
-../libopenjpeg/jp2.c \
-../libopenjpeg/jpt.c \
-../libopenjpeg/mct.c \
-../libopenjpeg/mqc.c \
-../libopenjpeg/openjpeg.c \
-../libopenjpeg/pi.c \
-../libopenjpeg/raw.c \
-../libopenjpeg/t1.c \
-../libopenjpeg/t2.c \
-../libopenjpeg/tcd.c \
-../libopenjpeg/tgt.c
-
-bin_PROGRAMS = \
-frames_to_mj2 \
-mj2_to_frames \
-extract_j2k_from_mj2 \
-wrap_j2k_in_mj2
-
-frames_to_mj2_CPPFLAGS = \
--I. \
--I$(top_srcdir)/common \
--I$(top_builddir)/common \
--I$(top_srcdir)/libopenjpeg \
--I$(top_builddir)/libopenjpeg \
--I$(top_srcdir)/mj2 \
--I$(top_builddir)/mj2 \
--DOPJ_STATIC
-frames_to_mj2_CFLAGS = 
-frames_to_mj2_LDADD = -lm
-frames_to_mj2_SOURCES = \
-$(OPJ_SRC) \
-../common/getopt.c \
-mj2_convert.c \
-mj2.c \
-frames_to_mj2.c \
-mj2.h \
-mj2_convert.h
-
-mj2_to_frames_CPPFLAGS = \
--I. \
--I$(top_srcdir)/common \
--I$(top_builddir)/common \
--I$(top_srcdir)/libopenjpeg \
--I$(top_builddir)/libopenjpeg \
--I$(top_srcdir)/mj2 \
--I$(top_builddir)/mj2 \
-@LCMS2_CFLAGS@ \
-@LCMS1_CFLAGS@ \
--DOPJ_STATIC
-mj2_to_frames_CFLAGS = 
-mj2_to_frames_LDADD = @LCMS2_LIBS@ @LCMS1_LIBS@
-mj2_to_frames_SOURCES = \
-$(OPJ_SRC) \
-../common/color.c \
-../common/getopt.c \
-mj2_convert.c \
-mj2.c \
-mj2_to_frames.c \
-mj2.h \
-mj2_convert.h
-
-extract_j2k_from_mj2_CPPFLAGS = \
--I. \
--I$(top_srcdir)/common \
--I$(top_builddir)/common \
--I$(top_srcdir)/libopenjpeg \
--I$(top_builddir)/libopenjpeg \
--I$(top_srcdir)/mj2 \
--I$(top_builddir)/mj2 \
--DOPJ_STATIC
-extract_j2k_from_mj2_CFLAGS = 
-extract_j2k_from_mj2_LDADD = -lm
-extract_j2k_from_mj2_SOURCES = \
-$(OPJ_SRC) \
-mj2.c \
-extract_j2k_from_mj2.c \
-mj2.h
-
-wrap_j2k_in_mj2_CPPFLAGS = \
--I. \
--I$(top_srcdir)/common \
--I$(top_builddir)/common \
--I$(top_srcdir)/libopenjpeg \
--I$(top_builddir)/libopenjpeg \
--I$(top_srcdir)/mj2 \
--I$(top_builddir)/mj2 \
--DOPJ_STATIC
-wrap_j2k_in_mj2_CFLAGS = 
-wrap_j2k_in_mj2_LDADD = -lm
-wrap_j2k_in_mj2_SOURCES = \
-$(OPJ_SRC) \
-mj2.c \
-wrap_j2k_in_mj2.c \
-mj2.h
-
-EXTRA_DIST = \
-CMakeLists.txt
-
-install-data-hook:
-       @echo -e " (B)\t$(bindir)/frames_to_mj2$(EXEEXT)" >> $(top_builddir)/report.txt
-       @echo -e " (B)\t$(bindir)/mj2_to_frames$(EXEEXT)" >> $(top_builddir)/report.txt
-       @echo -e " (B)\t$(bindir)/extract_j2k_from_mj2$(EXEEXT)" >> $(top_builddir)/report.txt
-       @echo -e " (B)\t$(bindir)/wrap_j2k_in_mj2$(EXEEXT)" >> $(top_builddir)/report.txt
diff --git a/mj2/Makefile.nix b/mj2/Makefile.nix
deleted file mode 100644 (file)
index 75302bd..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-#mj2 Makefile.nix
-include ../config.nix
-
-CFLAGS = -Wall
-
-INSTALL_BIN = $(prefix)/bin
-USERLIBS = -lm
-INCLUDE = -I.. -I. -I../libopenjpeg -I../common
-
-ifeq ($(WITH_LCMS2),yes)
-INCLUDE += $(LCMS2_INCLUDE)
-USERLIBS += $(LCMS2_LIB)
-endif
-
-ifeq ($(WITH_LCMS1),yes)
-INCLUDE += $(LCMS1_INCLUDE)
-USERLIBS += $(LCMS1_LIB)
-endif
-
-CFLAGS += $(INCLUDE) -lstdc++ # -g -p -pg
-
-ifeq ($(ENABLE_SHARED),yes)
-ELIB = ../libopenjpeg.so.$(MAJOR).$(MINOR).$(BUILD)
-else
-ELIB = ../libopenjpeg.a
-endif
-
-all: frames_to_mj2 mj2_to_frames extract_j2k_from_mj2 wrap_j2k_in_mj2
-       install -d ../bin
-       install frames_to_mj2 mj2_to_frames extract_j2k_from_mj2 \
-       wrap_j2k_in_mj2 ../bin
-
-frames_to_mj2: frames_to_mj2.c $(ELIB)
-       $(CC) $(CFLAGS) ../common/getopt.c mj2_convert.c mj2.c frames_to_mj2.c \
-       -o frames_to_mj2 $(ELIB) $(USERLIBS)
-
-mj2_to_frames: mj2_to_frames.c $(ELIB)
-       $(CC) $(CFLAGS) ../common/getopt.c mj2_convert.c mj2.c \
-       ../common/color.c mj2_to_frames.c \
-       -o mj2_to_frames $(ELIB) $(USERLIBS)
-
-extract_j2k_from_mj2: extract_j2k_from_mj2.c $(ELIB)
-       $(CC) $(CFLAGS) mj2.c extract_j2k_from_mj2.c \
-       -o extract_j2k_from_mj2 $(ELIB) $(USERLIBS)
-
-wrap_j2k_in_mj2: wrap_j2k_in_mj2.c $(ELIB)
-       $(CC) $(CFLAGS) mj2.c wrap_j2k_in_mj2.c \
-       -o wrap_j2k_in_mj2 $(ELIB) $(USERLIBS)
-
-clean:
-       rm -f frames_to_mj2 mj2_to_frames extract_j2k_from_mj2 wrap_j2k_in_mj2
-
-install: all
-       install -d $(DESTDIR)$(INSTALL_BIN)
-       install -m 755 -o root -g root frames_to_mj2 $(DESTDIR)$(INSTALL_BIN)
-       install -m 755 -o root -g root mj2_to_frames $(DESTDIR)$(INSTALL_BIN)
-       install -m 755 -o root -g root extract_j2k_from_mj2 $(DESTDIR)$(INSTALL_BIN)
-       install -m 755 -o root -g root wrap_j2k_in_mj2 $(DESTDIR)$(INSTALL_BIN)
-
-uninstall:
-       rm -f $(DESTDIR)$(INSTALL_BIN)/frames_to_mj2
-       rm -f $(DESTDIR)$(INSTALL_BIN)/mj2_to_frames
-       rm -f $(DESTDIR)$(INSTALL_BIN)/extract_j2k_from_mj2
-       rm -f $(DESTDIR)$(INSTALL_BIN)/wrap_j2k_in_mj2
diff --git a/mj2/extract_j2k_from_mj2.c b/mj2/extract_j2k_from_mj2.c
deleted file mode 100644 (file)
index 0872df1..0000000
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
- * Copyright (c) 2002-2007, Professor Benoit Macq
- * Copyright (c) 2003-2007, Francois-Olivier Devaux 
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "openjpeg.h"
-#include "../libopenjpeg/j2k.h"
-#include "../libopenjpeg/jp2.h"
-#include "mj2.h"
-
-/* -------------------------------------------------------------------------- */
-
-/**
-sample error callback expecting a FILE* client object
-*/
-void error_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[ERROR] %s", msg);
-}
-/**
-sample warning callback expecting a FILE* client object
-*/
-void warning_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[WARNING] %s", msg);
-}
-/**
-sample debug callback expecting a FILE* client object
-*/
-void info_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[INFO] %s", msg);
-}
-
-/* -------------------------------------------------------------------------- */
-
-
-int main(int argc, char *argv[]) {
-       opj_dinfo_t* dinfo; 
-       opj_event_mgr_t event_mgr;              /* event manager */
-  int tnum;
-  unsigned int snum;
-  opj_mj2_t *movie;
-  mj2_tk_t *track;
-  mj2_sample_t *sample;
-  unsigned char* frame_codestream;
-  FILE *file, *outfile;
-  char outfilename[50];
-       mj2_dparameters_t parameters;
-
-  if (argc != 3) {
-    printf("Usage: %s mj2filename output_location\n",argv[0]); 
-    printf("Example: %s foreman.mj2 output/foreman\n",argv[0]);
-    return 1;
-  }
-  
-  file = fopen(argv[1], "rb");
-  
-  if (!file) {
-    fprintf(stderr, "failed to open %s for reading\n", argv[1]);
-    return 1;
-  }
-
-       /*
-       configure the event callbacks (not required)
-       setting of each callback is optionnal
-       */
-       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
-       event_mgr.error_handler = error_callback;
-       event_mgr.warning_handler = warning_callback;
-       event_mgr.info_handler = info_callback;
-
-       /* get a MJ2 decompressor handle */
-       dinfo = mj2_create_decompress();
-
-       /* catch events using our callbacks and give a local context */
-       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);           
-
-       /* setup the decoder decoding parameters using user parameters */
-       memset(&parameters, 0, sizeof(mj2_dparameters_t));
-       movie = (opj_mj2_t*) dinfo->mj2_handle;
-       mj2_setup_decoder(movie, &parameters);
-
-  if (mj2_read_struct(file, movie)) // Creating the movie structure
-    return 1;
-
-  // Decode first video track 
-  tnum = 0;
-  while (movie->tk[tnum].track_type != 0)
-    tnum ++;
-
-  track = &movie->tk[tnum];
-
-  fprintf(stdout,"Extracting %d frames from file...\n",track->num_samples);
-
-  for (snum=0; snum < track->num_samples; snum++)
-  {
-    sample = &track->sample[snum];
-    frame_codestream = (unsigned char*) malloc (sample->sample_size-8); // Skipping JP2C marker
-    fseek(file,sample->offset+8,SEEK_SET);
-    fread(frame_codestream,sample->sample_size-8,1, file);  // Assuming that jp and ftyp markers size do
-
-    sprintf(outfilename,"%s_%05d.j2k",argv[2],snum);
-    outfile = fopen(outfilename, "wb");
-    if (!outfile) {
-      fprintf(stderr, "failed to open %s for writing\n",outfilename);
-      return 1;
-    }
-    fwrite(frame_codestream,sample->sample_size-8,1,outfile);
-    fclose(outfile);
-    free(frame_codestream);
-    }
-  fclose(file);
-  fprintf(stdout, "%d frames correctly extracted\n", snum);
-       
-       /* free remaining structures */
-       if(dinfo) {
-               mj2_destroy_decompress((opj_mj2_t*)dinfo->mj2_handle);
-       }
-       
-  return 0;
-}
diff --git a/mj2/frames_to_mj2.c b/mj2/frames_to_mj2.c
deleted file mode 100644 (file)
index f6b7765..0000000
+++ /dev/null
@@ -1,843 +0,0 @@
-/*
-* Copyright (c) 2003-2004, Fran�ois-Olivier Devaux
-* Copyright (c) 2002-2004,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
-* All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions
-* are met:
-* 1. Redistributions of source code must retain the above copyright
-*    notice, this list of conditions and the following disclaimer.
-* 2. Redistributions in binary form must reproduce the above copyright
-*    notice, this list of conditions and the following disclaimer in the
-*    documentation and/or other materials provided with the distribution.
-*
-* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-* POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "openjpeg.h"
-#include "../libopenjpeg/j2k_lib.h"
-#include "../libopenjpeg/j2k.h"
-#include "../libopenjpeg/jp2.h"
-#include "../libopenjpeg/cio.h"
-#include "mj2.h"
-#include "mj2_convert.h"
-#include "getopt.h"
-
-/**
-Size of memory first allocated for MOOV box
-*/
-#define TEMP_BUF 10000 
-
-#define ENUMCS_GRAY 16
-#define ENUMCS_SRGB 17
-#define ENUMCS_SYCC 18
-
-/* -------------------------------------------------------------------------- */
-
-/**
-sample error callback expecting a FILE* client object
-*/
-void error_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[ERROR] %s", msg);
-}
-/**
-sample warning callback expecting a FILE* client object
-*/
-void warning_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[WARNING] %s", msg);
-}
-/**
-sample debug callback expecting a FILE* client object
-*/
-void info_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[INFO] %s", msg);
-}
-
-/* -------------------------------------------------------------------------- */
-
-
-void help_display()
-{
-  fprintf(stdout,"HELP for frames_to_mj2\n----\n\n");
-  fprintf(stdout,"- the -h option displays this help information on screen\n\n");
-  
-  
-  fprintf(stdout,"List of parameters for the MJ2 encoder:\n");
-  fprintf(stdout,"\n");
-  fprintf(stdout,"REMARKS:\n");
-  fprintf(stdout,"---------\n");
-  fprintf(stdout,"\n");
-  fprintf
-    (stdout,"The markers written to the main_header are : SOC SIZ COD QCD COM.\n");
-  fprintf
-    (stdout,"COD and QCD never appear in the tile_header.\n");
-  fprintf(stdout,"\n");
-  fprintf(stdout,"By default:\n");
-  fprintf(stdout,"------------\n");
-  fprintf(stdout,"\n");
-  fprintf(stdout," * Lossless\n");
-  fprintf(stdout," * 1 tile\n");
-  fprintf(stdout," * Size of precinct : 2^15 x 2^15 (means 1 precinct)\n");
-  fprintf(stdout," * Size of code-block : 64 x 64\n");
-  fprintf(stdout," * Number of resolutions: 6\n");
-  fprintf(stdout," * No SOP marker in the codestream\n");
-  fprintf(stdout," * No EPH marker in the codestream\n");
-  fprintf(stdout," * No sub-sampling in x or y direction\n");
-  fprintf(stdout," * No mode switch activated\n");
-  fprintf(stdout," * Progression order: LRCP\n");
-  fprintf(stdout," * No index file\n");
-  fprintf(stdout," * No ROI upshifted\n");
-  fprintf(stdout," * No offset of the origin of the image\n");
-  fprintf(stdout," * No offset of the origin of the tiles\n");
-  fprintf(stdout," * Reversible DWT 5-3\n");
-  fprintf(stdout,"\n");
-  fprintf(stdout,"Parameters:\n");
-  fprintf(stdout,"------------\n");
-  fprintf(stdout,"\n");
-  fprintf
-    (stdout,"Required Parameters (except with -h):\n");
-  fprintf
-    (stdout,"-i : source file      (-i source.yuv) \n");
-  fprintf
-    (stdout,"-o : destination file (-o dest.mj2) \n");
-  fprintf
-    (stdout,"Optional Parameters:\n");
-  fprintf(stdout,"-h : display the help information \n");
-  fprintf(stdout,"-r : different compression ratios for successive layers (-r 20,10,5)\n");
-  fprintf(stdout,"     - The rate specified for each quality level is the desired \n");
-  fprintf(stdout,"       compression factor.\n");
-  fprintf(stdout,"       Example: -r 20,10,1 means quality 1: compress 20x, \n");
-  fprintf(stdout,"       quality 2: compress 10x and quality 3: compress lossless\n");
-  fprintf(stdout,"       (options -r and -q cannot be used together)\n");
-  
-  fprintf(stdout,"-q : different psnr for successive layers (-q 30,40,50) \n");
-  fprintf(stdout,"        (options -r and -q cannot be used together)\n");
-  
-  fprintf(stdout,"-n : number of resolutions (-n 3) \n");
-  fprintf(stdout,"-b : size of code block (-b 32,32) \n");
-  fprintf(stdout,"-c : size of precinct (-c 128,128) \n");
-  fprintf(stdout,"-t : size of tile (-t 512,512) \n");
-  fprintf
-    (stdout,"-p : progression order (-p LRCP) [LRCP, RLCP, RPCL, PCRL, CPRL] \n");
-  fprintf
-    (stdout,"-s : subsampling factor (-s 2,2) [-s X,Y] \n");
-  fprintf(stdout,"     Remark: subsampling bigger than 2 can produce error\n");
-  fprintf
-    (stdout,"-S : write SOP marker before each packet \n");
-  fprintf
-    (stdout,"-E : write EPH marker after each header packet \n");
-  fprintf
-    (stdout,"-M : mode switch (-M 3) [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
-  fprintf
-    (stdout,"             8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)] \n");
-  fprintf
-    (stdout,"             Indicate multiple modes by adding their values. \n");
-  fprintf
-    (stdout,"             Example: RESTART(4) + RESET(2) + SEGMARK(32) = -M 38\n");
-  fprintf
-    (stdout,"-R : c=%%d,U=%%d : quantization indices upshifted \n");
-  fprintf
-    (stdout,"             for component c=%%d [%%d = 0,1,2]\n");
-  fprintf
-    (stdout,"             with a value of U=%%d [0 <= %%d <= 37] (i.e. -ROI:c=0,U=25) \n");
-  fprintf
-    (stdout,"-d : offset of the origin of the image (-d 150,300) \n");
-  fprintf
-    (stdout,"-T : offset of the origin of the tiles (-T 100,75) \n");
-  fprintf(stdout,"-I : use the irreversible DWT 9-7 (-I) \n");
-  fprintf(stdout,"-W : image width, height and the dx and dy subsampling \n");
-  fprintf(stdout,"        of the Cb and Cr components for YUV files \n");
-  fprintf(stdout,"        (default is '352,288,2,2' for CIF format's 352x288 and 4:2:0)\n");
-  fprintf(stdout,"-F : video frame rate (set to 25 by default)\n");
-  fprintf(stdout,"-D : depth, precision in bits [8 .. 16]; default:8\n");
-  fprintf(stdout,"-C : comment\n");
-  fprintf(stdout,"\n");
-  fprintf(stdout,"IMPORTANT:\n");
-  fprintf(stdout,"-----------\n");
-  fprintf(stdout,"\n");
-  fprintf(stdout,"The index file has the structure below:\n");
-  fprintf(stdout,"---------------------------------------\n");
-  fprintf(stdout,"\n");
-  fprintf(stdout,"Image_height Image_width\n");
-  fprintf(stdout,"progression order\n");
-  fprintf(stdout,"Tiles_size_X Tiles_size_Y\n");
-  fprintf(stdout,"Components_nb\n");
-  fprintf(stdout,"Layers_nb\n");
-  fprintf(stdout,"decomposition_levels\n");
-  fprintf(stdout,"[Precincts_size_X_res_Nr Precincts_size_Y_res_Nr]...\n");
-  fprintf(stdout,"   [Precincts_size_X_res_0 Precincts_size_Y_res_0]\n");
-  fprintf(stdout,"Main_header_end_position\n");
-  fprintf(stdout,"Codestream_size\n");
-  fprintf(stdout,"Tile_0 start_pos end_Theader end_pos TotalDisto NumPix MaxMSE\n");
-  fprintf(stdout,"Tile_1   ''           ''        ''        ''       ''    ''\n");
-  fprintf(stdout,"...\n");
-  fprintf(stdout,"Tile_Nt   ''           ''        ''        ''       ''    ''\n");
-  fprintf(stdout,"Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");
-  fprintf(stdout,"...\n");
-  fprintf(stdout,"Tpacket_Np ''   ''    ''   ''    ''       ''       ''     ''\n");
-  
-  fprintf(stdout,"MaxDisto\n");
-  
-  fprintf(stdout,"TotalDisto\n\n");
-}
-
-int give_progression(char progression[4])
-{
-  if (progression[0] == 'L' && progression[1] == 'R'
-    && progression[2] == 'C' && progression[3] == 'P') {
-    return 0;
-  } else {
-    if (progression[0] == 'R' && progression[1] == 'L'
-      && progression[2] == 'C' && progression[3] == 'P') {
-      return 1;
-    } else {
-      if (progression[0] == 'R' && progression[1] == 'P'
-                               && progression[2] == 'C' && progression[3] == 'L') {
-                               return 2;
-      } else {
-                               if (progression[0] == 'P' && progression[1] == 'C'
-                                       && progression[2] == 'R' && progression[3] == 'L') {
-                                       return 3;
-                               } else {
-                                       if (progression[0] == 'C' && progression[1] == 'P'
-                                               && progression[2] == 'R' && progression[3] == 'L') {
-                                               return 4;
-                                       } else {
-                                               return -1;
-                                       }
-                               }
-      }
-    }
-  }
-}
-
-
-
-
-int main(int argc, char **argv)
-{
-       mj2_cparameters_t mj2_parameters;       /* MJ2 compression parameters */
-       opj_cparameters_t *j2k_parameters;      /* J2K compression parameters */
-       opj_event_mgr_t event_mgr;              /* event manager */
-       opj_cio_t *cio;
-       int value;
-       opj_mj2_t *movie;
-       opj_image_t *img;
-       int i, j;
-       char *s, S1, S2, S3;
-       unsigned char *buf;
-       int x1, y1,  len;
-       long mdat_initpos, offset;
-       FILE *mj2file;
-       int sampleno;  
-       opj_cinfo_t* cinfo;
-       bool bSuccess;
-       int numframes;
-       int prec = 8;/* DEFAULT */
-       double total_time = 0;  
-
-       memset(&mj2_parameters, 0, sizeof(mj2_cparameters_t));
-  /* default value */
-  /* ------------- */
-       mj2_parameters.w = 352;                 // CIF default value
-       mj2_parameters.h = 288;                 // CIF default value
-       mj2_parameters.CbCr_subsampling_dx = 2; // CIF default value
-       mj2_parameters.CbCr_subsampling_dy = 2; // CIF default value
-       mj2_parameters.frame_rate = 25;
-       mj2_parameters.prec = 8; /* DEFAULT */
-       mj2_parameters.enumcs = ENUMCS_SYCC; /* FIXME: ENUMCS_YUV420 */
-       mj2_parameters.meth = 1; /* enumerated color space */
-
-/*
-       configure the event callbacks (not required)
-       setting of each callback is optionnal
-*/
-       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
-       event_mgr.error_handler = error_callback;
-       event_mgr.warning_handler = warning_callback;
-       event_mgr.info_handler = NULL;
-    
-       /* set J2K encoding parameters to default values */
-       opj_set_default_encoder_parameters(&mj2_parameters.j2k_parameters);
-       j2k_parameters = &mj2_parameters.j2k_parameters;
-
-       /* Create comment for codestream */
-       if(j2k_parameters->cp_comment == NULL) {
-    const char comment[] = "Created by OpenJPEG version ";
-               const size_t clen = strlen(comment);
-    const char *version = opj_version();
-               j2k_parameters->cp_comment = (char*)malloc(clen+strlen(version)+1);
-               sprintf(j2k_parameters->cp_comment,"%s%s", comment, version);
-       }
-
-  while (1) {
-    int c = getopt(argc, argv,
-      "i:o:r:q:f:t:n:c:b:p:s:d:P:S:E:M:R:T:C:I:W:F:D:h");
-    if (c == -1)
-      break;
-    switch (c) {
-    case 'i':                  /* IN fill */
-                       {
-                               char *infile = optarg;
-                               s = optarg;
-                               while (*s) {
-                                       s++;
-                               }
-                               s--;
-                               S3 = *s;
-                               s--;
-                               S2 = *s;
-                               s--;
-                               S1 = *s;
-                               
-                               if ((S1 == 'y' && S2 == 'u' && S3 == 'v')
-                                       || (S1 == 'Y' && S2 == 'U' && S3 == 'V')) {
-                                       mj2_parameters.decod_format = YUV_DFMT;                         
-                               }
-                               else {
-                                       fprintf(stderr,
-                                               "!! Unrecognized format for infile : %c%c%c [accept only *.yuv] !!\n\n",
-                                               S1, S2, S3);
-                                       return 1;
-                               }
-                               strncpy(mj2_parameters.infile, infile, sizeof(mj2_parameters.infile)-1);
-                       }
-      break;
-      /* ----------------------------------------------------- */
-    case 'o':                  /* OUT fill */
-                       {
-                               char *outfile = optarg;
-                               while (*outfile) {
-                                       outfile++;
-                               }
-                               outfile--;
-                               S3 = *outfile;
-                               outfile--;
-                               S2 = *outfile;
-                               outfile--;
-                               S1 = *outfile;
-                               
-                               outfile = optarg;
-                               
-                               if ((S1 == 'm' && S2 == 'j' && S3 == '2')
-                                       || (S1 == 'M' && S2 == 'J' && S3 == '2'))
-                                       mj2_parameters.cod_format = MJ2_CFMT;
-                               else {
-                                       fprintf(stderr,
-                                               "Unknown output format image *.%c%c%c [only *.mj2]!! \n",
-                                               S1, S2, S3);
-                                       return 1;
-                               }
-                               strncpy(mj2_parameters.outfile, outfile, sizeof(mj2_parameters.outfile)-1);      
-      }
-      break;
-      /* ----------------------------------------------------- */
-    case 'r':                  /* rates rates/distorsion */
-                       {
-                               float rate;
-                               s = optarg;
-                               while (sscanf(s, "%f", &rate) == 1) {
-                                       j2k_parameters->tcp_rates[j2k_parameters->tcp_numlayers] = rate * 2;
-                                       j2k_parameters->tcp_numlayers++;
-                                       while (*s && *s != ',') {
-                                               s++;
-                                       }
-                                       if (!*s)
-                                               break;
-                                       s++;
-                               }
-                               j2k_parameters->cp_disto_alloc = 1;
-                       }
-      break;
-      /* ----------------------------------------------------- */
-    case 'q':                  /* add fixed_quality */
-      s = optarg;
-                       while (sscanf(s, "%f", &j2k_parameters->tcp_distoratio[j2k_parameters->tcp_numlayers]) == 1) {
-                               j2k_parameters->tcp_numlayers++;
-                               while (*s && *s != ',') {
-                                       s++;
-                               }
-                               if (!*s)
-                                       break;
-                               s++;
-                       }
-                       j2k_parameters->cp_fixed_quality = 1;
-      break;
-      /* dda */
-      /* ----------------------------------------------------- */
-    case 'f':                  /* mod fixed_quality (before : -q) */
-                       {
-                               int *row = NULL, *col = NULL;
-                               int numlayers = 0, numresolution = 0, matrix_width = 0;
-                               
-                               s = optarg;
-                               sscanf(s, "%d", &numlayers);
-                               s++;
-                               if (numlayers > 9)
-                                       s++;
-                               
-                               j2k_parameters->tcp_numlayers = numlayers;
-                               numresolution = j2k_parameters->numresolution;
-                               matrix_width = numresolution * 3;
-                               j2k_parameters->cp_matrice = (int *) malloc(numlayers * matrix_width * sizeof(int));
-                               s = s + 2;
-                               
-                               for (i = 0; i < numlayers; i++) {
-                                       row = &j2k_parameters->cp_matrice[i * matrix_width];
-                                       col = row;
-                                       j2k_parameters->tcp_rates[i] = 1;
-                                       sscanf(s, "%d,", &col[0]);
-                                       s += 2;
-                                       if (col[0] > 9)
-                                               s++;
-                                       col[1] = 0;
-                                       col[2] = 0;
-                                       for (j = 1; j < numresolution; j++) {
-                                               col += 3;
-                                               sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);
-                                               s += 6;
-                                               if (col[0] > 9)
-                                                       s++;
-                                               if (col[1] > 9)
-                                                       s++;
-                                               if (col[2] > 9)
-                                                       s++;
-                                       }
-                                       if (i < numlayers - 1)
-                                               s++;
-                               }
-                               j2k_parameters->cp_fixed_alloc = 1;
-                       }
-                       break;
-      /* ----------------------------------------------------- */
-    case 't':                  /* tiles */
-      sscanf(optarg, "%d,%d", &j2k_parameters->cp_tdx, &j2k_parameters->cp_tdy);
-                       j2k_parameters->tile_size_on = true;
-      break;
-      /* ----------------------------------------------------- */
-    case 'n':                  /* resolution */
-      sscanf(optarg, "%d", &j2k_parameters->numresolution);
-      break;
-      /* ----------------------------------------------------- */
-    case 'c':                  /* precinct dimension */
-                       {
-                               char sep;
-                               int res_spec = 0;
-
-                               char *s = optarg;
-                               do {
-                                       sep = 0;
-                                       sscanf(s, "[%d,%d]%c", &j2k_parameters->prcw_init[res_spec],
-                                 &j2k_parameters->prch_init[res_spec], &sep);
-                                       j2k_parameters->csty |= 0x01;
-                                       res_spec++;
-                                       s = strpbrk(s, "]") + 2;
-                               }
-                               while (sep == ',');
-                               j2k_parameters->res_spec = res_spec;
-                       }
-                       break;
-
-      /* ----------------------------------------------------- */
-    case 'b':                  /* code-block dimension */
-                       {
-                               int cblockw_init = 0, cblockh_init = 0;
-                               sscanf(optarg, "%d,%d", &cblockw_init, &cblockh_init);
-                               if (cblockw_init * cblockh_init > 4096 || cblockw_init > 1024
-                                       || cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {
-                                       fprintf(stderr,
-                                               "!! Size of code_block error (option -b) !!\n\nRestriction :\n"
-            "    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");
-                                       return 1;
-                               }
-                               j2k_parameters->cblockw_init = cblockw_init;
-                               j2k_parameters->cblockh_init = cblockh_init;
-                       }
-                       break;
-      /* ----------------------------------------------------- */
-    case 'p':                  /* progression order */
-                       {
-                               char progression[4];
-                               
-                               strncpy(progression, optarg, 4);
-                               j2k_parameters->prog_order = give_progression(progression);
-                               if (j2k_parameters->prog_order == -1) {
-                                       fprintf(stderr, "Unrecognized progression order "
-            "[LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
-                                       return 1;
-                               }
-                       }
-                       break;
-      /* ----------------------------------------------------- */
-    case 's':                  /* subsampling factor */
-      {
-                               if (sscanf(optarg, "%d,%d", &j2k_parameters->subsampling_dx,
-                                    &j2k_parameters->subsampling_dy) != 2) {
-                                       fprintf(stderr, "'-s' sub-sampling argument error !  [-s dx,dy]\n");
-                                       return 1;
-                               }
-                       }
-                       break;
-      /* ----------------------------------------------------- */
-    case 'd':                  /* coordonnate of the reference grid */
-      {
-                               if (sscanf(optarg, "%d,%d", &j2k_parameters->image_offset_x0,
-                                    &j2k_parameters->image_offset_y0) != 2) {
-                                       fprintf(stderr, "-d 'coordonnate of the reference grid' argument "
-            "error !! [-d x0,y0]\n");
-                                       return 1;
-                               }
-                       }
-                       break;
-      /* ----------------------------------------------------- */
-    case 'h':                  /* Display an help description */
-      help_display();
-      return 0;
-      break;
-      /* ----------------------------------------------------- */
-    case 'P':                  /* POC */
-      {
-                               int numpocs = 0;                /* number of progression order change (POC) default 0 */
-                               opj_poc_t *POC = NULL;  /* POC : used in case of Progression order change */
-
-                               char *s = optarg;
-                               POC = j2k_parameters->POC;
-
-                               while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%4s", &POC[numpocs].tile,
-                                       &POC[numpocs].resno0, &POC[numpocs].compno0,
-                                       &POC[numpocs].layno1, &POC[numpocs].resno1,
-                                       &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
-                                       POC[numpocs].prg1 = give_progression(POC[numpocs].progorder);
-                                       numpocs++;
-                                       while (*s && *s != '/') {
-                                               s++;
-                                       }
-                                       if (!*s) {
-                                               break;
-                                       }
-                                       s++;
-                               }
-                               j2k_parameters->numpocs = numpocs;
-                       }
-                       break;
-      /* ------------------------------------------------------ */
-    case 'S':                  /* SOP marker */
-      j2k_parameters->csty |= 0x02;
-      break;
-      /* ------------------------------------------------------ */
-    case 'E':                  /* EPH marker */
-      j2k_parameters->csty |= 0x04;
-      break;
-      /* ------------------------------------------------------ */
-    case 'M':                  /* Mode switch pas tous au point !! */
-      if (sscanf(optarg, "%d", &value) == 1) {
-                               for (i = 0; i <= 5; i++) {
-                                       int cache = value & (1 << i);
-                                       if (cache)
-                                               j2k_parameters->mode |= (1 << i);
-                               }
-      }
-      break;
-      /* ------------------------------------------------------ */
-    case 'R':                  /* ROI */
-      {
-                               if (sscanf(optarg, "OI:c=%d,U=%d", &j2k_parameters->roi_compno,
-                                           &j2k_parameters->roi_shift) != 2) {
-                                       fprintf(stderr, "ROI error !! [-ROI:c='compno',U='shift']\n");
-                                       return 1;
-                               }
-                       }
-                       break;
-      /* ------------------------------------------------------ */
-    case 'T':                  /* Tile offset */
-                       {
-                               if (sscanf(optarg, "%d,%d", &j2k_parameters->cp_tx0, &j2k_parameters->cp_ty0) != 2) {
-                                       fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");
-                                       return 1;
-                               }
-                       }
-                       break;
-      /* ------------------------------------------------------ */
-    case 'C':                  /* Add a comment */
-                       {
-                               j2k_parameters->cp_comment = (char*)malloc(strlen(optarg) + 1);
-                               if(j2k_parameters->cp_comment) {
-                                       strcpy(j2k_parameters->cp_comment, optarg);
-                               }
-                       }
-                       break;
-      /* ------------------------------------------------------ */
-    case 'I':                  /* reversible or not */
-                       {
-                               j2k_parameters->irreversible = 1;
-                       }
-                       break;
-      /* ------------------------------------------------------ */
-    case 'W':                  /* Width and Height and Cb and Cr subsampling in case of YUV format files */
-      if (sscanf
-                               (optarg, "%d,%d,%d,%d", &mj2_parameters.w, &mj2_parameters.h, &mj2_parameters.CbCr_subsampling_dx,
-                               &mj2_parameters.CbCr_subsampling_dy) != 4) {
-                               fprintf(stderr, "-W argument error");
-                               return 1;
-      }
-      break;
-      /* ------------------------------------------------------ */
-    case 'F':                  /* Video frame rate */
-      if (sscanf(optarg, "%d", &mj2_parameters.frame_rate) != 1) {
-                               fprintf(stderr, "-F argument error");
-                               return 1;
-      }
-      break;
-      /* ------------------------------------------------------ */
-       case 'D': /* Depth: the precision */
-               if(sscanf(optarg, "%d", &prec) != 1) prec = 0;
-               break;
-
-    default:
-      return 1;
-    }
-  }
-    
-  /* Error messages */
-  /* -------------- */
-       if (!mj2_parameters.cod_format || !mj2_parameters.decod_format) {
-    fprintf(stderr,
-      "Usage: %s -i yuv-file -o mj2-file (+ options)\n",argv[0]);
-    return 1;
-  }
-    if(prec < 1 || prec > 16)
-  {
-       fprintf(stderr, "Error: Depth %d must be in the range 8 .. 16\n",prec);
-       return 1;       
-  }
-       if ((j2k_parameters->cp_disto_alloc || j2k_parameters->cp_fixed_alloc || j2k_parameters->cp_fixed_quality)
-               && (!(j2k_parameters->cp_disto_alloc ^ j2k_parameters->cp_fixed_alloc ^ j2k_parameters->cp_fixed_quality))) {
-               fprintf(stderr, "Error: options -r -q and -f cannot be used together !!\n");
-               return 1;
-       }                               /* mod fixed_quality */
-
-       /* if no rate entered, lossless by default */
-       if (j2k_parameters->tcp_numlayers == 0) {
-               j2k_parameters->tcp_rates[0] = 0;       /* MOD antonin : losslessbug */
-               j2k_parameters->tcp_numlayers++;
-               j2k_parameters->cp_disto_alloc = 1;
-       }
-
-       if((j2k_parameters->cp_tx0 > j2k_parameters->image_offset_x0) || (j2k_parameters->cp_ty0 > j2k_parameters->image_offset_y0)) {
-               fprintf(stderr,
-                       "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
-                       j2k_parameters->cp_tx0, j2k_parameters->image_offset_x0, j2k_parameters->cp_ty0, j2k_parameters->image_offset_y0);
-               return 1;
-       }
-
-       for (i = 0; i < j2k_parameters->numpocs; i++) {
-               if (j2k_parameters->POC[i].prg == -1) {
-                       fprintf(stderr,
-                               "Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
-                               i + 1);
-               }
-       }
-  
-  if (j2k_parameters->cp_tdx > mj2_parameters.Dim[0] || j2k_parameters->cp_tdy > mj2_parameters.Dim[1]) {
-    fprintf(stderr,
-      "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
-      j2k_parameters->cp_tdx, mj2_parameters.Dim[0], j2k_parameters->cp_tdy, mj2_parameters.Dim[1]);
-    return 1;
-  }
-    
-  /* to respect profile - 0 */
-  /* ---------------------- */
-  
-  x1 = !mj2_parameters.Dim[0] ? (mj2_parameters.w - 1) * j2k_parameters->subsampling_dx 
-               + 1 : mj2_parameters.Dim[0] + (mj2_parameters.w - 1) * j2k_parameters->subsampling_dx + 1;
-  y1 = !mj2_parameters.Dim[1] ? (mj2_parameters.h - 1) * j2k_parameters->subsampling_dy 
-               + 1 : mj2_parameters.Dim[1] + (mj2_parameters.h - 1) * j2k_parameters->subsampling_dy + 1;   
-       mj2_parameters.numcomps = 3; /* YUV files only have 3 components */ 
-
-       mj2_parameters.prec = prec;
-
-       j2k_parameters->tcp_mct = 0;
-    
-       mj2file = fopen(mj2_parameters.outfile, "wb");
-  
-       if (!mj2file) {
-    fprintf(stderr, "failed to open %s for writing\n", argv[2]);
-    return 1;
-       }
-    
-       /* get a MJ2 decompressor handle */
-       cinfo = mj2_create_compress();
-       movie = (opj_mj2_t*)cinfo->mj2_handle;
-       
-       /* catch events using our callbacks and give a local context */
-       opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
-
-       /* setup encoder parameters */
-       mj2_setup_encoder(movie, &mj2_parameters);   
-  
-       movie->tk[0].num_samples = 
-        yuv_num_frames(&movie->tk[0],mj2_parameters.infile);
-
-       if (movie->tk[0].num_samples == -1) {
-               return 1;
-       }
-
-  // One sample per chunk
-       movie->tk[0].chunk = (mj2_chunk_t*) 
-        malloc(movie->tk[0].num_samples * sizeof(mj2_chunk_t));     
-       movie->tk[0].sample = (mj2_sample_t*) 
-        malloc(movie->tk[0].num_samples * sizeof(mj2_sample_t));
-  
-       if (mj2_init_stdmovie(movie)) {
-    fprintf(stderr, "Error with movie initialization");
-    return 1;
-       }    
-  
-// Writing JP, FTYP and MDAT boxes 
-// Assuming that the JP and FTYP boxes won't be longer than 300 bytes:
-       buf = (unsigned char*) 
-        malloc (300 * sizeof(unsigned char));
-
-       cio = opj_cio_open((opj_common_ptr)movie->cinfo, buf, 300);
-
-       mj2_write_jp(cio);
-       mj2_write_ftyp(movie, cio);
-
-       mdat_initpos = cio_tell(cio);
-       cio_skip(cio, 4);
-
-       cio_write(cio, MJ2_MDAT, 4);    
-
-       fwrite(buf,cio_tell(cio),1,mj2file);
-
-       offset = cio_tell(cio);
-       opj_cio_close(cio);
-       free(buf);
-
-       for(i = 0; i < movie->num_stk + movie->num_htk + movie->num_vtk; i++) 
-   {
-    if(movie->tk[i].track_type != 0) 
-  {
-       fprintf(stderr, "Unable to write sound or hint tracks\n");
-  }
-       else 
-  {
-       mj2_tk_t *tk;
-       int buflen = 0;
-  
-       tk = &movie->tk[i];     
-       tk->num_chunks = tk->num_samples;
-       numframes = tk->num_samples;
-       tk->depth = prec; 
-
-       fprintf(stderr, "Video Track number %d\n", i);
-
-       img = mj2_image_create(tk, j2k_parameters);          
-
-       buflen = 2 * (tk->w * tk->h * 8);
-       buf = (unsigned char *) malloc(buflen*sizeof(unsigned char));   
-
-       for(sampleno = 0; sampleno < numframes; sampleno++) 
- {
-       double init_time = opj_clock();
-       double elapsed_time;
-
-               if(yuvtoimage(tk, img, sampleno, j2k_parameters, 
-                       mj2_parameters.infile))
-          {
-               fprintf(stderr, "Error with frame number %d in YUV file\n", sampleno);
-               return 1;
-          }
-
-/* setup the encoder parameters using the current image and user parameters */
-       opj_setup_encoder(cinfo, j2k_parameters, img);
-
-       cio = opj_cio_open((opj_common_ptr)movie->cinfo, buf, buflen);
-                                                               
-       cio_skip(cio, 4);
-       cio_write(cio, JP2_JP2C, 4);    // JP2C
-
-/* encode the image */
-       bSuccess = opj_encode(cinfo, cio, img, NULL);
-
-       if (!bSuccess) {
-       opj_cio_close(cio);
-       fprintf(stderr, "failed to encode image\n");
-       return 1;
-       }
-
-       len = cio_tell(cio) - 8;
-       cio_seek(cio, 0);
-       cio_write(cio, len+8,4);
-       opj_cio_close(cio);
-
-       tk->sample[sampleno].sample_size = len+8;                               
-       tk->sample[sampleno].offset = offset;
-       tk->chunk[sampleno].offset = offset;    // There is one sample per chunk 
-       fwrite(buf, 1, len+8, mj2file);                         
-       offset += len+8;                                
-
-       elapsed_time = opj_clock()-init_time;
-       fprintf(stderr, "Frame number %d/%d encoded in %.2f mseconds\n", 
-               sampleno + 1, numframes, elapsed_time*1000);
-       total_time += elapsed_time;
- }     /* for(sampleno */
-
-       free(buf);
-       opj_image_destroy(img);
-  }
-   }/* for(i */
-  
-       fseek(mj2file, mdat_initpos, SEEK_SET);
-       
-       buf = (unsigned char*) malloc(4*sizeof(unsigned char));
-
-// Init a cio to write box length variable in a little endian way 
-       cio = opj_cio_open(NULL, buf, 4);
-       cio_write(cio, offset - mdat_initpos, 4);
-       fwrite(buf, 4, 1, mj2file);
-       fseek(mj2file,0,SEEK_END);
-       free(buf);
-
-// Writing MOOV box 
-       buf = (unsigned char*) 
-        malloc ((TEMP_BUF+numframes*20) * sizeof(unsigned char));
-       cio = opj_cio_open(movie->cinfo, buf, (TEMP_BUF+numframes*20));
-       mj2_write_moov(movie, cio);
-       fwrite(buf,cio_tell(cio),1,mj2file);
-       free(buf);
-
-       fprintf(stdout,"Total encoding time: %.2f s for %d frames (%.1f fps)\n",
-        total_time, numframes, (float)numframes/total_time);
-
-  // Ending program 
-  
-       fclose(mj2file);
-/* free remaining compression structures */
-       mj2_destroy_compress(movie);
-       free(cinfo);
-
-       if(j2k_parameters->cp_comment) free(j2k_parameters->cp_comment);
-       if(j2k_parameters->cp_matrice) free(j2k_parameters->cp_matrice);
-       opj_cio_close(cio);
-
-       return 0;
-}
diff --git a/mj2/meta_out.c b/mj2/meta_out.c
deleted file mode 100644 (file)
index ff80b5e..0000000
+++ /dev/null
@@ -1,2181 +0,0 @@
-/* meta_out.c */
-/* Dump MJ2, JP2 metadata (partial so far) to xml file */
-/* Callable from mj2_to_metadata */
-/* Contributed to Open JPEG by Glenn Pearson, contract software developer, U.S. National Library of Medicine.
-
-The base code in this file was developed by the author as part of a video archiving
-project for the U.S. National Library of Medicine, Bethesda, MD. 
-It is the policy of NLM (and U.S. government) to not assert copyright.
-
-A non-exclusive copy of this code has been contributed to the Open JPEG project.
-Except for copyright, inclusion of the code within Open JPEG for distribution and use
-can be bound by the Open JPEG open-source license and disclaimer, expressed elsewhere.
-*/
-
-#include <windows.h> /* for time functions */
-
-#include "../libopenjpeg/opj_includes.h"
-#include "mj2.h"
-
-#include <time.h>
-#include "meta_out.h"
-
-static BOOL notes = TRUE;
-static BOOL sampletables = FALSE;
-static BOOL raw = TRUE;
-static BOOL derived = TRUE;
-
-opj_tcp_t *j2k_default_tcp;
-
-/* Forwards */
-int xml_write_overall_header(FILE *file, FILE *xmlout, opj_mj2_t * movie, unsigned int sampleframe, opj_event_mgr_t *event_mgr);
-int xml_write_moov(FILE *file, FILE *xmlout, opj_mj2_t * movie, unsigned int sampleframe, opj_event_mgr_t *event_mgr);
-
-void uint_to_chars(unsigned int value, char* buf);
-
-void xml_write_trak(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum, unsigned int sampleframe, opj_event_mgr_t *event_mgr);
-void xml_write_tkhd(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum);
-void xml_write_udta(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum);
-void xml_write_mdia(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum);
-void xml_write_stbl(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum);
-
-void UnixTimeToFileTime(time_t t, LPFILETIME pft);
-void UnixTimeToSystemTime(time_t t, LPSYSTEMTIME pst);
-void xml_time_out(FILE* xmlout, time_t t);
-
-void int16_to_3packedchars(short int value, char* buf);
-
-void xml_write_moov_udta(FILE* xmlout, opj_mj2_t * movie);
-void xml_write_free_and_skip(FILE* xmlout, opj_mj2_t * movie);
-void xml_write_uuid(FILE* xmlout, opj_mj2_t * movie);
-
-int xml_out_frame(FILE* file, FILE* xmlout, mj2_sample_t *sample, unsigned int snum, opj_event_mgr_t *event_mgr);
-
-void xml_out_frame_siz(FILE* xmlout, opj_image_t *img, opj_cp_t *cp);
-void xml_out_frame_cod(FILE* xmlout, opj_tcp_t *tcp);
-void xml_out_frame_coc(FILE* xmlout, opj_tcp_t *tcp, int numcomps); /* opj_image_t *img); */
-BOOL same_component_style(opj_tccp_t *tccp1, opj_tccp_t *tccp2);
-void xml_out_frame_qcd(FILE* xmlout, opj_tcp_t *tcp);
-void xml_out_frame_qcc(FILE* xmlout, opj_tcp_t *tcp, int numcomps); /* opj_image_t *img); */
-BOOL same_component_quantization(opj_tccp_t *tccp1, opj_tccp_t *tccp2);
-void xml_out_frame_rgn(FILE* xmlout, opj_tcp_t *tcp, int numcomps);/* opj_image_t *img);*/
-void xml_out_frame_poc(FILE* xmlout, opj_tcp_t *tcp);
-void xml_out_frame_ppm(FILE* xmlout, opj_cp_t *cp);
-void xml_out_frame_ppt(FILE* xmlout, opj_tcp_t *tcp);
-void xml_out_frame_tlm(FILE* xmlout); /* j2k_default_tcp is passed globally */ /* NO-OP.  TLM NOT SAVED IN DATA STRUCTURE */
-void xml_out_frame_plm(FILE* xmlout); /* j2k_default_tcp is passed globally */ /* NO-OP.  PLM NOT SAVED IN DATA STRUCTURE.  opt in main; can be used in conjunction with PLT */
-void xml_out_frame_plt(FILE* xmlout, opj_tcp_t *tcp); /* NO-OP.  PLM NOT SAVED IN DATA STRUCTURE.  opt in main; can be used in conjunction with PLT */
-void xml_out_frame_crg(FILE* xmlout); /* j2k_default_tcp is passed globally */ /* opt in main; */
-void xml_out_frame_com(FILE* xmlout, opj_tcp_t *tcp); /* NO-OP.  COM NOT SAVED IN DATA STRUCTURE */ /* opt in main; */
-void xml_out_dump_hex(FILE* xmlout, char *data, int data_len, char* s);
-void xml_out_dump_hex_and_ascii(FILE* xmlout, char *data, int data_len, char* s);
-void xml_out_frame_jp2h(FILE* xmlout, opj_jp2_t *jp2_struct);
-#ifdef NOTYET
-/* Shown with cp, extended, as data structure... but it could be a new different one */
-void xml_out_frame_jp2i(FILE* xmlout, opj_cp_t *cp);/* IntellectualProperty 'jp2i' (no restrictions on location) */
-void xml_out_frame_xml(FILE* xmlout, opj_cp_t *cp); /* XML 'xml\040' (0x786d6c20).  Can appear multiply */
-void xml_out_frame_uuid(FILE* xmlout, opj_cp_t *cp); /* UUID 'uuid' (top level only) */
-void xml_out_frame_uinf(FILE* xmlout, opj_cp_t *cp); /* UUIDInfo 'uinf', includes UUIDList 'ulst' and URL 'url\40' */
-void xml_out_frame_unknown_type(FILE* xmlout, opj_cp_t *cp);
-#endif
-
-
-void xml_write_init(BOOL n, BOOL t, BOOL r, BOOL d)
-{
-  /* Init file globals */
-  notes = n;
-  sampletables = t;
-  raw = r;
-  derived = d;
-}
-
-int xml_write_struct(FILE* file, FILE *xmlout, opj_mj2_t * movie, unsigned int sampleframe, char* stringDTD, opj_event_mgr_t *event_mgr) {
-
-  if(stringDTD != NULL)
-  {
-    fprintf(xmlout,"<?xml version=\"1.0\" standalone=\"no\"?>\n");
-       /* stringDTD is known to start with "SYSTEM " or "PUBLIC " */
-       /* typical: SYSTEM mj2_to_metadata.dtd */
-       stringDTD[6] = '\0'; /* Break into two strings at space, so quotes can be inserted. */
-    fprintf(xmlout,"<!DOCTYPE MJ2_File %s \"%s\">\n", stringDTD, stringDTD+7); 
-       stringDTD[6] = ' '; /* restore for sake of debugger or memory allocator */
-  } else
-    fprintf(xmlout,"<?xml version=\"1.0\" standalone=\"yes\"?>\n");    
-
-  fprintf(xmlout, "<MJ2_File>\n");
-  xml_write_overall_header(file, xmlout, movie, sampleframe, event_mgr);
-  fprintf(xmlout, "</MJ2_File>");
-  return 0;
-}
-
-/* ------------- */
-
-int xml_write_overall_header(FILE *file, FILE *xmlout, opj_mj2_t * movie, unsigned int sampleframe, opj_event_mgr_t *event_mgr)
-{
-  int i;
-  char buf[5];
-  buf[4] = '\0';
-
-  fprintf(xmlout,   "  <JP2 BoxType=\"jP[space][space]\" Signature=\"0x0d0a870a\" />\n");
-  // Called after structure initialized by mj2_read_ftyp
-  fprintf(xmlout,   "  <FileType BoxType=\"ftyp\">\n");
-  uint_to_chars(movie->brand, buf);
-  fprintf(xmlout,   "    <Brand>%s</Brand>\n", buf);    /* 4 character; BR              */
-  fprintf(xmlout,   "    <MinorVersion>%u</MinorVersion>\n", movie->minversion);    /* 4 char; MinV            */
-  fprintf(xmlout,   "    <CompatibilityList Count=\"%d\">\n",movie->num_cl);
-  for (i = movie->num_cl - 1; i > -1; i--) /* read routine stored in reverse order, so let's undo damage */
-  {
-    uint_to_chars(movie->cl[i], buf);
-    fprintf(xmlout, "      <CompatibleBrand>%s</CompatibleBrand>\n", buf);    /*4 characters, each CLi */
-  }
-  fprintf(xmlout,   "    </CompatibilityList>\n");
-  fprintf(xmlout,   "  </FileType>\n");
-  xml_write_moov(file, xmlout, movie, sampleframe, event_mgr);
-  // To come?              <mdat>  // This is the container for media data that can also be accessed through track structures,
-                                   // so is redundant, and simply not of interest as metadata
-  //                       <moof>  // Allows incremental build up of movie.  Probably not in Simple Profile
-  xml_write_free_and_skip(xmlout, movie); /* NO OP so far */ /* May be a place where user squirrels metadata */
-  xml_write_uuid(xmlout, movie); /* NO OP so far */ /* May be a place where user squirrels metadata */
-  return 0;
-}
-
-/* ------------- */
-
-int xml_write_moov(FILE *file, FILE *xmlout, opj_mj2_t * movie, unsigned int sampleframe, opj_event_mgr_t *event_mgr)
-{
-  unsigned int tnum;
-  mj2_tk_t *track;
-
-  fprintf(xmlout,   "  <MovieBox BoxType=\"moov\">\n");
-  fprintf(xmlout,   "    <MovieHeader BoxType=\"mvhd\">\n");
-  fprintf(xmlout,   "      <CreationTime>\n");
-  if(raw)
-    fprintf(xmlout, "        <InSeconds>%u</InSeconds>\n", movie->creation_time);
-  if(notes)
-    fprintf(xmlout, "        <!-- Seconds since start of Jan. 1, 1904 UTC (Greenwich) -->\n");
-  /*  2082844800 = seconds between 1/1/04 and 1/1/70 */
-  /* There's still a time zone offset problem not solved... but spec is ambigous as to whether stored time
-     should be local or UTC */
-  if(derived) {
-    fprintf(xmlout, "        <AsLocalTime>"); 
-                             xml_time_out(xmlout, movie->creation_time - 2082844800);
-                                                     fprintf(xmlout,"</AsLocalTime>\n");
-  }
-  fprintf(xmlout,   "      </CreationTime>\n");
-  fprintf(xmlout,   "      <ModificationTime>\n");
-  if(raw)
-    fprintf(xmlout, "        <InSeconds>%u</InSeconds>\n", movie->modification_time);
-  if(derived) {
-    fprintf(xmlout, "        <AsLocalTime>"); 
-                             xml_time_out(xmlout, movie->modification_time - 2082844800);
-                                                     fprintf(xmlout,"</AsLocalTime>\n");
-  }
-  fprintf(xmlout,   "      </ModificationTime>\n");
-  fprintf(xmlout,   "      <Timescale>%d</Timescale>\n", movie->timescale);
-  if(notes)
-    fprintf(xmlout, "      <!-- Timescale defines time units in one second -->\n");
-  fprintf(xmlout,   "      <Rate>\n");        /* Rate to play presentation  (default = 0x00010000)          */
-  if(notes) {
-    fprintf(xmlout, "      <!-- Rate to play presentation is stored as fixed-point binary 16.16 value. Decimal value is approximation. -->\n");
-    fprintf(xmlout, "      <!-- Rate is expressed relative to normal (default) value of 0x00010000 (1.0) -->\n");
-  }
-  if(raw)
-    fprintf(xmlout, "        <AsHex>0x%08x</AsHex>\n", movie->rate);
-  if(derived)
-    fprintf(xmlout, "        <AsDecimal>%12.6f</AsDecimal>\n", (double)movie->rate/(double)0x00010000);
-  fprintf(xmlout,   "      </Rate>\n");
-  fprintf(xmlout,   "      <Duration>\n");
-  if(raw)
-    fprintf(xmlout, "        <InTimeUnits>%u</InTimeUnits>\n", movie->duration);
-  if(derived)
-    fprintf(xmlout, "        <InSeconds>%12.3f</InSeconds>\n", (double)movie->duration/(double)movie->timescale);    // Make this double later to get fractional seconds
-  fprintf(xmlout,   "      </Duration>\n");
-#ifdef CURRENTSTRUCT
-  movie->volume = movie->volume << 8;
-#endif
-  fprintf(xmlout,   "      <Volume>\n");
-  if(notes) {
-    fprintf(xmlout, "      <!-- Audio volume stored as fixed-point binary 8.8 value. Decimal value is approximation. -->\n");
-    fprintf(xmlout, "      <!-- Full, normal (default) value is 0x0100 (1.0) -->\n");
-  }
-  if(raw)
-    fprintf(xmlout, "        <AsHex>0x%04x</AsHex>\n", movie->volume);
-  if(derived)
-    fprintf(xmlout, "        <AsDecimal>%6.3f</AsDecimal>\n", (double)movie->volume/(double)0x0100);
-  fprintf(xmlout,   "      </Volume>\n");
-#ifdef CURRENTSTRUCT
-  if(notes)
-    fprintf(xmlout, "      <!-- Current m2j_to_metadata implementation always shows bits to right of decimal as zeroed. -->\n");
-  movie->volume = movie->volume >> 8;
-#endif
-  /* Transformation matrix for video                            */
-  fprintf(xmlout,   "      <TransformationMatrix>\n");
-  if(notes) {
-    fprintf(xmlout, "      <!-- 3 x 3 Video Transformation Matrix {a,b,u,c,d,v,x,y,w}.  Required: u=0, v=0, w=1 -->\n");
-    fprintf(xmlout, "      <!-- Maps decompressed point (p,q) to rendered point (ap + cq + x, bp + dq + y) -->\n");
-    fprintf(xmlout, "      <!-- Stored as Fixed Point Hex: all are binary 16.16, except u,v,w are 2.30 -->\n");
-    fprintf(xmlout, "      <!-- Unity = 0x00010000,0,0,0,0x00010000,0,0,0,0x40000000 -->\n");
-  }
-  fprintf(xmlout,   "        <TMa>0x%08x</TMa>\n", movie->trans_matrix[0]);    
-  fprintf(xmlout,   "        <TMb>0x%08x</TMb>\n", movie->trans_matrix[1]);    
-  fprintf(xmlout,   "        <TMu>0x%08x</TMu>\n", movie->trans_matrix[2]);    
-  fprintf(xmlout,   "        <TMc>0x%08x</TMc>\n", movie->trans_matrix[3]);    
-  fprintf(xmlout,   "        <TMd>0x%08x</TMd>\n", movie->trans_matrix[4]);    
-  fprintf(xmlout,   "        <TMv>0x%08x</TMv>\n", movie->trans_matrix[5]);    
-  fprintf(xmlout,   "        <TMx>0x%08x</TMx>\n", movie->trans_matrix[6]);    
-  fprintf(xmlout,   "        <TMy>0x%08x</TMy>\n", movie->trans_matrix[7]);    
-  fprintf(xmlout,   "        <TMw>0x%08x</TMw>\n", movie->trans_matrix[8]);
-  fprintf(xmlout,   "      </TransformationMatrix>\n");
-  fprintf(xmlout,   "    </MovieHeader>\n");
-  
-  fprintf(xmlout,   "    <Statistics>\n");
-  fprintf(xmlout,   "      <TracksFound>\n");
-  fprintf(xmlout,   "        <Video>%d</Video>\n", movie->num_vtk);
-  fprintf(xmlout,   "        <Audio>%d</Audio>\n", movie->num_stk);
-  fprintf(xmlout,   "        <Hint>%d</Hint>\n", movie->num_htk);
-  if(notes)
-    fprintf(xmlout, "        <!-- Hint tracks for streaming video are not part of MJ2, but are a defined extension. -->\n");
-  /* See Part 3 Amend 2 Section 4.2 for relation of MJ2 to Part 12 Sections 7 and 10 hints */
-  fprintf(xmlout,   "      </TracksFound>\n");
-  fprintf(xmlout,   "    </Statistics>\n");
-  /* Idea for the future:  It would be possible to add code to verify that the file values:
-    1) are legal and self-consistent
-       2) comply with particular JP2 and/or MJ2 profiles.
-       This could be reported here as additional XML elements */
-
-  // Find first video track 
-  tnum = 0;
-  while (movie->tk[tnum].track_type != 0)
-    tnum ++;
-
-  track = &(movie->tk[tnum]);
-  // For now, output info on first video track
-  xml_write_trak(file, xmlout, track, tnum, sampleframe, event_mgr);
-
-  // to come:                <MovieExtends mvek> // possibly not in Simple Profile
-  xml_write_moov_udta(xmlout, movie); /* NO OP so far */ /* <UserDataBox udta> contains <CopyrightBox cprt> */
-  fprintf(xmlout,   "  </MovieBox>\n");
-  return 0;
-}
-
-/* --------------- */
-
-void uint_to_chars(unsigned int value, char* buf)
-{
-       /* buf is at least char[5] */
-    int i;
-    for (i = 3; i >= 0; i--)
-    {
-        buf[i] = (value & 0x000000ff);
-        value = (value >> 8);
-    }
-       buf[4] = '\0'; /* Precautionary */
-}
-
-/* ------------- */
-
-/* WINDOWS SPECIFIC */
-
-void UnixTimeToFileTime(time_t t, LPFILETIME pft)
-{
-  /* Windows specific.  From MS Q167296 */
-  /* 'time_t' represents seconds since midnight January 1, 1970 UTC (coordinated universal time). */
-  /* 64-bit FILETIME structure represents the number of 100-nanosecond intervals since January 1, 1601 UTC (coordinate universal time). */
-  LONGLONG ll; /* LONGLONG is a 64-bit value. */
-  ll = Int32x32To64(t, 10000000) + 116444736000000000;
-  pft->dwLowDateTime = (DWORD)ll;
-  /* pft->dwLowDateTime = (DWORD)(0x00000000ffffffff & ll); */
-  pft->dwHighDateTime = (DWORD)(ll >> 32);
-} 
-// Once the UNIX time is converted to a FILETIME structure,
-// other Win32 time formats can be easily obtained by using Win32 functions such
-// as FileTimeToSystemTime() and FileTimeToDosDateTime().
-
-/* ------------- */
-
-void UnixTimeToSystemTime(time_t t, LPSYSTEMTIME pst)
-{
-  /* Windows specific */
-  FILETIME ft;
-  UnixTimeToFileTime(t, &ft);
-  FileTimeToLocalFileTime( &ft, &ft ); /* Adjust from UTC to local time zone */
-  FileTimeToSystemTime(&ft, pst);
-}
-
-/* ------------- */
-
-void xml_time_out(FILE* xmlout, time_t t)
-{
-  /* Windows specific */
-  SYSTEMTIME st;
-  char szLocalDate[255], szLocalTime[255];
-  UnixTimeToSystemTime( t, &st );
-  GetDateFormat( LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, szLocalDate, 255 );
-  GetTimeFormat( LOCALE_USER_DEFAULT, 0, &st, NULL, szLocalTime, 255 );
-  fprintf(xmlout, "%s %s", szLocalDate, szLocalTime ); 
-}
-
-/* END WINDOWS SPECIFIC */
-
-/* ------------- */
-
-void xml_write_moov_udta(FILE* xmlout, opj_mj2_t * movie) {
-  /* Compare with xml_write_udta */
-#ifdef NOTYET
-  /* NO-OP so far.  Optional UserData 'udta' (zero or one in moov or each trak)
-     can contain multiple Copyright 'cprt' with different language codes */
-  /* There may be nested non-standard boxes within udta */
-  IMAGINE movie->udta, movie->copyright_count, movie->copyright_language[i] (array of 16bit ints), movie->copyright_notice[i] (array of buffers)
-  PROBABLY ALSO NEED movie->udta_len or special handler for non-standard boxes
-  char buf[5];
-  int i;
-
-  if(movie->udta != 1)
-         return; /* Not present */
-
-  fprintf(xmlout,    "    <UserData BoxType=\"udta\">\n");
-  for(i = 0; i < movie->copyright_count; i++) {
-    fprintf(xmlout,  "      <Copyright BoxType=\"cprt\"> Instance=\"%d\">\n", i+1);
-    int16_to_3packedchars((short int)movie->copyright_languages[i], buf);
-    fprintf(xmlout,  "        <Language>%s</Language>\n", buf);    /* 3 chars */
-    fprintf(xmlout,  "        <Notice>%s</Notice>\n",movie->copyright_notices[i]);
-    fprintf(xmlout,  "      </Copyright>\n", i+1);
-  }
-  /* TO DO: Non-standard boxes */
-  fprintf(xmlout,    "    </UserData>\n");
-#endif
-}
-
-void xml_write_free_and_skip(FILE* xmlout, opj_mj2_t * movie) {
-#ifdef NOTYET
-  /* NO-OP so far.  There can be zero or more instances of free and/or skip
-     at the top level of the file.  This may be a place where the user squirrel's metadata.
-        Let's assume unstructured, and do a dump */
-  IMAGINE movie->free_and_skip, movie->free_and_skip_count, movie->free_and_skip_content[i] (array of buffers),
-         movie->free_and_skip_len[i] (array of ints), movie->is_skip[i] (array of BOOL)
-  int i;
-
-  if(movie->free_and_skip != 1)
-         return; /* Not present */
-
-  for(i = 0; i < movie->free_and_skip_count; i++) {
-    if(movie->is_skip[i])
-      fprintf(xmlout,    "  <Skip BoxType=\"skip\">\n");
-       else
-      fprintf(xmlout,    "  <Free BoxType=\"free\">\n");
-
-    xml_out_dump_hex_and_ascii(xmlout, movie->free_and_skip_contents[i], movie->free_and_skip_len[i]);
-
-    if(movie->is_skip[i])
-      fprintf(xmlout,    "  </Skip>\n");
-       else
-      fprintf(xmlout,    "  </Free>\n");
-  }
-#endif
-}
-
-void xml_write_uuid(FILE* xmlout, opj_mj2_t * movie) {
-/* Univeral Unique IDs of 16 bytes.  */
-#ifdef NOTYET
-  /* NO-OP so far.  There can be zero or more instances of private uuid boxes in a file.
-     This function supports the top level of the file, but uuid may be elsewhere [not yet supported].
-        This may be a place where the user squirrel's metadata.  Let's assume unstructured, and do a dump */
-  IMAGINE movie->uuid, movie->uuid_count, movie->uuid_content[i] (array of buffers),
-         movie->uuid_len[i] (array of ints), movie->uuid_type[i] (array of 17-byte (16+null termination) buffers)
-  int i;
-
-  if(movie->uuid != 1)
-         return; /* Not present */
-
-  for(i = 0; i < movie->uuid_count; i++) {
-    fprintf(xmlout,    "  <PrivateExtension BoxType=\"uuid\" UUID=\"%s\">\n", movie->uuid_type[i]);
-       // See Part III section 5.2.1, 6.1, 6.2
-    xml_out_dump_hex_and_ascii(xmlout, movie->uuid_contents[i], movie->uuid_len[i]);
-    fprintf(xmlout,    "  </PrivateExtension>\n");
-  }
-#endif
-}
-
-/* ------------- */
-
-void xml_write_trak(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum, unsigned int sampleframe, opj_event_mgr_t *event_mgr)
-{
-  fprintf(xmlout,    "    <Track BoxType=\"trak\" Instance=\"%d\">\n", tnum);
-  xml_write_tkhd(file, xmlout, track, tnum);
-  // TO DO: TrackReferenceContainer 'tref'  just used in hint track
-  // TO DO: EditListContainer 'edts', contains EditList 'elst' with media-time, segment-duration, media-rate
-  xml_write_mdia(file, xmlout, track, tnum);
-  xml_write_udta(file, xmlout, track, tnum); // NO-OP so far.  Optional UserData 'udta', can contain multiple Copyright 'cprt'
-
-  if(track->track_type==0) { /* Only do for visual track */
-       /* sampleframe is from user option -f.  1 = first frame */
-    /* sampleframe of 0 is a user requests: no jp2 header */
-       /* Treat out-of-bounds values in the same way */
-       if(sampleframe > 0 && sampleframe <= track->num_samples) 
-    {
-      mj2_sample_t *sample;
-      unsigned int snum;
-
-      snum = sampleframe-1;
-      // Someday maybe do a smart range scan... for (snum=0; snum < track->num_samples; snum++){
-      //  fprintf(stdout,"Frame %d: ",snum+1);
-      sample = &track->sample[snum];
-         if(xml_out_frame(file, xmlout, sample, snum, event_mgr))
-           return; /* Not great error handling here */
-    }
-  }
-  fprintf(xmlout,    "    </Track>\n");
-}
-
-/* ------------- */
-
-void xml_write_tkhd(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum)
-{
-  fprintf(xmlout,    "      <TrackHeader BoxType=\"tkhd\">\n");
-  if(notes) {
-    fprintf(xmlout,  "      <!-- Not shown here: CreationTime, ModificationTime, Duration. -->\n");
-    fprintf(xmlout,  "      <!-- These 3 fields are reported under MediaHeader below.   When reading these 3, -->\n");
-    fprintf(xmlout,  "      <!-- m2j_to_metadata currently doesn't distinguish between TrackHeader and MediaHeader source. -->\n");
-    fprintf(xmlout,  "      <!-- If both found, value read from MediaHeader is used. -->\n");
-  }
-  fprintf(xmlout,    "        <TrackID>%u</TrackID>\n", track->track_ID);
-  if(track->track_type==0) /* For visual track */
-  {
-    fprintf(xmlout,  "        <TrackLayer>%d</TrackLayer>\n", track->layer);
-    if(notes)
-      fprintf(xmlout,"        <!-- front-to-back ordering of video tracks. 0 = normal, -1 is closer, etc. -->\n");
-  }
-  if(track->track_type!=0) /* volume irrelevant for visual track */
-  {
-#ifdef CURRENTSTRUCT
-    track->volume = track->volume << 8;
-#endif
-    fprintf(xmlout,  "        <Volume>\n");
-       if(notes) {
-      fprintf(xmlout,"          <!-- Track audio volume stored as fixed-point binary 8.8 value. Decimal value is approximation. -->\n");
-      fprintf(xmlout,"          <!-- Full, normal (default) value is 0x0100 (1.0) -->\n");
-       }
-       if(raw)
-      fprintf(xmlout,"          <AsHex>0x%04x</AsHex>\n", track->volume);
-       if(derived)
-      fprintf(xmlout,"          <AsDecimal>%6.3f</AsDecimal>\n", (double)track->volume/(double)0x0100);
-    fprintf(xmlout,  "        </Volume>\n");
-#ifdef CURRENTSTRUCT
-  if(notes)
-    fprintf(xmlout,  "        <!-- Current m2j_to_metadata implementation always shows bits to right of decimal as zeroed. -->\n");
-       track->volume = track->volume >> 8;
-#endif
-  }
-  if(track->track_type==0)
-  {
-    /* Transformation matrix for video                            */
-    fprintf(xmlout,  "        <TransformationMatrix>\n");
-       if(notes) {
-      fprintf(xmlout,"          <!-- Comments about matrix in MovieHeader apply here as well. -->\n");
-      fprintf(xmlout,"          <!-- This matrix is applied before MovieHeader one. -->\n");
-       }
-    fprintf(xmlout,  "          <TMa>0x%08x</TMa>\n", track->trans_matrix[0]);    
-    fprintf(xmlout,  "          <TMb>0x%08x</TMb>\n", track->trans_matrix[1]);    
-    fprintf(xmlout,  "          <TMu>0x%08x</TMu>\n", track->trans_matrix[2]);    
-    fprintf(xmlout,  "          <TMc>0x%08x</TMc>\n", track->trans_matrix[3]);    
-    fprintf(xmlout,  "          <TMd>0x%08x</TMd>\n", track->trans_matrix[4]);    
-    fprintf(xmlout,  "          <TMv>0x%08x</TMv>\n", track->trans_matrix[5]);    
-    fprintf(xmlout,  "          <TMx>0x%08x</TMx>\n", track->trans_matrix[6]);    
-    fprintf(xmlout,  "          <TMy>0x%08x</TMy>\n", track->trans_matrix[7]);    
-    fprintf(xmlout,  "          <TMw>0x%08x</TMw>\n", track->trans_matrix[8]);
-    fprintf(xmlout,  "        </TransformationMatrix>\n");
-  }
-#ifdef CURRENTSTRUCT
-  track->w = track->w << 16;
-  track->h = track->h << 16;
-#endif
-  if(notes) {
-    fprintf(xmlout,  "        <!-- Width and Height in pixels are for the presentation; frames will be scaled to this. -->\n");
-    fprintf(xmlout,  "        <!-- Both stored as fixed-point binary 16.16 values. Decimal values are approximations. -->\n");
-  }
-  fprintf(xmlout,    "        <Width>\n");
-  if(raw)
-    fprintf(xmlout,  "          <AsHex>0x%08x</AsHex>\n", track->w);
-  if(derived)
-    fprintf(xmlout,  "          <AsDecimal>%12.6f</AsDecimal>\n", (double)track->w/(double)0x00010000);        /* Rate to play presentation  (default = 0x00010000)          */
-  fprintf(xmlout,    "        </Width>\n");
-  fprintf(xmlout,    "        <Height>\n");
-  if(raw)
-    fprintf(xmlout,  "          <AsHex>0x%08x</AsHex>\n", track->h);
-  if(derived)
-    fprintf(xmlout,  "          <AsDecimal>%12.6f</AsDecimal>\n", (double)track->h/(double)0x00010000);        /* Rate to play presentation  (default = 0x00010000)          */
-  fprintf(xmlout,    "        </Height>\n");
-#ifdef CURRENTSTRUCT
-  if(notes) {
-    fprintf(xmlout,  "        <!-- Current m2j_to_metadata implementation always shows bits to right of decimal as zeroed. -->\n");
-    fprintf(xmlout,  "        <!-- Also, width and height values shown here will actually be those read from track's <VisualSampleEntry> if given. -->\n");
-  }
-  track->w = track->w >> 16;
-  track->h = track->h >> 16;
-#endif
-  fprintf(xmlout,    "      </TrackHeader>\n");
-}
-
-/* ------------- */
-
-void xml_write_udta(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum) {
-  /* NO-OP so far.  Optional UserData 'udta' (zero or one in moov or each trak)
-     can contain multiple Copyright 'cprt' with different language codes */
-  /* There may be nested non-standard boxes within udta */
-#ifdef NOTYET
-  IMAGINE track->udta, track->copyright_count, track->copyright_language[i] (array of 16bit ints), track->copyright_notice[i] (array of buffers)
-  PROBABLY ALSO NEED track->udta_len or special handler for non-standard boxes
-  char buf[5];
-  int i;
-
-  if(track->udta != 1)
-         return; /* Not present */
-
-  fprintf(xmlout,    "      <UserData BoxType=\"udta\">\n");
-  for(i = 0; i < track->copyright_count; i++) {
-    fprintf(xmlout,  "        <Copyright BoxType=\"cprt\"> Instance=\"%d\">\n", i+1);
-    int16_to_3packedchars((short int)track->copyright_languages[i], buf);
-    fprintf(xmlout,  "          <Language>%s</Language>\n", buf);    /* 3 chars */
-    fprintf(xmlout,  "          <Notice>%s</Notice>\n",track->copyright_notices[i]);
-    fprintf(xmlout,  "        </Copyright>\n", i+1);
-  }
-  /* TO DO: Non-standard boxes */
-  fprintf(xmlout,    "      </UserData>\n");
-#endif
-}
-
-/* ------------- */
-
-void xml_write_mdia(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum)
-{
-  char buf[5];
-  int i, k;
-  buf[4] = '\0';
-
-  fprintf(xmlout,    "      <Media BoxType=\"mdia\">\n");
-  fprintf(xmlout,    "        <MediaHeader BoxType=\"mdhd\">\n");
-  fprintf(xmlout,    "          <CreationTime>\n");
-  if(raw)
-    fprintf(xmlout,  "            <InSeconds>%u</InSeconds>\n", track->creation_time);
-  if(notes)
-    fprintf(xmlout,  "            <!-- Seconds since start of Jan. 1, 1904 UTC (Greenwich) -->\n");
-  /*  2082844800 = seconds between 1/1/04 and 1/1/70 */
-  /* There's still a time zone offset problem not solved... but spec is ambigous as to whether stored time
-     should be local or UTC */
-  if(derived) {
-    fprintf(xmlout,  "            <AsLocalTime>"); 
-                                xml_time_out(xmlout, track->creation_time - 2082844800);
-                                                     fprintf(xmlout,"</AsLocalTime>\n");
-  }
-  fprintf(xmlout,    "          </CreationTime>\n");
-  fprintf(xmlout,    "          <ModificationTime>\n");
-  if(raw)
-    fprintf(xmlout,  "            <InSeconds>%u</InSeconds>\n", track->modification_time);
-  if(derived) {
-    fprintf(xmlout,  "            <AsLocalTime>"); 
-                                xml_time_out(xmlout, track->modification_time - 2082844800);
-                                                     fprintf(xmlout,"</AsLocalTime>\n");
-  }
-  fprintf(xmlout,    "          </ModificationTime>\n");
-  fprintf(xmlout,    "          <Timescale>%d</Timescale>\n", track->timescale);
-  if(notes)
-    fprintf(xmlout,  "          <!-- Timescale defines time units in one second -->\n");
-  fprintf(xmlout,    "          <Duration>\n");
-  if(raw)
-    fprintf(xmlout,  "            <InTimeUnits>%u</InTimeUnits>\n", track->duration);
-  if(derived)
-    fprintf(xmlout,  "            <InSeconds>%12.3f</InSeconds>\n", (double)track->duration/(double)track->timescale);    // Make this double later to get fractional seconds
-  fprintf(xmlout,    "          </Duration>\n");
-  int16_to_3packedchars((short int)track->language, buf);
-  fprintf(xmlout,    "          <Language>%s</Language>\n", buf);    /* 3 chars */
-  fprintf(xmlout,    "        </MediaHeader>\n");
-  fprintf(xmlout,    "        <HandlerReference BoxType=\"hdlr\">\n");
-  switch(track->track_type)
-  {
-  case 0:
-    fprintf(xmlout,  "          <HandlerType Code=\"vide\">video media track</HandlerType>\n"); break;
-  case 1:
-    fprintf(xmlout,  "          <HandlerType Code=\"soun\">Sound</HandlerType>\n"); break;
-  case 2:
-    fprintf(xmlout,  "          <HandlerType Code=\"hint\">Hint</HandlerType>\n"); break;
-  }
-  if(notes) {
-    fprintf(xmlout,  "          <!-- String value shown is not actually read from file. -->\n");
-    fprintf(xmlout,  "          <!-- Shown value is one used for our encode. -->\n");
-  }
-  fprintf(xmlout,    "        </HandlerReference>\n");
-  fprintf(xmlout,    "        <MediaInfoContainer BoxType=\"minf\">\n");
-  switch(track->track_type)
-  {
-  case 0:
-    fprintf(xmlout,  "          <VideoMediaHeader BoxType=\"vmhd\">\n");
-    fprintf(xmlout,  "            <GraphicsMode>0x%02x</GraphicsMode>\n", track->graphicsmode);
-       if(notes) {
-      fprintf(xmlout,"            <!-- Enumerated values of graphics mode: -->\n");
-      fprintf(xmlout,"            <!--  0x00 = copy (over existing image); -->\n");
-      fprintf(xmlout,"            <!--  0x24 = transparent; 'blue-screen' this image using opcolor; -->\n");
-      fprintf(xmlout,"            <!--  0x100 = alpha; alpha-blend this image -->\n");
-/*    fprintf(xmlout,"            <!--  0x101 = whitealpha; alpha-blend this image, which has been blended with white; -->\n"); This was evidently dropped upon amendment */
-      fprintf(xmlout,"            <!--  0x102 = pre-multiplied black alpha; image has been already been alpha-blended with black. -->\n");
-      fprintf(xmlout,"            <!--  0x110 = component alpha; blend alpha channel(s) and color channels individually. -->\n");
-       }
-    fprintf(xmlout,  "            <Opcolor>\n");
-    fprintf(xmlout,  "              <Red>0x%02x</Red>\n", track->opcolor[0]);
-    fprintf(xmlout,  "              <Green>0x%02x</Green>\n",track->opcolor[1]);
-    fprintf(xmlout,  "              <Blue>0x%02x</Blue>\n",track->opcolor[2]);
-    fprintf(xmlout,  "            </Opcolor>\n");
-    fprintf(xmlout,  "          </VideoMediaHeader>\n");
-    break;
-  case 1:
-    fprintf(xmlout,  "          <SoundMediaHeader BoxType=\"smhd\">\n");
-#ifdef CURRENTSTRUCT
-       track->balance = track->balance << 8;
-#endif
-    fprintf(xmlout,  "            <Balance>\n");
-       if(notes) {
-      fprintf(xmlout,"              <!-- Track audio balance fixes mono track in stereo space. -->\n");
-      fprintf(xmlout,"              <!-- Stored as fixed-point binary 8.8 value. Decimal value is approximation. -->\n");
-      fprintf(xmlout,"              <!-- 0.0 = center, -1.0 = full left, 1.0 = full right -->\n");
-       }
-       if(raw)
-      fprintf(xmlout,"              <AsHex>0x%04x</AsHex>\n", track->balance);
-    if(derived)
-         fprintf(xmlout,"              <AsDecimal>%6.3f</AsDecimal>\n", (double)track->balance/(double)0x0100);
-    fprintf(xmlout,  "            </Balance>\n");
-#ifdef CURRENTSTRUCT
-    if(notes)
-         fprintf(xmlout,"            <!-- Current m2j_to_metadata implementation always shows bits to right of decimal as zeroed. -->\n");
-       track->balance = track->balance >> 8;
-#endif
-    fprintf(xmlout,  "          </SoundMediaHeader>\n");
-    break;
-  case 2:
-    fprintf(xmlout,  "          <HintMediaHeader BoxType=\"hmhd\">\n");
-    fprintf(xmlout,  "            <MaxPDU_Size>%d</MaxPDU_Size>\n", track->maxPDUsize);
-    if(notes)
-      fprintf(xmlout,"            <!-- Size in bytes of largest PDU in this hint stream. -->\n");
-    fprintf(xmlout,  "            <AvgPDU_Size>%d</AvgPDU_Size>\n", track->avgPDUsize);
-    if(notes)
-      fprintf(xmlout,"            <!-- Average size in bytes of a PDU over the entire presentation. -->\n");
-    fprintf(xmlout,  "            <MaxBitRate>%d</MaxBitRate>\n", track->maxbitrate);
-    if(notes)
-      fprintf(xmlout,"            <!-- Maximum rate in bits per second over any window of 1 second. -->\n");
-    fprintf(xmlout,  "            <AvgBitRate>%d</AvgBitRate>\n", track->avgbitrate);
-    if(notes)
-      fprintf(xmlout,"            <!-- Averate rate in bits per second over the entire presentation. -->\n");
-    fprintf(xmlout,  "            <SlidingAvgBit>%d</SlidingAvgBitRate>\n", track->slidingavgbitrate);
-    if(notes)
-      fprintf(xmlout,"            <!-- Maximum rate in bits per second over any window of one minute. -->\n");
-    fprintf(xmlout,  "          </HintMediaHeader>\n");
-    break;
-  }
-  fprintf(xmlout,    "          <DataInfo BoxType=\"dinf\">\n");
-  fprintf(xmlout,    "            <DataReference BoxType=\"dref\"  URL_Count=\"%d\" URN_Count=\"%d\">\n", track->num_url, track->num_urn); // table w. flags, URLs, URNs
-  // Data structure does not distinguish between single URL, single URN, or DREF table or URLs & URNs.
-  // We could infer those, but for now just present everything as a DREF table.
-  if(notes)
-    fprintf(xmlout,  "              <!-- No entries here mean that file is self-contained, as required by Simple Profile. -->\n");
-  for(k = 0; k < track->num_url; k++) {
-    fprintf(xmlout,  "            <DataEntryUrlBox BoxType=\"url[space]\">\n"); // table w. flags, URLs, URNs
-    if(notes)
-      fprintf(xmlout,"              <!-- Only the first 16 bytes of URL location are recorded in mj2_to_metadata data structure. -->\n");
-    for(i = 0; i < 4; i++) {
-      uint_to_chars(track->url[track->num_url].location[i], buf);
-    fprintf(xmlout,  "              <Location>%s</Location>\n");
-    }
-    fprintf(xmlout,  "            </DataEntryUrlBox>\n"); // table w. flags, URLs, URNs
-  }
-  for(k = 0; k < track->num_urn; k++) {
-    fprintf(xmlout,"            <DataEntryUrnBox BoxType=\"urn[space]\">\n"); // table w. flags, URLs, URNs
-    // Only the first 16 bytes are recorded in the data structure currently.
-    if(notes)
-      fprintf(xmlout,"              <!-- Only the first 16 bytes each of URN name and optional location are recorded in mj2_to_metadata data structure. -->\n");
-    fprintf(xmlout,  "              <Name>");
-    for(i = 0; i < 4; i++) {
-      uint_to_chars(track->urn[track->num_urn].name[i], buf);
-      fprintf(xmlout,"%s", buf);
-    }
-    fprintf(xmlout,  "</Name>\n");
-    fprintf(xmlout,  "              <Location>");
-    for(i = 0; i < 4; i++) {
-      uint_to_chars(track->urn[track->num_urn].location[i], buf);
-      fprintf(xmlout,"%s");
-    }
-    fprintf(xmlout,  "</Location>\n");
-    fprintf(xmlout,  "            </DataEntryUrnBox>\n");
-  }
-  fprintf(xmlout,    "            </DataReference>\n");
-  fprintf(xmlout,    "          </DataInfo>\n");
-
-  xml_write_stbl(file, xmlout, track, tnum); /* SampleTable */
-
-  fprintf(xmlout,    "        </MediaInfoContainer>\n");  
-  fprintf(xmlout,    "      </Media>\n");
-}
-
-/* ------------- */
-
-void xml_write_stbl(FILE* file, FILE* xmlout, mj2_tk_t *track, unsigned int tnum)
-{
-  char buf[5], buf33[33];
-  int i, len;
-  buf[4] = '\0';
-
-  fprintf(xmlout,      "          <SampleTable BoxType=\"stbl\">\n");
-  if(notes)
-    fprintf(xmlout,    "            <!-- What follows are specific instances of generic SampleDescription BoxType=\"stsd\" -->\n");
-  switch(track->track_type)
-  {
-  case 0:
-    // There could be multiple instances of this, but "entry_count" is just a local at read-time.
-    // And it's used wrong, too, as count of just visual type, when it's really all 3 types.
-    // This is referred to as "smj2" within mj2.c
-    fprintf(xmlout,    "            <VisualSampleEntry BoxType=\"mjp2\">\n");
-       if(notes) {
-      fprintf(xmlout,  "            <!-- If multiple instances of this box, only first is shown here. -->\n");
-         fprintf(xmlout,  "            <!-- Width and Height are in pixels.  Unlike the Track Header, there is no fractional part. -->\n");
-         fprintf(xmlout,  "            <!-- In mj2_to_metadata implementation, the values are not represented separately from Track Header's values. -->\n");
-       }
-       /* No shifting required.  If CURRENTSTRUCT gets changed, then may need to revisit treatment of these */
-    fprintf(xmlout,    "              <WidthAsInteger>%d</WidthAsInteger>\n", track->w);
-    fprintf(xmlout,    "              <HeightAsInteger>%d</HeightAsInteger>\n", track->h);
-// Horizresolution and vertresolution don't require shifting, already stored right in CURRENTSTRUCT
-    if(notes) {
-      fprintf(xmlout,  "              <!-- Resolutions are in pixels per inch, for the highest-resolution component (typically luminance). -->\n");
-      fprintf(xmlout,  "              <!-- Both stored as fixed-point binary 16.16 values. Decimal values are approximations. -->\n");
-      fprintf(xmlout,  "              <!-- Typical value for both resolutions is 0x00480000  (72.0) -->\n");
-       }
-    fprintf(xmlout,    "              <HorizontalRes>\n");
-       if(raw)
-      fprintf(xmlout,  "                <AsHex>0x%08x</AsHex>\n", track->horizresolution);
-       if(derived)
-      fprintf(xmlout,  "                <AsDecimal>%12.6f</AsDecimal>\n", (double)track->horizresolution/(double)0x00010000);        /* Rate to play presentation  (default = 0x00010000)          */
-    fprintf(xmlout,    "              </HorizontalRes>\n");
-    fprintf(xmlout,    "              <VerticalRes>\n");
-       if(raw)
-      fprintf(xmlout,  "                <AsHex>0x%08x</AsHex>\n", track->vertresolution);
-       if(derived)
-      fprintf(xmlout,  "                <AsDecimal>%12.6f</AsDecimal>\n", (double)track->vertresolution/(double)0x00010000);        /* Rate to play presentation  (default = 0x00010000)          */
-    fprintf(xmlout,    "              </VerticalRes>\n");
-
-    buf33[0] = '\0';
-    for(i = 0; i < 8; i++) {
-      uint_to_chars((unsigned int)track->compressorname[i], buf);
-      strcat(buf33, buf); /* This loads up (4 * 8) + 1 chars, but trailing ones are usually junk */
-    }
-    len = (int)buf33[0]; /* First byte has string length in bytes.  There may be garbage beyond it. */
-    buf33[len+1] = '\0'; /* Suppress it */
-    fprintf(xmlout,    "              <CompressorName>%s</CompressorName>\n", buf33+1); /* Start beyond first byte */
-       if(notes) {
-      fprintf(xmlout,  "              <!-- Compressor name for debugging.  Standard restricts max length to 31 bytes. -->\n");
-      fprintf(xmlout,  "              <!-- Usually blank or \"Motion JPEG2000\" -->\n");
-       }
-    fprintf(xmlout,    "              <Depth>0x%02x</Depth>\n",track->depth);
-       if(notes) {
-      fprintf(xmlout,  "              <!-- Depth is: -->\n");
-      fprintf(xmlout,  "              <!--   0x20: alpha channels present (color or grayscale) -->\n");
-      fprintf(xmlout,  "              <!--   0x28: grayscale without alpha -->\n");
-      fprintf(xmlout,  "              <!--   0x18: color without alpha -->\n");
-       }
-
-    xml_out_frame_jp2h(xmlout, &(track->jp2_struct));  /* JP2 Header */
-    
-  /* Following subboxes are optional */
-    fprintf(xmlout,    "              <FieldCoding BoxType=\"fiel\">\n");
-    fprintf(xmlout,    "                <FieldCount>%d</FieldCount>\n", (unsigned int)track->fieldcount); /* uchar as 1 byte uint */
-    if(notes)
-      fprintf(xmlout,  "                <!-- Must be either 1 or 2 -->\n");
-    fprintf(xmlout,    "                <FieldOrder>%d</FieldOrder>\n", (unsigned int)track->fieldorder); /* uchar as 1 byte uint */
-       if(notes) {
-      fprintf(xmlout,  "                <!-- When FieldCount=2, FieldOrder means: -->\n");
-      fprintf(xmlout,  "                <!--   0: Field coding unknown -->\n");
-      fprintf(xmlout,  "                <!--   1: Field with topmost line is stored first in sample; fields are in temporal order -->\n");
-      fprintf(xmlout,  "                <!--   6: Field with topmost line is stored second in sample; fields are in temporal order -->\n");
-      fprintf(xmlout,  "                <!-- Defaults: FieldCount=1, FieldOrder=0 if FieldCoding box not present -->\n");
-      fprintf(xmlout,  "                <!-- Current implementation doesn't retain whether box was actually present. -->\n");
-       }
-    fprintf(xmlout,    "              </FieldCoding>\n");
-
-    fprintf(xmlout,    "              <MJP2_Profile BoxType=\"jp2p\" Count=\"%d\">\n",track->num_br);
-    for (i = 0; i < track->num_br; i++) /* read routine stored in reverse order, so let's undo damage */
-    {
-      uint_to_chars(track->br[i], buf);
-      fprintf(xmlout,  "                <CompatibleBrand>%s</CompatibleBrand>\n", buf);    /*4 characters, each CLi */
-    }
-    fprintf(xmlout,    "              </MJP2_Profile>\n");
-
-    fprintf(xmlout,    "              <MJP2_Prefix BoxType=\"jp2x\" Count=\"%d\">\n",track->num_jp2x);
-    for (i = 0; i < track->num_jp2x; i++)
-    { // We'll probably need better formatting than this
-      fprintf(xmlout,  "                <Data>0x%02x</Data>\n", track->jp2xdata[i]);    /* Each entry is single byte */
-    }
-    fprintf(xmlout,    "              </MJP2_Prefix>\n");
-
-    fprintf(xmlout,    "              <MJP2_SubSampling BoxType=\"jsub\">\n"); /* These values are all 1 byte */
-    if(notes)
-         fprintf(xmlout,  "              <!-- Typical subsample value is 2 for 4:2:0 -->\n");
-    fprintf(xmlout,    "                <HorizontalSub>%d</HorizontalSub>\n", track->hsub);
-    fprintf(xmlout,    "                <VerticalSub>%d</VerticalSub>\n", track->vsub);
-    fprintf(xmlout,    "                <HorizontalOffset>%d</HorizontalOffset>\n", track->hoff);
-    fprintf(xmlout,    "                <VerticalOffset>%d</VerticalOffset>\n", track->voff);
-       if(notes) {
-         fprintf(xmlout,  "                <!-- Typical {horizontal, vertical} chroma offset values: -->\n");
-         fprintf(xmlout,  "                <!-- 4:2:2 format (CCIR601, H.262, MPEG2, MPEG4, recom. Exif): {0, 0} -->\n");
-         fprintf(xmlout,  "                <!-- 4:2:2 format (JFIF):                                      {1, 0} -->\n");
-         fprintf(xmlout,  "                <!-- 4:2:0 format (H.262, MPEG2, MPEG4):                       {0, 1} -->\n");
-         fprintf(xmlout,  "                <!-- 4:2:0 format (MPEG1, H.261, JFIF, recom. Exif):           {1, 1} -->\n");
-       }
-    fprintf(xmlout,    "              </MJP2_SubSampling>\n"); /* These values are all 1 byte */
-
-    fprintf(xmlout,    "              <MJP2_OriginalFormat BoxType=\"orfo\">\n"); /* Part III Appx. 2 */
-    fprintf(xmlout,    "                <OriginalFieldCount>%u</OriginalFieldCount>\n", (unsigned int)track->or_fieldcount); /* uchar as 1-byte uint */
-    if(notes)
-      fprintf(xmlout,  "                <!-- In original material before encoding.  Must be either 1 or 2 -->\n");
-    fprintf(xmlout,    "                <OriginalFieldOrder>%u</OriginalFieldOrder>\n", (unsigned int)track->or_fieldorder); /* uchar as 1-byte uint */
-       if(notes) {
-      fprintf(xmlout,  "                <!-- When FieldCount=2, FieldOrder means: -->\n");
-      fprintf(xmlout,  "                <!--   0: Field coding unknown -->\n");
-      fprintf(xmlout,  "                <!--   11: Topmost line came from the earlier field; -->\n");
-      fprintf(xmlout,  "                <!--   16:  Topmost line came form the later field. -->\n");
-      fprintf(xmlout,  "                <!-- Defaults: FieldCount=1, FieldOrder=0 if FieldCoding box not present -->\n");
-      fprintf(xmlout,  "                <!-- Current implementation doesn't retain whether box was actually present. -->\n");
-       }
-    fprintf(xmlout,    "              </MJP2_OriginalFormat>\n");
-    fprintf(xmlout,    "            </VisualSampleEntry>\n");
-    break;
-  case 1: case 2:
-    if(notes)
-      fprintf(xmlout,  "            <!-- mj2_to_metadata's data structure doesn't record this currently. -->\n"); break;
-  }
-  fprintf(xmlout,      "            <TimeToSample BoxType=\"stts\">\n");  
-  fprintf(xmlout,      "              <SampleStatistics>\n");  
-  fprintf(xmlout,      "                <TotalSamples>%d</TotalSamples>\n", track->num_samples);
-  if(notes)
-    fprintf(xmlout,    "                <!-- For video, gives the total frames in the track, by summing all entries in the Sample Table -->\n");
-  fprintf(xmlout,      "              </SampleStatistics>\n"); 
-  fprintf(xmlout,      "              <SampleEntries EntryCount=\"%d\">\n", track->num_tts);
-  for (i = 0; i < track->num_tts; i++) {
-    fprintf(xmlout,    "                <Table Entry=\"%u\" SampleCount=\"%d\" SampleDelta=\"%u\" />\n",
-                                      i+1, track->tts[i].sample_count, track->tts[i].sample_delta);
-  }
-  fprintf(xmlout,      "              </SampleEntries>\n");
-  fprintf(xmlout,      "            </TimeToSample>\n");
-
-  fprintf(xmlout,      "            <SampleToChunk BoxType=\"stsc\" Count=\"%d\">\n", track->num_samplestochunk);
-  for (i = 0; i < track->num_samplestochunk; i++) {
-    fprintf(xmlout,    "              <FirstChunk>%u</FirstChunk>\n",track->sampletochunk[i].first_chunk); /* 4 bytes */
-    fprintf(xmlout,    "              <SamplesPerChunk>%u</SamplesPerChunk>\n",track->sampletochunk[i].samples_per_chunk); /* 4 bytes */
-    fprintf(xmlout,    "              <SampleDescrIndex>%u</SampleDescrIndex>\n",track->sampletochunk[i].sample_descr_idx); /* 4 bytes */
-  }
-  fprintf(xmlout,      "            </SampleToChunk>\n");
-  // After reading this info in, track->num_chunks is calculated and a decompressed table established internally.
-
-  fprintf(xmlout,      "            <SampleSize BoxType=\"stsz\">\n");
-  if(track->same_sample_size) {
-    // all values in track->sample[i].sample_size are equal.  Grab the first one.
-    fprintf(xmlout,    "              <Sample_Size>%u</Sample_Size>\n", track->sample[0].sample_size);
-       if(notes) {
-      fprintf(xmlout,  "              <!-- Non-zero value means all samples have that size. -->\n");
-         fprintf(xmlout,  "              <!-- So <Sample_Count> (aka Entry_Count in std.) has no meaning, is suppressed from this output, and no table follows. -->\n");
-       }
-  } else {
-    fprintf(xmlout,    "              <Sample_Size>0</Sample_Size>\n");
-    if(notes)
-         if(sampletables)
-        fprintf(xmlout,"              <!-- Zero value means samples have different sizes, given in table next of length Sample_Count (aka Entry_Count in std). -->\n");
-         else
-        fprintf(xmlout,"              <!-- Zero value means samples have different sizes, given in table (not shown) of length Sample_Count (aka Entry_Count in std). -->\n");
-       fprintf(xmlout,    "              <Sample_Count>%u</Sample_Count>\n", track->num_samples);
-       if(sampletables)
-     for (i = 0; i < (int)track->num_samples; i++) {
-      fprintf(xmlout,  "              <EntrySize Num=\"%u\">%u</EntrySize>\n", i+1, track->sample[i].sample_size);
-     }
-  }  
-  fprintf(xmlout,      "            </SampleSize>\n");
-
-  fprintf(xmlout,      "            <ChunkOffset BoxType=\"stco\">\n");
-  // Structure not yet - Variant ChunkLargeOffset 'co64'
-  fprintf(xmlout,      "              <EntryCount>%u</EntryCount>\n", track->num_chunks);
-  if(notes) {
-    fprintf(xmlout,    "              <!-- For this implementation, EntryCount shown is one calculated during file read of <SampleToChunk> data. -->\n");
-    fprintf(xmlout,    "              <!-- Implementation will report failure during file read of <ChunkOffset> data if read entry-count disagrees. -->\n");
-  }
-  if(sampletables)
-    for (i = 0; i < (int)track->num_chunks; i++)
-      fprintf(xmlout,  "              <Chunk_Offset Num=\"%d\">%u</Chunk_Offset>\n", i+1, track->chunk[i].offset);
-  fprintf(xmlout,      "            </ChunkOffset>\n");
-
-  fprintf(xmlout,      "          </SampleTable>\n");
-}
-
-/* ------------- */
-
-int xml_out_frame(FILE* file, FILE* xmlout, mj2_sample_t *sample, unsigned int snum, opj_event_mgr_t *event_mgr)
-{
-       opj_dparameters_t parameters;   /* decompression parameters */
-  opj_image_t *img;
-  opj_cp_t *cp;
-  int i;
-  int numcomps;
-  unsigned char* frame_codestream;
-       opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */
-       opj_cio_t *cio = NULL;  
-       opj_j2k_t *j2k;
-
-       /* JPEG 2000 compressed image data */
-
-       /* get a decoder handle */
-       dinfo = opj_create_decompress(CODEC_J2K);
-
-       /* catch events using our callbacks and give a local context */
-       opj_set_event_mgr((opj_common_ptr)dinfo, event_mgr, stderr);
-
-       /* setup the decoder decoding parameters using the current image and user parameters */
-       parameters.cp_limit_decoding = DECODE_ALL_BUT_PACKETS;
-       opj_setup_decoder(dinfo, &parameters);  
-
-  frame_codestream = (unsigned char*) malloc (sample->sample_size-8); /* Skipping JP2C marker */
-  if(frame_codestream == NULL)
-         return 1;
-
-  fseek(file,sample->offset+8,SEEK_SET);
-  fread(frame_codestream,sample->sample_size-8,1, file);  /* Assuming that jp and ftyp markers size do */
-
-       /* open a byte stream */
-       cio = opj_cio_open((opj_common_ptr)dinfo, frame_codestream, sample->sample_size-8);
-
-  /* Decode J2K to image: */
-       img = opj_decode(dinfo, cio);
-  if (!img) {
-               fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
-               opj_destroy_decompress(dinfo);
-               opj_cio_close(cio);
-               return 1;
-       }
-
-       j2k = (opj_j2k_t*)dinfo->j2k_handle;
-       j2k_default_tcp = j2k->default_tcp;
-       cp = j2k->cp;
-
-  numcomps = img->numcomps;
-  /*  Alignments:        "      <       To help maintain xml pretty-printing */  
-  fprintf(xmlout,      "      <JP2_Frame Num=\"%d\">\n", snum+1);
-  fprintf(xmlout,      "        <MainHeader>\n");
-  /* There can be multiple codestreams; a particular image is entirely within a single codestream */
-  /* TO DO:  A frame can be represented by two I-guess-contigious codestreams if its interleaved. */
-  fprintf(xmlout,      "          <StartOfCodestream Marker=\"SOC\" />\n");
-  /* "cp" stands for "coding parameter"; "tcp" is tile coding parameters, "tccp" is tile-component coding parameters */
-  xml_out_frame_siz(xmlout, img, cp); /* reqd in main */
-  xml_out_frame_cod(xmlout, j2k_default_tcp); /* reqd in main */
-  xml_out_frame_coc(xmlout, j2k_default_tcp, numcomps); /* opt in main, at most 1 per component */
-  xml_out_frame_qcd(xmlout, j2k_default_tcp); /* reqd in main */
-  xml_out_frame_qcc(xmlout, j2k_default_tcp, numcomps);        /* opt in main, at most 1 per component */
-  xml_out_frame_rgn(xmlout, j2k_default_tcp, numcomps); /* opt, at most 1 per component */
-  xml_out_frame_poc(xmlout, j2k_default_tcp); /*  opt (but reqd in main or tile for any progression order changes) */
-  /* Next four get j2k_default_tcp passed globally: */
-#ifdef SUPPRESS_FOR_NOW
-  xml_out_frame_ppm(xmlout, cp); /* opt (but either PPM or PPT [distributed in tile headers] or codestream packet header reqd) */
-#endif
-  xml_out_frame_tlm(xmlout); /* NO-OP.  TLM NOT SAVED IN DATA STRUCTURE */ /* opt */
-  xml_out_frame_plm(xmlout); /* NO-OP.  PLM NOT SAVED IN DATA STRUCTURE */ /* opt in main; can be used in conjunction with PLT */
-  xml_out_frame_crg(xmlout); /* NO-OP.  CRG NOT SAVED IN DATA STRUCTURE */ /* opt in main; */
-  xml_out_frame_com(xmlout, j2k_default_tcp); /* NO-OP.  COM NOT SAVED IN DATA STRUCTURE */ /* opt in main; */
-
-  fprintf(xmlout,      "        </MainHeader>\n");
-
-  /*   TO DO: all the tile headers (sigh)  */
-  fprintf(xmlout,      "        <TilePartHeaders Count=\"%d\">\n", cp->tileno_size);           /* size of the vector tileno */
-  for(i = 0; i < cp->tileno_size; i++) { /* I think cp->tileno_size will be same number as (cp->tw * cp->th) or as global j2k_curtileno */
-    // Standard seems to use zero-based # for tile-part.
-    fprintf(xmlout,    "          <TilePartHeader Num=\"%d\" ID=\"%d\">\n", i, cp->tileno[i]);                 /* ID number of the tiles present in the codestream */
-    fprintf(xmlout,    "            <StartOfTilePart Marker=\"SOT\" />\n");
-       /* All markers in tile-part headers (between SOT and SOD) are optional, unless structure requires. */
-    if(i == 0) {
-      xml_out_frame_cod(xmlout, &(cp->tcps[i])); /* No more than 1 per tile */
-      xml_out_frame_coc(xmlout, &(cp->tcps[i]), numcomps); /* No more than 1 per component */
-      xml_out_frame_qcd(xmlout, &(cp->tcps[i])); /* No more than 1 per tile */
-      xml_out_frame_qcc(xmlout, &(cp->tcps[i]), numcomps);     /* No more than 1 per component */
-      xml_out_frame_rgn(xmlout, &(cp->tcps[i]), numcomps); /* No more than 1 per component */
-    }
-    xml_out_frame_poc(xmlout, &(cp->tcps[i])); /* Reqd only if any progression order changes different from main POC */
-#ifdef SUPPRESS_FOR_NOW
-    xml_out_frame_ppt(xmlout, &(cp->tcps[i])); /* Either PPT [distributed in tile headers] or PPM or codestream packet header reqd. */
-#endif
-    xml_out_frame_plt(xmlout, &(cp->tcps[i])); /* NO-OP.  PLT NOT SAVED IN DATA STRUCTURE */ /* Can be used in conjunction with main's PLM */
-    xml_out_frame_com(xmlout, &(cp->tcps[i])); /* NO-OP.  COM NOT SAVED IN DATA STRUCTURE */
-    /* opj_tcp_t * cp->tcps; "tile coding parameters" */
-    /* Maybe not: fprintf(xmlout,  "        <>%d</>, cp->matrice[i];                   */ /* Fixed layer    */
-    fprintf(xmlout,    "            <StartOfData Marker=\"SOD\" />\n");
-    if(notes)
-      fprintf(xmlout,  "            <!-- Tile-part bitstream, not shown, follows tile-part header and SOD marker. -->\n");
-    fprintf(xmlout,    "          </TilePartHeader>\n");
-  }
-  fprintf(xmlout,      "        </TilePartHeaders>\n");                /* size of the vector tileno */
-
-#ifdef NOTYET
-  IMAGINE the cp object has data to support the following... but we could use an new different data structure instead
-  /* I'm unclear if the span of the original fread(frame_codestream...) included the following items if they're trailing. */
-  /* ALSO TO DO, BUT DATA STRUCTURE DOESN'T HANDLE YET: boxes (anywhere in file except before the Filetype box): */
-  xml_out_frame_jp2i(xmlout, &cp); /* IntellectualProperty 'jp2i' (no restrictions on location) */
-  xml_out_frame_xml(xmlout, &cp); /* XML 'xml\040' (0x786d6c20).  Can appear multiply */
-  xml_out_frame_uuid(xmlout, &cp); /* UUID 'uuid' (top level only) */
-  xml_out_frame_uinf(xmlout, &cp); /* UUIDInfo 'uinf', includes UUIDList 'ulst' and URL 'url\40' */
-#endif
-
-  fprintf(xmlout,      "      </JP2_Frame>\n");
-
-  /* Extra commentary: */
-  if(notes) {
-    fprintf(xmlout,    "      <!-- Given the number and size of components, mj2_to_frame would try to convert this -->\n");
-    if (((img->numcomps == 3) && (img->comps[0].dx == img->comps[1].dx / 2) 
-      && (img->comps[0].dx == img->comps[2].dx / 2 ) && (img->comps[0].dx == 1)) 
-      || (img->numcomps == 1)) {
-      fprintf(xmlout,  "      <!-- file to a YUV movie in the normal manner. -->\n");
-    }
-    else if ((img->numcomps == 3) && 
-      (img->comps[0].dx == 1) && (img->comps[1].dx == 1)&&
-         (img->comps[2].dx == 1))  {// If YUV 4:4:4 input --> to bmp
-         fprintf(xmlout,  "      <!-- YUV 4:4:4 file to a series of .bmp files. -->\n");
-    }
-    else {
-         fprintf(xmlout,  "      <!-- file whose image component dimension are unknown, to a series of .j2k files. -->\n");
-    }
-  }
-
-       opj_destroy_decompress(dinfo);
-       opj_cio_close(cio);
-  free(frame_codestream);
-
-  return 0;
-}
-
-/* ------------- */
-
-void int16_to_3packedchars(short int value, char* buf)
-{
-    /* This is to retrieve the 3-letter ASCII language code */
-    /* Each char is packed into 5 bits, as difference from 0x60 */
-    int i;
-    for (i = 2; i >= 0; i--)
-    {
-        buf[i] = (value & 0x001f) + 0x60;
-        value = (value >>5);
-    }
-    buf[3] = '\0';
-}
-
-/* ------------- */
-
-void xml_out_frame_siz(FILE* xmlout, opj_image_t *img, opj_cp_t *cp)
-{
-  opj_image_comp_t *comp;
-  int i;
-
-  fprintf(xmlout,    "          <ImageAndFileSize Marker=\"SIZ\">\n");
-  // This is similar to j2k.c's j2k_dump_image.
-  // Not of interest: Lsiz, Rsiz
-  fprintf(xmlout,    "            <Xsiz>%d</Xsiz>\n", img->x1);
-  fprintf(xmlout,    "            <Ysiz>%d</Ysiz>\n", img->y1);
-  if(notes)
-    fprintf(xmlout,  "            <!-- Xsiz, Ysiz is the size of the reference grid. -->\n");
-  fprintf(xmlout,    "            <XOsiz>%d</XOsiz>\n", img->x0);
-  fprintf(xmlout,    "            <YOsiz>%d</YOsiz>\n", img->y0);
-  if(notes)
-    fprintf(xmlout,  "            <!-- XOsiz, YOsiz are offsets from grid origin to image origin. -->\n");
-  fprintf(xmlout,    "            <XTsiz>%d</XTsiz>\n", cp->tdx);
-  fprintf(xmlout,    "            <YTsiz>%d</YTsiz>\n", cp->tdy);
-  if(notes)
-    fprintf(xmlout,  "            <!-- XTsiz, YTsiz is the size of one tile with respect to the grid. -->\n");
-  fprintf(xmlout,    "            <XTOsiz>%d</XTOsiz>\n", cp->tx0);
-  fprintf(xmlout,    "            <YTOsiz>%d</YTOsiz>\n", cp->ty0);
-  if(notes)
-    fprintf(xmlout,  "            <!-- XTOsiz, YTOsiz are offsets from grid origin to first tile origin. -->\n");
-  fprintf(xmlout,    "            <Csiz>%d</Csiz>\n", img->numcomps);
-  if(notes) {
-    fprintf(xmlout,  "            <!-- Csiz is the number of components in the image. -->\n");
-    fprintf(xmlout,  "            <!-- For image components next: -->\n");
-    fprintf(xmlout,  "            <!--   XRsiz, YRsiz denote pixel-sample-spacing on the grid, per Part I Annex B. -->\n");
-    //fprintf(xmlout,"            <!--   XO, YO is offset of the component compared to the whole image. -->\n");
-    fprintf(xmlout,  "            <!--   Bits per pixel (bpp) is the pixel depth. -->\n");
-    fprintf(xmlout,  "            <!--   WidthOfData and HeightOfData are calculated values, e.g.: w = roundup((Xsiz - XOsiz)/ XRsiz) -->\n");
-  }
-
-  for (i = 0; i < img->numcomps; i++) {/* image-components */
-    comp = &(img->comps[i]);
-    fprintf(xmlout,  "            <Component Num=\"%d\">\n", i+1);
-    fprintf(xmlout,  "              <Ssiz>\n");
-       if(raw)
-      fprintf(xmlout,"                <AsHex>0x%02x</AsHex>\n", (comp->sgnd << 7) & (comp->prec - 1));
-       if(derived) {
-      fprintf(xmlout,"                <Signed>%d</Signed>\n", comp->sgnd);
-      fprintf(xmlout,"                <PrecisionInBits>%d</PrecisionInBits>\n", comp->prec);
-       }
-    fprintf(xmlout,  "              </Ssiz>\n");
-    fprintf(xmlout,  "              <XRsiz>%d</XRsiz>\n", comp->dx);
-    fprintf(xmlout,  "              <YRsiz>%d</YRsiz>\n", comp->dy);
-    fprintf(xmlout,  "              <WidthOfData>%d</WidthOfData>\n", comp->w);
-    fprintf(xmlout,  "              <HeightOfData>%d</HeightOfData>\n", comp->h);
-    /* Rest of these aren't calculated when SIZ is read:
-    fprintf(xmlout,  "              <XO>%d</XO>\n", comp->x0);
-    fprintf(xmlout,  "              <YO>%d</YO>\n", comp->y0);
-       if(notes)
-         fprintf(xmlout,"              <!--  XO, YO is offset of the component compared to the whole image. -->\n");
-    fprintf(xmlout,  "              <BitsPerPixel>%d</BitsPerPixel>\n", comp->bpp);
-    fprintf(xmlout,  "              <NumberOfDecodedResolution>%d</NumberOfDecodedResolution>\n", comp->resno_decoded); */
-    // SUPPRESS: n/a to mj2_to_metadata.  fprintf(xmlout,"        <Factor>%d</Factor\n", comp->factor);
-    /* factor = number of division by 2 of the out image  compare to the original size of image */
-    // TO DO comp->data:  int *data;                   /* image-component data      */
-
-    fprintf(xmlout,  "            </Component>\n");
-  }
-  fprintf(xmlout,    "          </ImageAndFileSize>\n");
-}
-
-/* ------------- */
-
-void xml_out_frame_cod(FILE* xmlout, opj_tcp_t *tcp)
-{
-/* Could be called with tcp = &j2k_default_tcp;
-/* Or, for tile-part header, with &j2k_cp->tcps[j2k_curtileno]
-/*  Alignment for main:"          < < < <   To help maintain xml pretty-printing */  
-/*  Alignment for tile:"            < < <   To help maintain xml pretty-printing */  
-  opj_tccp_t *tccp;
-  int i;
-  char spaces[13] = "            "; /* 12 spaces if tilepart*/
-  char* s = spaces;
-  if(tcp == j2k_default_tcp) {
-    s++;s++; /* shorten s to 10 spaces if main */
-  }
-  tccp = &(tcp->tccps[0]);
-
-  fprintf(xmlout,      "%s<CodingStyleDefault Marker=\"COD\">\n",s); /* Required in main header */
-  /* Not retained or of interest: Lcod */
-  fprintf(xmlout,      "%s  <Scod>0x%02x</Scod>\n", s, tcp->csty); /* 1 byte */
-  if(notes) {
-    fprintf(xmlout,    "%s  <!-- For Scod, specific bits mean (where bit 0 is lowest or rightmost): -->\n",s);
-    fprintf(xmlout,    "%s  <!-- bit 0: Defines entropy coder precincts -->\n",s);
-    fprintf(xmlout,    "%s  <!--        0 = (PPx=15, PPy=15); 1 = precincts defined below. -->\n",s);
-    fprintf(xmlout,    "%s  <!-- bit 1: 1 = SOP marker may be used; 0 = not. -->\n",s);
-    fprintf(xmlout,    "%s  <!-- bit 2: 1 = EPH marker may be used; 0 = not. -->\n",s);
-  }
-  fprintf(xmlout,      "%s  <SGcod>\n",s);
-  fprintf(xmlout,      "%s    <ProgressionOrder>%d</ProgressionOrder>\n", s, tcp->prg); /* 1 byte, SGcod (A) */
-  if(notes) {
-    fprintf(xmlout,    "%s    <!-- Defined Progression Order Values are: -->\n",s);
-    fprintf(xmlout,    "%s    <!-- 0 = LRCP; 1 = RLCP; 2 = RPCL; 3 = PCRL; 4 = CPRL -->\n",s);
-    fprintf(xmlout,    "%s    <!-- where L = \"layer\", R = \"resolution level\", C = \"component\", P = \"position\". -->\n",s);
-  }
-  fprintf(xmlout,      "%s    <NumberOfLayers>%d</NumberOfLayers>\n", s, tcp->numlayers); /* 2 bytes, SGcod (B) */
-  fprintf(xmlout,      "%s    <MultipleComponentTransformation>%d</MultipleComponentTransformation>\n", s, tcp->mct); /* 1 byte, SGcod (C).  More or less boolean */
-  if(notes)
-    fprintf(xmlout,    "%s    <!-- For MCT, 0 = none, 1 = transform first 3 components for efficiency, per Part I Annex G -->\n",s);
-  fprintf(xmlout,      "%s  </SGcod>\n",s);
-  /* This code will compile only if declaration of j2k_default_tcp is changed from static (to implicit extern) in j2k.c */
-  fprintf(xmlout,      "%s  <SPcod>\n",s);
-  /* Internal data structure tccp defines separate defaults for each component, but they all get the same values */
-  /* So we only have to report the first component's values here. */
-  /* Compare j2k_read_cox(...) */
-  fprintf(xmlout,      "%s    <NumberOfDecompositionLevels>%d</NumberOfDecompositionLevels>\n", s, tccp->numresolutions - 1);  /* 1 byte, SPcox (D) */
-  fprintf(xmlout,      "%s    <CodeblockWidth>%d</CodeblockWidth>\n", s, tccp->cblkw - 2);     /* 1 byte, SPcox (E) */
-  fprintf(xmlout,      "%s    <CodeblockHeight>%d</CodeblockHeight>\n", s, tccp->cblkh - 2);   /* 1 byte, SPcox (F) */
-  if(notes) {
-    fprintf(xmlout,    "%s    <!-- CBW and CBH are non-negative, and summed cannot exceed 8 -->\n",s);
-    fprintf(xmlout,    "%s    <!-- Codeblock dimension is 2^(value + 2) -->\n", s);
-  }
-  fprintf(xmlout,      "%s    <CodeblockStyle>0x%02x</CodeblockStyle>\n", s, tccp->cblksty);   /* 1 byte, SPcox (G) */
-  if(notes) {
-    fprintf(xmlout,    "%s    <!-- For CodeblockStyle, bits mean (with value 1=feature on, 0=off): -->\n",s);
-    fprintf(xmlout,    "%s    <!-- bit 0: Selective arithmetic coding bypass. -->\n",s);
-    fprintf(xmlout,    "%s    <!-- bit 1: Reset context probabilities on coding pass boundaries. -->\n",s);
-    fprintf(xmlout,    "%s    <!-- bit 2: Termination on each coding pass. -->\n",s);
-    fprintf(xmlout,    "%s    <!-- bit 3: Vertically causal context. -->\n",s);
-    fprintf(xmlout,    "%s    <!-- bit 4: Predictable termination. -->\n",s);
-    fprintf(xmlout,    "%s    <!-- bit 5: Segmentation symbols are used. -->\n",s);
-  }
-  fprintf(xmlout,      "%s    <Transformation>%d</Transformation>\n", s, tccp->qmfbid);        /* 1 byte, SPcox (H) */
-  if(notes)
-    fprintf(xmlout,    "%s    <!-- For Transformation, 0=\"9-7 irreversible filter\", 1=\"5-3 reversible filter\" -->\n",s);
-  if (tccp->csty & J2K_CP_CSTY_PRT) {
-    fprintf(xmlout,    "%s    <PrecinctSize>\n",s); /* 1 byte, SPcox (I_i) */
-    if(notes)
-      fprintf(xmlout,  "%s    <!-- These are size exponents PPx and PPy. May be zero only for first level (aka N(L)LL subband)-->\n",s);
-    for (i = 0; i < tccp->numresolutions; i++) {       
-      fprintf(xmlout,  "%s      <PrecinctHeightAndWidth  ResolutionLevel=\"%d\">\n", s, i);
-         if(raw)
-        fprintf(xmlout,"%s        <AsHex>0x%02x</AsHex>\n", s, (tccp->prch[i] << 4) | tccp->prcw[i]);  /* packed into 1 byte, SPcox (G) */
-         if(derived) {
-        fprintf(xmlout,"%s        <WidthAsDecimal>%d</WidthAsDecimal>\n", s, tccp->prcw[i]);
-        fprintf(xmlout,"%s        <HeightAsDecimal>%d</HeightAsDecimal>\n", s, tccp->prch[i]);
-         }
-      fprintf(xmlout,  "%s      </PrecinctHeightAndWidth>\n", s, i);
-    }
-    fprintf(xmlout,    "%s    </PrecinctSize>\n",s); /* 1 byte, SPcox (I_i) */
-  }
-  fprintf(xmlout,      "%s  </SPcod>\n",s);
-  fprintf(xmlout,      "%s</CodingStyleDefault>\n",s);
-}
-
-/* ------------- */
-
-void xml_out_frame_coc(FILE* xmlout, opj_tcp_t *tcp, int numcomps) /* Optional in main & tile-part headers */
-{
-/* Uses global j2k_default_tcp */
-  opj_tccp_t *tccp, *firstcomp_tccp;
-  int i, compno;
-  char spaces[13] = "            "; /* 12 spaces if tilepart*/
-  char* s = spaces;
-  if(tcp == j2k_default_tcp) {
-    s++;s++; /* shorten s to 10 spaces if main */
-  }
-
-  firstcomp_tccp = &(tcp->tccps[0]);
-    /* Internal data structure tccp defines separate defaults for each component, set from main */
-       /* default, then selectively overwritten. */
-    /* Compare j2k_read_cox(...) */
-  /* We don't really know which was the default, and which were not */
-  /* Let's pretend that [0] is the default and all others are not */
-  if(notes) {
-    fprintf(xmlout,    "%s<!-- mj2_to_metadata implementation always reports component[0] as using default COD, -->\n", s);
-    if(tcp == j2k_default_tcp)
-      fprintf(xmlout,  "%s<!-- and any other component, with main-header style values different from [0], as COC. -->\n", s);
-    else
-      fprintf(xmlout,  "%s<!-- and any other component, with tile-part-header style values different from [0], as COC. -->\n", s);
-  }
-  for (compno = 1; compno < numcomps; compno++) /* spec says components are zero-based */
-  {
-    tccp = &tcp->tccps[compno];
-    if(same_component_style(firstcomp_tccp, tccp))
-               continue;
-
-/*  Alignments:          "      < < < < <   To help maintain xml pretty-printing */  
-    fprintf(xmlout,      "%s<CodingStyleComponent Marker=\"COC\">\n", s); /* Optional in main header, at most 1 per component */
-    if(notes)
-      fprintf(xmlout,    "%s  <!-- See Ccoc below for zero-based component number. -->\n", s);
-    /* Overrides the main COD for the specific component */
-    /* Not retained or of interest: Lcod */
-    fprintf(xmlout,      "%s  <Scoc>0x%02x</Scoc>\n", s, tccp->csty); /* 1 byte */
-       if(notes) {
-         fprintf(xmlout,    "%s  <!-- Scoc defines entropy coder precincts: -->\n", s);
-      fprintf(xmlout,    "%s  <!--   0 = maximum, namely (PPx=15, PPy=15); 1 = precincts defined below. -->\n", s);
-       }
-    fprintf(xmlout,      "%s  <Ccoc>%d</Ccoc>\n", s, compno); /* 1 or 2 bytes */
-    /* Unfortunately compo isn't retained in j2k_read_coc:  compno = cio_read(j2k_img->numcomps <= 256 ? 1 : 2);       /* Ccoc */
-    /*if(j2k_img_numcomps <=256)
-         component is 1 byte
-    else
-      compno is 2 byte */
-
-    /* This code will compile only if declaration of j2k_default_tcp is changed from static (to implicit extern) in j2k.c */
-    fprintf(xmlout,      "%s  <SPcoc>\n", s);
-    fprintf(xmlout,      "%s    <NumberOfDecompositionLevels>%d</NumberOfDecompositionLevels>\n", s, tccp->numresolutions - 1);        /* 1 byte, SPcox (D) */
-    fprintf(xmlout,      "%s    <CodeblockWidth>%d</CodeblockWidth>\n", s, tccp->cblkw - 2);   /* 1 byte, SPcox (E) */
-    fprintf(xmlout,      "%s    <CodeblockHeight>%d</CodeblockHeight>\n", s, tccp->cblkh - 2); /* 1 byte, SPcox (F) */
-       if(notes) {
-      fprintf(xmlout,    "%s    <!-- CBW and CBH are non-negative, and summed cannot exceed 8 -->\n", s);
-      fprintf(xmlout,    "%s    <!-- Codeblock dimension is 2^(value + 2) -->\n", s);
-       }
-    fprintf(xmlout,      "%s    <CodeblockStyle>0x%02x</CodeblockStyle>\n", s, tccp->cblksty); /* 1 byte, SPcox (G) */
-       if(notes) {
-      fprintf(xmlout,    "%s    <!-- For CodeblockStyle, bits mean (with value 1=feature on, 0=off): -->\n", s);
-      fprintf(xmlout,    "%s    <!-- bit 0: Selective arithmetic coding bypass. -->\n", s);
-      fprintf(xmlout,    "%s    <!-- bit 1: Reset context probabilities on coding pass boundaries. -->\n", s);
-      fprintf(xmlout,    "%s    <!-- bit 2: Termination on each coding pass. -->\n", s);
-      fprintf(xmlout,    "%s    <!-- bit 3: Vertically causal context. -->\n", s);
-      fprintf(xmlout,    "%s    <!-- bit 4: Predictable termination. -->\n", s);
-      fprintf(xmlout,    "%s    <!-- bit 5: Segmentation symbols are used. -->\n", s);
-       }
-    fprintf(xmlout,      "%s    <Transformation>%d</Transformation>\n", s, tccp->qmfbid);      /* 1 byte, SPcox (H) */
-    if(notes)
-      fprintf(xmlout,    "%s    <!-- For Transformation, 0=\"9-7 irreversible filter\", 1=\"5-3 reversible filter\" -->\n", s);
-    if (tccp->csty & J2K_CP_CSTY_PRT) {
-      fprintf(xmlout,    "%s    <PrecinctSize>\n", s); /* 1 byte, SPcox (I_i) */
-      if(notes)
-        fprintf(xmlout,  "%s      <!-- These are size exponents PPx and PPy. May be zero only for first level (aka N(L)LL subband)-->\n", s);
-      for (i = 0; i < tccp->numresolutions-1; i++) { /* subtract 1 to get # of decomposition levels */ 
-        fprintf(xmlout,  "%s      <PrecinctHeightAndWidth  ResolutionLevel=\"%d\">\n", s, i);
-               if(raw)
-          fprintf(xmlout,"%s        <AsHex>0x%02x</AsHex>\n", s, (tccp->prch[i] << 4) | tccp->prcw[i]);        /* packed into 1 byte, SPcox (G) */
-               if(derived) {
-          fprintf(xmlout,"%s        <WidthAsDecimal>%d</WidthAsDecimal>\n", s, tccp->prcw[i]);
-          fprintf(xmlout,"%s        <HeightAsDecimal>%d</HeightAsDecimal>\n", s, tccp->prch[i]);
-               }
-        fprintf(xmlout,  "%s      </PrecinctHeightAndWidth>\n", s, i);
-      }
-      fprintf(xmlout,    "%s    </PrecinctSize>\n", s); /* 1 byte, SPcox (I_i) */
-    }
-    fprintf(xmlout,      "%s  </SPcoc>\n", s);
-    fprintf(xmlout,      "%s</CodingStyleComponent>\n", s);
-  }
-}
-
-/* ------------- */
-
-BOOL same_component_style(opj_tccp_t *tccp1, opj_tccp_t *tccp2)
-{
-  int i;
-
-  if(tccp1->numresolutions != tccp2->numresolutions)
-         return FALSE;
-  if(tccp1->cblkw != tccp2->cblkw)
-         return FALSE;
-  if(tccp1->cblkh != tccp2->cblkh)
-         return FALSE;
-  if(tccp1->cblksty != tccp2->cblksty)
-         return FALSE;
-  if(tccp1->csty != tccp2->csty)
-         return FALSE;
-  
-  if (tccp1->csty & J2K_CP_CSTY_PRT) {
-      for (i = 0; i < tccp1->numresolutions; i++) {    
-         if(tccp1->prcw[i] != tccp2->prcw[i] || tccp1->prch[i] != tccp2->prch[i])
-                        return FALSE;
-      }
-  }
-  return TRUE;
-}
-
-/* ------------- */
-
-void xml_out_frame_qcd(FILE* xmlout, opj_tcp_t *tcp)
-{
-  /* This code will compile only if declaration of j2k_default_tcp is changed from static (to implicit extern) in j2k.c */
-  opj_tccp_t *tccp;
-  int bandno, numbands;
-  char spaces[13] = "            "; /* 12 spaces if tilepart*/
-  char* s = spaces;
-  if(tcp == j2k_default_tcp) {
-    s++;s++; /* shorten s to 10 spaces if main */
-  }
-
-  /* Compare j2k_read_qcx */
-  fprintf(xmlout,      "%s<QuantizationDefault Marker=\"QCD\">\n", s); /* Required in main header, single occurrence */
-  tccp = &(tcp->tccps[0]);
-  /* Not retained or of interest: Lqcd */
-  fprintf(xmlout,      "%s  <Sqcd>\n", s);             /* 1 byte */
-  if(notes)
-    fprintf(xmlout,    "%s  <!-- Default quantization style for all components. -->\n", s);
-  if(raw)
-    fprintf(xmlout,    "%s    <AsHex>0x%02x</AsHex>\n", s, (tccp->numgbits) << 5 | tccp->qntsty);
-  if(derived)
-    fprintf(xmlout,    "%s    <QuantizationStyle>%d</QuantizationStyle>\n", s, tccp->qntsty);
-  if(notes) {
-    fprintf(xmlout,    "%s    <!-- Quantization style (in Sqcd's low 5 bits) may be: -->\n", s);
-    fprintf(xmlout,    "%s    <!--   0 = No quantization. SPqcd size = 8 bits-->\n", s);
-    fprintf(xmlout,    "%s    <!--   1 = Scalar derived (values signaled for N(L)LL subband only). Use Eq. E.5. SPqcd size = 16. -->\n", s);
-    fprintf(xmlout,    "%s    <!--   2 = Scalar expounded (values signaled for each subband). SPqcd size = 16. -->\n", s);
-  }
-  if(derived)
-    fprintf(xmlout,    "%s    <NumberOfGuardBits>%d</NumberOfGuardBits>\n", s, tccp->numgbits);
-  if(notes)
-    fprintf(xmlout,    "%s    <!-- 0-7 guard bits allowed (stored in Sqcd's high 3 bits) -->\n", s);
-  fprintf(xmlout,      "%s  </Sqcd>\n", s);
-         
-  /* Problem: numbands in some cases is calculated from len, which is not retained or available here at this time */
-  /* So we'll just dump all internal values */
-  /* We could calculate it, but I'm having trouble believing the length equations in the standard */
-  
-  fprintf(xmlout,      "%s  <SPqcd>\n", s);
-  switch(tccp->qntsty) {
-  case J2K_CCP_QNTSTY_NOQNT: /* no quantization */
-    /* This is what standard says, but I don't believe it: len = 4 + (3*decomp); */
-    numbands = J2K_MAXBANDS; /* should be: numbands = len - 1; */
-       /* Better: IMAGINE numbands = tccp->stepsize_numbands; */
-    /* Instead look for first zero exponent, quit there.  Adequate? */
-    fprintf(xmlout,    "%s    <ReversibleStepSizeValue>\n", s);
-       if(notes) {
-      fprintf(xmlout,  "%s    <!-- Current mj2_to_metadata implementation dumps entire internal table, -->\n", s);
-         fprintf(xmlout,  "%s    <!-- until an exponent with zero value is reached. -->\n", s);
-         fprintf(xmlout,  "%s    <!-- Exponent epsilon(b) of reversible dynamic range. -->\n", s);
-         fprintf(xmlout,  "%s    <!-- Hex value is as stored, in high-order 5 bits. -->\n", s);
-       }
-    for (bandno = 0; bandno < numbands; bandno++) {
-      if(tccp->stepsizes[bandno].expn == 0)
-        break; /* Remove when we have real numbands */
-      fprintf(xmlout,  "%s      <DynamicRangeExponent Subband=\"%d\">\n", s, bandno);
-         if(raw)
-        fprintf(xmlout,"%s        <AsHex>0x%02x</AsHex>\n", s, tccp->stepsizes[bandno].expn << 3);
-         if(derived)
-        fprintf(xmlout,"%s        <AsDecimal>%d</AsDecimal>\n", s, tccp->stepsizes[bandno].expn);
-      fprintf(xmlout,  "%s      </DynamicRangeExponent>\n", s);
-    }
-    fprintf(xmlout,    "%s    </ReversibleStepSizeValue>\n", s);
-    break;
-  case J2K_CCP_QNTSTY_SIQNT:  /* scalar quantization derived */
-    /* This is what standard says.  Should I believe it:: len = 5;
-    /* numbands = 1; */
-    fprintf(xmlout,    "%s    <QuantizationStepSizeValues>\n", s);
-    if(notes)
-      fprintf(xmlout,  "%s    <!-- For irreversible transformation only.  See Part I Annex E Equation E.3 -->\n", s);
-    fprintf(xmlout,    "%s      <QuantizationValues Subband=\"0\">\n", s);
-    if(notes)
-      fprintf(xmlout,  "%s      <!-- For N(L)LL subband: >\n", s);
-       if(raw)
-      fprintf(xmlout,  "%s        <AsHex>0x%02x</AsHex>\n", s, (tccp->stepsizes[0].expn << 11) | tccp->stepsizes[0].mant);
-       if(derived) {
-      fprintf(xmlout,  "%s        <Exponent>%d</Exponent>\n", s, tccp->stepsizes[0].expn);
-      fprintf(xmlout,  "%s        <Mantissa>%d</Mantissa>\n", s, tccp->stepsizes[0].mant);
-       }
-    fprintf(xmlout,    "%s      </QuantizationValues>\n", s);
-       if(notes) {
-      fprintf(xmlout,  "%s      <!-- Exponents for subbands beyond 0 are not from header, but calculated per Eq. E.5 -->\n", s);
-      fprintf(xmlout,  "%s      <!-- The mantissa for all subbands is the same, given by the value above. -->\n", s);
-      fprintf(xmlout,  "%s      <!-- Current mj2_to_metadata implementation dumps entire internal table, -->\n", s);
-         fprintf(xmlout,  "%s      <!-- until a subband with exponent of zero value is reached. -->\n", s);
-       }
-
-    for (bandno = 1; bandno < J2K_MAXBANDS; bandno++) {
-      if(tccp->stepsizes[bandno].expn == 0)
-        break;
-
-      fprintf(xmlout,  "%s      <CalculatedExponent Subband=\"%d\">%d</CalculatedExponent>\n", s, bandno, tccp->stepsizes[bandno].expn);
-    }
-
-    fprintf(xmlout,    "%s    </QuantizationStepSizeValues>\n", s);
-    break;
-
-  default: /* J2K_CCP_QNTSTY_SEQNT */ /* scalar quantization expounded */
-    /* This is what standard says, but should I believe it: len = 5 + 6*decomp; */
-    numbands = J2K_MAXBANDS; /* should be: (len - 1) / 2;*/
-       /* Better: IMAGINE numbands = tccp->stepsize_numbands; */
-    fprintf(xmlout,    "%s    <QuantizationStepSizeValues>\n", s);
-       if(notes) {
-      fprintf(xmlout,  "%s    <!-- For irreversible transformation only.  See Part I Annex E Equation E.3 -->\n", s);
-      fprintf(xmlout,  "%s    <!-- Current mj2_to_metadata implementation dumps entire internal table, -->\n", s);
-      fprintf(xmlout,  "%s    <!-- until a subband with mantissa and exponent of zero values is reached. -->\n", s);
-    }
-    for (bandno = 0; bandno < numbands; bandno++) {
-      if(tccp->stepsizes[bandno].expn == 0 && tccp->stepsizes[bandno].mant == 0)
-        break; /* Remove when we have real numbands */
-
-      fprintf(xmlout,  "%s      <QuantizationValues Subband=\"%d\">\n", s, bandno);
-         if(raw)
-        fprintf(xmlout,"%s        <AsHex>0x%02x</AsHex>\n", s, (tccp->stepsizes[bandno].expn << 11) | tccp->stepsizes[bandno].mant);
-         if(derived) {
-        fprintf(xmlout,"%s        <Exponent>%d</Exponent>\n", s, tccp->stepsizes[bandno].expn);
-        fprintf(xmlout,"%s        <Mantissa>%d</Mantissa>\n", s, tccp->stepsizes[bandno].mant);
-         }
-      fprintf(xmlout,  "%s      </QuantizationValues>\n", s);
-    }
-    fprintf(xmlout,    "%s    </QuantizationStepSizeValues>\n", s);
-    break;
-  } /* switch */
-  fprintf(xmlout,      "%s  </SPqcd>\n", s);
-  fprintf(xmlout,      "%s</QuantizationDefault>\n", s);
-
-/*  Alignments:        "    < < < < <   To help maintain xml pretty-printing */  
-}
-
-/* ------------- */
-
-void xml_out_frame_qcc(FILE* xmlout, opj_tcp_t *tcp, int numcomps)
-{
-/* Uses global j2k_default_tcp */
-  /* This code will compile only if declaration of j2k_default_tcp is changed from static (to implicit extern) in j2k.c */
-  opj_tccp_t *tccp, *firstcomp_tccp;
-  int bandno, numbands;
-  int compno;
-  char spaces[13] = "            "; /* 12 spaces if tilepart*/
-  char* s = spaces;
-  if(tcp == j2k_default_tcp) {
-    s++;s++; /* shorten s to 10 spaces if main */
-  }
-
-  firstcomp_tccp = &(tcp->tccps[0]);
-    /* Internal data structure tccp defines separate defaults for each component, set from main */
-       /* default, then selectively overwritten. */
-    /* Compare j2k_read_qcx(...) */
-  /* We don't really know which was the default, and which were not */
-  /* Let's pretend that [0] is the default and all others are not */
-  if(notes) {
-    fprintf(xmlout,      "%s<!-- mj2_to_metadata implementation always reports component[0] as using default QCD, -->\n", s);
-    if(tcp == j2k_default_tcp)
-      fprintf(xmlout,    "%s<!-- and any other component, with main-header quantization values different from [0], as QCC. -->\n", s);
-    else
-      fprintf(xmlout,    "%s<!-- and any other component, with tile-part-header quantization values different from [0], as QCC. -->\n", s);
-  }
-  for (compno = 1; compno < numcomps; compno++) /* spec says components are zero-based */
-  {
-    tccp = &(tcp->tccps[compno]);
-    if(same_component_quantization(firstcomp_tccp, tccp))
-               continue;
-
-    /* Compare j2k_read_qcx */
-    fprintf(xmlout,      "%s<QuantizationComponent Marker=\"QCC\" Component=\"%d\">\n", s, compno); /* Required in main header, single occurrence */
-    tccp = &j2k_default_tcp->tccps[0];
-    /* Not retained or perhaps of interest: Lqcd   It maybe can be calculated.  */
-    fprintf(xmlout,      "%s  <Sqcc>\n", s);           /* 1 byte */
-    if(notes)
-      fprintf(xmlout,    "%s  <!-- Quantization style for this component. -->\n", s);
-       if(raw)
-      fprintf(xmlout,    "%s    <AsHex>0x%02x</AsHex>\n", s, (tccp->numgbits) << 5 | tccp->qntsty);
-       if(derived)
-      fprintf(xmlout,    "%s    <QuantizationStyle>%d</QuantizationStyle>\n", s, tccp->qntsty);
-       if(notes) {
-      fprintf(xmlout,    "%s    <!-- Quantization style (in Sqcc's low 5 bits) may be: -->\n", s);
-      fprintf(xmlout,    "%s    <!--   0 = No quantization. SPqcc size = 8 bits-->\n", s);
-      fprintf(xmlout,    "%s    <!--   1 = Scalar derived (values signaled for N(L)LL subband only). Use Eq. E.5. SPqcc size = 16. -->\n", s);
-      fprintf(xmlout,    "%s    <!--   2 = Scalar expounded (values signaled for each subband). SPqcc size = 16. -->\n", s);
-       }
-       if(derived)
-      fprintf(xmlout,    "%s    <NumberOfGuardBits>%d</NumberOfGuardBits>\n", s,       tccp->numgbits);
-    if(notes)
-      fprintf(xmlout,    "%s    <!-- 0-7 guard bits allowed (stored in Sqcc's high 3 bits) -->\n", s);
-    fprintf(xmlout,      "%s  </Sqcc>\n", s);
-         
-    /* Problem: numbands in some cases is calculated from len, which is not retained or available here at this time */
-    /* So we'll just dump all internal values */
-    fprintf(xmlout,      "%s  <SPqcc>\n", s);
-    switch(tccp->qntsty) {
-    case J2K_CCP_QNTSTY_NOQNT:
-      numbands = J2K_MAXBANDS; /* should be: numbands = len - 1; */
-         /* Better: IMAGINE numbands = tccp->stepsize_numbands; */
-
-      /* Instead look for first zero exponent, quit there.  Adequate? */
-      fprintf(xmlout,    "%s    <ReversibleStepSizeValue>\n", s);
-         if(notes) {
-        fprintf(xmlout,  "%s    <!-- Current mj2_to_metadata implementation dumps entire internal table, -->\n", s);
-           fprintf(xmlout,  "%s    <!-- until an exponent with zero value is reached. -->\n", s);
-           fprintf(xmlout,  "%s    <!-- Exponent epsilon(b) of reversible dynamic range. -->\n", s);
-           fprintf(xmlout,  "%s    <!-- Hex value is as stored, in high-order 5 bits. -->\n", s);
-         }
-      for (bandno = 0; bandno < numbands; bandno++) {
-        if(tccp->stepsizes[bandno].expn == 0)
-          break; /* Remove this once we have real numbands */
-        fprintf(xmlout,  "%s      <Exponent Subband=\"%d\">\n", s, bandno);
-               if(raw)
-          fprintf(xmlout,"%s        <AsHex>0x%02x</AsHex>\n", s, tccp->stepsizes[bandno].expn << 3);
-               if(derived)
-          fprintf(xmlout,"%s        <AsDecimal>%d</AsDecimal>\n", s, tccp->stepsizes[bandno].expn);
-        fprintf(xmlout,  "%s      </Exponent>\n", s);
-      }
-      fprintf(xmlout,    "%s    </ReversibleStepSizeValue>\n", s);
-      break;
-    case J2K_CCP_QNTSTY_SIQNT:
-      /* numbands = 1; */
-      fprintf(xmlout,    "%s    <QuantizationStepSizeValues>\n", s);
-      if(notes)
-        fprintf(xmlout,  "%s    <!-- For irreversible transformation only.  See Part I Annex E Equation E.3 -->\n", s);
-      fprintf(xmlout,    "%s      <QuantizationValuesForSubband0>\n", s);
-      if(notes)
-        fprintf(xmlout,  "%s      <!-- For N(L)LL subband: >\n", s);
-         if(raw)
-        fprintf(xmlout,  "%s        <AsHex>0x%02x</AsHex>\n", s, (tccp->stepsizes[0].expn << 11) | tccp->stepsizes[0].mant);
-         if(derived) {
-        fprintf(xmlout,  "%s        <Exponent>%d</Exponent>\n", s, tccp->stepsizes[0].expn);
-        fprintf(xmlout,  "%s        <Mantissa>%d</Mantissa>\n", s, tccp->stepsizes[0].mant);
-         }
-      fprintf(xmlout,    "%s      </QuantizationValuesForSubband0>\n", s);
-         if(notes) {
-        fprintf(xmlout,  "%s      <!-- Exponents for subbands beyond 0 are not from header, but calculated per Eq. E.5 -->\n", s);
-        fprintf(xmlout,  "%s      <!-- The mantissa for all subbands is the same, given by the value above. -->\n", s);
-        fprintf(xmlout,  "%s      <!-- Current mj2_to_metadata implementation dumps entire internal table, -->\n", s);
-           fprintf(xmlout,  "%s      <!-- until a subband with exponent of zero value is reached. -->\n", s);
-        }
-
-      for (bandno = 1; bandno < J2K_MAXBANDS; bandno++) {
-        if(tccp->stepsizes[bandno].expn == 0)
-          break;
-
-        fprintf(xmlout,  "%s      <CalculatedExponent Subband=\"%d\">%d</CalculatedExponent>\n", s, bandno, tccp->stepsizes[bandno].expn);
-      }
-      fprintf(xmlout,    "%s    </QuantizationStepSizeValues>\n", s);
-      break;
-
-    default: /* J2K_CCP_QNTSTY_SEQNT */
-      numbands = J2K_MAXBANDS; /* should be: (len - 1) / 2;*/
-         /* Better: IMAGINE numbands = tccp->stepsize_numbands; */
-      fprintf(xmlout,    "%s    <QuantizationStepSizeValues>\n", s);
-      if(notes) {
-        fprintf(xmlout,  "%s    <!-- For irreversible transformation only.  See Part I Annex E Equation E.3 -->\n", s);
-        fprintf(xmlout,  "%s    <!-- Current mj2_to_metadata implementation dumps entire internal table, -->\n", s);
-           fprintf(xmlout,  "%s    <!-- until a subband with mantissa and exponent of zero values is reached. -->\n", s);
-         }
-      for (bandno = 0; bandno < numbands; bandno++) {
-        if(tccp->stepsizes[bandno].expn == 0 && tccp->stepsizes[bandno].mant == 0)
-                       break; /* Remove this once we have real numbands count */
-        fprintf(xmlout,  "%s      <QuantizationValues Subband=\"%d\">\n", s, bandno);
-               if(raw)
-          fprintf(xmlout,"%s        <AsHex>0x%02x</AsHex>\n", s, (tccp->stepsizes[bandno].expn << 11) | tccp->stepsizes[bandno].mant);
-               if(derived) {
-          fprintf(xmlout,"%s        <Exponent>%d</Exponent>\n", s, tccp->stepsizes[bandno].expn);
-          fprintf(xmlout,"%s        <Mantissa>%d</Mantissa>\n", s, tccp->stepsizes[bandno].mant);
-               }
-        fprintf(xmlout,  "%s      </QuantizationValues>\n", s);
-      }
-      fprintf(xmlout,    "%s    </QuantizationStepSizeValues>\n", s);
-      break;
-    } /* switch */
-    fprintf(xmlout,      "%s  </SPqcc>\n", s);
-    fprintf(xmlout,      "%s</QuantizationComponent>\n", s);
-  }
-/*  Alignments:          "    < < < < <   To help maintain xml pretty-printing */  
-}
-
-/* ------------- */
-
-BOOL same_component_quantization(opj_tccp_t *tccp1, opj_tccp_t *tccp2)
-{
-  int bandno, numbands;
-
-  if(tccp1->qntsty != tccp2->qntsty)
-         return FALSE;
-  if(tccp1->numgbits != tccp2->numgbits)
-         return FALSE;
-
-  switch(tccp1->qntsty) {
-    case J2K_CCP_QNTSTY_NOQNT:
-      numbands = J2K_MAXBANDS; /* should be: numbands = len - 1; */
-      /* Instead look for first zero exponent, quit there.  Adequate? */
-      for (bandno = 0; bandno < numbands; bandno++) {
-        if(tccp1->stepsizes[bandno].expn == 0)
-          break;
-        if(tccp1->stepsizes[bandno].expn != tccp2->stepsizes[bandno].expn)
-         return FALSE;
-      }
-      break;
-    case J2K_CCP_QNTSTY_SIQNT:
-      /* numbands = 1; */
-      if(tccp1->stepsizes[0].expn != tccp2->stepsizes[0].expn || tccp1->stepsizes[0].mant != tccp2->stepsizes[0].mant)
-        return FALSE;
-         /* Don't need to check remainder, since they are calculated from [0] */
-      break;
-
-    default: /* J2K_CCP_QNTSTY_SEQNT */
-      numbands = J2K_MAXBANDS; /* should be: (len - 1) / 2;*/
-         /* This comparison may cause us problems with trailing junk values. */
-      for (bandno = 0; bandno < numbands; bandno++) {
-        if(tccp1->stepsizes[bandno].expn != tccp2->stepsizes[bandno].expn || tccp1->stepsizes[bandno].mant != tccp2->stepsizes[bandno].mant);
-          return FALSE;
-      }
-      break;
-    } /* switch */
-  return TRUE;
-}
-
-/* ------------- */
-
-void xml_out_frame_rgn(FILE* xmlout, opj_tcp_t *tcp, int numcomps)
-{
-  int compno, SPrgn;
-  /* MJ2 files can have regions of interest if hybridized with JPX Part II */
-  char spaces[13] = "            "; /* 12 spaces if tilepart*/
-  char* s = spaces;
-  if(tcp == j2k_default_tcp) {
-    s++;s++; /* shorten s to 10 spaces if main */
-  }
-
-  for(compno = 0; compno < numcomps; compno++) {
-    SPrgn = tcp->tccps[compno].roishift;       /* 1 byte; SPrgn */
-    if(SPrgn == 0)
-               continue; /* Yet another kludge */
-
-    fprintf(xmlout,    "%s<RegionOfInterest Marker=\"RGN\">\n", s); /* Optional in main header, at most 1 per component */
-    if(notes)
-      fprintf(xmlout,  "%s<!-- See Crgn below for zero-based component number. -->\n", s);
-    /* Not retained or of interest: Lrgd */
-    fprintf(xmlout,    "%s  <Srgn>0</Srgn>\n", s); /* 1 byte */
-    if(notes)
-         fprintf(xmlout,  "%s  <!-- Srgn is ROI style.  Only style=0 defined: Implicit ROI (max. shift) -->\n", s);
-    fprintf(xmlout,    "%s  <Crgn>%d</Crgn>\n", s, compno); /* 1 or 2 bytes */
-    fprintf(xmlout,    "%s  <SPrgn>%d</SPrgn>\n", s, SPrgn); /* 1 byte */
-    if(notes)
-      fprintf(xmlout,  "%s  <!-- SPrgn is implicit ROI shift, i.e., binary shifting of ROI coefficients above background. -->\n", s);
-    fprintf(xmlout,    "</RegionOfInterest\n", s); /* Optional in main header, at most 1 per component */
-  }
-}
-
-/* ------------- */
-
-void xml_out_frame_poc(FILE* xmlout, opj_tcp_t *tcp) { /* Progression Order Change */
-  /* Compare j2k_read_poc() */
-  int i;
-  opj_poc_t *poc;
-  char spaces[13] = "            "; /* 12 spaces if tilepart*/
-  char* s = spaces;
-  if(tcp == j2k_default_tcp) {
-    s++;s++; /* shorten s to 10 spaces if main */
-  }
-  
-  if(tcp->POC != 1)
-         return; /* Not present */
-
-  fprintf(xmlout,    "%s<ProgressionOrderChange Marker=\"POC\">\n", s); /* Optional in main header, at most 1 per component */
-  /* j2k_read_poc seems to allow accumulation of default pocs from multiple POC segments, but does
-  the spec really allow that? */
-  /* 2 bytes, not retained; Lpoc */
-  /* I probably didn't get this dump precisely right. */
-  for (i = 0; i < tcp->numpocs; i++) {
-    poc = &tcp->pocs[i];
-    fprintf(xmlout,  "%s  <Progression Num=\"%d\">\n", s, i+1);
-    fprintf(xmlout,  "%S    <RSpoc>%d</RSpoc>\n", s, poc->resno0);     /* 1 byte, RSpoc_i */
-    if(notes)
-         fprintf(xmlout,"%s    <!-- Resolution level index (inclusive) for progression start. Range: 0 to 33 -->\n", s);
-    fprintf(xmlout,  "%s    <CSpoc>%d</CSpoc>\n", s, poc->compno0);/* j2k_img->numcomps <= 256 ? 1 byte : 2 bytes; CSpoc_i */
-    if(notes)
-      fprintf(xmlout,"%s    <!-- Component index (inclusive) for progression start. -->\n", s);
-    fprintf(xmlout,  "%s    <LYEpoc>%d</LYEpoc>\n", s, poc->layno1); /* int_min(cio_read(2), tcp->numlayers);  /* 2 bytes; LYEpoc_i */
-    if(notes)
-      fprintf(xmlout,"%s    <!-- Layer index (exclusive) for progression end. -->\n", s);
-    fprintf(xmlout,  "%s    <REpoc>%d</REpoc>\n", s, poc->resno1); /*int_min(cio_read(1), tccp->numresolutions);       /* REpoc_i */
-    if(notes)
-      fprintf(xmlout,"%s    <!-- Resolution level index (exclusive) for progression end. Range: RSpoc to 33 -->\n", s);
-    fprintf(xmlout,  "%s    <CEpoc>%d</CEpoc>\n", s, poc->compno1); /* int_min(cio_read(j2k_img->numcomps <= 256 ? 1 : 2), j2k_img->numcomps); /* CEpoc_i */
-    if(notes)
-         fprintf(xmlout,"%s    <!-- Component index (exclusive) for progression end.  Minimum: CSpoc -->\n", s);
-    fprintf(xmlout,  "%s    <Ppoc>%d</Ppoc>\n", s, poc->prg); /* 1 byte Ppoc_i */
-       if(notes) {
-      fprintf(xmlout,"%s    <!-- Defined Progression Order Values are: -->\n", s);
-      fprintf(xmlout,"%s    <!-- 0 = LRCP; 1 = RLCP; 2 = RPCL; 3 = PCRL; 4 = CPRL -->\n", s);
-      fprintf(xmlout,"%s    <!-- where L = \"layer\", R = \"resolution level\", C = \"component\", P = \"position\". -->\n", s);
-       }
-    fprintf(xmlout,  "%s  </Progression>\n", s);
-  }
-  fprintf(xmlout,    "%s</ProgressionOrderChange\n", s);
-}
-
-/* ------------- */
-
-#ifdef SUPPRESS_FOR_NOW
-/* Suppress PPM and PPT since we're not showing data from the third option, namely within the codestream, and
-that's evidently what frames_to_mj2 uses.  And a hex dump isn't so useful anyway */
-
-void xml_out_frame_ppm(FILE *xmlout, opj_cp_t *cp) { /* For main header, not tile-part (which uses PPT instead). */
-/* Either the PPM or PPT is required if the packet headers are not distributed in the bit stream */
-/* Use of PPM and PPT are mutually exclusive. */
-/* Compare j2k_read_ppm() */
-  int j;
-  
-  if(cp->ppm != 1)
-         return; /* Not present */
-/* Main header uses indent of 10 spaces */
-  fprintf(xmlout,    "          <PackedPacketHeadersMainHeader Marker=\"PPM\">\n"); /* Optional in main header, but if not, must be in PPT or codestream */
-  /* 2 bytes Lppm not saved */
-  if(notes) {
-    fprintf(xmlout,  "          <!-- If there are multiple PPM marker segments in the main header, -->\n");
-    fprintf(xmlout,  "          <!-- this mj2_to_metadata implementation will report them as a single consolidated PPM header. -->\n");
-    fprintf(xmlout,  "          <!-- The implementation can't currently segregate by tile-part. -->\n");
-    fprintf(xmlout,  "          <!-- TO DO? further map the packet headers to xml. -->\n");
-  }
-  /* 1 byte, not retained ; Zppm is sequence # of this PPM header */
-  /* 4 bytes, possibly overwritten multiple times in j2k_cp->ppm_previous: Nppm */
-  /* Use j symbol for index instead of i, to make comparable with j2k_read_ppm */
-  /* Not real clear whether to use ppm->store or ppm_len as upper bound */
-  fprintf(xmlout,    "            <PackedData>\n");
-  xml_out_dump_hex(xmlout, cp->ppm_data, cp->ppm_len);
-  /* Dump packet headers 1 byte at a time: lppm[i][j] */
-  fprintf(xmlout,    "            </PackedData>\n");
-  fprintf(xmlout,    "          </PackedPacketHeadersMainHeader>\n"); /* Optional in main header, but if not, must be in PPT or codestream */
-}
-
-/* ------------- */
-
-void xml_out_frame_ppt(FILE *xmlout, opj_tcp_t *tcp) { /* For tile-part header, not main (which uses PPM instead). */
-/* Either the PPM or PPT is required if the packet headers are not distributed in the bit stream */
-/* Use of PPM and PPT are mutually exclusive. */
-/* Compare j2k_read_ppt() */
-  int j;
-  
-  if(tcp->ppt != 1)
-         return; /* Not present */
-
-  /* Tile-part indents are 12 spaces */
-  fprintf(xmlout,    "            <PackedPacketHeadersTilePartHeader Marker=\"PPT\">\n"); /* Optional in main header, but if not, must be in PPT or codestream */
-  /* 2 bytes Lppm not saved */
-  if(notes) {
-    fprintf(xmlout,  "            <!-- If there are multiple PPT marker segments in the tile-part header, -->\n");
-    fprintf(xmlout,  "            <!-- this mj2_to_metadata implementation will report them as a single consolidated PPT header. -->\n");
-    fprintf(xmlout,  "            <!-- The implementation can't currently segregate by tile-part. -->\n");
-    fprintf(xmlout,  "            <!-- TO DO? further map the packet headers to xml. -->\n");
-  }
-  /* 1 byte, not retained ; Zppt is sequence # of this PPT header */
-  /* 4 bytes, possibly overwritten multiple times in j2k_cp->ppt_previous: Nppt */
-  /* Use j symbol for index instead of i, to make comparable with j2k_read_ppt */
-  /* Not real clear whether to use ppt->store or ppt_len as upper bound */
-  fprintf(xmlout,    "              <PackedData>\n");
-  xml_out_dump_hex(xmlout, tcp->ppt_data, tcp->ppt_len);
-  /* Dump packet headers 1 byte at a time: lppt[i][j] */
-  fprintf(xmlout,    "              </PackedData>\n");
-  fprintf(xmlout,    "            </PackedPacketHeadersTileHeader>\n"); /* Optional in tile-part header, but if not, must be in PPM or codestream */
-}
-#endif SUPPRESS_FOR_NOW
-
-/* ------------- */
-
-void xml_out_frame_tlm(FILE* xmlout) { /* opt, main header only.  May be multiple. */
-/* Compare j2k_read_tlm()... which doesn't retain anything! */
-/* Plan:  Since this is only called from main header, not tilepart, use global j2k_default_tcp rather than parameter */
-/* Main header indents are 10 spaces */
-}
-
-/* ------------- */
-
-void xml_out_frame_plm(FILE* xmlout) { /* opt, main header only; can be used in conjunction with tile-part's PLT */
-/* NO-OP.  PLM NOT SAVED IN DATA STRUCTURE */
-       /* Compare j2k_read_plm()... which doesn't retain anything! */
-/* Plan:  Since this is only called from main header, not tilepart, use global j2k_default_tcp rather than parameter */
-/* Main header indents are 10 spaces */
-}
-
-/* ------------- */
-
-void xml_out_frame_plt(FILE* xmlout, opj_tcp_t *tcp) { /* opt, tile-part headers only; can be used in conjunction with main header's PLM */
-/* NO-OP.  PLT NOT SAVED IN DATA STRUCTURE */
-       /* Compare j2k_read_plt()... which doesn't retain anything! */
-/* Tile-part header indents are 12 spaces */
-}
-
-/* ------------- */
-
-void xml_out_frame_crg(FILE* xmlout) { /* NO-OP.  CRG NOT SAVED IN DATA STRUCTURE */ /* opt, main header only; */
-/* Compare j2k_read_crg()... which doesn't retain anything! */
-/* Plan:  Since this is only called from main header, not tilepart, use global j2k_default_tcp rather than parameter */
-#ifdef NOTYET
-  THIS PSEUDOCODE IMAGINES THESE EXIST: j2k_default_tcp->crg, j2k_default_tcp->crg_i, j2k_default_tcp->crg_xcrg*, j2k_default_tcp->crg_ycrg* 
-  (POSSIBLY DON'T NEED crg_i, CAN GET NUMBER OR COMPONENTS FROM ELSEWHERE)
-  if(j2k_default_tcp->crg != 1 || j2k_default_tcp->crg_i == 0)
-         return; /* Not present */
-
-/* Main header indents are 10 spaces */
-  fprintf(xmlout,    "          <ComponentRegistration Marker=\"RG\" Count=\"%d\">\n", j2k_default_tcp->crg_i);
-  if(notes) {
-    fprintf(xmlout,  "          <!-- Fine tuning of registration of components with respect to each other, -->\n");
-    fprintf(xmlout,  "          <!-- not required but potentially helpful for decoder. -->\n");
-    fprintf(xmlout,  "          <!-- These supplementary fractional offsets are in units of 1/65536 of the horizontal -->\n");
-    fprintf(xmlout,  "          <!-- or vertical separation (e.g., XRsiz[i] or YRsiz[i] for component i). -->\n");
-  }
-  /* This isn't the most compact form of table, but is OK when number of components is small, as is likely. */
-  for (i = 0; i < j2k_default_tcp->crg_i; i++) {
-    fprintf(xmlout,  "            <Component Num=\"%d\">\n", i+1);
-    fprintf(xmlout,  "              <Xcrg>\n");
-       if(raw)
-      fprintf(xmlout,"                <AsNumerator>%d</AsNumerator>\n", j2k_default_tcp->crg_xcrg[i]);
-       if(derived) {
-         /* Calculate n * 100%/65536; 4 digits after decimal point is sufficiently accurate */
-      fprintf(xmlout,"                <AsPercentage>%.4f</AsPercentage>\n", ((double)j2k_default_tcp->crg_xcrg[i])/655.36);
-         /* We could do another calculation that include XRsiz[i]; maybe later. */
-       }
-    fprintf(xmlout,  "              </Xcrg>\n");
-    fprintf(xmlout,  "              <Ycrg>\n");
-       if(raw)
-      fprintf(xmlout,"                <AsNumerator>%d</AsNumerator>\n", j2k_default_tcp->crg_ycrg[i]);
-       if(derived) {
-      fprintf(xmlout,"                <AsPercentage>%f</AsPercentage>\n", ((double)j2k_default_tcp->crg_ycrg[i])/655.36);
-       }
-    fprintf(xmlout,  "              </Ycrg>\n");
-    fprintf(xmlout,  "            </Component>\n");
-  }
-
-  fprintf(xmlout,    "          </ComponentRegistration>\n");
-
-#endif
-}
-
-/* ------------- */
-
-/* Regrettably from a metadata point of view, j2k_read_com() skips over any comments in main header or tile-part-header */
-void xml_out_frame_com(FILE* xmlout, opj_tcp_t *tcp) { /* NO-OP.  COM NOT SAVED IN DATA STRUCTURE */ /* opt in main or tile-part headers; */
-/* Compare j2k_read_com()... which doesn't retain anything! */
-#ifdef NOTYET
-  char spaces[13] = "            "; /* 12 spaces if tilepart*/
-  char* s = spaces;
-  if(tcp == &j2k_default_tcp) {
-    s++;s++; /* shorten s to 10 spaces if main */
-  }
-  THIS PSEUDOCODE IMAGINES THESE EXIST: tcp->com, tcp->com_len, tcp->com_data array 
-  if(tcp->com != 1)
-         return; /* Not present */
-
-  fprintf(xmlout,    "%s<Comment Marker=\"COM\">\n", s); /* Optional in main or tile-part header */
-  xml_out_dump_hex_and_ascii(tcp->com_data, tcp->com_len, s);
-  fprintf(xmlout,    "%s</Comment>\n", s);
-#endif
-}
-
-void xml_out_dump_hex(FILE* xmlout, char *data, int data_len, char* s) {
-  /* s is a string of spaces for indent */
-  int i;
-  
-  /* This is called when raw is true, or there is no appropriate derived form */
-  fprintf(xmlout,    "%s<AsHex>\n", s);
-  fprintf(xmlout,    "%s  ", s); /* Inadequate for pretty printing */
-  for (i = 0; i < data_len; i++) {     /* Dump packet headers */
-    fprintf(xmlout,  "%02x", data[i]);
-  }
-  fprintf(xmlout,    "%s</AsHex>\n", s);
-}
-
-/* Define this as an even number: */
-#define BYTES_PER_DUMP_LINE 40
-/* Current total width for Hex and ASCII is : 11 spaces lead + (3 * BPDL) + 2 spaces + BPDL */
-void xml_out_dump_hex_and_ascii(FILE* xmlout, char *data, int data_len, char* s) {
-  /* s is a string of spaces for indent */
-  int i,j;
-  
-  if(raw)
-    xml_out_dump_hex(xmlout, data, data_len, s);
-
-  if(derived) {
-    fprintf(xmlout,  "%s<AsHexAndASCII>\n", s);
-       for (i = 0; i < data_len; ) {
-      fprintf(xmlout,"%s ", s); /* Additional leading space added in loop */
-         /* First column: hex */
-      for (j = 0; j < BYTES_PER_DUMP_LINE; j++)        /* Dump bytes */
-        fprintf(xmlout," %02x", data[i+j]);
-      /* Space between columns... */ fprintf(xmlout,  "  ");
-         /* Second column: ASCII */
-         for (j = 0; j < BYTES_PER_DUMP_LINE; j++, i++) {
-           if(isprint((int)data[i]) && i < data_len)
-          fprintf(xmlout,"%c", data[i]);
-           else
-             fprintf(xmlout," ");
-      }
-      /* If we also wanted to output UCS-2 Unicode as a third column, then entire document
-      must use fwprintf.  Forget about it for now.  As it stands, if data is UCS-2 format but still
-      the ASCII set, then we'll be able to read every other byte as ASCII in column 2.  If
-      data is UTF-8 format but still ASCII, then we'll be able to read every byte as ASCII
-      in column 2. */
-    }
-    fprintf(xmlout,  "%s</AsHexAndASCII>\n", s);
-  }
-}
-
-
-/* ------------- */
-
-void xml_out_frame_jp2h(FILE* xmlout, opj_jp2_t *jp2_struct) {  /* JP2 Header */
-/* Compare jp2_read_jp2h(opj_jp2_t * jp2_struct) */
-  int i;
-
-  fprintf(xmlout,      "              <JP2Header BoxType=\"jp2h\">\n");
-
-/* Compare jp2_read_ihdr(jp2_struct)) */
-  fprintf(xmlout,      "                <ImageHeader BoxType=\"ihdr\">\n");
-  fprintf(xmlout,      "                  <HEIGHT>%d</HEIGHT>\n", jp2_struct->h); /* 4 bytes */
-  fprintf(xmlout,      "                  <WIDTH>%d</WIDTH>\n", jp2_struct->w); /* 4 bytes */
-  if(notes)
-    fprintf(xmlout,    "                  <!-- HEIGHT here, if 2 fields per image, is of total deinterlaced height. -->\n");
-  fprintf(xmlout,      "                  <NC>%d</NC>\n", jp2_struct->numcomps); /* 2 bytes */
-  if(notes)
-    fprintf(xmlout,    "                  <!-- NC is number of components -->\n"); /* 2 bytes */
-  fprintf(xmlout,      "                  <BPC>\n"); /* 1 byte */
-  if(jp2_struct->bpc == 255) {
-    fprintf(xmlout,    "                    <AsHex>0x%02x</AsHex>\n", jp2_struct->bpc); /* 1 byte */
-    if(notes)
-      fprintf(xmlout,  "                    <!-- BPC = 0xff means bits per pixel varies with component; see table below. -->\n");
-  } else { /* Not 0xff */
-    if(raw) {
-      fprintf(xmlout,  "                    <AsHex>0x%02x</AsHex>\n", jp2_struct->bpc); /* 1 byte */
-      if(notes)
-        fprintf(xmlout,"                    <!-- BPC = 0xff means bits per pixel varies with component; see table below. -->\n");
-       }
-    if(derived) {
-      fprintf(xmlout,  "                    <BitsPerPixel>%d</BitsPerPixel>\n", jp2_struct->bpc & 0x7f);
-      fprintf(xmlout,  "                    <Signed>%d</Signed>\n", jp2_struct->bpc >> 7);
-       }
-  }
-  fprintf(xmlout,      "                  </BPC>\n");
-  fprintf(xmlout,      "                  <C>%d</C>\n", jp2_struct->C); /* 1 byte */
-  if(notes)
-    fprintf(xmlout,    "                  <!-- C is compression type.  Only \"7\" is allowed to date. -->\n"); /* 2 bytes */
-  fprintf(xmlout,      "                  <UnkC>%d</UnkC>\n", jp2_struct->UnkC); /* 1 byte */
-  if(notes)
-    fprintf(xmlout,    "                  <!-- Colourspace Unknown. 1 = unknown, 0 = known (e.g., colourspace spec is accurate) -->\n"); /* 1 byte */
-  fprintf(xmlout,      "                  <IPR>%d</IPR>\n", jp2_struct->IPR); /* 1 byte */
-  if(notes)
-    fprintf(xmlout,    "                  <!-- IPR is 1 if frame contains an Intellectual Property box; 0 otherwise. -->\n"); /* 2 bytes */
-  fprintf(xmlout,      "                </ImageHeader>\n");
-
-  if (jp2_struct->bpc == 255)
-  {
-    fprintf(xmlout,    "                <BitsPerComponent BoxType=\"bpcc\">\n");
-    if(notes)
-      fprintf(xmlout,  "                <!-- Pixel depth (range 1 to 38) is low 7 bits of hex value + 1 -->\n");
-       /* Bits per pixel varies with components */
-    /* Compare jp2_read_bpcc(jp2_struct) */
-       for (i = 0; i < (int)jp2_struct->numcomps; i++) {
-         if(raw)
-        fprintf(xmlout,"                  <AsHex>0x%02x</AsHex>\n", jp2_struct->comps[i].bpcc); /* 1 byte */
-         if(derived) {
-        fprintf(xmlout,"                  <BitsPerPixel>%d</BitsPerPixel>\n", (jp2_struct->comps[i].bpcc & 0x7f)+1);
-        fprintf(xmlout,"                  <Signed>%d</Signed>\n", jp2_struct->comps[i].bpcc >> 7);
-         }
-       }
-    fprintf(xmlout,    "                </BitsPerComponent>\n");
-  }
-
-  /* Compare jp2_read_colr(jp2_struct) */
-  fprintf(xmlout,      "                <ColourSpecification BoxType=\"colr\">\n");
-  fprintf(xmlout,      "                  <METH>%d</METH>\n", jp2_struct->meth); /* 1 byte */
-  if(notes) {
-    fprintf(xmlout,    "                  <!-- Valid values of specification method so far: -->\n");
-    fprintf(xmlout,    "                  <!--   1 = Enumerated colourspace, in EnumCS field -->\n");
-    fprintf(xmlout,    "                  <!--   2 = Restricted ICC Profile, in PROFILE field -->\n");
-  }
-  fprintf(xmlout,      "                  <PREC>%d</PREC>\n", jp2_struct->precedence); /* 1 byte */
-  if(notes)
-    fprintf(xmlout,    "                  <!-- 0 is only valid value of precedence so far. -->\n");
-  fprintf(xmlout,      "                  <APPROX>%d</APPROX>\n", jp2_struct->approx); /* 1 byte */
-  if(notes)
-    fprintf(xmlout,    "                  <!-- 0 is only valid value of colourspace approximation so far. -->\n");
-
-  if (jp2_struct->meth == 1) {
-    fprintf(xmlout,    "                  <EnumCS>%d</EnumCS>\n", jp2_struct->enumcs); /* 4 bytes */
-       if(notes) {
-         fprintf(xmlout,  "                  <!-- Valid values of enumerated MJ2 colourspace so far: -->\n");
-         fprintf(xmlout,  "                  <!--   16: sRGB as defined by IEC 61966-2-1. -->\n");
-         fprintf(xmlout,  "                  <!--   17: greyscale (related to sRGB). -->\n");
-         fprintf(xmlout,  "                  <!--   18: sRGB YCC (from JPEG 2000 Part II). -->\n");
-         fprintf(xmlout,  "                  <!-- (Additional JPX values are defined in Part II). -->\n");
-       }
-  }
-  else
-    if(notes)
-      fprintf(xmlout,  "                  <!-- PROFILE is not handled by current OpenJPEG implementation. -->\n");
-    /* only 1 byte is read and nothing stored */
-  fprintf(xmlout,      "                </ColourSpecification>\n");
-
-  /* TO DO?  No OpenJPEG support.
-  Palette 'pclr'
-  ComponentMapping 'cmap'
-  ChannelDefinition 'cdef'
-  Resolution 'res'
-  */
-  fprintf(xmlout,      "              </JP2Header>\n");
-}
-/* ------------- */
-
-#ifdef NOTYET
-IMAGE these use cp structure, extended... but we could use a new data structure instead
-void xml_out_frame_jp2i(FILE* xmlout, opj_cp_t *cp) {
-  /* IntellectualProperty 'jp2i' (no restrictions on location) */
-  int i;
-  IMAGE cp->jp2i, cp->jp2i_count, cp->jp2i_data (array of chars), cp->cp2i_len (array of ints)
-  if(cp->jp2i != 1)
-         return; /* Not present */
-
-  for(i = 0; i < cp->jp2i_count; i++)
-  {
-    fprintf(xmlout,      "            <IntellectualProperty BoxType=\"jp2i\">\n");
-  /* I think this can be anything, including binary, so do a dump */
-    /* Is it better to indent or not indent this content?  Indent is better for reading, but
-    worse for cut/paste. */
-    xml_out_dump_hex_and_ascii(xmlout, cp->jp2i_data[i], cp->jp2i_len[i]);
-    fprintf(xmlout,      "            </IntellectualProperty>\n");
-  }
-}
-
-void xml_out_frame_xml(FILE* xmlout, opj_cp_t *cp) {
-  /* XML 'xml\040' (0x786d6c20).  Can appear multiply, before or after jp2c codestreams */
-  IMAGE cp->xml, cp->xml_count, cp->xml_data (array of chars)
-  MAYBE WE DON'T NEED cp->xml_len (array of ints) IF WE ASSUME xml_data IS NULL-TERMINATED.
-  ASSUME ASSUME EACH LINE IS ENDED BY \n.
-  int i;
-  if(cp->xml != 1)
-         return; /* Not present */
-
-  for(i = 0; i < cp->xml_count; i++)
-  {
-    fprintf(xmlout,      "            <TextFormXML BoxType=\"xml[space]" Instance=\"%d\">\n", i+1);
-    /* Is it better to indent or not indent this content?  Indent is better for reading, but
-    worse for cut/paste. Being lazy, didn't indent here. */
-    fprintf(xmlout,cp->xml_data[i]); /* May be multiple lines */ /* Could check if this is well-formed */
-    fprintf(xmlout,      "            </TextFormXML>\n");
-  }
-}
-
-void xml_out_frame_uuid(FILE* xmlout, opj_cp_t *cp) {
-       /* UUID 'uuid' (top level only) */
-       /* Part I 1.7.2 says: may appear multiply in JP2 file, anywhere except before File Type box */
-       /* Part III 5.2.1 says: Private extensions shall be achieved through the 'uuid' type. */
-       /* A UUID is a 16-byte value.  There is a conventional string representation for it:
-          "0x12345678-9ABC-DEF0-1234-567890ABCDEF".  Let's assume that is what is stored in uuid_value */
-
-       /* Part III 6.1 Any other MJ2 box type could be alternatively written as a 'uuid' box, with value given
-          as : 0xXXXXXXXX-0011-0010-8000-00AA00389B71, where the Xs are the boxtype in hex.  However,
-          such a file is "not compliant; systems may choose to read [such] objects ... as equivalent to the box of
-          the same type, or not."  Here, we choose not to. */
-  int i;
-  IMAGE cp->uuid, cp->uuid_count, cp->uuid_value (array of uuids... let's say fixed-length strings) cp->uuid_data (array of char buffers), cp->uuid_len (array of ints)
-  if(cp->juuid != 1)
-         return; /* Not present */
-
-  for(i = 0; i < cp->uuid_count; i++)
-  {
-    fprintf(xmlout,      "            <UniversalUniqueID BoxType=\"uuid\">
-       fprintf(xmlout,      "              <UUID>%s</UUDI>\n", cp->uuid_value[i]);
-       fprintf(xmlout,      "              <Data>\n");
-  /* I think this can be anything, including binary, so do a dump */
-    /* Is it better to indent or not indent this content?  Indent is better for reading, but
-    worse for cut/paste. */
-    xml_out_dump_hex_and_ascii(xmlout, cp->uuid_data[i], cp->uuid_len[i]);
-       fprintf(xmlout,      "              </Data>\n");
-    fprintf(xmlout,      "            </UniversalUniqueID>\n");
-  }
-}
-
-void xml_out_frame_uinf(FILE* xmlout, opj_cp_t *cp) {
-       /* UUIDInfo 'uinf', includes UUIDList 'ulst' and URL 'url\40' */
-       /* Part I 1.7.3 says: may appear multiply in JP2 file, anywhere at the top level except before File Type box */
-       /* So there may be multiple ulst's, and each can have multiple UUIDs listed (with a single URL) */
-       /* This is not quite as vendor-specific as UUIDs, or at least is meant to be generally readable */
-       /* Assume UUIDs stored in canonical string format */
-  int i, j;
-  IMAGE cp->uinf, cp->uinf_count, cp->uinf_ulst_nu (array of ints)
-    cp->uinf_uuid (2 dimensional array of uuids... let's say fixed-length strings),
-    cp->uinf_url (array of char buffers)
-
-  if(cp->uinf != 1)
-         return; /* Not present */
-
-  for(i = 0; i < cp->uuid_count; i++)
-  {
-    fprintf(xmlout,      "            <UUIDInfo BoxType=\"uinf\">\n");
-    fprintf(xmlout,      "              <UUIDList BoxType=\"ulst\" Count=\"%d\">\n",cp->cp->uinf_ulst_nu[i]);
-       for(j = 0; j < cp->uinf_ulst_nu[i];  j++)
-         fprintf(xmlout,    "              <ID Instance=\"%s\">%s</ID>\n", cp->uuif_uuid[i][j], j+1);
-    fprintf(xmlout,      "              </UUIDList>\n");
-       fprintf(xmlout,      "              <DataEntryURL>\n");
-       /* Could add VERS and FLAG here */
-       fprintf(xmlout,      "                <LOC>\n");
-    fprintf(xmlout,      "                  %s",cp->uinf_url[i]); /* Probably single line, so indent works */ /* In theory, could check if this is well-formed, or good live link */
-       fprintf(xmlout,      "                </LOC>\n");
-       fprintf(xmlout,      "              </DataEntryURL>\n");
-    fprintf(xmlout,      "            </UUIDInfo>\n");
-  }
-}
-
-IMAGE these use cp structure, extended... but we could use a new data structure instead
-void xml_out_frame_unknown_type(FILE* xmlout, opj_cp_t *cp) {
-  /* Part III 5.2.1 says "Type fields not defined here are reserved.  Private extensions
-     shall be acieved through the 'uuid' type." [This implies an unknown
-     type would be an error, but then...] "Boxes not explicitly defined in this standard,
-        or otherwise unrecognized by a reader, may be ignored."
-        Also, it says  "the following types are not and will not be used, or used only in
-        their existing sense, in future versions of this specification, to avoid conflict
-        with existing content using earlier pre-standard versions of this format:
-          clip, crgn, matt, kmat, pnot, ctab, load, imap;
-          track reference types tmcd, chap, sync,scpt, ssrc"
-        [But good luck figuring out the mapping.]
-        Part III Amend. 2 4.1 is stronger: "All these specifications [of this family, e.g.,
-        JP2 Part I, ISO Base format (Part 12) leading to MP4, Quicktime, and possibly including
-        MJ2] require that readers ignore objects that are unrecognizable to them".
-        */
-  int i;
-  IMAGE cp->unknown_type, cp->unknown_type_count, cp->unknown_type_boxtype (array of buf[5]s), cp->unknown_type_data (array of chars), cp->unknown_type_len (array of ints)
-  if(cp->unknown_type != 1)
-         return; /* Not present */
-
-  for(i = 0; i < cp->unknown_type_count; i++)
-  {
-    fprintf(xmlout,      "            <UnknownType BoxType=\"%s\">\n", cp->unknown_type_boxtype[i]);
-    /* Can be anything, including binary, so do a dump */
-    /* Is it better to indent or not indent this content?  Indent is better for reading, but
-    worse for cut/paste. */
-    xml_out_dump_hex_and_ascii(xmlout, cp->unknown_type_data[i], cp->unknown_type_len[i]);
-    fprintf(xmlout,      "            </UnknownType>\n");
-  }
-}
-
-#endif
diff --git a/mj2/meta_out.h b/mj2/meta_out.h
deleted file mode 100644 (file)
index 293316d..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-/* meta_out.h */
-/* Dump MJ2, JP2 metadata (partial so far) to xml file */
-/* Callable from mj2_to_metadata */
-/* Contributed to Open JPEG by Glenn Pearson, U.S. National Library of Medicine */
-
-#define BOOL int
-#define FALSE 0
-#define TRUE 1
-
-void xml_write_init(BOOL n, BOOL t, BOOL r, BOOL d);
-
-int xml_write_struct(FILE *file, FILE *xmlout, opj_mj2_t * movie, unsigned int sampleframe, char* stringDTD, opj_event_mgr_t *event_mgr);
-
diff --git a/mj2/mj2.c b/mj2/mj2.c
deleted file mode 100644 (file)
index 131eace..0000000
--- a/mj2/mj2.c
+++ /dev/null
@@ -1,2922 +0,0 @@
-/*
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
- * Copyright (c) 2002-2007, Professor Benoit Macq
- * Copyright (c) 2003-2007, Francois-Olivier Devaux 
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "../libopenjpeg/opj_includes.h"
-#include "mj2.h"
-
-/** @defgroup JP2 JP2 - JPEG-2000 file format reader/writer */
-/*@{*/
-
-/** @name Local static functions */
-/*@{*/
-
-/**
-Read box headers
-@param cinfo Codec context info
-@param cio Input stream
-@param box
-@return Returns true if successful, returns false otherwise
-*/
-/*-- UNUSED
-static bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_box_t *box);
---*/
-/*
-* 
-* Read box headers
-*
-*/
-
-int mj2_read_boxhdr(mj2_box_t * box, opj_cio_t *cio)
-{
-  box->init_pos = cio_tell(cio);
-  box->length = cio_read(cio, 4);
-  box->type = cio_read(cio, 4);
-  if (box->length == 1) {
-    if (cio_read(cio, 4) != 0) {
-      opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Cannot handle box sizes higher than 2^32\n");
-      return 1;
-    };
-    box->length = cio_read(cio, 4);
-    if (box->length == 0) 
-      box->length = cio_numbytesleft(cio) + 12;
-  }
-  else if (box->length == 0) {
-    box->length = cio_numbytesleft(cio) + 8;
-  }
-  return 0;
-}
-
-/*
-* 
-* Initialisation of a Standard Movie, given a simple movie structure defined by the user 
-* The movie will have one sample per chunk
-* 
-* Arguments: opj_mj2_t * movie
-* Several variables of "movie" must be defined in order to enable a correct execution of 
-* this function:
-*   - The number of tracks of each type (movie->num_vtk, movie->num_stk, movie->num_htk)
-*   - The memory for each must be allocated (movie->tk)
-*   - For each track:
-*        The track type (tk->track_type)
-*        The number of sample (tk->num_samples)
-*        The sample rate (tk->sample_rate)
-*
-*/
-
-int mj2_init_stdmovie(opj_mj2_t * movie)
-{
-  mj2_tk_t *tk0;
-  int i, w, h, prec;
-  unsigned int j;
-  time_t ltime;
-       
-  movie->brand = MJ2_MJ2;
-  movie->minversion = 0;
-  movie->num_cl = 2;
-  movie->cl = (unsigned int*) opj_malloc(movie->num_cl * sizeof(unsigned int));
-
-  movie->cl[0] = MJ2_MJ2;
-  movie->cl[1] = MJ2_MJ2S;
-  time(&ltime);                        /* Time since 1/1/70 */
-  movie->creation_time = (unsigned int) ltime + 2082844800;    /* Seconds between 1/1/04 and 1/1/70 */
-  movie->timescale = 1000;
-       
-  movie->rate = 1 << 16;               /* Rate to play presentation  (default = 0x00010000)          */
-  movie->volume = 1 << 8;              /* Movie volume (default = 0x0100)                            */
-  movie->trans_matrix[0] = 0x00010000; /* Transformation matrix for video                            */
-  movie->trans_matrix[1] = 0;  /* Unity is { 0x00010000,0,0,0,0x00010000,0,0,0,0x40000000 }  */
-  movie->trans_matrix[2] = 0;
-  movie->trans_matrix[3] = 0;
-  movie->trans_matrix[4] = 0x00010000;
-  movie->trans_matrix[5] = 0;
-  movie->trans_matrix[6] = 0;
-  movie->trans_matrix[7] = 0;
-  movie->trans_matrix[8] = 0x40000000;
-  movie->next_tk_id = 1;
-
-  tk0 = &movie->tk[0];
-  w = tk0->w; h = tk0->h; prec = tk0->depth;
-
-       for (i = 0; i < movie->num_htk + movie->num_stk + movie->num_vtk; i++) 
-   {
-    mj2_tk_t *tk = &movie->tk[i];
-
-    movie->next_tk_id++;
-    tk->jp2_struct.comps = NULL;
-    tk->jp2_struct.cl = NULL;
-  
-    if (tk->track_type == 0) /* no sound or hint track */
-   {
-    if (tk->num_samples == 0)
-                               return 1;
-                       
-    tk->w = w; tk->h = h; tk->depth = prec;
-      tk->Dim[0] = 0;
-      tk->Dim[1] = 0;
-                       
-      tk->timescale = 1000;    /* Timescale = 1 ms                                          */
-                       
-      tk->chunk[0].num_samples = 1;
-      tk->chunk[0].sample_descr_idx = 1;
-                       
-      tk->same_sample_size = 0;
-                       
-      tk->num_samplestochunk = 1;      /* One sample per chunk  */
-               tk->sampletochunk = (mj2_sampletochunk_t*) opj_malloc(tk->num_samplestochunk * sizeof(mj2_sampletochunk_t));
-      tk->sampletochunk[0].first_chunk = 1;
-      tk->sampletochunk[0].samples_per_chunk = 1;
-      tk->sampletochunk[0].sample_descr_idx = 1;
-      
-      if (tk->sample_rate == 0) 
-  {
-       opj_event_msg(tk->cinfo, EVT_ERROR,
-       "Error while initializing MJ2 movie: Sample rate of track"
-       " %d must be different from zero\n", tk->track_ID);
-       return 1;
-  }
-                       
-      for (j = 0; j < tk->num_samples; j++) 
-  {
-       tk->sample[j].sample_delta = tk->timescale / tk->sample_rate;
-  }
-                       
-      tk->num_tts = 1;
-               tk->tts = (mj2_tts_t*) opj_malloc(tk->num_tts * sizeof(mj2_tts_t));
-      tk->tts[0].sample_count = tk->num_samples;
-      tk->tts[0].sample_delta = tk->timescale / tk->sample_rate;
-                       
-      tk->horizresolution = 0x00480000;        /* Horizontal resolution (typically 72)                       */
-      tk->vertresolution = 0x00480000; /* Vertical resolution (typically 72)                         */
-      tk->compressorname[0] = 0x0f4d6f74;      /* Compressor Name[]: Motion JPEG2000                         */
-      tk->compressorname[1] = 0x696f6e20;
-      tk->compressorname[2] = 0x4a504547;
-      tk->compressorname[3] = 0x32303030;
-      tk->compressorname[4] = 0x00120000;
-      tk->compressorname[5] = 0;
-      tk->compressorname[6] = 0x00000042;
-      tk->compressorname[7] = 0x000000DC;
-      tk->num_url = 0;         /* Number of URL                                              */
-      tk->num_urn = 0;         /* Number of URN                                              */
-      tk->graphicsmode = 0;    /* Graphicsmode                                               */
-      tk->opcolor[0] = 0;      /* OpColor                                                    */
-      tk->opcolor[1] = 0;      /* OpColor                                                    */
-      tk->opcolor[2] = 0;      /* OpColor                                                    */
-      tk->creation_time = movie->creation_time;        /* Seconds between 1/1/04 and 1/1/70          */
-      tk->language = 0;                /* Language (undefined)                                       */
-      tk->layer = 0;
-      tk->volume = 1 << 8;             /* Movie volume (default = 0x0100) */
-      tk->trans_matrix[0] = 0x00010000;        /* Transformation matrix for track */
-      tk->trans_matrix[1] = 0; /* Unity is { 0x00010000,0,0,0,0x00010000,0,0,0,0x40000000 }  */
-      tk->trans_matrix[2] = 0;
-      tk->trans_matrix[3] = 0;
-      tk->trans_matrix[4] = 0x00010000;
-      tk->trans_matrix[5] = 0;
-      tk->trans_matrix[6] = 0;
-      tk->trans_matrix[7] = 0;
-      tk->trans_matrix[8] = 0x40000000;
-      tk->fieldcount = 1;
-      tk->fieldorder = 0;
-      tk->or_fieldcount = 1;
-      tk->or_fieldorder = 0;
-      tk->num_br = 2;
-               tk->br = (unsigned int*) opj_malloc(tk->num_br * sizeof(unsigned int));
-      tk->br[0] = MJ2_JP2;
-      tk->br[1] = MJ2_J2P0;
-      tk->num_jp2x = 0;
-      tk->hsub = 2;            /* 4:2:0                                                      */
-      tk->vsub = 2;            /* 4:2:0                                                      */
-      tk->hoff = 0;
-      tk->voff = 0;
-      tk->visual_w = tk->w << 16;
-      tk->visual_h = tk->h << 16;
-    }
-    else {
-      tk->num_br = 0;
-      tk->jp2xdata = NULL;
-    }
-  }
-  return 0;
-}
-
-/*
-* Time To Sample box Decompact
-*
-*/
-void mj2_tts_decompact(mj2_tk_t * tk)
-{
-  int i, j;
-  tk->num_samples = 0;
-  for (i = 0; i < tk->num_tts; i++) {
-    tk->num_samples += tk->tts[i].sample_count;
-  }
-
-  tk->sample = (mj2_sample_t*) opj_malloc(tk->num_samples * sizeof(mj2_sample_t));
-
-  for (i = 0; i < tk->num_tts; i++) {
-    for (j = 0; j < tk->tts[i].sample_count; j++) {
-      tk->sample[j].sample_delta = tk->tts[i].sample_delta;
-    }
-  }
-}
-
-/*
-* Sample To Chunk box Decompact
-*
-*/
-void mj2_stsc_decompact(mj2_tk_t * tk)
-{
-  int j, i;
-  unsigned int k;
-  int sampleno=0;
-  
-  if (tk->num_samplestochunk == 1) {
-    tk->num_chunks =
-      (unsigned int) ceil((double) tk->num_samples /
-      (double) tk->sampletochunk[0].samples_per_chunk);
-        tk->chunk = (mj2_chunk_t*) opj_malloc(tk->num_chunks * sizeof(mj2_chunk_t));
-    for (k = 0; k < tk->num_chunks; k++) {
-      tk->chunk[k].num_samples = tk->sampletochunk[0].samples_per_chunk;
-    }
-    
-  } else {
-    tk->chunk = (mj2_chunk_t*) opj_malloc(tk->num_samples * sizeof(mj2_chunk_t));
-    tk->num_chunks = 0;
-    for (i = 0; i < tk->num_samplestochunk -1 ; i++) {
-      for (j = tk->sampletochunk[i].first_chunk - 1;
-      j < tk->sampletochunk[i + 1].first_chunk - 1; j++) {
-                               tk->chunk[j].num_samples = tk->sampletochunk[i].samples_per_chunk;
-                               tk->num_chunks++;
-                               sampleno += tk->chunk[j].num_samples;
-      }
-    }
-    tk->num_chunks += (int)(tk->num_samples  - sampleno) / tk->sampletochunk[tk->num_samplestochunk - 1].samples_per_chunk;
-    for (k = tk->sampletochunk[tk->num_samplestochunk - 1].first_chunk - 1;
-    k < tk->num_chunks; k++) {
-      tk->chunk[k].num_samples =
-                               tk->sampletochunk[tk->num_samplestochunk - 1].samples_per_chunk;
-    }
-    tk->chunk = (mj2_chunk_t*)
-        opj_realloc(tk->chunk, tk->num_chunks * sizeof(mj2_chunk_t));
-  }
-  
-}
-
-
-/*
-* Chunk offset box Decompact
-*
-*/
-void mj2_stco_decompact(mj2_tk_t * tk)
-{
-  int j;
-  unsigned int i;
-  int k = 0;
-  int intra_chunk_offset;
-       
-  for (i = 0; i < tk->num_chunks; i++) {
-    intra_chunk_offset = 0;
-    for (j = 0; j < tk->chunk[i].num_samples; j++) {
-      tk->sample[k].offset = intra_chunk_offset + tk->chunk[i].offset;
-      intra_chunk_offset += tk->sample[k].sample_size;
-      k++;
-    }
-  }
-}
-
-/*
-* Write the JP box
-*
-* JP Signature box
-*
-*/
-void mj2_write_jp(opj_cio_t *cio)
-{
-  mj2_box_t box;
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-       
-  cio_write(cio, MJ2_JP, 4);           /* JP */
-  cio_write(cio, 0x0d0a870a, 4);       /* 0x0d0a870a required in a JP box */
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the JP box
-*
-* JPEG 2000 signature
-*
-*/
-int mj2_read_jp(opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_JP != box.type) {    /* Check Marker */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected JP Marker\n");
-    return 1;
-  }
-  if (0x0d0a870a != cio_read(cio, 4)) {        /* read the 0x0d0a870a required in a JP box */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with JP Marker\n");
-    return 1;
-  }
-  if (cio_tell(cio) - box.init_pos != box.length) {    /* Check box length */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with JP Box size \n");
-    return 1;
-  }
-  return 0;
-       
-}
-
-/*
-* Write the FTYP box
-*
-* File type box
-*
-*/
-void mj2_write_ftyp(opj_mj2_t * movie, opj_cio_t *cio)
-{
-  int i;
-  mj2_box_t box;
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-       
-  cio_write(cio, MJ2_FTYP, 4); /* FTYP       */
-  cio_write(cio, movie->brand, 4);     /* BR         */
-  cio_write(cio, movie->minversion, 4);        /* MinV       */
-       
-  for (i = 0; i < movie->num_cl; i++)
-    cio_write(cio, movie->cl[i], 4);   /* CL         */
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* Length     */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the FTYP box
-*
-* File type box
-*
-*/
-int mj2_read_ftyp(opj_mj2_t * movie, opj_cio_t *cio)
-{
-  int i;
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);  /* Box Size */
-  if (MJ2_FTYP != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected FTYP Marker\n");
-    return 1;
-  }
-       
-  movie->brand = cio_read(cio, 4);     /* BR              */
-  movie->minversion = cio_read(cio, 4);        /* MinV            */
-  movie->num_cl = (box.length - 16) / 4;
-  movie->cl = (unsigned int*) opj_malloc(movie->num_cl * sizeof(unsigned int));
-
-  for (i = movie->num_cl - 1; i > -1; i--)
-    movie->cl[i] = cio_read(cio, 4);   /* CLi */
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with FTYP Box\n");
-    return 1;
-  }
-  return 0;
-}
-
-
-/*
-* Write the STCO box
-*
-* Chunk Offset Box
-*
-*/
-void mj2_write_stco(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-  unsigned int i;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_STCO, 4); /* STCO       */
-       
-  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
-       
-  cio_write(cio, tk->num_chunks, 4);   /* Entry Count */
-       
-  for (i = 0; i < tk->num_chunks; i++) {
-    cio_write(cio, tk->chunk[i].offset, 4);    /* Entry offset */
-  }
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the STCO box
-*
-* Chunk Offset Box
-*
-*/
-int mj2_read_stco(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  unsigned int i;
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);  /* Box Size */
-  if (MJ2_STCO != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected STCO Marker\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in STCO box\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in STCO box. Expected flag 0\n");
-    return 1;
-  }
-       
-       
-  if (cio_read(cio, 4) != tk->num_chunks) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, 
-                       "Error in STCO box: expecting same amount of entry-count as chunks \n");
-  } else {
-    for (i = 0; i < tk->num_chunks; i++) {
-      tk->chunk[i].offset = cio_read(cio, 4);  /* Entry offset */
-    }
-  }
-       
-  mj2_stco_decompact(tk);
-       
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with STCO Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the STSZ box
-*
-* Sample size box
-*
-*/
-void mj2_write_stsz(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-  unsigned int i;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_STSZ, 4); /* STSZ       */
-       
-  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
-       
-  if (tk->same_sample_size == 1) {     /* If they all have the same size */
-    cio_write(cio, tk->sample[0].sample_size, 4);      /* Size */
-               
-    cio_write(cio, 1, 4);              /* Entry count = 1 */
-  }
-       
-  else {
-    cio_write(cio, 0, 4);              /* Sample Size = 0 becase they all have different sizes */
-               
-    cio_write(cio, tk->num_samples, 4);        /* Sample Count */
-               
-    for (i = 0; i < tk->num_samples; i++) {
-      cio_write(cio, tk->sample[i].sample_size, 4);
-    }
-  }
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the STSZ box
-*
-* Sample size box
-*
-*/
-int mj2_read_stsz(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  int sample_size;
-  unsigned int i;
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);  /* Box Size */
-  if (MJ2_STSZ != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected STSZ Marker\n");
-    return 1;
-  }
-       
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in STSZ box\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in STSZ box. Expected flag 0\n");
-    return 1;
-  }
-       
-  sample_size = cio_read(cio, 4);
-       
-  if (sample_size != 0) {      /* Samples do have the same size */
-    tk->same_sample_size = 1;
-    for (i = 0; i < tk->num_samples; i++) {
-      tk->sample[i].sample_size = sample_size;
-    }
-    cio_skip(cio,4);           /* Sample count = 1 */
-  } else {
-    tk->same_sample_size = 0;
-    if (tk->num_samples != cio_read(cio, 4)) { /* Sample count */
-      opj_event_msg(cio->cinfo, EVT_ERROR,
-                               "Error in STSZ box. Expected that sample-count is number of samples in track\n");
-      return 1;
-    }
-    for (i = 0; i < tk->num_samples; i++) {
-      tk->sample[i].sample_size = cio_read(cio, 4);    /* Sample Size */
-    }
-               
-    if (cio_tell(cio) - box.init_pos != box.length) {
-      opj_event_msg(cio->cinfo, EVT_ERROR, "Error with STSZ Box size\n");
-      return 1;
-    }
-  }
-  return 0;
-       
-}
-
-/*
-* Write the STSC box
-*
-* Sample to Chunk
-*
-*/
-void mj2_write_stsc(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  int i;
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_STSC, 4); /* STSC       */
-       
-  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
-       
-  cio_write(cio, tk->num_samplestochunk, 4);   /* Entry Count */
-       
-  for (i = 0; i < tk->num_samplestochunk; i++) {
-    cio_write(cio, tk->sampletochunk[i].first_chunk, 4);       /* First Chunk */
-    cio_write(cio, tk->sampletochunk[i].samples_per_chunk, 4); /* Samples per chunk */
-    cio_write(cio, tk->sampletochunk[i].sample_descr_idx, 4);  /* Samples description index */
-  }
-       
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the STSC box
-*
-* Sample to Chunk
-*
-*/
-int mj2_read_stsc(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  int i;
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);  /* Box Size */
-  if (MJ2_STSC != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected STSC Marker\n");
-    return 1;
-  }
-       
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in STSC box\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in STSC box. Expected flag 0\n");
-    return 1;
-  }
-       
-  tk->num_samplestochunk = cio_read(cio, 4);
-
-  tk->sampletochunk = (mj2_sampletochunk_t*) opj_malloc(tk->num_samplestochunk * sizeof(mj2_sampletochunk_t));
-
-  for (i = 0; i < tk->num_samplestochunk; i++) {
-    tk->sampletochunk[i].first_chunk = cio_read(cio, 4);
-    tk->sampletochunk[i].samples_per_chunk = cio_read(cio, 4);
-    tk->sampletochunk[i].sample_descr_idx = cio_read(cio, 4);
-  }
-       
-  mj2_stsc_decompact(tk);      /* decompact sample to chunk box */
-       
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with STSC Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the STTS box
-*
-* Time to Sample Box
-*
-*/
-void mj2_write_stts(mj2_tk_t * tk, opj_cio_t *cio)
-{
-       
-  int i;
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_STTS, 4); /* STTS       */
-       
-  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
-       
-  cio_write(cio, tk->num_tts, 4);      /* entry_count */
-  for (i = 0; i < tk->num_tts; i++) {
-    cio_write(cio, tk->tts[i].sample_count, 4);        /* Sample-count */
-    cio_write(cio, tk->tts[i].sample_delta, 4);        /* Sample-Delta */
-  }
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the STTS box
-*
-* 
-*
-*/
-int mj2_read_stts(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  int i;
-       
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_STTS != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected STTS Marker\n");
-    return 1;
-  }
-       
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in STTS box\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in STTS box. Expected flag 0\n");
-    return 1;
-  }
-       
-  tk->num_tts = cio_read(cio, 4);
-
-  tk->tts = (mj2_tts_t*) opj_malloc(tk->num_tts * sizeof(mj2_tts_t));
-
-  for (i = 0; i < tk->num_tts; i++) {
-    tk->tts[i].sample_count = cio_read(cio, 4);
-    tk->tts[i].sample_delta = cio_read(cio, 4);
-  }
-       
-  mj2_tts_decompact(tk);
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with STTS Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the FIEL box
-*
-* Field coding Box
-*
-*/
-void mj2_write_fiel(mj2_tk_t * tk, opj_cio_t *cio)
-{
-       
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_FIEL, 4); /* STTS       */
-       
-  cio_write(cio, tk->fieldcount, 1);   /* Field count */
-  cio_write(cio, tk->fieldorder, 1);   /* Field order */
-       
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the FIEL box
-*
-* Field coding Box
-*
-*/
-int mj2_read_fiel(mj2_tk_t * tk, opj_cio_t *cio)
-{
-       
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_FIEL != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected FIEL Marker\n");
-    return 1;
-  }
-       
-       
-  tk->fieldcount = cio_read(cio, 1);
-  tk->fieldorder = cio_read(cio, 1);
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with FIEL Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the ORFO box
-*
-* Original Format Box
-*
-*/
-void mj2_write_orfo(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_ORFO, 4);
-       
-  cio_write(cio, tk->or_fieldcount, 1);        /* Original Field count */
-  cio_write(cio, tk->or_fieldorder, 1);        /* Original Field order */
-       
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the ORFO box
-*
-* Original Format Box
-*
-*/
-int mj2_read_orfo(mj2_tk_t * tk, opj_cio_t *cio)
-{
-       
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_ORFO != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected ORFO Marker\n");
-    return 1;
-  }
-       
-       
-  tk->or_fieldcount = cio_read(cio, 1);
-  tk->or_fieldorder = cio_read(cio, 1);
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with ORFO Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the JP2P box
-*
-* MJP2 Profile Box
-*
-*/
-void mj2_write_jp2p(mj2_tk_t * tk, opj_cio_t *cio)
-{
-       
-  int i;
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_JP2P, 4);
-       
-  cio_write(cio, 0, 4);                /* Version 0, flags =0 */
-       
-  for (i = 0; i < tk->num_br; i++) {
-    cio_write(cio, tk->br[i], 4);
-  }
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the JP2P box
-*
-* MJP2 Profile Box
-*
-*/
-int mj2_read_jp2p(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  int i;
-       
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_JP2P != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected JP2P Marker\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in JP2P box\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in JP2P box. Expected flag 0\n");
-    return 1;
-  }
-       
-       
-  tk->num_br = (box.length - 12) / 4;
-  tk->br = (unsigned int*) opj_malloc(tk->num_br * sizeof(unsigned int));
-
-  for (i = 0; i < tk->num_br; i++) {
-    tk->br[i] = cio_read(cio, 4);
-  }
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with JP2P Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the JP2X box
-*
-* MJP2 Prefix Box
-*
-*/
-void mj2_write_jp2x(mj2_tk_t * tk, opj_cio_t *cio)
-{
-       
-  int i;
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_JP2X, 4);
-       
-  for (i = 0; i < tk->num_jp2x; i++) {
-    cio_write(cio, tk->jp2xdata[i], 1);
-  }
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the JP2X box
-*
-* MJP2 Prefix Box
-*
-*/
-int mj2_read_jp2x(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  unsigned int i;
-       
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_JP2X != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected JP2X Marker\n");
-    return 1;
-  }
-       
-       
-  tk->num_jp2x = (box.length - 8);
-  tk->jp2xdata = (unsigned char*) opj_malloc(tk->num_jp2x * sizeof(unsigned char));
-
-  for (i = 0; i < tk->num_jp2x; i++) {
-    tk->jp2xdata[i] = cio_read(cio, 1);
-  }
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with JP2X Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the JSUB box
-*
-* MJP2 Subsampling Box
-*
-*/
-void mj2_write_jsub(mj2_tk_t * tk, opj_cio_t *cio)
-{
-       
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_JSUB, 4);
-       
-  cio_write(cio, tk->hsub, 1);
-  cio_write(cio, tk->vsub, 1);
-  cio_write(cio, tk->hoff, 1);
-  cio_write(cio, tk->voff, 1);
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the JSUB box
-*
-* MJP2 Subsampling Box
-*
-*/
-int mj2_read_jsub(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_JSUB != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected JSUB Marker\n");
-    return 1;
-  }
-       
-  tk->hsub = cio_read(cio, 1);
-  tk->vsub = cio_read(cio, 1);
-  tk->hoff = cio_read(cio, 1);;
-  tk->voff = cio_read(cio, 1);
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with JSUB Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the SMJ2 box
-*
-* Visual Sample Entry Description
-*
-*/
-void mj2_write_smj2(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_MJ2, 4);  /* MJ2       */
-       
-  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
-       
-  cio_write(cio, 1, 4);
-       
-  cio_write(cio, 0, 2);                /* Pre-defined */
-       
-  cio_write(cio, 0, 2);                /* Reserved */
-       
-  cio_write(cio, 0, 4);                /* Pre-defined */
-  cio_write(cio, 0, 4);                /* Pre-defined */
-  cio_write(cio, 0, 4);                /* Pre-defined */
-       
-  cio_write(cio, tk->w, 2);            /* Width  */
-  cio_write(cio, tk->h, 2);            /* Height */
-       
-  cio_write(cio, tk->horizresolution, 4);      /* Horizontal resolution */
-  cio_write(cio, tk->vertresolution, 4);       /* Vertical resolution   */
-       
-  cio_write(cio, 0, 4);                /* Reserved */
-       
-  cio_write(cio, 1, 2);                /* Pre-defined = 1 */
-       
-  cio_write(cio, tk->compressorname[0], 4);    /* Compressor Name */
-  cio_write(cio, tk->compressorname[1], 4);
-  cio_write(cio, tk->compressorname[2], 4);
-  cio_write(cio, tk->compressorname[3], 4);
-  cio_write(cio, tk->compressorname[4], 4);
-  cio_write(cio, tk->compressorname[5], 4);
-  cio_write(cio, tk->compressorname[6], 4);
-  cio_write(cio, tk->compressorname[7], 4);
-       
-  cio_write(cio, tk->depth, 2);        /* Depth */
-       
-  cio_write(cio, 0xffff, 2);           /* Pre-defined = -1 */
-       
-  jp2_write_jp2h(&tk->jp2_struct, cio);
-       
-  mj2_write_fiel(tk, cio);
-       
-  if (tk->num_br != 0)
-    mj2_write_jp2p(tk, cio);
-  if (tk->num_jp2x != 0)
-    mj2_write_jp2x(tk, cio);
-       
-  mj2_write_jsub(tk, cio);
-  mj2_write_orfo(tk, cio);
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the SMJ2 box
-*
-* Visual Sample Entry Description
-*
-*/
-int mj2_read_smj2(opj_image_t * img, mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-  mj2_box_t box2;
-  int i;
-  opj_jp2_color_t color;
-       
-  mj2_read_boxhdr(&box, cio);
-       
-  if (MJ2_MJ2 != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error in SMJ2 box: Expected MJ2 Marker\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in MJP2 box\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in MJP2 box. Expected flag 0\n");
-    return 1;
-  }
-       
-  cio_skip(cio,4);
-       
-  cio_skip(cio,2);                     /* Pre-defined */
-       
-  cio_skip(cio,2);                     /* Reserved */
-       
-  cio_skip(cio,4);                     /* Pre-defined */
-  cio_skip(cio,4);                     /* Pre-defined */
-  cio_skip(cio,4);                     /* Pre-defined */
-       
-  tk->w = cio_read(cio, 2);            /* Width  */
-  tk->h = cio_read(cio, 2);            /* Height */
-       
-  tk->horizresolution = cio_read(cio, 4);      /* Horizontal resolution */
-  tk->vertresolution = cio_read(cio, 4);       /* Vertical resolution   */
-       
-  cio_skip(cio,4);                     /* Reserved */
-       
-  cio_skip(cio,2);                     /* Pre-defined = 1 */
-       
-  tk->compressorname[0] = cio_read(cio, 4);    /* Compressor Name */
-  tk->compressorname[1] = cio_read(cio, 4);
-  tk->compressorname[2] = cio_read(cio, 4);
-  tk->compressorname[3] = cio_read(cio, 4);
-  tk->compressorname[4] = cio_read(cio, 4);
-  tk->compressorname[5] = cio_read(cio, 4);
-  tk->compressorname[6] = cio_read(cio, 4);
-  tk->compressorname[7] = cio_read(cio, 4);
-       
-  tk->depth = cio_read(cio, 2);        /* Depth */
-       
-  /* Init std value */
-  tk->num_jp2x = 0;
-  tk->fieldcount = 1;
-  tk->fieldorder = 0;
-  tk->or_fieldcount = 1;
-  tk->or_fieldorder = 0;
-       
-  cio_skip(cio,2);                     /* Pre-defined = -1 */
-  memset(&color, 0, sizeof(opj_jp2_color_t));
-       
-  if (!jp2_read_jp2h(&tk->jp2_struct, cio, &color)) {
-               opj_event_msg(tk->cinfo, EVT_ERROR, "Error reading JP2H Box\n");
-    return 1;
-  }
-
-  tk->jp2_struct.comps = (opj_jp2_comps_t*) opj_malloc(tk->jp2_struct.numcomps * sizeof(opj_jp2_comps_t));
-  tk->jp2_struct.cl = (unsigned int*) opj_malloc(sizeof(unsigned int));
-
-  tk->num_br = 0;
-  tk->num_jp2x = 0;
-       
-  for (i = 0; cio_tell(cio) - box.init_pos < box.length; i++) {
-    mj2_read_boxhdr(&box2, cio);
-    cio_seek(cio, box2.init_pos);
-    switch (box2.type) {
-    case MJ2_FIEL:
-      if (mj2_read_fiel(tk, cio))
-                               return 1;
-      break;
-                       
-    case MJ2_JP2P:
-      if (mj2_read_jp2p(tk, cio))
-                               return 1;
-      break;
-                       
-    case MJ2_JP2X:
-      if (mj2_read_jp2x(tk, cio))
-                               return 1;
-      break;
-                       
-    case MJ2_JSUB:
-      if (mj2_read_jsub(tk, cio))
-                               return 1;
-      break;
-                       
-    case MJ2_ORFO:
-      if (mj2_read_orfo(tk, cio))
-                               return 1;
-      break;
-                       
-    default:
-      opj_event_msg(cio->cinfo, EVT_ERROR, "Error with MJP2 Box size\n");
-      return 1;
-      break;
-                       
-    }
-  }
-  return 0;
-}
-
-
-/*
-* Write the STSD box
-*
-* Sample Description
-*
-*/
-void mj2_write_stsd(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_STSD, 4); /* STSD       */
-       
-  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
-       
-  cio_write(cio, 1, 4);                /* entry_count = 1 (considering same JP2 headerboxes) */
-       
-  if (tk->track_type == 0) {
-    mj2_write_smj2(tk, cio);
-  } else if (tk->track_type == 1) {
-    // Not implemented
-  }
-  if (tk->track_type == 2) {
-    // Not implemented
-  }
-       
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the STSD box
-*
-* Sample Description
-*
-*/
-int mj2_read_stsd(mj2_tk_t * tk, opj_image_t * img, opj_cio_t *cio)
-{
-  int i;
-  int entry_count, len_2skip;
-       
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-       
-  if (MJ2_STSD != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected STSD Marker\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in STSD box\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in STSD box. Expected flag 0\n");
-    return 1;
-  }
-       
-  entry_count = cio_read(cio, 4);
-       
-  if (tk->track_type == 0) {
-    for (i = 0; i < entry_count; i++) {
-      if (mj2_read_smj2(img, tk, cio))
-                               return 1;
-    }
-  } else if (tk->track_type == 1) {
-    len_2skip = cio_read(cio, 4);      // Not implemented -> skipping box
-    cio_skip(cio,len_2skip - 4);
-  } else if (tk->track_type == 2) {
-    len_2skip = cio_read(cio, 4);      // Not implemented -> skipping box
-    cio_skip(cio,len_2skip - 4);
-  }
-       
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with STSD Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the STBL box
-*
-* Sample table box box
-*
-*/
-void mj2_write_stbl(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_STBL, 4); /* STBL       */
-       
-  mj2_write_stsd(tk, cio);
-  mj2_write_stts(tk, cio);
-  mj2_write_stsc(tk, cio);
-  mj2_write_stsz(tk, cio);
-  mj2_write_stco(tk, cio);
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the STBL box
-*
-* Sample table box box
-*
-*/
-int mj2_read_stbl(mj2_tk_t * tk, opj_image_t * img, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_STBL != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected STBL Marker\n");
-    return 1;
-  }
-       
-  if (mj2_read_stsd(tk, img, cio))
-    return 1;
-  if (mj2_read_stts(tk, cio))
-    return 1;
-  if (mj2_read_stsc(tk, cio))
-    return 1;
-  if (mj2_read_stsz(tk, cio))
-    return 1;
-  if (mj2_read_stco(tk, cio))
-    return 1;
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with STBL Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the URL box
-*
-* URL box
-*
-*/
-void mj2_write_url(mj2_tk_t * tk, int url_num, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_URL, 4);  /* URL       */
-       
-  if (url_num == 0)
-    cio_write(cio, 1, 4);              /* Version = 0, flags = 1 because stored in same file */
-  else {
-    cio_write(cio, 0, 4);              /* Version = 0, flags =  0 */
-    cio_write(cio, tk->url[url_num - 1].location[0], 4);
-    cio_write(cio, tk->url[url_num - 1].location[1], 4);
-    cio_write(cio, tk->url[url_num - 1].location[2], 4);
-    cio_write(cio, tk->url[url_num - 1].location[3], 4);
-  }
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the URL box
-*
-* URL box
-*
-*/
-int mj2_read_url(mj2_tk_t * tk, int urn_num, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_URL != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected URL Marker\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in URL box\n");
-    return 1;
-  }
-       
-  if (1 != cio_read(cio, 3)) { /* If flags = 1 --> media data in file */
-    tk->url[urn_num].location[0] = cio_read(cio, 4);
-    tk->url[urn_num].location[1] = cio_read(cio, 4);
-    tk->url[urn_num].location[2] = cio_read(cio, 4);
-    tk->url[urn_num].location[3] = cio_read(cio, 4);
-  } else {
-    tk->num_url--;
-  }
-       
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with URL Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the URN box
-*
-* URN box
-*
-*/
-void mj2_write_urn(mj2_tk_t * tk, int urn_num, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_URN, 4);  /* URN       */
-       
-  cio_write(cio, 0, 4);                /* Version = 0, flags =  0 */
-       
-  cio_write(cio, tk->urn[urn_num].name[0], 4);
-  cio_write(cio, tk->urn[urn_num].name[1], 4);
-  cio_write(cio, tk->urn[urn_num].name[2], 4);
-  cio_write(cio, tk->urn[urn_num].name[3], 4);
-  cio_write(cio, tk->urn[urn_num].location[0], 4);
-  cio_write(cio, tk->urn[urn_num].location[1], 4);
-  cio_write(cio, tk->urn[urn_num].location[2], 4);
-  cio_write(cio, tk->urn[urn_num].location[3], 4);
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the URN box
-*
-* URN box
-*
-*/
-int mj2_read_urn(mj2_tk_t * tk, int urn_num, opj_cio_t *cio)
-{
-       
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_URN != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected URN Marker\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in URN box\n");
-    return 1;
-  }
-       
-  if (1 != cio_read(cio, 3)) { /* If flags = 1 --> media data in file */
-    tk->urn[urn_num].name[0] = cio_read(cio, 4);
-    tk->urn[urn_num].name[1] = cio_read(cio, 4);
-    tk->urn[urn_num].name[2] = cio_read(cio, 4);
-    tk->urn[urn_num].name[3] = cio_read(cio, 4);
-    tk->urn[urn_num].location[0] = cio_read(cio, 4);
-    tk->urn[urn_num].location[1] = cio_read(cio, 4);
-    tk->urn[urn_num].location[2] = cio_read(cio, 4);
-    tk->urn[urn_num].location[3] = cio_read(cio, 4);
-  }
-       
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with URN Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-
-/*
-* Write the DREF box
-*
-* Data reference box
-*
-*/
-void mj2_write_dref(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  int i;
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_DREF, 4); /* DREF       */
-       
-  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
-       
-  if (tk->num_url + tk->num_urn == 0) {        /* Media data in same file */
-    cio_write(cio, 1, 4);              /* entry_count = 1 */
-    mj2_write_url(tk, 0, cio);
-  } else {
-    cio_write(cio, tk->num_url + tk->num_urn, 4);      /* entry_count */
-               
-    for (i = 0; i < tk->num_url; i++)
-      mj2_write_url(tk, i + 1, cio);
-               
-    for (i = 0; i < tk->num_urn; i++)
-      mj2_write_urn(tk, i, cio);
-  }
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the DREF box
-*
-* Data reference box
-*
-*/
-int mj2_read_dref(mj2_tk_t * tk, opj_cio_t *cio)
-{
-       
-  int i;
-  int entry_count, marker;
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_DREF != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected DREF Marker\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in DREF box\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in DREF box. Expected flag 0\n");
-    return 1;
-  }
-       
-  entry_count = cio_read(cio, 4);
-  tk->num_url = 0;
-  tk->num_urn = 0;
-       
-  for (i = 0; i < entry_count; i++) {
-    cio_skip(cio,4);
-    marker = cio_read(cio, 4);
-    if (marker == MJ2_URL) {
-      cio_skip(cio,-8);
-      tk->num_url++;
-      if (mj2_read_url(tk, tk->num_url, cio))
-                               return 1;
-    } else if (marker == MJ2_URN) {
-      cio_skip(cio,-8);
-      tk->num_urn++;
-      if (mj2_read_urn(tk, tk->num_urn, cio))
-                               return 1;
-    } else {
-      opj_event_msg(cio->cinfo, EVT_ERROR, "Error with in DREF box. Expected URN or URL box\n");
-      return 1;
-    }
-               
-  }
-       
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with DREF Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the DINF box
-*
-* Data information box
-*
-*/
-void mj2_write_dinf(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_DINF, 4); /* DINF       */
-       
-  mj2_write_dref(tk, cio);
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the DINF box
-*
-* Data information box
-*
-*/
-int mj2_read_dinf(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_DINF != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected DINF Marker\n");
-    return 1;
-  }
-       
-  if (mj2_read_dref(tk, cio))
-    return 1;
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with DINF Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the VMHD box
-*
-* Video Media information box
-*
-*/
-void mj2_write_vmhd(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_VMHD, 4); /* VMHD       */
-       
-  cio_write(cio, 1, 4);                /* Version = 0, flags = 1 */
-       
-  cio_write(cio, tk->graphicsmode, 2);
-  cio_write(cio, tk->opcolor[0], 2);
-  cio_write(cio, tk->opcolor[1], 2);
-  cio_write(cio, tk->opcolor[2], 2);
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the VMHD box
-*
-* Video Media information box
-*
-*/
-int mj2_read_vmhd(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_VMHD != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected VMHD Marker\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in VMHD box\n");
-    return 1;
-  }
-       
-  if (1 != cio_read(cio, 3)) { /* Flags = 1  */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in VMHD box. Expected flag 1\n");
-    return 1;
-  }
-       
-  tk->track_type = 0;
-  tk->graphicsmode = cio_read(cio, 2);
-  tk->opcolor[0] = cio_read(cio, 2);
-  tk->opcolor[1] = cio_read(cio, 2);
-  tk->opcolor[2] = cio_read(cio, 2);
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with VMHD Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the SMHD box
-*
-* Sound Media information box
-*
-*/
-void mj2_write_smhd(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_SMHD, 4); /* SMHD       */
-       
-  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
-       
-  cio_write(cio, tk->balance, 2);
-       
-  cio_write(cio, 0, 2);                /* Reserved */
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the SMHD box
-*
-* Sound Media information box
-*
-*/
-int mj2_read_smhd(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_SMHD != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected SMHD Marker\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in SMHD box\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in SMHD box. Expected flag 0\n");
-    return 1;
-  }
-       
-  tk->track_type = 1;
-  tk->balance = cio_read(cio, 2);
-       
-  /* Init variables to zero to avoid problems when freeeing memory
-  The values will possibly be overidded when decoding the track structure */
-  tk->num_br = 0;
-  tk->num_url = 0;
-  tk->num_urn = 0;
-  tk->num_chunks = 0;
-  tk->num_tts = 0;
-  tk->num_samplestochunk = 0;
-  tk->num_samples = 0;
-       
-  cio_skip(cio,2);                     /* Reserved */
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with SMHD Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the HMHD box
-*
-* Hint Media information box
-*
-*/
-void mj2_write_hmhd(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_HMHD, 4); /* HMHD       */
-       
-  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
-       
-  cio_write(cio, tk->maxPDUsize, 2);
-  cio_write(cio, tk->avgPDUsize, 2);
-  cio_write(cio, tk->maxbitrate, 4);
-  cio_write(cio, tk->avgbitrate, 4);
-  cio_write(cio, tk->slidingavgbitrate, 4);
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the HMHD box
-*
-* Hint Media information box
-*
-*/
-int mj2_read_hmhd(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_HMHD != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected HMHD Marker\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in HMHD box\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in HMHD box. Expected flag 0\n");
-    return 1;
-  }
-       
-  tk->track_type = 2;
-  tk->maxPDUsize = cio_read(cio, 2);
-  tk->avgPDUsize = cio_read(cio, 2);
-  tk->maxbitrate = cio_read(cio, 4);
-  tk->avgbitrate = cio_read(cio, 4);
-  tk->slidingavgbitrate = cio_read(cio, 4);
-       
-  /* Init variables to zero to avoid problems when freeeing memory
-  The values will possibly be overidded when decoding the track structure */
-  tk->num_br = 0;
-  tk->num_url = 0;
-  tk->num_urn = 0;
-  tk->num_chunks = 0;
-  tk->num_tts = 0;
-  tk->num_samplestochunk = 0;
-  tk->num_samples = 0;
-       
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with HMHD Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the MINF box
-*
-* Media information box
-*
-*/
-void mj2_write_minf(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_MINF, 4); /* MINF       */
-       
-  if (tk->track_type == 0) {
-    mj2_write_vmhd(tk, cio);
-  } else if (tk->track_type == 1) {
-    mj2_write_smhd(tk, cio);
-  } else if (tk->track_type == 2) {
-    mj2_write_hmhd(tk, cio);
-  }
-       
-  mj2_write_dinf(tk, cio);
-  mj2_write_stbl(tk, cio);
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the MINF box
-*
-* Media information box
-*
-*/
-int mj2_read_minf(mj2_tk_t * tk, opj_image_t * img, opj_cio_t *cio)
-{
-       
-  unsigned int box_type;
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_MINF != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected MINF Marker\n");
-    return 1;
-  }
-       
-  cio_skip(cio,4);
-  box_type = cio_read(cio, 4);
-  cio_skip(cio,-8);
-       
-  if (box_type == MJ2_VMHD) {
-    if (mj2_read_vmhd(tk, cio))
-      return 1;
-  } else if (box_type == MJ2_SMHD) {
-    if (mj2_read_smhd(tk, cio))
-      return 1;
-  } else if (box_type == MJ2_HMHD) {
-    if (mj2_read_hmhd(tk, cio))
-      return 1;
-  } else {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error in MINF box expected vmhd, smhd or hmhd\n");
-    return 1;
-  }
-       
-  if (mj2_read_dinf(tk, cio))
-    return 1;
-       
-  if (mj2_read_stbl(tk, img, cio))
-    return 1;
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with MINF Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the HDLR box
-*
-* Handler reference box
-*
-*/
-void mj2_write_hdlr(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_HDLR, 4); /* HDLR       */
-       
-  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
-       
-  cio_write(cio, 0, 4);                /* Predefine */
-       
-  tk->name = 0;                        /* The track name is immediately determined by the track type */
-       
-  if (tk->track_type == 0) {
-    tk->handler_type = 0x76696465;     /* Handler type: vide */
-    cio_write(cio, tk->handler_type, 4);
-               
-    cio_write(cio, 0, 4);
-    cio_write(cio, 0, 4);
-    cio_write(cio, 0, 4);              /* Reserved */
-               
-    cio_write(cio, 0x76696465, 4);
-    cio_write(cio, 0x6F206d65, 4);
-    cio_write(cio, 0x64696120, 4);
-    cio_write(cio, 0x74726163, 4);
-    cio_write(cio, 0x6b00, 2); /* String: video media track */
-  } else if (tk->track_type == 1) {
-    tk->handler_type = 0x736F756E;     /* Handler type: soun */
-    cio_write(cio, tk->handler_type, 4);
-               
-    cio_write(cio, 0, 4);
-    cio_write(cio, 0, 4);
-    cio_write(cio, 0, 4);              /* Reserved */
-               
-    cio_write(cio, 0x536F756E, 4);
-    cio_write(cio, 0x6400, 2); /* String: Sound */
-  } else if (tk->track_type == 2) {
-    tk->handler_type = 0x68696E74;     /* Handler type: hint */
-    cio_write(cio, tk->handler_type, 4);
-               
-    cio_write(cio, 0, 4);
-    cio_write(cio, 0, 4);
-    cio_write(cio, 0, 4);              /* Reserved */
-               
-    cio_write(cio, 0x48696E74, 4);
-    cio_write(cio, 0, 2);              /* String: Hint */
-  }
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the HDLR box
-*
-* Handler reference box
-*
-*/
-int mj2_read_hdlr(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  int i;
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_HDLR != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected HDLR Marker\n");
-    return 1;
-  }
-       
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in HDLR box\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 3)) { /* Flags = 0  */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in HDLR box. Expected flag 0\n");
-    return 1;
-  }
-       
-  cio_skip(cio,4);                     /* Reserved */
-       
-  tk->handler_type = cio_read(cio, 4);
-  cio_skip(cio,12);                    /* Reserved */
-       
-  tk->name_size = box.length - 32;
-
-  tk->name = (char*) opj_malloc(tk->name_size * sizeof(char));
-  for (i = 0; i < tk->name_size; i++) {
-    tk->name[i] = cio_read(cio, 1);    /* Name */
-  }
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with HDLR Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the MDHD box
-*
-* Media Header Box
-*
-*/
-void mj2_write_mdhd(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-  unsigned int i;
-  time_t ltime;
-  unsigned int modification_time;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_MDHD, 4); /* MDHD       */
-       
-  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
-       
-  cio_write(cio, tk->creation_time, 4);        /* Creation Time */
-       
-  time(&ltime);                        /* Time since 1/1/70 */
-  modification_time = (unsigned int)ltime + 2082844800;        /* Seoonds between 1/1/04 and 1/1/70 */
-       
-  cio_write(cio, modification_time, 4);        /* Modification Time */
-       
-  cio_write(cio, tk->timescale, 4);    /* Timescale */
-       
-  tk->duration = 0;
-       
-  for (i = 0; i < tk->num_samples; i++)
-    tk->duration += tk->sample[i].sample_delta;
-       
-  cio_write(cio, tk->duration, 4);     /* Duration */
-       
-  cio_write(cio, tk->language, 2);     /* Language */
-       
-  cio_write(cio, 0, 2);                /* Predefined */
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the MDHD box
-*
-* Media Header Box
-*
-*/
-int mj2_read_mdhd(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (!(MJ2_MHDR == box.type || MJ2_MDHD == box.type)) {       // Kakadu writes MHDR instead of MDHD
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected MDHD Marker\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in MDHD box\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 3)) { /* Flags = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with flag in MDHD box. Expected flag 0\n");
-    return 1;
-  }
-       
-       
-  tk->creation_time = cio_read(cio, 4);        /* Creation Time */
-       
-  tk->modification_time = cio_read(cio, 4);    /* Modification Time */
-       
-  tk->timescale = cio_read(cio, 4);    /* Timescale */
-       
-  tk->duration = cio_read(cio, 4);     /* Duration */
-       
-  tk->language = cio_read(cio, 2);     /* Language */
-       
-  cio_skip(cio,2);                     /* Predefined */
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with MDHD Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the MDIA box
-*
-* Media box
-*
-*/
-void mj2_write_mdia(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_MDIA, 4); /* MDIA       */
-       
-  mj2_write_mdhd(tk, cio);
-  mj2_write_hdlr(tk, cio);
-  mj2_write_minf(tk, cio);
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the MDIA box
-*
-* Media box
-*
-*/
-int mj2_read_mdia(mj2_tk_t * tk, opj_image_t * img, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_MDIA != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected MDIA Marker\n");
-    return 1;
-  }
-       
-  if (mj2_read_mdhd(tk, cio))
-    return 1;
-  if (mj2_read_hdlr(tk, cio))
-    return 1;
-  if (mj2_read_minf(tk, img, cio))
-    return 1;
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with MDIA Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the TKHD box
-*
-* Track Header box
-*
-*/
-void mj2_write_tkhd(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-  unsigned int i;
-  time_t ltime;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-       
-  cio_write(cio, MJ2_TKHD, 4); /* TKHD       */
-       
-  cio_write(cio, 3, 4);                /* Version=0, flags=3 */
-       
-  time(&ltime);                        /* Time since 1/1/70 */
-  tk->modification_time = (unsigned int)ltime + 2082844800;    /* Seoonds between 1/1/04 and 1/1/70 */
-       
-  cio_write(cio, tk->creation_time, 4);        /* Creation Time */
-       
-  cio_write(cio, tk->modification_time, 4);    /* Modification Time */
-       
-  cio_write(cio, tk->track_ID, 4);     /* Track ID */
-       
-  cio_write(cio, 0, 4);                /* Reserved */
-       
-  tk->duration = 0;
-       
-  for (i = 0; i < tk->num_samples; i++)
-    tk->duration += tk->sample[i].sample_delta;
-       
-  cio_write(cio, tk->duration, 4);     /* Duration */
-       
-  cio_write(cio, 0, 4);                /* Reserved */
-  cio_write(cio, 0, 4);                /* Reserved */
-       
-  cio_write(cio, tk->layer, 2);        /* Layer    */
-       
-  cio_write(cio, 0, 2);                /* Predefined */
-       
-  cio_write(cio, tk->volume, 2);       /* Volume       */
-       
-  cio_write(cio, 0, 2);                /* Reserved */
-       
-  cio_write(cio, tk->trans_matrix[0], 4);      /* Transformation matrix for track */
-  cio_write(cio, tk->trans_matrix[1], 4);
-  cio_write(cio, tk->trans_matrix[2], 4);
-  cio_write(cio, tk->trans_matrix[3], 4);
-  cio_write(cio, tk->trans_matrix[4], 4);
-  cio_write(cio, tk->trans_matrix[5], 4);
-  cio_write(cio, tk->trans_matrix[6], 4);
-  cio_write(cio, tk->trans_matrix[7], 4);
-  cio_write(cio, tk->trans_matrix[8], 4);
-       
-  cio_write(cio, tk->visual_w, 4);     /* Video Visual Width  */
-       
-  cio_write(cio, tk->visual_h, 4);     /* Video Visual Height */
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the TKHD box
-*
-* Track Header box
-*
-*/
-int mj2_read_tkhd(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  int flag;
-       
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-       
-  if (MJ2_TKHD != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected TKHD Marker\n");
-    return 1;
-  }
-       
-  if (0 != cio_read(cio, 1)) { /* Version = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in TKHD box\n");
-    return 1;
-  }
-       
-  flag = cio_read(cio, 3);
-       
-  if (!(flag == 1 || flag == 2 || flag == 3 || flag == 4)) {   /* Flags = 1,2,3 or 4 */
-    opj_event_msg(cio->cinfo, EVT_ERROR,
-                       "Error with flag in TKHD box: Expected flag 1,2,3 or 4\n");
-    return 1;
-  }
-       
-  tk->creation_time = cio_read(cio, 4);        /* Creation Time */
-       
-  tk->modification_time = cio_read(cio, 4);    /* Modification Time */
-       
-  tk->track_ID = cio_read(cio, 4);     /* Track ID */
-       
-  cio_skip(cio,4);                     /* Reserved */
-       
-  tk->duration = cio_read(cio, 4);     /* Duration */
-       
-  cio_skip(cio,8);                     /* Reserved */
-       
-  tk->layer = cio_read(cio, 2);        /* Layer    */
-       
-  cio_read(cio, 2);                    /* Predefined */
-       
-  tk->volume = cio_read(cio, 2);       /* Volume       */
-       
-  cio_skip(cio,2);                     /* Reserved */
-       
-  tk->trans_matrix[0] = cio_read(cio, 4);      /* Transformation matrix for track */
-  tk->trans_matrix[1] = cio_read(cio, 4);
-  tk->trans_matrix[2] = cio_read(cio, 4);
-  tk->trans_matrix[3] = cio_read(cio, 4);
-  tk->trans_matrix[4] = cio_read(cio, 4);
-  tk->trans_matrix[5] = cio_read(cio, 4);
-  tk->trans_matrix[6] = cio_read(cio, 4);
-  tk->trans_matrix[7] = cio_read(cio, 4);
-  tk->trans_matrix[8] = cio_read(cio, 4);
-       
-  tk->visual_w = cio_read(cio, 4);     /* Video Visual Width  */
-       
-  tk->visual_h = cio_read(cio, 4);     /* Video Visual Height */
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with TKHD Box size\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the TRAK box
-*
-* Track box
-*
-*/
-void mj2_write_trak(mj2_tk_t * tk, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-       
-  cio_write(cio, MJ2_TRAK, 4); /* TRAK       */
-       
-  mj2_write_tkhd(tk, cio);
-  mj2_write_mdia(tk, cio);
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the TRAK box
-*
-* Track box
-*
-*/
-int mj2_read_trak(mj2_tk_t * tk, opj_image_t * img, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_TRAK != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected TRAK Marker\n");
-    return 1;
-  }
-  if (mj2_read_tkhd(tk, cio))
-    return 1;
-  if (mj2_read_mdia(tk, img, cio))
-    return 1;
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with TRAK Box\n");
-    return 1;
-  }
-  return 0;
-}
-
-/*
-* Write the MVHD box
-*
-* Movie header Box
-*
-*/
-void mj2_write_mvhd(opj_mj2_t * movie, opj_cio_t *cio)
-{
-  int i;
-  mj2_box_t box;
-  unsigned j;
-  time_t ltime;
-  int max_tk_num = 0;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_MVHD, 4); /* MVHD       */
-       
-  cio_write(cio, 0, 4);                /* Version = 0, flags = 0 */
-       
-  time(&ltime);                        /* Time since 1/1/70 */
-  movie->modification_time = (unsigned int)ltime + 2082844800; /* Seoonds between 1/1/04 and 1/1/70 */
-       
-  cio_write(cio, movie->creation_time, 4);     /* Creation Time */
-       
-  cio_write(cio, movie->modification_time, 4); /* Modification Time */
-       
-  cio_write(cio, movie->timescale, 4); /* Timescale */
-       
-  movie->duration = 0;
-       
-  for (i = 0; i < (movie->num_stk + movie->num_htk + movie->num_vtk); i++) {
-    mj2_tk_t *tk = &movie->tk[i];
-               
-    for (j = 0; j < tk->num_samples; j++) {
-      movie->duration += tk->sample[j].sample_delta;
-    }
-  }
-       
-  cio_write(cio, movie->duration, 4);
-       
-  cio_write(cio, movie->rate, 4);      /* Rate to play presentation    */
-       
-  cio_write(cio, movie->volume, 2);    /* Volume       */
-       
-  cio_write(cio, 0, 2);                /* Reserved */
-  cio_write(cio, 0, 4);                /* Reserved */
-  cio_write(cio, 0, 4);                /* Reserved */
-       
-  cio_write(cio, movie->trans_matrix[0], 4);   /* Transformation matrix for video */
-  cio_write(cio, movie->trans_matrix[1], 4);
-  cio_write(cio, movie->trans_matrix[2], 4);
-  cio_write(cio, movie->trans_matrix[3], 4);
-  cio_write(cio, movie->trans_matrix[4], 4);
-  cio_write(cio, movie->trans_matrix[5], 4);
-  cio_write(cio, movie->trans_matrix[6], 4);
-  cio_write(cio, movie->trans_matrix[7], 4);
-  cio_write(cio, movie->trans_matrix[8], 4);
-       
-  cio_write(cio, 0, 4);                /* Pre-defined */
-  cio_write(cio, 0, 4);                /* Pre-defined */
-  cio_write(cio, 0, 4);                /* Pre-defined */
-  cio_write(cio, 0, 4);                /* Pre-defined */
-  cio_write(cio, 0, 4);                /* Pre-defined */
-  cio_write(cio, 0, 4);                /* Pre-defined */
-       
-       
-  for (i = 0; i < movie->num_htk + movie->num_stk + movie->num_vtk; i++) {
-    if (max_tk_num < movie->tk[i].track_ID)
-      max_tk_num = movie->tk[i].track_ID;
-  }
-       
-  movie->next_tk_id = max_tk_num + 1;
-       
-  cio_write(cio, movie->next_tk_id, 4);        /* ID of Next track to be added */
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);
-}
-
-/*
-* Read the MVHD box
-*
-* Movie header Box
-*
-*/
-int mj2_read_mvhd(opj_mj2_t * movie, opj_cio_t *cio)
-{
-  mj2_box_t box;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_MVHD != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected MVHD Marker\n");
-    return 1;
-  }
-       
-       
-  if (0 != cio_read(cio, 4)) { /* Version = 0, flags = 0 */
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Only Version 0 handled in MVHD box\n");
-  }
-       
-  movie->creation_time = cio_read(cio, 4);     /* Creation Time */
-       
-  movie->modification_time = cio_read(cio, 4); /* Modification Time */
-       
-  movie->timescale = cio_read(cio, 4); /* Timescale */
-       
-  movie->duration = cio_read(cio, 4);  /* Duration */
-       
-  movie->rate = cio_read(cio, 4);              /* Rate to play presentation    */
-       
-  movie->volume = cio_read(cio, 2);            /* Volume       */
-       
-  cio_skip(cio,10);                            /* Reserved */
-       
-  movie->trans_matrix[0] = cio_read(cio, 4);   /* Transformation matrix for video */
-  movie->trans_matrix[1] = cio_read(cio, 4);
-  movie->trans_matrix[2] = cio_read(cio, 4);
-  movie->trans_matrix[3] = cio_read(cio, 4);
-  movie->trans_matrix[4] = cio_read(cio, 4);
-  movie->trans_matrix[5] = cio_read(cio, 4);
-  movie->trans_matrix[6] = cio_read(cio, 4);
-  movie->trans_matrix[7] = cio_read(cio, 4);
-  movie->trans_matrix[8] = cio_read(cio, 4);
-       
-  cio_skip(cio,24);                    /* Pre-defined */
-       
-  movie->next_tk_id = cio_read(cio, 4);        /* ID of Next track to be added */
-       
-  if (cio_tell(cio) - box.init_pos != box.length) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error with MVHD Box Size\n");
-    return 1;
-  }
-  return 0;
-}
-
-
-/*
-* Write the MOOV box
-*
-* Movie Box
-*
-*/
-void mj2_write_moov(opj_mj2_t * movie, opj_cio_t *cio)
-{
-  int i;
-  mj2_box_t box;
-       
-  box.init_pos = cio_tell(cio);
-  cio_skip(cio,4);
-  cio_write(cio, MJ2_MOOV, 4); /* MOOV       */
-       
-  mj2_write_mvhd(movie, cio);
-       
-  for (i = 0; i < (movie->num_stk + movie->num_htk + movie->num_vtk); i++) {
-    mj2_write_trak(&movie->tk[i], cio);
-  }
-       
-  box.length = cio_tell(cio) - box.init_pos;
-  cio_seek(cio, box.init_pos);
-  cio_write(cio, box.length, 4);       /* L          */
-  cio_seek(cio, box.init_pos + box.length);    
-}
-
-/*
-* Read the MOOV box
-*
-* Movie Box
-*
-*/
-int mj2_read_moov(opj_mj2_t * movie, opj_image_t * img, opj_cio_t *cio)
-{
-  unsigned int i;
-  mj2_box_t box;
-  mj2_box_t box2;
-       
-  mj2_read_boxhdr(&box, cio);
-  if (MJ2_MOOV != box.type) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "Error: Expected MOOV Marker\n");
-    return 1;
-  }
-       
-  if (mj2_read_mvhd(movie, cio))
-    return 1;
-
-  movie->tk = (mj2_tk_t*) opj_malloc((movie->next_tk_id - 1) * sizeof(mj2_tk_t));
-
-  for (i = 0; cio_tell(cio) - box.init_pos < box.length; i++) {
-               mj2_tk_t *tk = &movie->tk[i];
-               tk->cinfo = movie->cinfo;
-    mj2_read_boxhdr(&box2, cio);
-    if (box2.type == MJ2_TRAK) {
-      cio_seek(cio, box2.init_pos);
-      if (mj2_read_trak(tk, img, cio))
-                               return 1;
-                       
-      if (tk->track_type == 0) {
-                               movie->num_vtk++;
-      } else if (tk->track_type == 1) {
-                               movie->num_stk++;
-      } else if (tk->track_type == 2) {
-                               movie->num_htk++;
-      }
-    } else if (box2.type == MJ2_MVEX) {
-      cio_seek(cio, box2.init_pos);
-      cio_skip(cio,box2.length);
-      i--;
-    } else {
-      opj_event_msg(cio->cinfo, EVT_ERROR, "Error with MOOV Box: Expected TRAK or MVEX box\n");
-      return 1;
-    }
-  }
-  return 0;
-}
-
-int mj2_read_struct(FILE *file, opj_mj2_t *movie) {
-  mj2_box_t box;
-  opj_image_t img;
-  unsigned char * src;
-  int fsresult;
-  int foffset;
-       opj_cio_t *cio;
-       
-       /* open a byte stream for reading */    
-       src = (unsigned char*) opj_malloc(300 * sizeof(unsigned char)); 
-
-       /* Assuming that jp and ftyp markers size do
-     not exceed 300 bytes */
-  fread(src,300,1, file);  
-  
-  cio = opj_cio_open((opj_common_ptr)movie->cinfo, src, 300);
-  
-  if (mj2_read_jp(cio))
-    return 1;
-  if (mj2_read_ftyp(movie, cio))
-    return 1;
-       
-  fsresult = fseek(file,cio_tell(cio),SEEK_SET);
-  if( fsresult ) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read data after FTYP box\n" );
-    return 1;
-  }
-       
-  foffset = cio_tell(cio);
-  
-  box.type = 0;
-  
-  fread(src,30,1,file);
-  cio = opj_cio_open((opj_common_ptr)movie->cinfo, src, 300);
-  mj2_read_boxhdr(&box, cio);
-  
-  while(box.type != MJ2_MOOV) {
-    
-    switch(box.type)
-    {
-    case MJ2_MDAT:
-      fsresult = fseek(file,foffset+box.length,SEEK_SET);
-      if( fsresult ) {
-                               opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read MDAT box\n" );
-                               return 1;
-      }
-      foffset += box.length;
-      break;
-      
-    case MJ2_MOOF:
-      fsresult = fseek(file,foffset+box.length,SEEK_SET);
-      if( fsresult ) {
-                               opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read MOOF box\n" );
-                               return 1;
-      }
-      foffset += box.length;
-      break;      
-    case MJ2_FREE:
-      fsresult = fseek(file,foffset+box.length,SEEK_SET);
-      if( fsresult ) {
-                               opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read FREE box\n" );
-                               return 1;
-      }
-      foffset += box.length;
-      break;      
-    case MJ2_SKIP:
-      fsresult = fseek(file,foffset+box.length,SEEK_SET);
-      if( fsresult ) {
-                               opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read SKIP box\n" );
-                               return 1;
-      }
-      foffset += box.length;
-      break;      
-    default:
-      opj_event_msg(cio->cinfo, EVT_ERROR, "Unknown box in MJ2 stream\n");
-      fsresult = fseek(file,foffset+box.length,SEEK_SET);
-      if( fsresult ) {
-                               opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read end of unknown box\n"); 
-                               return 1;
-      }      
-      foffset += box.length;
-      break;
-    }
-    fsresult = fread(src,8,1,file);
-    if (fsresult != 1) {
-      opj_event_msg(cio->cinfo, EVT_ERROR, "MOOV box not found in file\n"); 
-      return 1;
-    }
-               cio = opj_cio_open((opj_common_ptr)movie->cinfo, src, 8);               
-    mj2_read_boxhdr(&box, cio);
-  }    
-
-  fseek(file,foffset,SEEK_SET);
-  src = (unsigned char*)opj_realloc(src,box.length);
-  fsresult = fread(src,box.length,1,file);
-  if (fsresult != 1) {
-    opj_event_msg(cio->cinfo, EVT_ERROR, "End of file reached while trying to read MOOV box\n"); 
-    return 1;
-  }
-       
-       cio = opj_cio_open((opj_common_ptr)movie->cinfo, src, box.length);
-  
-  if (mj2_read_moov(movie, &img, cio))
-    return 1;
-
-  opj_free(src);
-  return 0;
-}
-
-/* ----------------------------------------------------------------------- */
-/* MJ2 decoder interface                                                                                                                                            */
-/* ----------------------------------------------------------------------- */
-
-opj_dinfo_t* mj2_create_decompress() {
-       opj_mj2_t* mj2;
-       opj_dinfo_t *dinfo = (opj_dinfo_t*) opj_calloc(1, sizeof(opj_dinfo_t));
-       if(!dinfo) return NULL;
-
-       dinfo->is_decompressor = true;  
-
-       mj2 = (opj_mj2_t*) opj_calloc(1, sizeof(opj_mj2_t));
-       dinfo->mj2_handle = mj2;
-       if(mj2) {
-               mj2->cinfo = (opj_common_ptr)dinfo;
-       }
-       mj2->j2k = j2k_create_decompress((opj_common_ptr)dinfo);
-       dinfo->j2k_handle = mj2->j2k;
-
-       return dinfo;
-}
-
-void mj2_setup_decoder(opj_mj2_t *movie, mj2_dparameters_t *mj2_parameters) {
-       movie->num_vtk=0;
-  movie->num_stk=0;
-  movie->num_htk=0;    
-
-       /* setup the J2K decoder parameters */
-       j2k_setup_decoder((opj_j2k_t*)movie->cinfo->j2k_handle, 
-               &mj2_parameters->j2k_parameters);
-
-}
-
-void mj2_destroy_decompress(opj_mj2_t *movie) {
-       if(movie) {
-               int i;
-               mj2_tk_t *tk=NULL;
-
-               if (movie->cinfo->j2k_handle) 
-                       j2k_destroy_compress(movie->j2k);
-               
-               if (movie->num_cl != 0)
-                       opj_free(movie->cl);
-               
-               for (i = 0; i < movie->num_vtk + movie->num_stk + movie->num_htk; i++) {
-                       tk = &movie->tk[i];
-                       if (tk->name_size != 0)
-                               opj_free(tk->name);
-                       if (tk->track_type == 0)  {// Video track
-                               if (tk->jp2_struct.comps != 0)
-                                       opj_free(tk->jp2_struct.comps);
-                               if (tk->jp2_struct.cl != 0)
-                                       opj_free(tk->jp2_struct.cl);
-                               if (tk->num_jp2x != 0)
-                                       opj_free(tk->jp2xdata);
-                               
-                       }
-                       if (tk->num_url != 0)
-                               opj_free(tk->url);
-                       if (tk->num_urn != 0)
-                               opj_free(tk->urn);
-                       if (tk->num_br != 0)
-                               opj_free(tk->br);
-                       if (tk->num_tts != 0)
-                               opj_free(tk->tts);
-                       if (tk->num_chunks != 0)
-                               opj_free(tk->chunk);
-                       if (tk->num_samplestochunk != 0)
-                               opj_free(tk->sampletochunk);
-                       if (tk->num_samples != 0)
-                               opj_free(tk->sample);
-               }
-               
-               opj_free(movie->tk);
-       }       
-       opj_free(movie);
-}
-
-/* ----------------------------------------------------------------------- */
-/* MJ2 encoder interface                                                                                                                                            */
-/* ----------------------------------------------------------------------- */
-
-
-opj_cinfo_t* mj2_create_compress() {
-       opj_mj2_t* mj2;
-       opj_cinfo_t *cinfo = (opj_cinfo_t*) opj_calloc(1, sizeof(opj_cinfo_t));
-       if(!cinfo) return NULL;
-
-       mj2 = (opj_mj2_t*) opj_calloc(1, sizeof(opj_mj2_t));
-       cinfo->mj2_handle = mj2;
-       if(mj2) {
-               mj2->cinfo = (opj_common_ptr)cinfo;
-       }
-
-       mj2->j2k = j2k_create_compress(mj2->cinfo);
-       cinfo->j2k_handle = mj2->j2k;
-
-       return cinfo;
-}
-
-void mj2_setup_encoder(opj_mj2_t *movie, mj2_cparameters_t *parameters) {
-       if(movie && parameters) {
-               opj_jp2_t *jp2_struct;
-                       
-               movie->num_htk = 0;       // No hint tracks
-               movie->num_stk = 0;       // No sound tracks
-               movie->num_vtk = 1;       // One video track  
-
-               movie->brand = MJ2_MJ2;  // One brand: MJ2
-               movie->num_cl = 2;        // Two compatible brands: MJ2 and MJ2S
-               movie->cl = (unsigned int*) opj_malloc(movie->num_cl * sizeof(unsigned int));
-               movie->cl[0] = MJ2_MJ2;
-               movie->cl[1] = MJ2_MJ2S;
-               movie->minversion = 0;    // Minimum version: 0         
-
-               movie->tk = (mj2_tk_t*) opj_malloc(sizeof(mj2_tk_t)); //Memory allocation for the video track
-               movie->tk[0].track_ID = 1;        // Track ID = 1 
-               movie->tk[0].track_type = 0;      // Video track
-               movie->tk[0].Dim[0] = parameters->Dim[0];
-               movie->tk[0].Dim[1] = parameters->Dim[1];
-               movie->tk[0].w = parameters->w;
-               movie->tk[0].h = parameters->h;
-               movie->tk[0].CbCr_subsampling_dx = parameters->CbCr_subsampling_dx;
-               movie->tk[0].CbCr_subsampling_dy = parameters->CbCr_subsampling_dy;
-               movie->tk[0].sample_rate = parameters->frame_rate;
-               movie->tk[0].name_size = 0;
-               movie->tk[0].chunk = (mj2_chunk_t*) opj_malloc(sizeof(mj2_chunk_t));  
-               movie->tk[0].sample = (mj2_sample_t*) opj_malloc(sizeof(mj2_sample_t));
-               movie->tk[0].depth = parameters->prec;
-
-               jp2_struct = &movie->tk[0].jp2_struct;
-               jp2_struct->numcomps = parameters->numcomps;    // NC           
-               jp2_struct->comps = (opj_jp2_comps_t*) opj_malloc(jp2_struct->numcomps * sizeof(opj_jp2_comps_t));
-               jp2_struct->precedence = 0;   /* PRECEDENCE*/
-               jp2_struct->approx = 0;   /* APPROX*/           
-               jp2_struct->brand = JP2_JP2;    /* BR         */
-               jp2_struct->minversion = 0;     /* MinV       */
-               jp2_struct->numcl = 1;
-               jp2_struct->cl = (unsigned int*) opj_malloc(jp2_struct->numcl * sizeof(unsigned int));
-               jp2_struct->cl[0] = JP2_JP2;    /* CL0 : JP2  */                
-               jp2_struct->C = 7;      /* C : Always 7*/
-               jp2_struct->UnkC = 0;      /* UnkC, colorspace specified in colr box*/
-               jp2_struct->IPR = 0;      /* IPR, no intellectual property*/                                            
-               jp2_struct->w = parameters->w;
-               jp2_struct->h = parameters->h;
-               jp2_struct->bpc = 7;  
-               jp2_struct->meth = parameters->meth;
-               jp2_struct->enumcs = parameters->enumcs;
-  }
-}
-
-void mj2_destroy_compress(opj_mj2_t *movie) {
-       if(movie) {
-               int i;
-               mj2_tk_t *tk=NULL;
-
-               if (movie->cinfo->j2k_handle) {
-                       j2k_destroy_compress(movie->j2k);
-               }
-               
-               if (movie->num_cl != 0)
-                       opj_free(movie->cl);
-               
-               for (i = 0; i < movie->num_vtk + movie->num_stk + movie->num_htk; i++) {
-                       tk = &movie->tk[i];
-                       if (tk->name_size != 0)
-                               opj_free(tk->name);
-                       if (tk->track_type == 0)  {// Video track
-                               if (tk->jp2_struct.comps != 0)
-                                       opj_free(tk->jp2_struct.comps);
-                               if (tk->jp2_struct.cl != 0)
-                                       opj_free(tk->jp2_struct.cl);
-                               if (tk->num_jp2x != 0)
-                                       opj_free(tk->jp2xdata);
-                               
-                       }
-                       if (tk->num_url != 0)
-                               opj_free(tk->url);
-                       if (tk->num_urn != 0)
-                               opj_free(tk->urn);
-                       if (tk->num_br != 0)
-                               opj_free(tk->br);
-                       if (tk->num_tts != 0)
-                               opj_free(tk->tts);
-                       if (tk->num_chunks != 0)
-                               opj_free(tk->chunk);
-                       if (tk->num_samplestochunk != 0)
-                               opj_free(tk->sampletochunk);
-                       if (tk->num_samples != 0)
-                               opj_free(tk->sample);
-               }
-               
-               opj_free(movie->tk);
-       }       
-       opj_free(movie);
-}
diff --git a/mj2/mj2.h b/mj2/mj2.h
deleted file mode 100644 (file)
index 0ddb6b8..0000000
--- a/mj2/mj2.h
+++ /dev/null
@@ -1,393 +0,0 @@
-/*
-* Copyright (c) 2003-2004, Fran�ois-Olivier Devaux
-* Copyright (c) 2003-2004,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
-* All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __MJ2_H
-#define __MJ2_H
-/**
-@file mj2.h
-@brief The Motion JPEG 2000 file format Reader/Writer (MJ22)
-
-*/
-
-/** @defgroup MJ2 MJ2 - Motion JPEG 2000 file format reader/writer */
-/*@{*/
-
-#define MJ2_JP    0x6a502020
-#define MJ2_FTYP  0x66747970
-#define MJ2_MJ2   0x6d6a7032
-#define MJ2_MJ2S  0x6d6a3273
-#define MJ2_MDAT  0x6d646174
-#define MJ2_MOOV  0x6d6f6f76
-#define MJ2_MVHD  0x6d766864
-#define MJ2_TRAK  0x7472616b
-#define MJ2_TKHD  0x746b6864
-#define MJ2_MDIA  0x6d646961
-#define MJ2_MDHD  0x6d646864
-#define MJ2_MHDR  0x6d686472
-#define MJ2_HDLR  0x68646C72
-#define MJ2_MINF  0x6d696e66
-#define MJ2_VMHD  0x766d6864
-#define MJ2_SMHD  0x736d6864
-#define MJ2_HMHD  0x686d6864
-#define MJ2_DINF  0x64696e66
-#define MJ2_DREF  0x64726566
-#define MJ2_URL   0x75726c20
-#define MJ2_URN   0x75726e20
-#define MJ2_STBL  0x7374626c
-#define MJ2_STSD  0x73747364
-#define MJ2_STTS  0x73747473
-#define MJ2_STSC  0x73747363
-#define MJ2_STSZ  0x7374737a
-#define MJ2_STCO  0x7374636f
-#define MJ2_MOOF  0x6d6f6f66
-#define MJ2_FREE  0x66726565
-#define MJ2_SKIP  0x736b6970
-#define MJ2_JP2C  0x6a703263
-#define MJ2_FIEL  0x6669656c
-#define MJ2_JP2P  0x6a703270
-#define MJ2_JP2X  0x6a703278
-#define MJ2_JSUB  0x6a737562
-#define MJ2_ORFO  0x6f72666f
-#define MJ2_MVEX  0x6d766578
-#define MJ2_JP2   0x6a703220
-#define MJ2_J2P0  0x4a325030
-
-/**
-Decompressed format used in parameters
-YUV = 0
-*/
-#define YUV_DFMT 1 
-
-/**
-Compressed format used in parameters
-MJ2 = 0
-*/
-#define MJ2_CFMT 2
-
-
-/* ----------------------------------------------------------------------- */
-
-/**
-Time To Sample
-*/
-typedef struct mj2_tts {
-  int sample_count;
-  int sample_delta;
-} mj2_tts_t;
-
-/**
-Chunk
-*/
-typedef struct mj2_chunk {             
-  int num_samples;
-  int sample_descr_idx;
-  int offset;
-} mj2_chunk_t;
-
-/**
-Sample to chunk
-*/
-typedef struct mj2_sampletochunk {             
-  int first_chunk;
-  int samples_per_chunk;
-  int sample_descr_idx;
-} mj2_sampletochunk_t;
-
-/**
-Sample
-*/
-typedef struct mj2_sample {            
-  unsigned int sample_size;
-  unsigned int offset;
-  unsigned int sample_delta;
-} mj2_sample_t;
-
-/**
-URL
-*/
-typedef struct mj2_url {
-  int location[4];
-} mj2_url_t;
-
-/**
-URN
-*/
-typedef struct mj2_urn {               
-  int name[2];
-  int location[4];
-} mj2_urn_t;
-
-/**
-Video Track Parameters
-*/
-typedef struct mj2_tk {
-       /** codec context */
-       opj_common_ptr cinfo;
-  int track_ID;
-  int track_type;
-  unsigned int creation_time;
-  unsigned int modification_time;
-  int duration;
-  int timescale;
-  int layer;
-  int volume;
-  int language;
-  int balance;
-  int maxPDUsize;
-  int avgPDUsize;
-  int maxbitrate;
-  int avgbitrate;
-  int slidingavgbitrate;
-  int graphicsmode;
-  int opcolor[3];
-  int num_url;
-  mj2_url_t *url;
-  int num_urn;
-  mj2_urn_t *urn;
-  int Dim[2];
-  int w;
-  int h;
-  int visual_w;
-  int visual_h;
-  int CbCr_subsampling_dx;
-  int CbCr_subsampling_dy;
-  int sample_rate;
-  int sample_description;
-  int horizresolution;
-  int vertresolution;
-  int compressorname[8];
-  int depth;
-  unsigned char fieldcount;
-  unsigned char fieldorder;
-  unsigned char or_fieldcount;
-  unsigned char or_fieldorder;
-  int num_br;
-  unsigned int *br;
-  unsigned char num_jp2x;
-  unsigned char *jp2xdata;
-  unsigned char hsub;
-  unsigned char vsub;
-  unsigned char hoff;
-  unsigned char voff;
-  int trans_matrix[9];
-       /** Number of samples */
-  unsigned int num_samples;    
-  int transorm;
-  int handler_type;
-  int name_size;
-  unsigned char same_sample_size;
-  int num_tts;
-       /** Time to sample    */
-  mj2_tts_t *tts;              
-  unsigned int num_chunks;
-  mj2_chunk_t *chunk;
-  int num_samplestochunk;
-  mj2_sampletochunk_t *sampletochunk;
-  char *name;
-  opj_jp2_t jp2_struct;
-       /** Sample parameters */
-  mj2_sample_t *sample;                
-} mj2_tk_t;                    
-
-/**
-MJ2 box
-*/
-typedef struct mj2_box {
-  int length;
-  int type;
-  int init_pos;
-} mj2_box_t;
-
-/**
-MJ2 Movie
-*/
-typedef struct opj_mj2 {               
-       /** codec context */
-       opj_common_ptr cinfo;
-       /** handle to the J2K codec  */
-       opj_j2k_t *j2k;
-  unsigned int brand;
-  unsigned int minversion;
-  int num_cl;
-  unsigned int *cl;
-  unsigned int creation_time;
-  unsigned int modification_time;
-  int timescale;
-  unsigned int duration;
-  int rate;
-  int num_vtk;
-  int num_stk;
-  int num_htk;
-  int volume;
-  int trans_matrix[9];
-  int next_tk_id;
-       /** Track Parameters  */
-  mj2_tk_t *tk;                        
-} opj_mj2_t;
-
-/**
-Decompression parameters
-*/
-typedef struct mj2_dparameters {
-       /**@name command line encoder parameters (not used inside the library) */
-       /*@{*/
-       /** input file name */
-       char infile[OPJ_PATH_LEN];
-       /** output file name */
-       char outfile[OPJ_PATH_LEN];     
-       /** J2K decompression parameters */
-       opj_dparameters_t j2k_parameters;       
-} mj2_dparameters_t;
-
-/**
-Compression parameters
-*/
-typedef struct mj2_cparameters {
-       /**@name command line encoder parameters (not used inside the library) */
-       /*@{*/
-       /** J2K compression parameters */
-       opj_cparameters_t j2k_parameters;       
-       /** input file name */
-       char infile[OPJ_PATH_LEN];
-       /** output file name */
-       char outfile[OPJ_PATH_LEN];     
-       /** input file format 0:MJ2 */
-       int decod_format;
-       /** output file format 0:YUV */
-       int cod_format;
-       /** Portion of the image coded */
-       int Dim[2];
-       /** YUV Frame width */
-       int w;
-       /** YUV Frame height */
-       int h;
-       /*   Sample rate of YUV 4:4:4, 4:2:2 or 4:2:0 */
-       int CbCr_subsampling_dx;        
-       /*   Sample rate of YUV 4:4:4, 4:2:2 or 4:2:0 */
-  int CbCr_subsampling_dy;     
-       /*   Video Frame Rate  */
-  int frame_rate;              
-       /*   In YUV files, numcomps always considered as 3 */
-  int numcomps;                        
-       /*   In YUV files, precision always considered as 8 */
-  int prec;            
-  unsigned int meth;
-  unsigned int enumcs;
-} mj2_cparameters_t;
-
-
-/** @name Exported functions */
-/*@{*/
-/* ----------------------------------------------------------------------- */
-/**
-Write the JP box 
-*/
-void mj2_write_jp(opj_cio_t *cio);
-/**
-Write the FTYP box
-@param movie MJ2 movie
-@param cio Output buffer stream
-*/
-void mj2_write_ftyp(opj_mj2_t *movie, opj_cio_t *cio);
-/**
-Creates an MJ2 decompression structure
-@return Returns a handle to a MJ2 decompressor if successful, returns NULL otherwise
-*/
-opj_dinfo_t* mj2_create_decompress();
-/**
-Destroy a MJ2 decompressor handle
-@param movie MJ2 decompressor handle to destroy
-*/
-void mj2_destroy_decompress(opj_mj2_t *movie);
-/**
-Setup the decoder decoding parameters using user parameters.
-Decoding parameters are returned in mj2->j2k->cp. 
-@param movie MJ2 decompressor handle
-@param parameters decompression parameters
-*/
-void mj2_setup_decoder(opj_mj2_t *movie, mj2_dparameters_t *mj2_parameters);
-/**
-Decode an image from a JPEG-2000 file stream
-@param movie MJ2 decompressor handle
-@param cio Input buffer stream
-@return Returns a decoded image if successful, returns NULL otherwise
-*/
-opj_image_t* mj2_decode(opj_mj2_t *movie, opj_cio_t *cio);
-/**
-Creates a MJ2 compression structure
-@return Returns a handle to a MJ2 compressor if successful, returns NULL otherwise
-*/
-opj_cinfo_t* mj2_create_compress();
-/**
-Destroy a MJ2 compressor handle
-@param movie MJ2 compressor handle to destroy
-*/
-void mj2_destroy_compress(opj_mj2_t *movie);
-/**
-Setup the encoder parameters using the current image and using user parameters. 
-Coding parameters are returned in mj2->j2k->cp. 
-@param movie MJ2 compressor handle
-@param parameters compression parameters
-*/
-void mj2_setup_encoder(opj_mj2_t *movie, mj2_cparameters_t *parameters);
-/**
-Encode an image into a JPEG-2000 file stream
-@param movie MJ2 compressor handle
-@param cio Output buffer stream
-@param image Image to encode
-@param index Name of the index file if required, NULL otherwise
-@return Returns true if successful, returns false otherwise
-*/
-bool mj2_encode(opj_mj2_t *movie, opj_cio_t *cio, opj_image_t *image, char *index);
-
-/**
-Init a Standard MJ2 movie
-@param movie MJ2 Movie
-@return Returns 0 if successful, returns 1 otherwise
-*/
-int mj2_init_stdmovie(opj_mj2_t *movie);
-/**
-Read the structure of an MJ2 file
-@param File MJ2 input File
-@param movie J2 movie structure 
-@return Returns 0 if successful, returns 1 otherwise
-*/
-int mj2_read_struct(FILE *file, opj_mj2_t *mj2);
-/**
-Write the the MOOV box to an output buffer stream
-@param movie MJ2 movie structure 
-@param cio Output buffer stream
-*/
-void mj2_write_moov(opj_mj2_t *movie, opj_cio_t *cio);
-
-
-/* ----------------------------------------------------------------------- */
-/*@}*/
-
-/*@}*/
-
-#endif /* __MJ2_H */
diff --git a/mj2/mj2_convert.c b/mj2/mj2_convert.c
deleted file mode 100644 (file)
index 3e6c122..0000000
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
-* Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
-* Copyright (c) 2002-2007, Professor Benoit Macq
-* Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
-* All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions
-* are met:
-* 1. Redistributions of source code must retain the above copyright
-*    notice, this list of conditions and the following disclaimer.
-* 2. Redistributions in binary form must reproduce the above copyright
-*    notice, this list of conditions and the following disclaimer in the
-*    documentation and/or other materials provided with the distribution.
-*
-* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-* POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include "../libopenjpeg/opj_includes.h"
-#include "mj2.h"
-
-/*  -----------------------          */
-/*                                   */
-/*                                   */
-/*  Count the number of frames       */
-/*  in a YUV file                    */
-/*                                   */
-/*  -----------------------          */
-
-int yuv_num_frames(mj2_tk_t * tk, char *infile)
-{
-  int numimages, frame_size, prec_size;
-  long end_of_f;
-       FILE *f;
-
-  f = fopen(infile,"rb");
-  if (!f) {  
-    fprintf(stderr, "failed to open %s for reading\n",infile);
-    return -1;
-  }
-       prec_size = (tk->depth + 7)/8;/* bytes of precision */
-
-  frame_size = (int) (tk->w * tk->h * (1.0 + (double) 2 / (double) (tk->CbCr_subsampling_dx * tk->CbCr_subsampling_dy)));      /* Calculate frame size */
-       frame_size *= prec_size; 
-       
-  fseek(f, 0, SEEK_END);
-  end_of_f = ftell(f);         /* Calculate file size */
-       
-  if (end_of_f < frame_size) {
-    fprintf(stderr,
-                       "YUV does not contains any frame of %d x %d size\n", tk->w,
-                       tk->h);
-    return -1;
-  }
-       
-  numimages = end_of_f / frame_size;   /* Calculate number of images */
-       fclose(f);
-
-  return numimages;
-}
-
-//  -----------------------
-//
-//
-//  YUV to IMAGE
-//
-//  -----------------------
-
-opj_image_t *mj2_image_create(mj2_tk_t * tk, opj_cparameters_t *parameters)
-{
-       opj_image_cmptparm_t cmptparm[3];
-       opj_image_t * img;
-       int i;
-       int numcomps = 3;
-       int subsampling_dx = parameters->subsampling_dx;
-       int subsampling_dy = parameters->subsampling_dy;
-
-       /* initialize image components */
-       memset(&cmptparm[0], 0, 3 * sizeof(opj_image_cmptparm_t));
-       for(i = 0; i < numcomps; i++) {
-               cmptparm[i].prec = tk->depth;
-               cmptparm[i].bpp = tk->depth;
-               cmptparm[i].sgnd = 0;           
-               cmptparm[i].dx = i ? subsampling_dx * tk->CbCr_subsampling_dx : subsampling_dx;
-               cmptparm[i].dy = i ? subsampling_dy * tk->CbCr_subsampling_dy : subsampling_dy;
-               cmptparm[i].w = tk->w;
-               cmptparm[i].h = tk->h;
-       }
-       /* create the image */
-       img = opj_image_create(numcomps, cmptparm, CLRSPC_SRGB);
-       return img;
-}
-
-char yuvtoimage(mj2_tk_t * tk, opj_image_t * img, int frame_num, opj_cparameters_t *parameters, char* infile)
-{
-  int i, compno;
-  int offset, size, max, prec_bytes, is_16, v;
-  long end_of_f, position;
-       int numcomps = 3;
-       int subsampling_dx = parameters->subsampling_dx;
-       int subsampling_dy = parameters->subsampling_dy;
-       FILE *yuvfile;
-       int *data;
-       unsigned char uc;
-
-  yuvfile = fopen(infile,"rb");
-  if (!yuvfile) {  
-    fprintf(stderr, "failed to open %s for readings\n",parameters->infile);
-    return 1;
-  }
-       is_16 = (tk->depth > 8);
-       prec_bytes = (is_16?2:1);
-
-  offset = (int) ((double) (frame_num * tk->w * tk->h) * (1.0 +
-               1.0 * (double) 2 / (double) (tk->CbCr_subsampling_dx * tk->CbCr_subsampling_dy)));
-  offset *= prec_bytes;
-
-  fseek(yuvfile, 0, SEEK_END);
-  end_of_f = ftell(yuvfile);
-  fseek(yuvfile, sizeof(unsigned char) * offset, SEEK_SET);
-  position = ftell(yuvfile);
-  if (position >= end_of_f) {
-    fprintf(stderr, "Cannot reach frame number %d in yuv file !!\n",
-                       frame_num);
-               fclose(yuvfile);
-    return 1;
-  }
-       
-  img->x0 = tk->Dim[0];
-  img->y0 = tk->Dim[1];
-  img->x1 = !tk->Dim[0] ? (tk->w - 1) * subsampling_dx + 1 : tk->Dim[0] +
-    (tk->w - 1) * subsampling_dx + 1;
-  img->y1 = !tk->Dim[1] ? (tk->h - 1) * subsampling_dy + 1 : tk->Dim[1] +
-    (tk->h - 1) * subsampling_dy + 1;
-
-       size = tk->w * tk->h * prec_bytes;
-       
-       for(compno = 0; compno < numcomps; compno++) 
-   {
-       max = size/(img->comps[compno].dx * img->comps[compno].dy);
-       data = img->comps[compno].data;
-
-       for (i = 0; i < max && !feof(yuvfile); i++)
-  {
-       v = 0;
-       fread(&uc, 1, 1, yuvfile);
-       v = uc;
-
-       if(is_16)
- {
-       fread(&uc, 1, 1, yuvfile);
-       v |= (uc<<8);
- }
-       *data++ = v;
-  }
-   }
-       fclose(yuvfile);
-       
-  return 0;
-}
-
-
-
-//  -----------------------
-//
-//
-//  IMAGE to YUV
-//
-//  -----------------------
-
-
-bool imagetoyuv(opj_image_t * img, char *outfile)
-{
-  FILE *f;
-  int *data;
-  int i, v, is_16, prec_bytes;
-  unsigned char buf[2];
-
-  if (img->numcomps == 3) {
-    if (img->comps[0].dx != img->comps[1].dx / 2
-      || img->comps[1].dx != img->comps[2].dx) {
-      fprintf(stderr,
-                               "Error with the input image components size: cannot create yuv file)\n");
-      return false;
-    }
-  } else if (!(img->numcomps == 1)) {
-    fprintf(stderr,
-      "Error with the number of image components(must be one or three)\n");
-    return false;
-  }
-  
-  f = fopen(outfile, "a+b");
-  if (!f) {
-    fprintf(stderr, "failed to open %s for writing\n", outfile);
-    return false;
-  }
-  is_16 = (img->comps[0].prec > 8);
-  prec_bytes = (is_16?2:1);
-  data = img->comps[0].data;
-  
-  for (i = 0; i < (img->comps[0].w * img->comps[0].h); i++) {
-    v = *data++;
-    buf[0] = (unsigned char)v;
-
-       if(is_16) buf[1] = (unsigned char)(v>>8);
-
-    fwrite(buf, 1, prec_bytes, f);
-  }
-  
-  
-  if (img->numcomps == 3) {
-       data = img->comps[1].data;
-
-    for (i = 0; i < (img->comps[1].w * img->comps[1].h); i++) {
-      v = *data++;
-      buf[0] = (unsigned char)v;
-
-      if(is_16) buf[1] = (unsigned char)(v>>8);
-
-      fwrite(buf, 1, prec_bytes, f);
-    }
-    data = img->comps[2].data;
-    
-    for (i = 0; i < (img->comps[2].w * img->comps[2].h); i++) {
-      v = *data++;
-      buf[0] = (unsigned char)v;
-
-      if(is_16) buf[1] = (unsigned char)(v>>8);
-
-      fwrite(buf, 1, prec_bytes, f);
-    }
-  } else if (img->numcomps == 1) {
-/* fake CbCr values */
-       if(is_16) 
-  { 
-       buf[0] = 255;
-       if(img->comps[0].prec == 10) buf[1] = 1;
-       else
-       if(img->comps[0].prec == 12) buf[1] = 3;
-       else
-        buf[1] = 125;
-  } 
-       else buf[0] = 125;
-
-    for (i = 0; i < (img->comps[0].w * img->comps[0].h * 0.25); i++) {
-      fwrite(buf, 1, prec_bytes, f);
-    }
-    
-    
-    for (i = 0; i < (img->comps[0].w * img->comps[0].h * 0.25); i++) {
-      fwrite(buf, 1, prec_bytes, f);
-    }
-  }  
-  fclose(f);
-  return true;
-}
-
-//  -----------------------
-//
-//
-//  IMAGE to BMP
-//
-//  -----------------------
-
-int imagetobmp(opj_image_t * img, char *outfile) {
-  int w,wr,h,hr,i,pad;
-  FILE *f;
-  
-  if (img->numcomps == 3 && img->comps[0].dx == img->comps[1].dx
-    && img->comps[1].dx == img->comps[2].dx
-    && img->comps[0].dy == img->comps[1].dy
-    && img->comps[1].dy == img->comps[2].dy
-    && img->comps[0].prec == img->comps[1].prec
-    && img->comps[1].prec == img->comps[2].prec) {
-    /* -->> -->> -->> -->>
-    
-      24 bits color
-      
-    <<-- <<-- <<-- <<-- */
-    
-    f = fopen(outfile, "wb");
-    if (!f) {
-      fprintf(stderr, "failed to open %s for writing\n", outfile);
-      return 1;
-    }   
-    
-    w = img->comps[0].w;
-    wr = int_ceildivpow2(img->comps[0].w, img->comps[0].factor);
-    
-    h = img->comps[0].h;
-    hr = int_ceildivpow2(img->comps[0].h, img->comps[0].factor);
-    
-    fprintf(f, "BM");
-    
-    /* FILE HEADER */
-    /* ------------- */
-    fprintf(f, "%c%c%c%c",
-      (unsigned char) (hr * wr * 3 + 3 * hr * (wr % 2) +
-      54) & 0xff,
-      (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2) + 54)
-      >> 8) & 0xff,
-      (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2) + 54)
-      >> 16) & 0xff,
-      (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2) + 54)
-      >> 24) & 0xff);
-    fprintf(f, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff,
-      ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
-    fprintf(f, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,
-      ((54) >> 16) & 0xff, ((54) >> 24) & 0xff);
-    
-    /* INFO HEADER   */
-    /* ------------- */
-    fprintf(f, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff,
-      ((40) >> 16) & 0xff, ((40) >> 24) & 0xff);
-    fprintf(f, "%c%c%c%c", (unsigned char) ((wr) & 0xff),
-      (unsigned char) ((wr) >> 8) & 0xff,
-      (unsigned char) ((wr) >> 16) & 0xff,
-      (unsigned char) ((wr) >> 24) & 0xff);
-    fprintf(f, "%c%c%c%c", (unsigned char) ((hr) & 0xff),
-      (unsigned char) ((hr) >> 8) & 0xff,
-      (unsigned char) ((hr) >> 16) & 0xff,
-      (unsigned char) ((hr) >> 24) & 0xff);
-    fprintf(f, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
-    fprintf(f, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff);
-    fprintf(f, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff,
-      ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
-    fprintf(f, "%c%c%c%c",
-      (unsigned char) (3 * hr * wr +
-      3 * hr * (wr % 2)) & 0xff,
-      (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2)) >>
-      8) & 0xff,
-      (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2)) >>
-      16) & 0xff,
-      (unsigned char) ((hr * wr * 3 + 3 * hr * (wr % 2)) >>
-      24) & 0xff);
-    fprintf(f, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff,
-      ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
-    fprintf(f, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff,
-      ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
-    fprintf(f, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff,
-      ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
-    fprintf(f, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff,
-      ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
-    
-    for (i = 0; i < wr * hr; i++) {
-      unsigned char R, G, B;
-      /* a modifier */
-      // R = img->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
-      R = img->comps[0].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
-      // G = img->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
-      G = img->comps[1].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
-      // B = img->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
-      B = img->comps[2].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
-      fprintf(f, "%c%c%c", B, G, R);
-      
-      if ((i + 1) % wr == 0) {
-                               for (pad = (3 * wr) % 4 ? 4 - (3 * wr) % 4 : 0; pad > 0; pad--) /* ADD */
-                                       fprintf(f, "%c", 0);
-      }
-    }
-    fclose(f);
-  }
-  return 0;
-}
diff --git a/mj2/mj2_convert.h b/mj2/mj2_convert.h
deleted file mode 100644 (file)
index 78e6c47..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
-* Copyright (c) 2003-2004, Fran�ois-Olivier Devaux
-* Copyright (c) 2002-2004,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
-* All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions
-* are met:
-* 1. Redistributions of source code must retain the above copyright
-*    notice, this list of conditions and the following disclaimer.
-* 2. Redistributions in binary form must reproduce the above copyright
-*    notice, this list of conditions and the following disclaimer in the
-*    documentation and/or other materials provided with the distribution.
-*
-* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-* POSSIBILITY OF SUCH DAMAGE.
-*/
-
-
-#include "mj2.h"
-
-#ifndef __MJ2_CONVERT_H
-#define __MJ2_CONVERT_H
-
-int imagetoyuv(opj_image_t * img, char *outfile);
-
-int imagetobmp(opj_image_t * img, char *outfile);
-
-opj_image_t *mj2_image_create(mj2_tk_t * tk, opj_cparameters_t *parameters);
-
-char yuvtoimage(mj2_tk_t * tk, opj_image_t * img, int frame_num, opj_cparameters_t *parameters, char* infile);
-
-int yuv_num_frames(mj2_tk_t * tk, char *infile);
-
-
-#endif
diff --git a/mj2/mj2_to_frames.c b/mj2/mj2_to_frames.c
deleted file mode 100644 (file)
index 156a101..0000000
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
-* Copyright (c) 2003-2004, Fran�ois-Olivier Devaux
-* Copyright (c) 2002-2004,  Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
-* All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions
-* are met:
-* 1. Redistributions of source code must retain the above copyright
-*    notice, this list of conditions and the following disclaimer.
-* 2. Redistributions in binary form must reproduce the above copyright
-*    notice, this list of conditions and the following disclaimer in the
-*    documentation and/or other materials provided with the distribution.
-*
-* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-* POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "opj_config.h"
-#include "openjpeg.h"
-#include "../libopenjpeg/j2k_lib.h"
-#include "../libopenjpeg/j2k.h"
-#include "../libopenjpeg/jp2.h"
-#include "mj2.h"
-#include "mj2_convert.h"
-
-#ifdef HAVE_LIBLCMS2
-#include <lcms2.h>
-#endif
-#ifdef HAVE_LIBLCMS1
-#include <lcms.h>
-#endif
-#include "color.h"
-/* -------------------------------------------------------------------------- */
-
-/**
-sample error callback expecting a FILE* client object
-*/
-void error_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[ERROR] %s", msg);
-}
-/**
-sample warning callback expecting a FILE* client object
-*/
-void warning_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[WARNING] %s", msg);
-}
-/**
-sample debug callback expecting a FILE* client object
-*/
-void info_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[INFO] %s", msg);
-}
-
-/* -------------------------------------------------------------------------- */
-
-
-int main(int argc, char *argv[]) {
-       mj2_dparameters_t mj2_parameters;                       /* decompression parameters */
-       opj_dinfo_t* dinfo; 
-       opj_event_mgr_t event_mgr;              /* event manager */     
-       opj_cio_t *cio = NULL;
-  unsigned int tnum, snum;
-  opj_mj2_t *movie;
-  mj2_tk_t *track;
-  mj2_sample_t *sample;
-  unsigned char* frame_codestream;
-  FILE *file, *outfile;
-  char outfilename[50];
-  opj_image_t *img = NULL;
-       unsigned int max_codstrm_size = 0;
-       double total_time = 0;
-       unsigned int numframes = 0;
-                       
-  if (argc != 3) {
-    printf("Usage: %s inputfile.mj2 outputfile.yuv\n",argv[0]); 
-    return 1;
-  }
-  
-  file = fopen(argv[1], "rb");
-  
-  if (!file) {
-    fprintf(stderr, "failed to open %s for reading\n", argv[1]);
-    return 1;
-  }
-       
-  // Checking output file
-  outfile = fopen(argv[2], "w");
-  if (!file) {
-    fprintf(stderr, "failed to open %s for writing\n", argv[2]);
-    return 1;
-  }
-  fclose(outfile);
-       
-       /*
-       configure the event callbacks (not required)
-       setting of each callback is optionnal
-       */
-       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
-       event_mgr.error_handler = error_callback;
-       event_mgr.warning_handler = warning_callback;
-       event_mgr.info_handler = NULL;
-       
-       /* get a MJ2 decompressor handle */
-       dinfo = mj2_create_decompress();
-       movie = (opj_mj2_t*)dinfo->mj2_handle;
-       
-       /* catch events using our callbacks and give a local context */
-       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);           
-
-       memset(&mj2_parameters, 0, sizeof(mj2_dparameters_t));
-       /* set J2K decoding parameters to default values */
-       opj_set_default_decoder_parameters(&mj2_parameters.j2k_parameters);
-       
-       /* setup the decoder decoding parameters using user parameters */
-       mj2_setup_decoder(movie, &mj2_parameters);
-                       
-  if (mj2_read_struct(file, movie)) // Creating the movie structure
-    return 1;  
-       
-  // Decode first video track 
-       for (tnum=0; tnum < (unsigned int)(movie->num_htk + movie->num_stk + movie->num_vtk); tnum++) {
-               if (movie->tk[tnum].track_type == 0) 
-                       break;
-       }
-       
-       if (movie->tk[tnum].track_type != 0) {
-               printf("Error. Movie does not contain any video track\n");
-               return 1;
-       }
-       
-  track = &movie->tk[tnum];
-       
-  // Output info on first video tracl
-  fprintf(stdout,"The first video track contains %d frames.\nWidth: %d, Height: %d \n\n",
-    track->num_samples, track->w, track->h);
-       
-       max_codstrm_size = track->sample[0].sample_size-8;
-       frame_codestream = (unsigned char*) malloc(max_codstrm_size * sizeof(unsigned char)); 
-
-       numframes = track->num_samples;
-       
-  for (snum=0; snum < numframes; snum++)
-  {
-               double init_time = opj_clock();
-               double elapsed_time;
-
-    sample = &track->sample[snum];
-               if (sample->sample_size-8 > max_codstrm_size) {
-                       max_codstrm_size =  sample->sample_size-8;
-                       if ((frame_codestream = (unsigned char*)
-                               realloc(frame_codestream, max_codstrm_size)) == NULL) {
-                               printf("Error reallocation memory\n");
-                               return 1;
-                       };              
-               }
-    fseek(file,sample->offset+8,SEEK_SET);
-    fread(frame_codestream, sample->sample_size-8, 1, file);  // Assuming that jp and ftyp markers size do
-               
-               /* open a byte stream */
-               cio = opj_cio_open((opj_common_ptr)dinfo, frame_codestream, sample->sample_size-8);
-               
-               img = opj_decode(dinfo, cio); // Decode J2K to image
-
-#ifdef WANT_SYCC_TO_RGB
-       if(img->color_space == CLRSPC_SYCC)
-  {
-       color_sycc_to_rgb(img);
-  }
-#endif
-
-       if(img->icc_profile_buf)
-  {
-#if defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2)
-       color_apply_icc_profile(img);
-#endif
-
-       free(img->icc_profile_buf);
-       img->icc_profile_buf = NULL; img->icc_profile_len = 0;
-  }
-
-    if (((img->numcomps == 3) && (img->comps[0].dx == img->comps[1].dx / 2) 
-      && (img->comps[0].dx == img->comps[2].dx / 2 ) && (img->comps[0].dx == 1)) 
-      || (img->numcomps == 1)) {
-      
-      if (!imagetoyuv(img, argv[2]))   // Convert image to YUV
-                               return 1;
-    }
-    else if ((img->numcomps == 3) && 
-      (img->comps[0].dx == 1) && (img->comps[1].dx == 1)&&
-      (img->comps[2].dx == 1))// If YUV 4:4:4 input --> to bmp
-    {
-      fprintf(stdout,"The frames will be output in a bmp format (output_1.bmp, ...)\n");
-      sprintf(outfilename,"output_%d.bmp",snum);
-      if (imagetobmp(img, outfilename))        // Convert image to BMP
-                               return 1;
-      
-    }
-    else {
-      fprintf(stdout,"Image component dimensions are unknown. Unable to output image\n");
-      fprintf(stdout,"The frames will be output in a j2k file (output_1.j2k, ...)\n");
-                       
-      sprintf(outfilename,"output_%d.j2k",snum);
-      outfile = fopen(outfilename, "wb");
-      if (!outfile) {
-                               fprintf(stderr, "failed to open %s for writing\n",outfilename);
-                               return 1;
-      }
-      fwrite(frame_codestream,sample->sample_size-8,1,outfile);
-      fclose(outfile);
-    }
-               /* close the byte stream */
-               opj_cio_close(cio);     
-               /* free image data structure */
-               opj_image_destroy(img);
-               elapsed_time = opj_clock()-init_time;
-               fprintf(stderr, "Frame number %d/%d decoded in %.2f mseconds\n", snum + 1, numframes, elapsed_time*1000);
-               total_time += elapsed_time;
-
-  }
-       
-       free(frame_codestream); 
-  fclose(file);        
-
-       /* free remaining structures */
-       if(dinfo) {
-               mj2_destroy_decompress((opj_mj2_t*)dinfo->mj2_handle);
-       }
-       free(dinfo);
-       
-       fprintf(stdout, "%d frame(s) correctly decompressed\n", snum);
-       fprintf(stdout,"Total decoding time: %.2f seconds (%.1f fps)\n", total_time, (float)numframes/total_time);
-               
-  return 0;
-}
diff --git a/mj2/mj2_to_metadata.c b/mj2/mj2_to_metadata.c
deleted file mode 100644 (file)
index 90be620..0000000
+++ /dev/null
@@ -1,312 +0,0 @@
-/* mj2_to_metadata.c */
-/* Dump MJ2, JP2 metadata (partial so far) to xml file */
-/* Contributed to Open JPEG by Glenn Pearson, contract software developer, U.S. National Library of Medicine.
-
-The base code in this file was developed by the author as part of a video archiving
-project for the U.S. National Library of Medicine, Bethesda, MD. 
-It is the policy of NLM (and U.S. government) to not assert copyright.
-
-A non-exclusive copy of this code has been contributed to the Open JPEG project.
-Except for copyright, inclusion of the code within Open JPEG for distribution and use
-can be bound by the Open JPEG open-source license and disclaimer, expressed elsewhere.
-*/
-
-#include "../libopenjpeg/opj_includes.h"
-#include "mj2.h"
-
-#include "mj2_to_metadata.h"
-#include <string.h>
-#include "getopt.h"
-
-/* -------------------------------------------------------------------------- */
-
-/**
-sample error callback expecting a FILE* client object
-*/
-void error_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[ERROR] %s", msg);
-}
-/**
-sample warning callback expecting a FILE* client object
-*/
-void warning_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[WARNING] %s", msg);
-}
-/**
-sample debug callback expecting a FILE* client object
-*/
-void info_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[INFO] %s", msg);
-}
-
-/* -------------------------------------------------------------------------- */
-
-
-
-/* ------------- */
-
-void help_display()
-{
-  /*             "1234567890123456789012345678901234567890123456789012345678901234567890123456789" */
-  fprintf(stdout,"                Help for the 'mj2_to_metadata' Program\n");
-  fprintf(stdout,"                ======================================\n");
-  fprintf(stdout,"The -h option displays this information on screen.\n\n");
-  
-  fprintf(stdout,"mj2_to_metadata generates an XML file from a Motion JPEG 2000 file.\n");
-  fprintf(stdout,"The generated XML shows the structural, but not (yet) curatorial,\n");
-  fprintf(stdout,"metadata from the movie header and from the JPEG 2000 image and tile\n");
-  fprintf(stdout,"headers of a sample frame.  Excluded: low-level packed-bits image data.\n\n");
-
-  fprintf(stdout,"By Default\n");
-  fprintf(stdout,"----------\n");
-  fprintf(stdout,"The metadata includes the jp2 image and tile headers of the first frame.\n");
-  fprintf(stdout,"\n");
-  fprintf(stdout,"Metadata values are shown in 'raw' form (e.g., hexidecimal) as stored in the\n");
-  fprintf(stdout,"file, and, if apt, in a 'derived' form that is more quickly grasped.\n");
-  fprintf(stdout,"\n");
-  fprintf(stdout,"Notes explaining the XML are embedded as terse comments.  These include\n");
-  fprintf(stdout,"   meaning of non-obvious tag abbreviations;\n");
-  fprintf(stdout,"   range and precision of valid values;\n");
-  fprintf(stdout,"   interpretations of values, such as enumerations; and\n");
-  fprintf(stdout,"   current implementation limitations.\n");
-  fprintf(stdout,"\n");
-  fprintf(stdout,"The sample-size and chunk-offset tables, each with 1 row per frame, are not reported.\n");
-  fprintf(stdout,"\n");
-  fprintf(stdout,"The file is self-contained and no verification (e.g., against a DTD) is requested.\n");
-  fprintf(stdout,"\n");
-  fprintf(stdout,"Required Parameters (except with -h)\n");
-  fprintf(stdout,"------------------------------------\n");
-  fprintf(stdout,"[Caution: file strings that contain spaces should be wrapped with quotes.]\n");
-  fprintf(stdout,"-i input.mj2  : where 'input' is any source file name or path.\n");
-  fprintf(stdout,"                MJ2 files created with 'frames_to_mj2' are supported so far.\n");
-  fprintf(stdout,"                These are silent, single-track, 'MJ2 Simple Profile' videos.\n");
-  fprintf(stdout,"-o output.xml : where 'output' is any destination file name or path.\n");
-  fprintf(stdout,"\n");
-  fprintf(stdout,"Optional Parameters\n");
-  fprintf(stdout,"-------------------\n");
-  fprintf(stdout,"-h            : Display this help information.\n");
-  fprintf(stdout,"-n            : Suppress all mj2_to_metadata notes.\n");
-  fprintf(stdout,"-t            : Include sample-size and chunk-offset tables.\n");
-  fprintf(stdout,"-f n          : where n > 0.  Include jp2 header info for frame n [default=1].\n");
-  fprintf(stdout,"-f 0          : No jp2 header info.\n");
-  fprintf(stdout,"-r            : Suppress all 'raw' data for which a 'derived' form exists.\n");
-  fprintf(stdout,"-d            : Suppress all 'derived' data.\n");
-  fprintf(stdout,"                (If both -r and -d given, -r will be ignored.)\n");
-  fprintf(stdout,"-v string     : Verify against the DTD file located by the string.\n");
-  fprintf(stdout,"                Prepend quoted 'string' with either SYSTEM or PUBLIC keyword.\n");
-  fprintf(stdout,"                Thus, for the distributed DTD placed in the same directory as\n");
-  fprintf(stdout,"                the output file: -v \"SYSTEM mj2_to_metadata.dtd\"\n");
-  fprintf(stdout,"                \"PUBLIC\" is used with an access protocol (e.g., http:) + URL.\n");
-  /* More to come */
-  fprintf(stdout,"\n");
-  /*             "1234567890123456789012345678901234567890123456789012345678901234567890123456789" */
-}
-
-/* ------------- */
-
-int main(int argc, char *argv[]) {
-
-       opj_dinfo_t* dinfo; 
-       opj_event_mgr_t event_mgr;              /* event manager */
-
-  FILE *file, *xmlout;
-/*  char xmloutname[50]; */
-  opj_mj2_t *movie;
-
-  char* infile = 0;
-  char* outfile = 0;
-  char* s, S1, S2, S3;
-  int len;
-  unsigned int sampleframe = 1; /* First frame */
-  char* stringDTD = NULL;
-  BOOL notes = TRUE;
-  BOOL sampletables = FALSE;
-  BOOL raw = TRUE;
-  BOOL derived = TRUE;
-       mj2_dparameters_t parameters;
-
-  while (TRUE) {
-       /* ':' after letter means it takes an argument */
-    int c = getopt(argc, argv, "i:o:f:v:hntrd");
-       /* FUTURE:  Reserve 'p' for pruning file (which will probably make -t redundant) */
-    if (c == -1)
-      break;
-    switch (c) {
-    case 'i':                  /* IN file */
-      infile = optarg;
-      s = optarg;
-      while (*s) { s++; } /* Run to filename end */
-      s--;
-      S3 = *s;
-      s--;
-      S2 = *s;
-      s--;
-      S1 = *s;
-      
-      if ((S1 == 'm' && S2 == 'j' && S3 == '2')
-      || (S1 == 'M' && S2 == 'J' && S3 == '2')) {
-       break;
-      }
-      fprintf(stderr, "Input file name must have .mj2 extension, not .%c%c%c.\n", S1, S2, S3);
-      return 1;
-
-      /* ----------------------------------------------------- */
-    case 'o':                  /* OUT file */
-      outfile = optarg;
-      while (*outfile) { outfile++; } /* Run to filename end */
-      outfile--;
-      S3 = *outfile;
-      outfile--;
-      S2 = *outfile;
-      outfile--;
-      S1 = *outfile;
-      
-      outfile = optarg;
-      
-      if ((S1 == 'x' && S2 == 'm' && S3 == 'l')
-         || (S1 == 'X' && S2 == 'M' && S3 == 'L'))
-        break;
-    
-      fprintf(stderr,
-         "Output file name must have .xml extension, not .%c%c%c\n", S1, S2, S3);
-         return 1;
-
-      /* ----------------------------------------------------- */
-    case 'f':                  /* Choose sample frame.  0 = none */
-      sscanf(optarg, "%u", &sampleframe);
-      break;
-
-      /* ----------------------------------------------------- */
-    case 'v':                  /* Verification by DTD. */
-      stringDTD = optarg;
-         /* We will not insist upon last 3 chars being "dtd", since non-file
-         access protocol may be used. */
-         if(strchr(stringDTD,'"') != NULL) {
-        fprintf(stderr, "-D's string must not contain any embedded double-quote characters.\n");
-           return 1;
-         }
-
-      if (strncmp(stringDTD,"PUBLIC ",7) == 0 || strncmp(stringDTD,"SYSTEM ",7) == 0)
-        break;
-    
-      fprintf(stderr, "-D's string must start with \"PUBLIC \" or \"SYSTEM \"\n");
-         return 1;
-
-    /* ----------------------------------------------------- */
-    case 'n':                  /* Suppress comments */
-      notes = FALSE;
-      break;
-
-    /* ----------------------------------------------------- */
-    case 't':                  /* Show sample size and chunk offset tables */
-      sampletables = TRUE;
-      break;
-
-    /* ----------------------------------------------------- */
-    case 'h':                  /* Display an help description */
-      help_display();
-      return 0;
-
-    /* ----------------------------------------------------- */
-    case 'r':                  /* Suppress raw data */
-      raw = FALSE;
-      break;
-
-    /* ----------------------------------------------------- */
-    case 'd':                  /* Suppress derived data */
-      derived = FALSE;
-      break;
-
-   /* ----------------------------------------------------- */
-    default:
-      return 1;
-    } /* switch */
-  } /* while */
-
-  if(!raw && !derived)
-         raw = TRUE; /* At least one of 'raw' and 'derived' must be true */
-
-    /* Error messages */
-  /* -------------- */
-  if (!infile || !outfile) {
-    fprintf(stderr,"Correct usage: mj2_to_metadata -i mj2-file -o xml-file (plus options)\n");
-    return 1;
-  }
-
-/* was:
-  if (argc != 3) {
-    printf("Bad syntax: Usage: MJ2_to_metadata inputfile.mj2 outputfile.xml\n"); 
-    printf("Example: MJ2_to_metadata foreman.mj2 foreman.xml\n");
-    return 1;
-  }
-*/
-  len = strlen(infile);
-  if(infile[0] == ' ')
-  {
-    infile++; /* There may be a leading blank if user put space after -i */
-  }
-  
-  file = fopen(infile, "rb"); /* was: argv[1] */
-  
-  if (!file) {
-    fprintf(stderr, "Failed to open %s for reading.\n", infile); /* was: argv[1] */
-    return 1;
-  }
-
-  len = strlen(outfile);
-  if(outfile[0] == ' ')
-  {
-    outfile++; /* There may be a leading blank if user put space after -o */
-  }
-
-  // Checking output file
-  xmlout = fopen(outfile, "w"); /* was: argv[2] */
-  if (!xmlout) {
-    fprintf(stderr, "Failed to open %s for writing.\n", outfile); /* was: argv[2] */
-    return 1;
-  }
-  // Leave it open
-
-       /*
-       configure the event callbacks (not required)
-       setting of each callback is optionnal
-       */
-       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
-       event_mgr.error_handler = error_callback;
-       event_mgr.warning_handler = warning_callback;
-       event_mgr.info_handler = info_callback;
-
-       /* get a MJ2 decompressor handle */
-       dinfo = mj2_create_decompress();
-
-       /* catch events using our callbacks and give a local context */
-       opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);           
-
-       /* setup the decoder decoding parameters using user parameters */
-       movie = (opj_mj2_t*) dinfo->mj2_handle;
-       mj2_setup_decoder(dinfo->mj2_handle, &parameters);
-
-  if (mj2_read_struct(file, movie)) // Creating the movie structure
-  {
-    fclose(xmlout);
-    return 1;
-  }
-
-  xml_write_init(notes, sampletables, raw, derived);
-  xml_write_struct(file, xmlout, movie, sampleframe, stringDTD, &event_mgr);
-  fclose(xmlout);
-
-       fprintf(stderr,"Metadata correctly extracted to XML file \n");; 
-
-       /* free remaining structures */
-       if(dinfo) {
-               mj2_destroy_decompress((opj_mj2_t*)dinfo->mj2_handle);
-       }
-
-  return 0;
-}
-
-
diff --git a/mj2/mj2_to_metadata.dtd b/mj2/mj2_to_metadata.dtd
deleted file mode 100644 (file)
index 249de1a..0000000
+++ /dev/null
@@ -1,425 +0,0 @@
-<!--
-Preliminary DTD for Open JPEG "mj2_to_metadata" function.
-Last revised: April 20, 2005
-Author:  Glenn Pearson, at U.S. National Library of Medicine.
-See mj2_to_metadata.c regarding copyright, license, disclaimer status.
-
-While the vocabulary of this DTD is based on the relevant portions of the
-ISO/IEC JPEG 200 standard, the detailed representation is the author's own.
-It is neither an ISO/IEC nor NLM official or consensus representation.
-Furthermore, it deviates from a pure representation of the ISO/IEC standard
-in these aspects:
-
-  - it is incomplete in a number of ways (which to some extent may be
-    addressed over time);
-  - it has extensions for "derived" data and "statistics";
-  - it is more flexible.  That is, some elements are marked as optional
-    not because they are optional in an MJ2 file, but because reporting
-    of them is optional based on current or projected mj2_to_metadata
-    command-line flags.
--->
-<!ELEMENT MJ2_File (JP2?, FileType?, MovieBox?)>
-<!ELEMENT JP2 EMPTY>
-<!ATTLIST JP2 BoxType CDATA #FIXED "jP[space][space]">
-<!ATTLIST JP2 Signature CDATA #FIXED "0x0d0a870a">
-<!ELEMENT FileType (Brand, MinorVersion, CompatibilityList)>
-<!ATTLIST FileType BoxType CDATA #FIXED "ftyp">
-<!ELEMENT Brand (#PCDATA)> <!-- 4 characters max -->
-<!ELEMENT MinorVersion (#PCDATA)> <!-- 4 chararcters max -->
-<!ELEMENT CompatibilityList (CompatibleBrand)*>
-<!ATTLIST CompatibilityList Count CDATA #REQUIRED>  <!-- Count >= 0 -->
-<!ELEMENT CompatibleBrand (#PCDATA)> <!-- 4 characters max -->
-<!ELEMENT MovieBox (MovieHeader, Statistics?, Track*)>
-<!ATTLIST MovieBox BoxType CDATA #FIXED "moov">
-<!ELEMENT MovieHeader (CreationTime, ModificationTime, Timescale, Rate, Duration, Volume, TransformationMatrix)>
-<!ATTLIST MovieHeader BoxType CDATA #FIXED "mvhd">
-<!ELEMENT CreationTime (InSeconds?,AsLocalTime?)>
-<!ELEMENT InSeconds (#PCDATA)>
-<!ELEMENT AsLocalTime (#PCDATA)>
-<!ELEMENT ModificationTime (InSeconds?,AsLocalTime?)>
-<!ELEMENT Timescale (#PCDATA)> <!-- Timescale defines time units in one second -->
-<!ELEMENT Rate (AsHex | (AsHex, AsDecimal) | AsDecimal)>  <!-- Decimal is Approximation; Optional on input. -->
-<!ELEMENT AsHex (#PCDATA)>
-<!ELEMENT AsDecimal (#PCDATA)> 
-<!ELEMENT Duration (InTimeUnits | (InTimeUnits, InSeconds) | InSeconds)>  <!-- InSeconds Optional on input. -->
-<!ELEMENT InTimeUnits (#PCDATA)>
-<!ELEMENT Volume (AsHex | (AsHex, AsDecimal) | AsDecimal)>   <!-- hex default = 0x0100 -->
-<!-- Fixed 8.8 value of audio volume.  Full, normal value is 1.0 (0x0100) -->
-<!ELEMENT TransformationMatrix (TMa,TMb,TMu,TMc,TMd,TMv,TMx,TMy,TMw)> <!-- for video -->
-<!-- 3 x 3 Video Transformation Matrix {a,b,u,c,d,v,x,y,w}.  Required: u=0, v=0, w=1 -->
-<!-- Maps decompressed point (p,q) to rendered point (ap + cq + x, bp + dq + y) -->
-<!-- Stored as Fixed Point Hex: all are 16.16, except u,v,w are 2.30 -->
-<!-- Unity = 0x00010000,0,0,0,0x00010000,0,0,0,0x40000000 -->
-<!ELEMENT TMa (#PCDATA)>    
-<!ELEMENT TMb (#PCDATA)>  
-<!ELEMENT TMu (#PCDATA)> <!--Always "0x00000000" -->
-<!ELEMENT TMc (#PCDATA)>
-<!ELEMENT TMd (#PCDATA)>
-<!ELEMENT TMv (#PCDATA)> <!--Always "0x00000000" -->
-<!ELEMENT TMx (#PCDATA)>
-<!ELEMENT TMy (#PCDATA)>
-<!ELEMENT TMw (#PCDATA)> <!--Always "0x40000000" -->
-
-<!ELEMENT Statistics (TracksFound)>
-<!ELEMENT TracksFound (Video,Audio,Hint)>
-<!ELEMENT Video (#PCDATA)>
-<!ELEMENT Audio (#PCDATA)>
-<!ELEMENT Hint (#PCDATA)>
-
-<!-- For now, output info on at most one video track -->
-
-
-<!ELEMENT Track (TrackHeader, TrackReferenceContainer?, EditListContainer?, Media, JP2_Frame?)>  <!-- JP2_Frame is mj2_to_metadata extension -->
-<!ATTLIST Track BoxType CDATA #FIXED "trak">
-<!ATTLIST Track Instance CDATA #REQUIRED>
-<!ELEMENT TrackHeader (TrackID, TrackLayer?, Volume?, TransformationMatrix?, Width?, Height?)>
-<!ATTLIST TrackHeader BoxType CDATA #FIXED "tkhd">
-<!-- Not shown here: CreationTime, ModificationTime, Duration. -->
-<!-- These 3 fields are reported under MediaHeader below.   When reading these 3, -->
-<!-- m2j_to_metadata currently doesn't distinguish between TrackHeader and MediaHeader source. -->
-<!-- If both found, value read from MediaHeader is used. -->
-<!ELEMENT TrackID (#PCDATA)>
-<!ELEMENT TrackLayer (#PCDATA)>  <!-- front-to-back ordering of video tracks. 0 = normal, -1 is closer, etc. -->
-<!-- "Volume" element described above; here it is for particular audio track.  Full, normal (default = 0x0100) -->
-<!-- "TransformationMatrix" element described above; matrix here is applied before MovieHeader one. -->
-<!ELEMENT Width (AsHex | (AsHex, AsDecimal) | AsDecimal)>
-<!ELEMENT Height (AsHex | (AsHex, AsDecimal) | AsDecimal)>
-<!-- AsHex, AsDecimal already defined above -->
- <!-- Width and Height are for the presentation; frames will be scaled to this -->
-<!-- /TrackHeader -->
-<!ELEMENT TrackReferenceContainer ANY>  <!-- TO DO: TrackReferenceContainer 'tref'  just used in hint track -->
-<!ELEMENT EditListContainer ANY>  <!-- TO DO: EditListContainer 'edts', contains EditList 'elst' with media-time, segment-duration, media-rate -->
-<!ELEMENT Media (MediaHeader, HandlerReference,MediaInfoContainer)>
-<!ATTLIST Media BoxType CDATA #FIXED "mdia">
-<!ELEMENT MediaHeader (CreationTime,ModificationTime,Timescale,Duration,Language)>
-<!ATTLIST MediaHeader BoxType CDATA #FIXED "mdhd">
-<!-- Elements already defined above: CreationTime, ModificationTime, Timescale, Duration -->
-<!ELEMENT Language (#PCDATA)> <!-- 3 chars max.  There's an enumeration available -->
-<!ELEMENT HandlerReference (HandlerType)>
-<!ATTLIST HandlerReference BoxType CDATA #FIXED "hdlr">
-<!ELEMENT HandlerType (#PCDATA)>
-<!ATTLIST HandlerType Code ( vide | soun | hint ) "vide">
-
-<!-- make the media headers multiple? -->
-<!ELEMENT MediaInfoContainer ((VideoMediaHeader | SoundMediaHeader | HintMediaHeader), DataInfo, SampleTable)>
-<!ATTLIST MediaInfoContainer BoxType CDATA #FIXED "minf">
-<!ELEMENT VideoMediaHeader (GraphicsMode, Opcolor)>
-<!ATTLIST VideoMediaHeader BoxType CDATA #FIXED "vmhd">
-<!ELEMENT GraphicsMode (#PCDATA)>
-          <!-- Enumerated values of graphics mode: -->
-          <!--  0x00 = copy (over existing image); -->
-          <!--  0x24 = transparent; 'blue-screen' this image using opcolor; -->
-          <!--  0x100 = alpha; alpha-blend this image -->
-          <!--  0x101 = whitealpha; alpha-blend this image, which has been blended with white; -->
-          <!--  0x102 = blackalpha; alpha-blend this image, which has been blended with black. -->
-<!ELEMENT Opcolor (Red,Green,Blue)>
-<!ELEMENT Red (#PCDATA)>
-<!ELEMENT Green (#PCDATA)>
-<!ELEMENT Blue (#PCDATA)>
-<!ELEMENT SoundMediaHeader (Balance)>
-<!ATTLIST SoundMediaHeader BoxType CDATA #FIXED "smhd">
-<!ELEMENT Balance (#PCDATA)>
-          <!-- Fixed Point 8.8, fixes mono track in stereo space. -->
-          <!-- 0.0 = center, -1.0 = full left, 1.0 = full right -->
-<!ELEMENT HintMediaHeader (MaxPDU_Size, AvgPDU_Size, MaxBitRate, AvgBitRate, SlidingAvgBitRate)>
-<!ATTLIST HintMediaHeader BoxType CDATA #FIXED "hmhd">
-<!ELEMENT MaxPDU_Size (#PCDATA)>
-          <!-- Size in bytes of largest PDU in this hint stream. -->
-<!ELEMENT AvgPDU_Size (#PCDATA)>
-           <!-- Average size in bytes of a PDU over the entire presentation. -->
-<!ELEMENT MaxBitRate (#PCDATA)>
-          <!-- Maximum rate in bits per second over any window of 1 second. -->
-<!ELEMENT AvgBitRate (#PCDATA)>
-          <!-- Averate rate in bits per second over the entire presentation. -->
-<!ELEMENT SlidingAvgBit (#PCDATA)>
-          <!-- Maximum rate in bits per second over any window of one minute. -->
-<!ELEMENT DataInfo (DataReference)>
-<!ATTLIST DataInfo BoxType CDATA #FIXED "dinf">
-<!ELEMENT DataReference (DataEntryUrlBox | DataEntryUrnBox )*>
-<!ATTLIST DataReference BoxType CDATA #FIXED "dref">
-<!ATTLIST DataReference URL_Count CDATA #REQUIRED>
-<!ATTLIST DataReference URN_Count CDATA #REQUIRED> <!-- table w. flags, URLs, URNs -->
-<!--  // Data structure does not distinguish between single URL, single URN, or DREF table or URLs & URNs.
-  // We could infer those, but for now just present everything as a DREF table.
--->
-              <!-- No entries here mean that file is self-contained, as required by Simple Profile. -->
-
-<!ELEMENT DataEntryUrlBox (Location)>
-<!ATTLIST DataEntryUrlBox BoxType CDATA #FIXED "url[space]"> <!-- table w. flags, URLs, URNs -->
-            <!-- Only the first 16 bytes of URL location are recorded in mj2_to_metadata data structure. -->
-<!ELEMENT DataEntryUrnBox (Name, Location?)>
-<!ATTLIST DataEntryUrnBox BoxType CDATA #FIXED "urn[space]\">
-            <!-- Only the first 16 bytes each of URN name and optional location are recorded in mj2_to_metadata data structure. -->
-
-<!ELEMENT SampleTable (VisualSampleEntry,TimeToSample,SampleToChunk,SampleSize,ChunkOffset)>  <!-- structure doesn't do non-visual sample entry yet -->
-<!ATTLIST SampleTable BoxType CDATA #FIXED "stbl">  <!-- to add: entry count -->
-            <!-- Next are instances of generic SampleDescription BoxType=\"stsd\" -->
-    <!-- There could be multiple instances of this, but "entry_count" is just a local at read-time.
-       And it's used wrong, too, as count of just visual type, when it's really all 3 types.
-       This is referred to as "smj2" within mj2.c -->
-<!ELEMENT VisualSampleEntry (WidthAsInteger, HeightAsInteger, HorizontalRes, VerticalRes, CompressorName, Depth, JP2Header?, FieldCoding?, MJP2_Profile?, MJP2_Prefix?, MJP2_SubSampling?, MJP2_OriginalFormat?)>
-<!ATTLIST VisualSampleEntry BoxType CDATA #FIXED "mjp2">
-          <!-- If multiple instances of this, only first is shown here. -->
-<!ELEMENT WidthAsInteger (#PCDATA)>
-<!ELEMENT HeightAsInteger (#PCDATA)>
-<!ELEMENT HorizontalRes (AsHex | (AsHex, AsDecimal) | AsDecimal)>
-<!ELEMENT VerticalRes (AsHex | (AsHex, AsDecimal) | AsDecimal)>
-<!-- Typical value for both resolution is 72 (0x00480000) -->
-<!ELEMENT CompressorName (#PCDATA)>
-          <!-- Compressor name for debugging.  Standard restricts max length to 31 bytes. -->
-          <!-- Usually blank or \"Motion JPEG2000\" -->
-<!ELEMENT Depth (#PCDATA)>
-          <!-- Depth is: -->
-          <!--   0x20: alpha channels present (color or grayscale) -->
-          <!--   0x28: grayscale without alpha -->
-          <!--   0x18: color without alpha -->
-
-<!-- TODO somewhere: tk->jp2_struct.numcomps -->
-<!ELEMENT JP2Header (ImageHeader, ColourSpecification)>
-<!ATTLIST JP2Header BoxType CDATA #FIXED "jp2h">
-<!ELEMENT ImageHeader (HEIGHT, WIDTH, NC, BPC, C, UnkC, IPR)>
-<!ATTLIST ImageHeader BoxType CDATA #FIXED "ihdr">
-<!ELEMENT HEIGHT (#PCDATA)>  <!-- If 2 fields/frame, total deinterlaced height -->
-<!ELEMENT WIDTH (#PCDATA)>
-<!ELEMENT NC (#PCDATA)>  <!-- number of components -->
-<!ELEMENT BPC (AsHex | (AsHex,BitsPerPixel,Signed) | (BitsPerPixel,Signed))>
-<!ELEMENT BitsPerPixel (#PCDATA)>
-<!ELEMENT Signed (#PCDATA)>
-<!ELEMENT C (#PCDATA)>  <!-- Compression type.  Only "7" defined -->
-<!ELEMENT UnkC (#PCDATA)>  <!-- Colourspace Unknown. 1 = unknown, 0 = known -->
-<!ELEMENT IPR (#PCDATA)>  <!-- 1 = frame has Intellectual Prop. box; otherwise 0 -->
-<!ELEMENT ColourSpecification (METH, PREC, APPROX, EnumCS)>
-<!ATTLIST ColourSpecification BoxType CDATA #FIXED "colr">
-<!ELEMENT METH (#PCDATA)>  <!-- 1 = EnumCS field; 2 = PROFILE field (not yet generated) -->
-<!ELEMENT PREC (#PCDATA)> <!-- precedence must be 0 so far -->
-<!ELEMENT APPROX (#PCDATA)>  <!-- colourspace approximation must be 0 so far -->
-<!ELEMENT EnumCS (#PCDATA)> <!-- Valid enumerated MJ2 colourspaces: 16 (sRGB), 17 (grey sRGB), 18 (YCC) -->
-
-<!-- Following subboxes are optional -->
-<!ELEMENT FieldCoding (FieldCount, FieldOrder)>
-<!ATTLIST FieldCoding BoxType CDATA #FIXED "fiel">
-<!ELEMENT FieldCount (#PCDATA)>
-            <!-- Must be either 1 or 2 -->
-<!ELEMENT FieldOrder (#PCDATA)>
-            <!-- When FieldCount=2, FieldOrder means: -->
-            <!--   0: Field coding unknown -->
-            <!--   1: Field with topmost line is stored first in sample; fields are in temporal order -->
-            <!--   6: Field with topmost line is stored second in sample; fields are in temporal order -->
-            <!-- Defaults: FieldCount=1, FieldOrder=0 if FieldCoding box not present -->
-            <!-- Current implementation doesn't retain whether box was actually present. -->
-
-<!ELEMENT MJP2_Profile (CompatibleBrand*)>
-<!ATTLIST MJP2_Profile BoxType CDATA #FIXED "jp2p">
-<!ATTLIST MJP2_Profile Count CDATA #REQUIRED>
-
-<!ELEMENT MJP2_Prefix (Data*)>
-<!ATTLIST MJP2_Prefix BoxType CDATA #FIXED "jp2x">
-<!ATTLIST MJP2_Prefix Count CDATA #REQUIRED>
-<!-- We'll probably need better formatting than this  -->
-<!ELEMENT Data (#PCDATA)>    <!-- Multiple. Each entry is single byte -->
-
-<!ELEMENT MJP2_SubSampling (HorizontalSub, VerticalSub, HorizontalOffset, VerticalOffset)>
-<!ATTLIST MJP2_SubSampling BoxType CDATA #FIXED "jsub">
-<!-- These values are all 1 byte -->
-            <!-- Typical subsample value is 2 for 4:2:0 -->
-<!ELEMENT HorizontalSub (#PCDATA)>
-<!ELEMENT VerticalSub (#PCDATA)>
-<!ELEMENT HorizontalOffset (#PCDATA)>
-<!ELEMENT VerticalOffset (#PCDATA)>
-
-<!ELEMENT MJP2_OriginalFormat (OriginalFieldCount, OriginalFieldOrder)>
-<!ATTLIST MJP2_OriginalFormat BoxType CDATA #FIXED "orfo"> <!-- Part III Appx. 2 -->
-<!ELEMENT OriginalFieldCount (#PCDATA)>
-            <!-- In original material before encoding.  Must be either 1 or 2 -->
-<!ELEMENT OriginalFieldOrder (#PCDATA)>
-            <!-- When FieldCount=2, FieldOrder means: -->
-            <!--   0: Field coding unknown -->
-            <!--   11: Topmost line came from the earlier field; -->
-            <!--   16:  Topmost line came form the later field. -->
-            <!-- Defaults: FieldCount=1, FieldOrder=0 if FieldCoding box not present -->
-            <!-- Current implementation doesn't retain whether box was actually present. -->
-
-
-            <!-- mj2_to_metadata's data structure doesn't record Audio and Hint sample data currently. -->
-
-<!-- Within SampleTable: -->
-<!ELEMENT TimeToSample (SampleStatistics, SampleEntries)>
-<!ATTLIST TimeToSample BoxType CDATA #FIXED "stts">  
-<!ELEMENT SampleStatistics (TotalSamples)>  <!-- Not part of standard -->  
-<!ELEMENT TotalSamples (#PCDATA)>
-                <!-- For video, gives the total frames in the track, by summing all entries in the Sample Table -->
-
-<!ELEMENT SampleEntries (Table*)>
-<!ATTLIST SampleEntries EntryCount CDATA #REQUIRED>
-<!ELEMENT Table EMPTY> <!-- Multiple.  Attributes have values -->
-<!ATTLIST Table Entry CDATA #REQUIRED>
-<!ATTLIST Table SampleCount CDATA #REQUIRED>
-<!ATTLIST Table SampleDelta CDATA #REQUIRED>
-
-<!-- Within SampleTable: -->
-<!ELEMENT SampleToChunk (FirstChunk,SamplesPerChunk,SampleDescrIndex)>
-<!ATTLIST SampleToChunk BoxType CDATA #FIXED "stsc">
-<!ATTLIST SampleToChunk Count CDATA #REQUIRED>
-<!ELEMENT FirstChunk (#PCDATA)>
-<!ELEMENT SamplesPerChunk (#PCDATA)>
-<!ELEMENT SampleDescrIndex (#PCDATA)>
-<!ELEMENT SampleSize (Sample_Size,Sample_Count,EntrySize*)>
-<!ATTLIST SampleSize BoxType CDATA #FIXED "stsz">
-<!ELEMENT Sample_Size (#PCDATA)>
-<!ELEMENT Sample_Count (#PCDATA)>
-<!ELEMENT EntrySize (#PCDATA)>  <!-- appears multiply, but only with mj2_to_metadata option -t -->
-<!ATTLIST EntrySize Num CDATA #REQUIRED>
-<!ELEMENT ChunkOffset (EntryCount, Chunk_Offset*)>
-<!ATTLIST ChunkOffset BoxType CDATA #FIXED "stco">
-<!ELEMENT EntryCount (#PCDATA)>
-<!ELEMENT Chunk_Offset (#PCDATA)>  <!-- appears multiply, but only with mj2_to_metadata option -t -->
-<!ATTLIST Chunk_Offset Num CDATA #REQUIRED>
-<!-- </SampleTable> </MediaInfoContainer> </Media> -->
-
-<!-- TO DO: optional UserData 'udat', can contain multiple Copyright 'cprt' -->
-
-
-<!-- Optional, and only for Visual Track: given individual frame -->
-<!ELEMENT JP2_Frame (MainHeader, TilePartHeaders)>
-<!ATTLIST JP2_Frame Num CDATA #REQUIRED>
-<!ELEMENT MainHeader (StartOfCodestream,ImageAndFileSize,CodingStyleDefault,QuantizationDefault,QuantizationComponent*,RegionOfInterest?,ProgressionOrderChange*)>
-<!ELEMENT StartOfCodestream EMPTY>
-<!ATTLIST StartOfCodestream Marker CDATA #FIXED "SOC">
-<!ELEMENT ImageAndFileSize (Xsiz,Ysiz,XOsiz,YOsiz,XTsiz,YTsiz,XTOsiz,YTOsiz,Csiz,Component+)>
-<!ATTLIST ImageAndFileSize Marker CDATA #FIXED "SIZ">
-<!ELEMENT Xsiz (#PCDATA)>
-<!ELEMENT Ysiz (#PCDATA)>  <!-- Xsiz, Ysiz is the size of the reference grid. -->
-<!ELEMENT XOsiz (#PCDATA)>
-<!ELEMENT YOsiz (#PCDATA)>  <!-- XOsiz, YOsiz are offsets from grid origin to image origin. -->
-<!ELEMENT XTsiz (#PCDATA)>
-<!ELEMENT YTsiz (#PCDATA)>  <!-- XTsiz, YTsiz is the size of one tile with respect to the grid. -->
-<!ELEMENT XTOsiz (#PCDATA)>
-<!ELEMENT YTOsiz (#PCDATA)> <!-- XTOsiz, YTOsiz are offsets from grid origin to first tile origin. -->
-<!ELEMENT Csiz (#PCDATA)>  <!-- Csiz is the number of components in the image. -->
-<!-- For image components next -->
-<!ELEMENT Component (Ssiz,XRsiz,YRsiz,WidthOfData,HeightOfData)>
-<!ATTLIST Component Num CDATA #REQUIRED>
-<!ELEMENT Ssiz (AsHex | (AsHex,Signed,PrecisionInBits) | (Signed,PrecisionInBits))>
-<!-- Signed already defined -->
-<!ELEMENT PrecisionInBits (#PCDATA)>  <!--   Bits per pixel (bpp) or pixel depth. -->
-<!ELEMENT XRsiz (#PCDATA)>
-<!ELEMENT YRsiz (#PCDATA)> <!-- XRsiz, YRsiz denote pixel-sample-spacing on the grid, per Part I Annex B. -->
-<!ELEMENT WidthOfData (#PCDATA)>
-<!ELEMENT HeightOfData (#PCDATA)>  <!-- WidthOfData and HeightOfData are calculated values, e.g.: w = roundup((Xsiz - XOsiz)/ XRsiz) -->
-<!-- -->
-<!ELEMENT CodingStyleDefault (Scod,SGcod,SPcod)>
-<!ATTLIST CodingStyleDefault Marker CDATA #FIXED "COD">
-<!ELEMENT Scod (#PCDATA)>
-          <!-- For Scod, specific bits mean (where bit 0 is lowest or rightmost): -->
-          <!-- bit 0: Defines entropy coder precincts -->
-          <!--        0 = (PPx=15, PPy=15); 1 = precincts defined below. -->
-          <!-- bit 1: 1 = SOP marker may be used; 0 = not. -->
-          <!-- bit 2: 1 = EPH marker may be used; 0 = not. -->
-<!ELEMENT SGcod (ProgressionOrder,NumberOfLayers,MultipleComponentTransformation)>
-<!ELEMENT ProgressionOrder (#PCDATA)>
-            <!-- Defined Progression Order Values are: -->
-            <!-- 0 = LRCP; 1 = RLCP; 2 = RPCL; 3 = PCRL; 4 = CPRL -->
-            <!-- where L = "layer", R = "resolution level", C = "component", P = "position". -->
-<!ELEMENT NumberOfLayers (#PCDATA)>
-<!ELEMENT MultipleComponentTransformation (#PCDATA)>
-            <!-- For MCT, 0 = none, 1 = transform first 3 components for efficiency, per Part I Annex G -->
-<!ELEMENT SPcod (NumberOfDecompositionLevels,CodeblockWidth,CodeblockHeight,CodeblockStyle,Transformation)>
-<!ELEMENT NumberOfDecompositionLevels (#PCDATA)>
-<!ELEMENT CodeblockWidth (#PCDATA)>   <!-- CBW and CBH are non-negative, and summed cannot exceed 8 -->
-<!ELEMENT CodeblockHeight (#PCDATA)>  <!-- Codeblock dimension is 2^(value + 2) -->
-<!ELEMENT CodeblockStyle (#PCDATA)>
-            <!-- For CodeblockStyle, bits mean (with value 1=feature on, 0=off): -->
-            <!-- bit 0: Selective arithmetic coding bypass. -->
-            <!-- bit 1: Reset context probabilities on coding pass boundaries. -->
-            <!-- bit 2: Termination on each coding pass. -->
-            <!-- bit 3: Vertically causal context. -->
-            <!-- bit 4: Predictable termination. -->
-            <!-- bit 5: Segmentation symbols are used. -->
-<!ELEMENT Transformation (#PCDATA)> <!-- For Transformation, 0="9-7 irreversible filter", 1="5-3 reversible filter" -->
-        <!-- mj2_to_metadata implementation always reports component[0] as using default COD, -->
-        <!-- and any other component, with main-header style values different from [0], as COC. -->
-<!ELEMENT QuantizationDefault (Sqcd,SPqcd)>
-<!ATTLIST QuantizationDefault Marker CDATA #FIXED "QCD">
-<!ELEMENT Sqcd (AsHex | (AsHex,QuantizationStyle,NumberOfGuardBits) | (QuantizationStyle,NumberOfGuardBits))>
-<!ELEMENT QuantizationStyle (#PCDATA)>  <!-- Default quantization style for all components. -->
-            <!-- Quantization style (in Sqcd's low 5 bits) may be: -->
-            <!--   0 = No quantization. SPqcd size = 8 bits-->
-            <!--   1 = Scalar derived (values signaled for N(L)LL subband only). Use Eq. E.5. SPqcd size = 16. -->
-            <!--   2 = Scalar expounded (values signaled for each subband). SPqcd size = 16. -->
-<!ELEMENT NumberOfGuardBits (#PCDATA)>  <!-- 0-7 guard bits allowed (stored in Sqcd's high 3 bits) -->
-<!ELEMENT SPqcd (ReversibleStepSizeValue | QuantizationStepSizeValues )>  <!-- TO DO: Irreversible choices -->
-<!ELEMENT ReversibleStepSizeValue (DynamicRangeExponent+)>
-            <!-- Current mj2_to_metadata implementation dumps entire internal table, -->
-            <!-- until an exponent with zero value is reached. -->
-            <!-- Exponent epsilon(b) of reversible dynamic range. -->
-            <!-- Hex value is as stored, in high-order 5 bits. -->
-<!ELEMENT DynamicRangeExponent (AsHex | (AsHex, AsDecimal) | AsDecimal)>
-<!ATTLIST DynamicRangeExponent Subband CDATA #REQUIRED>
-<!ELEMENT QuantizationStepSizeValues (QuantizationValues+, CalculatedExponent*)>  <!-- Calculated exponents iff only subband 0 reported -->
-<!ELEMENT QuantizationValues (AsHex | (AsHex,Exponent,Mantissa) | (Exponent,Mantissa))>
-<!ATTLIST QuantizationValues Subband CDATA #REQUIRED>
-<!ELEMENT Exponent (#PCDATA)>
-<!ELEMENT Mantissa (#PCDATA)>
-<!ELEMENT CalculatedExponent (#PCDATA)>
-<!ATTLIST CalculatedExponent Subband CDATA #REQUIRED>
-<!-- /QuantizationDefault -->
-        <!-- mj2_to_metadata implementation always reports component[0] as using default QCD, -->
-        <!-- and any other component, with main-header quantization values different from [0], as QCC. -->
-<!ELEMENT QuantizationComponent (Sqcc,SPqcc)>
-<!ATTLIST QuantizationComponent Marker CDATA #FIXED "QCC">
-<!ATTLIST QuantizationComponent Component CDATA #REQUIRED>
-<!ELEMENT Sqcc (AsHex | (AsHex,QuantizationStyle,NumberOfGuardBits) | (QuantizationStyle,NumberOfGuardBits))>
-<!ELEMENT SPqcc (ReversibleStepSizeValue | QuantizationStepSizeValues )>  <!-- TO DO: Irreversible choices -->
-<!-- /QuantizationComponent -->
-<!-- Don't know if MJ2 files can have regions of interest.  Assume yes -->
-<!ELEMENT RegionOfInterest (Srgn,Crgn,Sprgn)> <!-- Optional in main header, at most 1 per component -->
-<!ATTLIST RegionOfInterest Marker CDATA #FIXED "RGN">
-<!ELEMENT Srgn (#PCDATA)>  <!-- ROI style.  Only style=0 defined: Implicit ROI (max. shift) -->
-<!ELEMENT Crgn (#PCDATA)>  <!-- Zero-based component number. -->
-<!ELEMENT SPrgn (#PCDATA)> <!-- Implicit ROI shift, i.e., binary shifting of ROI coefficients above background. -->
-<!-- </RegionOfInterest> -->
-<!ELEMENT ProgressionOrderChange (Progression+)> <!-- Optional in main header, at most 1 per component (but impl allows more?) -->
-<!ATTLIST ProgressionOrderChange Marker CDATA #REQUIRED>
-<!ELEMENT Progression (RSpoc,CSpoc,LYEpoc,REpoc,CEpoc,Ppoc)>
-<!ATTLIST Progression Num CDATA #REQUIRED>
-<!ELEMENT RSpoc (#PCDATA)> <!-- Resolution level index (inclusive) for progression start. Range: 0 to 33 -->
-<!ELEMENT CSpoc (#PCDATA)> <!-- Component index (inclusive) for progression start. -->
-<!ELEMENT LYEpoc (#PCDATA)> <!-- Layer index (exclusive) for progression end. -->
-<!ELEMENT REpoc (#PCDATA)> <!-- Resolution level index (exclusive) for progression end. Range: RSpoc to 33 -->
-<!ELEMENT CEpoc (#PCDATA)> <!-- Component index (exclusive) for progression end.  Minimum: CSpoc -->
-<!ELEMENT Ppoc (#PCDATA)> <!-- Defined Progression Order Values are: -->
-                          <!-- 0 = LRCP; 1 = RLCP; 2 = RPCL; 3 = PCRL; 4 = CPRL -->
-                          <!-- where L = "layer", R = "resolution level", C = "component", P = "position". -->
-<!-- </Progression>, </ProgressionOrderChange -->
-<!-- /MainHeader -->
-<!ELEMENT TilePartHeaders (TilePartHeader+)>
-<!ATTLIST TilePartHeaders Count CDATA #REQUIRED>
-<!ELEMENT TilePartHeader (StartOfTilePart,CodingStyleDefault,QuantizationDefault,QuantizationComponent*,RegionOfInterest?,ProgressionOrderChange*,StartOfData)>
-<!ATTLIST TilePartHeader Num CDATA #REQUIRED>
-<!ATTLIST TilePartHeader ID CDATA #REQUIRED>
-<!ELEMENT StartOfTilePart EMPTY>
-<!ATTLIST StartOfTilePart Marker CDATA #FIXED "SOT">
-<!-- CodingStyleDefault, QuantizationDefault, QuantizationComponent already defined -->
-        <!-- mj2_to_metadata implementation always reports component[0] as using default QCD, -->
-        <!-- and any other component, with tile-part-header quantization values different from [0], as QCC. -->
-<!ELEMENT StartOfData EMPTY> <!-- always empty for now -->
-<!ATTLIST StartOfData Marker CDATA #FIXED "SOD">
-          <!-- Tile-part bitstream, not shown, follows tile-part header and SOD marker. -->
-<!-- /TilePartHeader, /TilePartHeaders, /JP2_Frame -->
-<!-- </Track> -->
-
-<!-- to come:
-  <MovieExtends mvek> // possibly not in Simple Profile
-  <UserDataBox udat> contains <CopyrightBox cprt>
-  -->
-<!-- /MovieBox -->
-<!-- To come:
-  <mdat>
-  <moof>  // probably not in Simple Profile
-  <free>
-  <skip>
-  -->
-<!-- </MJ2_File> -->
\ No newline at end of file
diff --git a/mj2/mj2_to_metadata.h b/mj2/mj2_to_metadata.h
deleted file mode 100644 (file)
index f4c3491..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-/* mj2_to_metadata.h */
-/* Dump MJ2, JP2 metadata (partial so far) to xml file */
-/* Contributed to Open JPEG by Glenn Pearson, U.S. National Library of Medicine */
-
-#define BOOL int
-#define FALSE 0
-#define TRUE 1
-
-#include "meta_out.h"
diff --git a/mj2/mj2_to_metadata.sln b/mj2/mj2_to_metadata.sln
deleted file mode 100644 (file)
index 32b926d..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-\r
-Microsoft Visual Studio Solution File, Format Version 9.00\r
-# Visual Studio 2005\r
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mj2_to_metadata", "mj2_to_metadata.vcproj", "{69BE42AB-E7CE-4DA1-BBD2-39FEA2C91E0B}"\r
-       ProjectSection(ProjectDependencies) = postProject\r
-               {0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD} = {0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD}\r
-       EndProjectSection\r
-EndProject\r
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibOpenJPEG", "..\LibOpenJPEG.vcproj", "{0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD}"\r
-EndProject\r
-Global\r
-       GlobalSection(SolutionConfigurationPlatforms) = preSolution\r
-               Debug|Win32 = Debug|Win32\r
-               Release|Win32 = Release|Win32\r
-       EndGlobalSection\r
-       GlobalSection(ProjectConfigurationPlatforms) = postSolution\r
-               {69BE42AB-E7CE-4DA1-BBD2-39FEA2C91E0B}.Debug|Win32.ActiveCfg = Debug|Win32\r
-               {69BE42AB-E7CE-4DA1-BBD2-39FEA2C91E0B}.Debug|Win32.Build.0 = Debug|Win32\r
-               {69BE42AB-E7CE-4DA1-BBD2-39FEA2C91E0B}.Release|Win32.ActiveCfg = Release|Win32\r
-               {69BE42AB-E7CE-4DA1-BBD2-39FEA2C91E0B}.Release|Win32.Build.0 = Release|Win32\r
-               {0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD}.Debug|Win32.ActiveCfg = Debug|Win32\r
-               {0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD}.Debug|Win32.Build.0 = Debug|Win32\r
-               {0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD}.Release|Win32.ActiveCfg = Release|Win32\r
-               {0B1B7713-35B6-40A7-9BFF-A7D0EB06A8BD}.Release|Win32.Build.0 = Release|Win32\r
-       EndGlobalSection\r
-       GlobalSection(SolutionProperties) = preSolution\r
-               HideSolutionNode = FALSE\r
-       EndGlobalSection\r
-EndGlobal\r
diff --git a/mj2/mj2_to_metadata.vcproj b/mj2/mj2_to_metadata.vcproj
deleted file mode 100644 (file)
index 4207365..0000000
+++ /dev/null
@@ -1,349 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>\r
-<VisualStudioProject\r
-       ProjectType="Visual C++"\r
-       Version="8,00"\r
-       Name="mj2_to_metadata"\r
-       ProjectGUID="{69BE42AB-E7CE-4DA1-BBD2-39FEA2C91E0B}"\r
-       >\r
-       <Platforms>\r
-               <Platform\r
-                       Name="Win32"\r
-               />\r
-       </Platforms>\r
-       <ToolFiles>\r
-       </ToolFiles>\r
-       <Configurations>\r
-               <Configuration\r
-                       Name="Debug|Win32"\r
-                       OutputDirectory=".\mj2_to_metadata___Win32_Debug0"\r
-                       IntermediateDirectory=".\mj2_to_metadata___Win32_Debug0"\r
-                       ConfigurationType="1"\r
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"\r
-                       UseOfMFC="0"\r
-                       ATLMinimizesCRunTimeLibraryUsage="false"\r
-                       CharacterSet="2"\r
-                       >\r
-                       <Tool\r
-                               Name="VCPreBuildEventTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCCustomBuildTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCXMLDataGeneratorTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCWebServiceProxyGeneratorTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCMIDLTool"\r
-                               TypeLibraryName=".\mj2_to_metadata___Win32_Debug0/mj2_to_metadata.tlb"\r
-                               HeaderFileName=""\r
-                       />\r
-                       <Tool\r
-                               Name="VCCLCompilerTool"\r
-                               Optimization="0"\r
-                               AdditionalIncludeDirectories="../libopenjpeg"\r
-                               PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;OPJ_STATIC;_CRT_SECURE_NO_DEPRECATE"\r
-                               MinimalRebuild="true"\r
-                               BasicRuntimeChecks="3"\r
-                               RuntimeLibrary="1"\r
-                               PrecompiledHeaderFile=".\mj2_to_metadata___Win32_Debug0/mj2_to_metadata.pch"\r
-                               AssemblerListingLocation=".\mj2_to_metadata___Win32_Debug0/"\r
-                               ObjectFile=".\mj2_to_metadata___Win32_Debug0/"\r
-                               ProgramDataBaseFileName=".\mj2_to_metadata___Win32_Debug0/"\r
-                               BrowseInformation="1"\r
-                               WarningLevel="3"\r
-                               SuppressStartupBanner="true"\r
-                               DebugInformationFormat="4"\r
-                       />\r
-                       <Tool\r
-                               Name="VCManagedResourceCompilerTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCResourceCompilerTool"\r
-                               PreprocessorDefinitions="_DEBUG"\r
-                               Culture="2057"\r
-                       />\r
-                       <Tool\r
-                               Name="VCPreLinkEventTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCLinkerTool"\r
-                               OutputFile=".\mj2_to_metadata___Win32_Debug0/mj2_to_metadata.exe"\r
-                               LinkIncremental="2"\r
-                               SuppressStartupBanner="true"\r
-                               IgnoreDefaultLibraryNames="LIBCMT"\r
-                               GenerateDebugInformation="true"\r
-                               ProgramDatabaseFile=".\mj2_to_metadata___Win32_Debug0/mj2_to_metadata.pdb"\r
-                               SubSystem="1"\r
-                               TargetMachine="1"\r
-                       />\r
-                       <Tool\r
-                               Name="VCALinkTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCManifestTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCXDCMakeTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCBscMakeTool"\r
-                               SuppressStartupBanner="true"\r
-                               OutputFile=".\mj2_to_metadata___Win32_Debug0/mj2_to_metadata.bsc"\r
-                       />\r
-                       <Tool\r
-                               Name="VCFxCopTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCAppVerifierTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCWebDeploymentTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCPostBuildEventTool"\r
-                       />\r
-               </Configuration>\r
-               <Configuration\r
-                       Name="Release|Win32"\r
-                       OutputDirectory=".\Release"\r
-                       IntermediateDirectory=".\Release"\r
-                       ConfigurationType="1"\r
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"\r
-                       UseOfMFC="0"\r
-                       ATLMinimizesCRunTimeLibraryUsage="false"\r
-                       CharacterSet="2"\r
-                       >\r
-                       <Tool\r
-                               Name="VCPreBuildEventTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCCustomBuildTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCXMLDataGeneratorTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCWebServiceProxyGeneratorTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCMIDLTool"\r
-                               TypeLibraryName=".\Release/mj2_to_metadata.tlb"\r
-                               HeaderFileName=""\r
-                       />\r
-                       <Tool\r
-                               Name="VCCLCompilerTool"\r
-                               Optimization="2"\r
-                               InlineFunctionExpansion="1"\r
-                               AdditionalIncludeDirectories="../libopenjpeg"\r
-                               PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;OPJ_STATIC;_CRT_SECURE_NO_DEPRECATE"\r
-                               StringPooling="true"\r
-                               RuntimeLibrary="0"\r
-                               EnableFunctionLevelLinking="true"\r
-                               PrecompiledHeaderFile=".\Release/mj2_to_metadata.pch"\r
-                               AssemblerListingLocation=".\Release/"\r
-                               ObjectFile=".\Release/"\r
-                               ProgramDataBaseFileName=".\Release/"\r
-                               WarningLevel="3"\r
-                               SuppressStartupBanner="true"\r
-                       />\r
-                       <Tool\r
-                               Name="VCManagedResourceCompilerTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCResourceCompilerTool"\r
-                               PreprocessorDefinitions="NDEBUG"\r
-                               Culture="2057"\r
-                       />\r
-                       <Tool\r
-                               Name="VCPreLinkEventTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCLinkerTool"\r
-                               OutputFile=".\Release/mj2_to_metadata.exe"\r
-                               LinkIncremental="1"\r
-                               SuppressStartupBanner="true"\r
-                               IgnoreDefaultLibraryNames="libcmtd"\r
-                               ProgramDatabaseFile=".\Release/mj2_to_metadata.pdb"\r
-                               SubSystem="1"\r
-                               TargetMachine="1"\r
-                       />\r
-                       <Tool\r
-                               Name="VCALinkTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCManifestTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCXDCMakeTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCBscMakeTool"\r
-                               SuppressStartupBanner="true"\r
-                               OutputFile=".\Release/mj2_to_metadata.bsc"\r
-                       />\r
-                       <Tool\r
-                               Name="VCFxCopTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCAppVerifierTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCWebDeploymentTool"\r
-                       />\r
-                       <Tool\r
-                               Name="VCPostBuildEventTool"\r
-                       />\r
-               </Configuration>\r
-       </Configurations>\r
-       <References>\r
-       </References>\r
-       <Files>\r
-               <Filter\r
-                       Name="MJ2"\r
-                       >\r
-                       <Filter\r
-                               Name="MJ2 Header Files"\r
-                               >\r
-                               <File\r
-                                       RelativePath="compat\getopt.h"\r
-                                       >\r
-                               </File>\r
-                               <File\r
-                                       RelativePath="meta_out.h"\r
-                                       >\r
-                               </File>\r
-                               <File\r
-                                       RelativePath="mj2.h"\r
-                                       >\r
-                               </File>\r
-                               <File\r
-                                       RelativePath="mj2_convert.h"\r
-                                       >\r
-                               </File>\r
-                               <File\r
-                                       RelativePath="mj2_to_metadata.h"\r
-                                       >\r
-                               </File>\r
-                       </Filter>\r
-                       <Filter\r
-                               Name="MJ2 Source Files"\r
-                               >\r
-                               <File\r
-                                       RelativePath="compat\getopt.c"\r
-                                       >\r
-                                       <FileConfiguration\r
-                                               Name="Debug|Win32"\r
-                                               >\r
-                                               <Tool\r
-                                                       Name="VCCLCompilerTool"\r
-                                                       AdditionalIncludeDirectories=""\r
-                                                       PreprocessorDefinitions=""\r
-                                               />\r
-                                       </FileConfiguration>\r
-                                       <FileConfiguration\r
-                                               Name="Release|Win32"\r
-                                               >\r
-                                               <Tool\r
-                                                       Name="VCCLCompilerTool"\r
-                                                       AdditionalIncludeDirectories=""\r
-                                                       PreprocessorDefinitions=""\r
-                                               />\r
-                                       </FileConfiguration>\r
-                               </File>\r
-                               <File\r
-                                       RelativePath="meta_out.c"\r
-                                       >\r
-                                       <FileConfiguration\r
-                                               Name="Debug|Win32"\r
-                                               >\r
-                                               <Tool\r
-                                                       Name="VCCLCompilerTool"\r
-                                                       AdditionalIncludeDirectories=""\r
-                                                       PreprocessorDefinitions=""\r
-                                               />\r
-                                       </FileConfiguration>\r
-                                       <FileConfiguration\r
-                                               Name="Release|Win32"\r
-                                               >\r
-                                               <Tool\r
-                                                       Name="VCCLCompilerTool"\r
-                                                       AdditionalIncludeDirectories=""\r
-                                                       PreprocessorDefinitions=""\r
-                                               />\r
-                                       </FileConfiguration>\r
-                               </File>\r
-                               <File\r
-                                       RelativePath="mj2.c"\r
-                                       >\r
-                                       <FileConfiguration\r
-                                               Name="Debug|Win32"\r
-                                               >\r
-                                               <Tool\r
-                                                       Name="VCCLCompilerTool"\r
-                                                       AdditionalIncludeDirectories=""\r
-                                                       PreprocessorDefinitions=""\r
-                                               />\r
-                                       </FileConfiguration>\r
-                                       <FileConfiguration\r
-                                               Name="Release|Win32"\r
-                                               >\r
-                                               <Tool\r
-                                                       Name="VCCLCompilerTool"\r
-                                                       AdditionalIncludeDirectories=""\r
-                                                       PreprocessorDefinitions=""\r
-                                               />\r
-                                       </FileConfiguration>\r
-                               </File>\r
-                               <File\r
-                                       RelativePath="mj2_convert.c"\r
-                                       >\r
-                                       <FileConfiguration\r
-                                               Name="Debug|Win32"\r
-                                               >\r
-                                               <Tool\r
-                                                       Name="VCCLCompilerTool"\r
-                                                       AdditionalIncludeDirectories=""\r
-                                                       PreprocessorDefinitions=""\r
-                                               />\r
-                                       </FileConfiguration>\r
-                                       <FileConfiguration\r
-                                               Name="Release|Win32"\r
-                                               >\r
-                                               <Tool\r
-                                                       Name="VCCLCompilerTool"\r
-                                                       AdditionalIncludeDirectories=""\r
-                                                       PreprocessorDefinitions=""\r
-                                               />\r
-                                       </FileConfiguration>\r
-                               </File>\r
-                               <File\r
-                                       RelativePath="mj2_to_metadata.c"\r
-                                       >\r
-                                       <FileConfiguration\r
-                                               Name="Debug|Win32"\r
-                                               >\r
-                                               <Tool\r
-                                                       Name="VCCLCompilerTool"\r
-                                                       AdditionalIncludeDirectories=""\r
-                                                       PreprocessorDefinitions=""\r
-                                               />\r
-                                       </FileConfiguration>\r
-                                       <FileConfiguration\r
-                                               Name="Release|Win32"\r
-                                               >\r
-                                               <Tool\r
-                                                       Name="VCCLCompilerTool"\r
-                                                       AdditionalIncludeDirectories=""\r
-                                                       PreprocessorDefinitions=""\r
-                                               />\r
-                                       </FileConfiguration>\r
-                               </File>\r
-                       </Filter>\r
-               </Filter>\r
-       </Files>\r
-       <Globals>\r
-       </Globals>\r
-</VisualStudioProject>\r
diff --git a/mj2/mj2_to_metadata_Notes.doc b/mj2/mj2_to_metadata_Notes.doc
deleted file mode 100644 (file)
index 05ccec2..0000000
Binary files a/mj2/mj2_to_metadata_Notes.doc and /dev/null differ
diff --git a/mj2/readme.txt b/mj2/readme.txt
deleted file mode 100644 (file)
index 9419d2a..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-Attention : the motion jpeg 2000 files currently only work with OpenJPEG v0.97 that you can find here : 
-
-http://www.openjpeg.org/openjpeg_v097.tar.gz
\ No newline at end of file
diff --git a/mj2/wrap_j2k_in_mj2.c b/mj2/wrap_j2k_in_mj2.c
deleted file mode 100644 (file)
index 7766dd3..0000000
+++ /dev/null
@@ -1,516 +0,0 @@
-/*
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
- * Copyright (c) 2002-2007, Professor Benoit Macq
- * Copyright (c) 2003-2007, Francois-Olivier Devaux 
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "openjpeg.h"
-#include "../libopenjpeg/j2k.h"
-#include "../libopenjpeg/jp2.h"
-#include "../libopenjpeg/cio.h"
-#include "mj2.h"
-
-static int int_ceildiv(int a, int b) {
-       return (a + b - 1) / b;
-}
-
-/**
-Size of memory first allocated for MOOV box
-*/
-#define TEMP_BUF 10000 
-
-#define ENUMCS_GRAY 16
-#define ENUMCS_SRGB 17
-#define ENUMCS_SYCC 18
-
-#define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51"
-
-/* -------------------------------------------------------------------------- */
-
-static int test_image(const char *fname, mj2_cparameters_t *cp)
-{
-       FILE *reader;
-       opj_image_t *image;
-       unsigned char *src;
-       opj_dinfo_t *dinfo;
-       opj_cio_t *cio;
-       opj_dparameters_t dparameters;
-       int success;
-       long src_len;
-
-       success = 0;
-
-       if((reader = fopen(fname, "rb")) == NULL) return success;
-
-       fseek(reader, 0, SEEK_END);
-       src_len = ftell(reader);
-       fseek(reader, 0, SEEK_SET);
-       src = (unsigned char*) malloc(src_len);
-       fread(src, 1, src_len, reader);
-       fclose(reader);
-
-       if(memcmp(src, J2K_CODESTREAM_MAGIC, 4) != 0)
-   {
-       free(src); return success;
-   }
-       memset(&dparameters, 0, sizeof(opj_dparameters_t));
-
-       opj_set_default_decoder_parameters(&dparameters);
-
-       dinfo = opj_create_decompress(CODEC_J2K);
-
-       opj_setup_decoder(dinfo, &dparameters);
-
-       cio = opj_cio_open((opj_common_ptr)dinfo, src, src_len);
-
-       image = opj_decode(dinfo, cio);
-
-       free(src); cio->buffer = NULL;
-       opj_cio_close(cio);
-
-       if(image == NULL) goto fin;
-
-       cp->numcomps = image->numcomps;
-       cp->w = image->comps[0].w;
-       cp->h = image->comps[0].h;
-       cp->prec = image->comps[0].prec;
-
-       if(image->numcomps > 2 )
-   {
-       if((image->comps[0].dx == 1)
-       && (image->comps[1].dx == 2)
-       && (image->comps[2].dx == 2)
-       && (image->comps[0].dy == 1)
-       && (image->comps[1].dy == 2)
-       && (image->comps[2].dy == 2))// horizontal and vertical
-  {
-//   Y420
-       cp->enumcs = ENUMCS_SYCC;
-       cp->CbCr_subsampling_dx = 2;
-       cp->CbCr_subsampling_dy = 2;
-  }
-       else
-       if((image->comps[0].dx == 1)
-       && (image->comps[1].dx == 2)
-       && (image->comps[2].dx == 2)
-       && (image->comps[0].dy == 1)
-       && (image->comps[1].dy == 1)
-       && (image->comps[2].dy == 1))// horizontal only
-  {
-//   Y422
-       cp->enumcs = ENUMCS_SYCC;
-       cp->CbCr_subsampling_dx = 2;
-       cp->CbCr_subsampling_dy = 1;
-  }
-       else
-       if((image->comps[0].dx == 1)
-       && (image->comps[1].dx == 1)
-       && (image->comps[2].dx == 1)
-       && (image->comps[0].dy == 1)
-       && (image->comps[1].dy == 1)
-       && (image->comps[2].dy == 1))
-  {
-//   Y444 or RGB
-
-       if(image->color_space ==  CLRSPC_SRGB)
- {
-       cp->enumcs = ENUMCS_SRGB;
-
-//    cp->CbCr_subsampling_dx = 0;
-//    cp->CbCr_subsampling_dy = 0;
- }
-       else
- {
-       cp->enumcs = ENUMCS_SYCC;
-
-       cp->CbCr_subsampling_dx = 1;
-       cp->CbCr_subsampling_dy = 1;
- }
-  }
-       else
-  {
-       goto fin;
-  }
-   }
-       else
-   {
-       cp->enumcs = ENUMCS_GRAY;
-//  cp->CbCr_subsampling_dx = 0;
-//  cp->CbCr_subsampling_dy = 0;
-   }
-       if(image->icc_profile_buf)
-   {
-       cp->meth = 2;
-       free(image->icc_profile_buf); image->icc_profile_buf = NULL;
-   }
-       else cp->meth = 1;
-
-       success = 1;
-fin:
-       if(dinfo)
-        opj_destroy_decompress(dinfo);
-
-       if(image)
-        opj_image_destroy(image);
-
-       return success;
-}
-
-/**
-sample error callback expecting a FILE* client object
-*/
-void error_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[ERROR] %s", msg);
-}
-/**
-sample warning callback expecting a FILE* client object
-*/
-void warning_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[WARNING] %s", msg);
-}
-/**
-sample debug callback expecting a FILE* client object
-*/
-void info_callback(const char *msg, void *client_data) {
-       FILE *stream = (FILE*)client_data;
-       fprintf(stream, "[INFO] %s", msg);
-}
-
-/* -------------------------------------------------------------------------- */
-
-
-
-static void read_siz_marker(FILE *file, opj_image_t *image)
-{
-  int len,i;
-  char buf, buf2[2];
-  unsigned char *siz_buffer;
-       opj_cio_t *cio;
-  
-  fseek(file, 0, SEEK_SET);
-  do {
-    fread(&buf,1,1, file);
-    if (buf==(char)0xff)
-      fread(&buf,1,1, file);
-  }
-  while (!(buf==(char)0x51));
-  
-  fread(buf2,2,1,file);                /* Lsiz                */
-  len = ((buf2[0])<<8) + buf2[1];
-  
-  siz_buffer = (unsigned char*) malloc(len * sizeof(unsigned char));
-  fread(siz_buffer,len, 1, file);
-       cio = opj_cio_open(NULL, siz_buffer, len);
-  
-  cio_read(cio, 2);                    /* Rsiz (capabilities) */
-  image->x1 = cio_read(cio, 4);        /* Xsiz                */
-  image->y1 = cio_read(cio, 4);        /* Ysiz                */
-  image->x0 = cio_read(cio, 4);        /* X0siz               */
-  image->y0 = cio_read(cio, 4);        /* Y0siz               */
-  cio_skip(cio, 16);                   /* XTsiz, YTsiz, XT0siz, YT0siz        */
-  
-  image->numcomps = cio_read(cio,2);   /* Csiz                */
-  image->comps =
-    (opj_image_comp_t *) malloc(image->numcomps * sizeof(opj_image_comp_t));
-       
-  for (i = 0; i < image->numcomps; i++) {
-    int tmp;
-    tmp = cio_read(cio,1);             /* Ssiz_i          */
-    image->comps[i].prec = (tmp & 0x7f) + 1;
-    image->comps[i].sgnd = tmp >> 7;
-    image->comps[i].dx = cio_read(cio,1);      /* XRsiz_i         */
-    image->comps[i].dy = cio_read(cio,1);      /* YRsiz_i         */
-    image->comps[i].resno_decoded = 0; /* number of resolution decoded */
-    image->comps[i].factor = 0;        /* reducing factor by component */
-  }
-  fseek(file, 0, SEEK_SET);
-       opj_cio_close(cio);
-  free(siz_buffer);
-}
-
-static void setparams(opj_mj2_t *movie, opj_image_t *image) {
-  int i, depth_0, depth, sign;
-  
-  movie->tk[0].w = int_ceildiv(image->x1 - image->x0, image->comps[0].dx);
-  movie->tk[0].h = int_ceildiv(image->y1 - image->y0, image->comps[0].dy);
-  mj2_init_stdmovie(movie);
-  
-  movie->tk[0].depth = image->comps[0].prec;
-       
-  if (image->numcomps==3) {
-    if ((image->comps[0].dx == 1) 
-       && (image->comps[1].dx == 1) 
-       && (image->comps[2].dx == 1)) 
-      movie->tk[0].CbCr_subsampling_dx = 1;
-    else 
-       if ((image->comps[0].dx == 1) 
-       && (image->comps[1].dx == 2) 
-       && (image->comps[2].dx == 2))
-      movie->tk[0].CbCr_subsampling_dx = 2;
-    else
-      fprintf(stderr,"Image component sizes are incoherent\n");
-    
-    if ((image->comps[0].dy == 1) 
-       && (image->comps[1].dy == 1) 
-       && (image->comps[2].dy == 1)) 
-      movie->tk[0].CbCr_subsampling_dy = 1;
-    else 
-       if ((image->comps[0].dy == 1) 
-       && (image->comps[1].dy == 2) 
-       && (image->comps[2].dy == 2))
-      movie->tk[0].CbCr_subsampling_dy = 2;
-    else
-      fprintf(stderr,"Image component sizes are incoherent\n");
-  }
-  
-  movie->tk[0].sample_rate = 25;
-  
-  movie->tk[0].jp2_struct.numcomps = image->numcomps;  // NC  
-       
-       /* Init Standard jp2 structure */
-       
-       movie->tk[0].jp2_struct.comps =
-    (opj_jp2_comps_t *) malloc(movie->tk[0].jp2_struct.numcomps * sizeof(opj_jp2_comps_t));
-  movie->tk[0].jp2_struct.precedence = 0;   /* PRECEDENCE*/
-  movie->tk[0].jp2_struct.approx = 0;   /* APPROX*/
-  movie->tk[0].jp2_struct.brand = JP2_JP2;     /* BR         */
-  movie->tk[0].jp2_struct.minversion = 0;      /* MinV       */
-  movie->tk[0].jp2_struct.numcl = 1;
-  movie->tk[0].jp2_struct.cl = (unsigned int *) malloc(movie->tk[0].jp2_struct.numcl * sizeof(int));
-  movie->tk[0].jp2_struct.cl[0] = JP2_JP2;     /* CL0 : JP2  */
-  movie->tk[0].jp2_struct.C = 7;      /* C : Always 7*/
-  movie->tk[0].jp2_struct.UnkC = 0;      /* UnkC, colorspace specified in colr box*/
-  movie->tk[0].jp2_struct.IPR = 0;      /* IPR, no intellectual property*/
-  movie->tk[0].jp2_struct.w = int_ceildiv(image->x1 - image->x0, image->comps[0].dx);
-  movie->tk[0].jp2_struct.h = int_ceildiv(image->y1 - image->y0, image->comps[0].dy);
-  
-  depth_0 = image->comps[0].prec - 1;
-  sign = image->comps[0].sgnd;
-  movie->tk[0].jp2_struct.bpc = depth_0 + (sign << 7);
-  
-  for (i = 1; i < image->numcomps; i++) {
-    depth = image->comps[i].prec - 1;
-    sign = image->comps[i].sgnd;
-    if (depth_0 != depth)
-      movie->tk[0].jp2_struct.bpc = 255;
-  }
-  
-  for (i = 0; i < image->numcomps; i++)
-    movie->tk[0].jp2_struct.comps[i].bpcc =
-    image->comps[i].prec - 1 + (image->comps[i].sgnd << 7);
-  
-  if ((image->numcomps == 1 || image->numcomps == 3)
-    && (movie->tk[0].jp2_struct.bpc != 255))
-    movie->tk[0].jp2_struct.meth = 1;
-  else
-    movie->tk[0].jp2_struct.meth = 2;
-       
-    if (image->numcomps == 1)
-     movie->tk[0].jp2_struct.enumcs = 17;  // Grayscale
-  
-    else   
-       if ((image->comps[0].dx == 1) 
-       && (image->comps[1].dx == 1) 
-       && (image->comps[2].dx == 1) 
-    && (image->comps[0].dy == 1) 
-       && (image->comps[1].dy == 1) 
-       && (image->comps[2].dy == 1)) 
-     movie->tk[0].jp2_struct.enumcs = 16;    // RGB
-  
-    else   
-       if ((image->comps[0].dx == 1) 
-       && (image->comps[1].dx == 2) 
-       && (image->comps[2].dx == 2) 
-    && (image->comps[0].dy == 1) 
-       && (image->comps[1].dy == 2) 
-       && (image->comps[2].dy == 2)) 
-     movie->tk[0].jp2_struct.enumcs = 18;  // YUV
-  
-  else
-    movie->tk[0].jp2_struct.enumcs = 0;        // Unkown profile */
-}
-
-int main(int argc, char *argv[]) {
-       opj_cinfo_t* cinfo; 
-       opj_event_mgr_t event_mgr;              /* event manager */  
-  unsigned int snum;
-  opj_mj2_t *movie;
-  mj2_sample_t *sample;
-  unsigned char* frame_codestream;
-  FILE *mj2file, *j2kfile;
-  char *j2kfilename;
-  unsigned char *buf;
-  int offset, mdat_initpos;
-  opj_image_t img;
-       opj_cio_t *cio;
-       mj2_cparameters_t parameters;
-       
-  if (argc != 3) {
-    printf("Usage: %s source_location mj2_filename\n",argv[0]);
-    printf("Example: %s input/input output.mj2\n",argv[0]);
-    return 1;
-  }
-  
-  mj2file = fopen(argv[2], "wb");
-  
-  if (!mj2file) {
-    fprintf(stderr, "failed to open %s for writing\n", argv[2]);
-    return 1;
-  }
-       memset(&img, 0, sizeof(opj_image_t));
-       /*
-       configure the event callbacks (not required)
-       setting of each callback is optionnal
-       */
-       memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
-       event_mgr.error_handler = error_callback;
-       event_mgr.warning_handler = warning_callback;
-       event_mgr.info_handler = info_callback;
-
-       /* get a MJ2 decompressor handle */
-       cinfo = mj2_create_compress();
-
-       /* catch events using our callbacks and give a local context */
-       opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);   
-       
-       /* setup the decoder encoding parameters using user parameters */
-       memset(&parameters, 0, sizeof(mj2_cparameters_t));
-       movie = (opj_mj2_t*) cinfo->mj2_handle;
-
-       j2kfilename = (char*)malloc(strlen(argv[1]) + 12);/* max. '%6d' */
-       sprintf(j2kfilename, "%s_00001.j2k",argv[1]);
-
-       if(test_image(j2kfilename, &parameters) == 0) goto fin;
-
-       parameters.frame_rate = 25; /* DEFAULT */
-
-       mj2_setup_encoder(movie, &parameters);
-
-  
-       /* Writing JP, FTYP and MDAT boxes 
-       Assuming that the JP and FTYP boxes won't be longer than 300 bytes */
-       
-  buf = (unsigned char*) malloc (300 * sizeof(unsigned char)); 
-  cio = opj_cio_open(movie->cinfo, buf, 300);
-  mj2_write_jp(cio);
-  mj2_write_ftyp(movie, cio);
-  mdat_initpos = cio_tell(cio);
-  cio_skip(cio, 4);
-  cio_write(cio,MJ2_MDAT, 4);  
-  fwrite(buf,cio_tell(cio),1,mj2file);
-  free(buf);
-       
-  // Insert each j2k codestream in a JP2C box  
-  snum=0;
-  offset = 0;  
-  while(1)
-  {
-    sample = &movie->tk[0].sample[snum];
-    sprintf(j2kfilename,"%s_%05d.j2k",argv[1],snum);
-    j2kfile = fopen(j2kfilename, "rb");
-    if (!j2kfile) {
-      if (snum==0) {  // Could not open a single codestream
-                               fprintf(stderr, "failed to open %s for reading\n",j2kfilename);
-                               return 1;
-      }
-      else {         // Tried to open a inexistant codestream
-                               fprintf(stdout,"%d frames are being added to the MJ2 file\n",snum);
-                               break;
-      }
-    }
-
-    // Calculating offset for samples and chunks
-    offset += cio_tell(cio);     
-    sample->offset = offset;
-    movie->tk[0].chunk[snum].offset = offset;  // There will be one sample per chunk
-    
-    // Calculating sample size
-    fseek(j2kfile,0,SEEK_END); 
-    sample->sample_size = ftell(j2kfile) + 8; // Sample size is codestream + JP2C box header
-    fseek(j2kfile,0,SEEK_SET);
-    
-    // Reading siz marker of j2k image for the first codestream
-    if (snum==0)             
-      read_siz_marker(j2kfile, &img);
-    
-    // Writing JP2C box header                     
-    frame_codestream = (unsigned char*) malloc (sample->sample_size+8); 
-               cio = opj_cio_open(movie->cinfo, frame_codestream, sample->sample_size);    
-    cio_write(cio,sample->sample_size, 4);  // Sample size
-    cio_write(cio,JP2_JP2C, 4);        // JP2C
-    
-    // Writing codestream from J2K file to MJ2 file
-    fread(frame_codestream+8,sample->sample_size-8,1,j2kfile);
-    fwrite(frame_codestream,sample->sample_size,1,mj2file);
-    cio_skip(cio, sample->sample_size-8);
-    
-    // Ending loop
-    fclose(j2kfile);
-    snum++;
-    movie->tk[0].sample = (mj2_sample_t*)
-               realloc(movie->tk[0].sample, (snum+1) * sizeof(mj2_sample_t));
-    movie->tk[0].chunk = (mj2_chunk_t*)
-               realloc(movie->tk[0].chunk, (snum+1) * sizeof(mj2_chunk_t));
-    free(frame_codestream);
-  }
-  
-  // Writing the MDAT box length in header
-  offset += cio_tell(cio);
-  buf = (unsigned char*) malloc (4 * sizeof(unsigned char));
-       cio = opj_cio_open(movie->cinfo, buf, 4);
-  cio_write(cio,offset-mdat_initpos,4); 
-  fseek(mj2file,(long)mdat_initpos,SEEK_SET);
-  fwrite(buf,4,1,mj2file);
-  fseek(mj2file,0,SEEK_END);
-  free(buf);
-       
-  // Setting movie parameters
-  movie->tk[0].num_samples=snum;
-  movie->tk[0].num_chunks=snum;
-  setparams(movie, &img);
-       
-  // Writing MOOV box 
-       buf = (unsigned char*) malloc ((TEMP_BUF+snum*20) * sizeof(unsigned char));
-       cio = opj_cio_open(movie->cinfo, buf, (TEMP_BUF+snum*20));
-       mj2_write_moov(movie, cio);
-  fwrite(buf,cio_tell(cio),1,mj2file);
-       
-  // Ending program
-  free(img.comps);
-  opj_cio_close(cio);
-
-fin:
-  fclose(mj2file);
-  mj2_destroy_compress(movie);
-  free(j2kfilename);
-
-  return 0;
-}
diff --git a/testing/Makefile b/testing/Makefile
new file mode 100644 (file)
index 0000000..c5434f0
--- /dev/null
@@ -0,0 +1,2 @@
+OPJ_Validate_Makee: OPJ_Validate.c md5.c 
+       gcc -o OPJ_Validate OPJ_Validate.c md5.c  -I.
diff --git a/testing/OPJ_Param_File_v0_1.txt b/testing/OPJ_Param_File_v0_1.txt
new file mode 100644 (file)
index 0000000..881c92d
--- /dev/null
@@ -0,0 +1,100 @@
+#Version 0.1 - February 9th 2007\r
+#Usage: OPJ_Validate OpenJPEG_command_line\r
+#Example: OPJ_Validate image_to_j2k.exe -i original/Bretagne1.ppm -o original/Bretagne1.j2k -r 200, 50, 10\r
+#Attention: don't forget the *.exe extension for the executable file, and check the paths\r
+\r
+image_to_j2k.exe -i original/Bretagne1.ppm -o temp/Bretagne1_0.j2k -r 200,50,10\r
+j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1.ppm\r
+image_to_j2k.exe -i original/Bretagne2.ppm -o temp/Bretagne2_0.j2k -c [128,128],[128,128],[128,128] -r 100,20,2 -t 640,480 -b 32,32\r
+j2k_to_image.exe -i original/Bretagne2.j2k -o temp/Bretagne2.ppm -r 2\r
+image_to_j2k.exe -i original/Cevennes1.bmp -o temp/Cevennes1.j2k -r 10\r
+j2k_to_image.exe -i original/Cevennes1.j2k -o temp/Cevennes1.bmp -l 2\r
+image_to_j2k.exe -i original/Cevennes2.ppm -o temp/Cevennes2.jp2 -r 50\r
+j2k_to_image.exe -i original/Cevennes2.jp2 -o temp/Cevennes2.ppm\r
+image_to_j2k.exe -i original/Rome.bmp -o temp/Rome.jp2 -q 30,35,50 -p LRCP -n 3\r
+j2k_to_image.exe -i original/Rome.jp2 -o temp/Rome.ppm\r
+image_to_j2k.exe -i original/Bretagne1.ppm -o temp/Bretagne1_1.j2k -q 30,35,40 -n 2\r
+image_to_j2k.exe -i original/Bretagne1.ppm -o temp/Bretagne1_2.j2k -q 30,35,40 -b 16,16 -c [101,101]\r
+image_to_j2k.exe -i original/Bretagne2.ppm -o temp/Bretagne2_1.j2k -t 127,127 -p PCRL\r
+image_to_j2k.exe -i original/X_4_2K_24_185_CBR_WB_000.tif -o temp/X_4_2K_24_185_CBR_WB_000.j2k -cinema2K 24\r
+image_to_j2k.exe -i original/X_5_2K_24_235_CBR_STEM24_000.tif -o temp/X_5_2K_24_235_CBR_STEM24_000.j2k -cinema2K 48\r
+image_to_j2k.exe -i original/X_6_2K_24_FULL_CBR_CIRCLE_000.tif -o temp/X_6_2K_24_FULL_CBR_CIRCLE_000.j2k -cinema2K 24\r
+#� remettre\r
+#image_to_j2k.exe -i original/X_16_4K_24_185_CBR_WB_000.tif -o temp/X_16_4K_24_185_CBR_WB_000.j2k -cinema4K\r
+j2k_to_image.exe -i original/A_4_2K_24_185_CBR_WB_000.j2k -o temp/A_4_2K_24_185_CBR_WB_000.tif\r
+j2k_to_image.exe -i original/B_5_2K_24_235_CBR_STEM24_000.j2k -o temp/B_5_2K_24_235_CBR_STEM24_000.tif\r
+j2k_to_image.exe -i original/C_6_2K_24_FULL_CBR_CIRCLE_000.j2k -o temp/C_6_2K_24_FULL_CBR_CIRCLE_000.tif\r
+#� remettre\r
+#j2k_to_image.exe -i original/C_18_4K_24_FULL_CBR_CIRCLE_000.j2k -o temp/C_18_4K_24_FULL_CBR_CIRCLE_000.tif\r
+j2k_to_image.exe -i original/p0_01.j2k -o temp/p0_01.tif\r
+j2k_to_image.exe -i original/p0_02.j2k -o temp/p0_02.tif\r
+j2k_to_image.exe -i original/p0_03.j2k -o temp/p0_03.tif\r
+j2k_to_image.exe -i original/p0_04.j2k -o temp/p0_04.tif\r
+#� remettre\r
+#j2k_to_image.exe -i original/p0_07.j2k -o temp/p0_07.tif\r
+j2k_to_image.exe -i original/p0_08.j2k -o temp/p0_08.tif\r
+j2k_to_image.exe -i original/p0_09.j2k -o temp/p0_09.tif\r
+j2k_to_image.exe -i original/p0_10.j2k -o temp/p0_10.tif\r
+j2k_to_image.exe -i original/p0_11.j2k -o temp/p0_11.tif\r
+j2k_to_image.exe -i original/p0_12.j2k -o temp/p0_12.tif\r
+j2k_to_image.exe -i original/p0_14.j2k -o temp/p0_14.tif\r
+j2k_to_image.exe -i original/p0_15.j2k -o temp/p0_15.tif\r
+j2k_to_image.exe -i original/p0_16.j2k -o temp/p0_16.tif\r
+j2k_to_image.exe -i original/p1_01.j2k -o temp/p1_01.tif\r
+j2k_to_image.exe -i original/p1_02.j2k -o temp/p1_02.tif\r
+j2k_to_image.exe -i original/p1_04.j2k -o temp/p1_04.tif\r
+j2k_to_image.exe -i original/p1_05.j2k -o temp/p1_05.tif\r
+j2k_to_image.exe -i original/p1_06.j2k -o temp/p1_06.tif\r
+image_to_j2k.exe -i original/c0p0_01.pgx -o temp/c0p0_01.j2k\r
+image_to_j2k.exe -i original/c0p0_02.pgx -o temp/c0p0_02.j2k\r
+image_to_j2k.exe -i original/c0p0_03r0.pgx -o temp/c0p0_03r0.j2k\r
+image_to_j2k.exe -i original/c0p0_03r1.pgx -o temp/c0p0_03r1.j2k\r
+image_to_j2k.exe -i original/c0p0_04.pgx -o temp/c00_p04.j2k\r
+image_to_j2k.exe -i original/c0p0_05.pgx -o temp/c0p0_05.j2k\r
+image_to_j2k.exe -i original/c0p0_06.pgx -o temp/c0p0_06.j2k\r
+image_to_j2k.exe -i original/c0p0_07.pgx -o temp/c0p0_07.j2k\r
+image_to_j2k.exe -i original/c0p0_08.pgx -o temp/c0p0_08.j2k\r
+image_to_j2k.exe -i original/c0p0_09.pgx -o temp/c0p0_09.j2k\r
+image_to_j2k.exe -i original/c0p0_10.pgx -o temp/c0p0_10.j2k\r
+image_to_j2k.exe -i original/c0p0_11.pgx -o temp/c0p0_11.j2k\r
+image_to_j2k.exe -i original/c0p0_12.pgx -o temp/c0p0_12.j2k\r
+image_to_j2k.exe -i original/c0p0_13.pgx -o temp/c0p0_13.j2k\r
+image_to_j2k.exe -i original/c0p0_14.pgx -o temp/c0p0_14.j2k\r
+image_to_j2k.exe -i original/c0p0_15r0.pgx -o temp/c0p0_15r0.j2k\r
+image_to_j2k.exe -i original/c0p0_15r1.pgx -o temp/c0p0_15r1.j2k\r
+image_to_j2k.exe -i original/c0p0_16.pgx -o temp/c0p0_16.j2k\r
+image_to_j2k.exe -i original/c0p1_04r0.pgx -o temp/c0p1_04r0.j2k\r
+image_to_j2k.exe -i original/c0p1_05.pgx -o temp/c0p1_05.j2k\r
+image_to_j2k.exe -i original/c1p0_01_0.pgx -o temp/c1p0_01_0.j2k\r
+image_to_j2k.exe -i original/c1p0_02_0.pgx -o temp/c1p0_02_0.j2k\r
+image_to_j2k.exe -i original/c1p0_03_0.pgx -o temp/c1p0_03_0.j2k\r
+image_to_j2k.exe -i original/c1p0_04_0.pgx -o temp/c1p0_04_0.j2k\r
+image_to_j2k.exe -i original/c1p0_05_0.pgx -o temp/c1p0_05_0.j2k\r
+image_to_j2k.exe -i original/c1p0_06_0.pgx -o temp/c1p0_06_0.j2k\r
+image_to_j2k.exe -i original/c1p0_07_0.pgx -o temp/c1p0_07_0.j2k\r
+image_to_j2k.exe -i original/c1p0_08_0.pgx -o temp/c1p0_08_0.j2k\r
+image_to_j2k.exe -i original/c1p0_09_0.pgx -o temp/c1p0_09_0.j2k\r
+image_to_j2k.exe -i original/c1p0_10_0.pgx -o temp/c1p0_10_0.j2k\r
+image_to_j2k.exe -i original/c1p0_11_0.pgx -o temp/c1p0_11_0.j2k\r
+image_to_j2k.exe -i original/c1p0_12_0.pgx -o temp/c1p0_12_0.j2k\r
+image_to_j2k.exe -i original/c1p0_13_0.pgx -o temp/c1p0_13_0.j2k\r
+image_to_j2k.exe -i original/c1p0_14_0.pgx -o temp/c1p0_14_0.j2k\r
+image_to_j2k.exe -i original/c1p0_15_0.pgx -o temp/c1p0_15_0.j2k\r
+image_to_j2k.exe -i original/c1p0_16_0.pgx -o temp/c1p0_16_0.j2k\r
+image_to_j2k.exe -i original/c1p1_02_0.pgx -o temp/c1p1_02_0.j2k\r
+image_to_j2k.exe -i original/c1p1_05_0.pgx -o temp/c1p1_05_0.j2k\r
+image_to_j2k.exe -i original/Bretagne2.ppm -o temp/Bretagne2_2.j2k -s 2,2 -SOP\r
+image_to_j2k.exe -i original/Bretagne2.ppm -o temp/Bretagne2_3.j2k -EPH -M 38\r
+image_to_j2k.exe -i original/Bretagne2.ppm -o temp/Bretagne2_4.j2k -d 150,300 -r 800\r
+j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1.bmp\r
+j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1r2.bmp -r 2\r
+j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1.tga\r
+j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1r2.tga -r 2\r
+j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1.pnm\r
+j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1r2.pnm -r 2\r
+j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1r2.ppm -r 2\r
+j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1.raw\r
+j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1r2.raw -r 2\r
+j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1.tif\r
+j2k_to_image.exe -i original/Bretagne1.j2k -o temp/Bretagne1r2.tif -r 2\r
+j2k_to_image.exe -i original/p0_03.j2k -o p0_03.pgx\r
diff --git a/testing/OPJ_Validate.c b/testing/OPJ_Validate.c
new file mode 100644 (file)
index 0000000..9bd1da5
--- /dev/null
@@ -0,0 +1,244 @@
+/*\r
+* Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium\r
+* Copyright (c) 2002-2007, Professor Benoit Macq\r
+* Copyright (c) 2003-2007, Francois-Olivier Devaux \r
+* All rights reserved.\r
+*\r
+* Redistribution and use in source and binary forms, with or without\r
+* modification, are permitted provided that the following conditions\r
+* are met:\r
+* 1. Redistributions of source code must retain the above copyright\r
+*    notice, this list of conditions and the following disclaimer.\r
+* 2. Redistributions in binary form must reproduce the above copyright\r
+*    notice, this list of conditions and the following disclaimer in the\r
+*    documentation and/or other materials provided with the distribution.\r
+*\r
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'\r
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\r
+* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+* POSSIBILITY OF SUCH DAMAGE.\r
+*/\r
+\r
+#ifdef _WIN32\r
+#include <windows.h>\r
+#endif /* _WIN32 */\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include "md5.h"\r
+\r
+#define OPJ_Bin_Dir "OPJ_Binaries"\r
+\r
+int doprocess(char programme[4096],char command_line[4096]) {\r
+\r
+#ifdef _WIN32\r
+       \r
+       int exit=STILL_ACTIVE;\r
+       STARTUPINFO siStartupInfo;\r
+       PROCESS_INFORMATION piProcessInfo;\r
+       \r
+       memset(&siStartupInfo, 0, sizeof(siStartupInfo));\r
+       memset(&piProcessInfo, 0, sizeof(piProcessInfo));\r
+       siStartupInfo.cb = sizeof(siStartupInfo);\r
+       \r
+       if(CreateProcess(programme, // Application name\r
+               command_line, // Application arguments\r
+               0,\r
+               0,\r
+               FALSE,\r
+               CREATE_DEFAULT_ERROR_MODE,\r
+               0,\r
+               0, // Working directory\r
+               &siStartupInfo,\r
+               &piProcessInfo) == FALSE)       \r
+               return 1;\r
+       \r
+       exit=STILL_ACTIVE;\r
+       while(exit==STILL_ACTIVE) {\r
+               Sleep(1000);\r
+               GetExitCodeProcess(piProcessInfo.hProcess,&exit);\r
+       }\r
+       \r
+       return 0;\r
+\r
+#else /* !_WIN32 */\r
+       printf("\n%s\n", command_line);\r
+       system(command_line);\r
+       return 0;\r
+\r
+#endif /* _WIN32 */\r
+       \r
+}\r
+\r
+char MD5_process(char *input_filename, char *md5_filename) {\r
+       MD5_CTX mdContext;\r
+       int bytes;\r
+  unsigned char data[1024];\r
+       FILE *input_file, *md5_file;\r
+       \r
+       input_file = fopen(input_filename, "rb");\r
+       if (!input_file) {\r
+               printf("Error opening file %s\n", input_filename);\r
+               return 1;\r
+       }\r
+       \r
+       md5_file = fopen(md5_filename, "wb");\r
+       if (!md5_file) {\r
+               printf("Error opening file %s\n", md5_filename);\r
+               return 1;\r
+       }\r
+       \r
+       MD5Init (&mdContext);\r
+  while ((bytes = fread (data, 1, 1024, input_file)) != 0)\r
+    MD5Update (&mdContext, data, bytes);\r
+  MD5Final (&mdContext);\r
+       \r
+       fwrite(mdContext.digest,16,1,md5_file);\r
+       \r
+       fclose(input_file);\r
+       fclose(md5_file);\r
+       \r
+       return 0;\r
+}\r
+\r
+char fcompare(char *input_filename, char *output_filename) {\r
+       FILE *input_file, *output_file;\r
+       unsigned char input_buffer[17], output_buffer[17];\r
+       char comparison;\r
+       \r
+       input_file = fopen(input_filename, "rb");\r
+       if (!input_file) {\r
+               printf("Error opening file %s\n", input_filename);\r
+               return -1;\r
+       }\r
+       \r
+       output_file = fopen(output_filename, "rb");\r
+       if (!output_file) {\r
+               printf("Error opening file %s\n", output_filename);\r
+               return -1;\r
+       }\r
+       \r
+       fread(input_buffer,16,1,input_file);\r
+       fread(output_buffer,16,1,output_file);\r
+       fclose(input_file);\r
+       fclose(output_file);\r
+       input_buffer[16] = 0;\r
+       output_buffer[16] = 0;\r
+       \r
+       comparison = strcmp(input_buffer, output_buffer);\r
+       \r
+       if (comparison)\r
+               return 1;\r
+       return 0;\r
+}\r
+\r
+int main(int argc, char* argv[]) {\r
+       FILE *param_file, *md5_file;\r
+       FILE *report_file;\r
+       char line[4096];\r
+       char md5_filename[4096], tempmd5_filename[4096], temp[4096], report_filename[4096];\r
+       char output_filename[4096];\r
+       char input_cmdline[4096];\r
+       char command_line[4096], exefile[4096];\r
+       int task_counter = 0, word_counter;\r
+       char bin_dir[4096];\r
+       unsigned int word_pointer;\r
+       char ch[4096];                          \r
+       char comparison;\r
+       int num_failed = 0;\r
+       int num_inexistant = 0;\r
+       int num_passed = 0;\r
+               \r
+       if (argc != 3) {\r
+               printf("Error with command line. \nExpected: OPJ_Validate parameter_filename bin_directory\n Example: OPJ_Validate parameters_01.txt version1.1.a\n\n");\r
+               return 1;\r
+       }\r
+       \r
+       param_file = fopen(argv[1],"rb");\r
+       if (!param_file) {\r
+               printf("Error opening parameter file %s\n",argv[1]);\r
+               return 1;\r
+       }       \r
+       \r
+       sprintf(bin_dir,"%s/%s",OPJ_Bin_Dir,argv[2]);\r
+       sprintf(tempmd5_filename,"temp/tempmd5.txt");\r
+       sprintf(report_filename,"%s/report.txt",bin_dir);\r
+       report_file = fopen(report_filename, "wb");\r
+       if (!report_file) {\r
+               printf("Unable to open report file %s", report_filename);\r
+               return 1;\r
+       }\r
+       \r
+       while (fgets(line, 4096, param_file) != NULL) {\r
+               \r
+               if (line[0] != '#' && line[0] != 0x0d) {        // If not a comment line\r
+                       sscanf(line, "%s", temp);\r
+                       word_pointer = 0;\r
+                       sprintf(input_cmdline,"");      \r
+                       sscanf(line+word_pointer,"%s",ch);\r
+                       sprintf(exefile,"%s/%s",bin_dir,ch);                            \r
+                       word_counter = 0;\r
+                       while (sscanf(line+word_pointer,"%s",ch) > 0) {\r
+                               if (word_counter == 4) \r
+                                       strcpy(output_filename, ch);\r
+                               word_pointer += strlen(ch)+1;\r
+                               sprintf(input_cmdline,"%s%s ",input_cmdline, ch);                               \r
+                               word_counter++;\r
+                       }                       \r
+                       sprintf(md5_filename,"%s.md5",output_filename);\r
+                       task_counter++;\r
+                       sprintf(command_line,"%s/%s",bin_dir,input_cmdline);\r
+                       printf("Task %d\nMD5 file: %s\nCommand line: \"%s\"\n",task_counter, md5_filename,command_line);\r
+                       fprintf(report_file,"Task %d\n   MD5 file: %s\n   Command line: \"%s\"\n",task_counter, md5_filename,command_line);\r
+                       \r
+                       if (doprocess(exefile,command_line)) {\r
+                               printf("Error executing: \"%s\" \n", command_line);\r
+                               fprintf(report_file,"Task %d failed because command line is not valid.\n\n", task_counter);\r
+                       }\r
+                       else {\r
+                               \r
+                               // Check if MD5 reference exists\r
+                               md5_file = fopen(md5_filename,"rb");\r
+                               if (md5_file) {\r
+                                       fclose(md5_file);\r
+                                       if (MD5_process(output_filename, tempmd5_filename)) \r
+                                               return 1;\r
+                                       \r
+                                       comparison = fcompare(tempmd5_filename, md5_filename);\r
+                                       if (comparison == -1)\r
+                                               return 1;\r
+                                       else if (comparison) {\r
+                                               printf("ERROR: %s and %s are different.\nThe codec seems to behave differently.\n\n", tempmd5_filename, md5_filename);\r
+                                               fprintf(report_file,"ERROR: %s and %s are different.\nThe codec seems to behave differently.\n\n", tempmd5_filename, md5_filename);\r
+                                               num_failed++;\r
+                                       }\r
+                                       else {\r
+                                               printf("%s and %s are the same.\nTask %d OK\n\n",tempmd5_filename, md5_filename, task_counter);\r
+                                               fprintf(report_file,"   %s and %s are the same.\nTask %d OK\n\n",tempmd5_filename, md5_filename, task_counter);\r
+                                               num_passed++;\r
+                                       }\r
+                                       remove(tempmd5_filename);\r
+                               }       \r
+                               else {\r
+                                       if (MD5_process(output_filename, md5_filename))\r
+                                               return 1;\r
+                                       printf("...  MD5 of %s was inexistant. It has been created\n\n", output_filename);\r
+                                       fprintf(report_file,"MD5 of %s was inexistant. It has been created\n\n", output_filename);\r
+                                       num_inexistant++;\r
+                               }\r
+                       }\r
+               }\r
+       }               \r
+\r
+       printf("\nREPORT;\n%d tests num_passed\n%d tests num_failed\n%d MD5 were num_inexistant\n", num_passed, num_failed, num_inexistant);\r
+       fprintf(report_file,"\nREPORT;\n%d tests num_passed\n%d tests num_failed\n%d MD5 were num_inexistant\n", num_passed, num_failed, num_inexistant);\r
+       fclose(param_file);\r
+       fclose(report_file);\r
+               \r
+}\r
diff --git a/testing/OPJ_Validate.dsp b/testing/OPJ_Validate.dsp
new file mode 100644 (file)
index 0000000..7463089
--- /dev/null
@@ -0,0 +1,108 @@
+# Microsoft Developer Studio Project File - Name="OPJ_Validate" - Package Owner=<4>\r
+# Microsoft Developer Studio Generated Build File, Format Version 6.00\r
+# ** DO NOT EDIT **\r
+\r
+# TARGTYPE "Win32 (x86) Console Application" 0x0103\r
+\r
+CFG=OPJ_Validate - Win32 Debug\r
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r
+!MESSAGE use the Export Makefile command and run\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "OPJ_Validate.mak".\r
+!MESSAGE \r
+!MESSAGE You can specify a configuration when running NMAKE\r
+!MESSAGE by defining the macro CFG on the command line. For example:\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "OPJ_Validate.mak" CFG="OPJ_Validate - Win32 Debug"\r
+!MESSAGE \r
+!MESSAGE Possible choices for configuration are:\r
+!MESSAGE \r
+!MESSAGE "OPJ_Validate - Win32 Release" (based on "Win32 (x86) Console Application")\r
+!MESSAGE "OPJ_Validate - Win32 Debug" (based on "Win32 (x86) Console Application")\r
+!MESSAGE \r
+\r
+# Begin Project\r
+# PROP AllowPerConfigDependencies 0\r
+# PROP Scc_ProjName ""\r
+# PROP Scc_LocalPath ""\r
+CPP=cl.exe\r
+RSC=rc.exe\r
+\r
+!IF  "$(CFG)" == "OPJ_Validate - Win32 Release"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 0\r
+# PROP BASE Output_Dir "Release"\r
+# PROP BASE Intermediate_Dir "Release"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 0\r
+# PROP Output_Dir "Release"\r
+# PROP Intermediate_Dir "Release"\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
+# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
+# ADD BASE RSC /l 0x80c /d "NDEBUG"\r
+# ADD RSC /l 0x80c /d "NDEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
+\r
+!ELSEIF  "$(CFG)" == "OPJ_Validate - Win32 Debug"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 1\r
+# PROP BASE Output_Dir "Debug"\r
+# PROP BASE Intermediate_Dir "Debug"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 1\r
+# PROP Output_Dir "Debug"\r
+# PROP Intermediate_Dir "Debug"\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c\r
+# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /FR /YX /FD /GZ /c\r
+# ADD BASE RSC /l 0x80c /d "_DEBUG"\r
+# ADD RSC /l 0x80c /d "_DEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+\r
+!ENDIF \r
+\r
+# Begin Target\r
+\r
+# Name "OPJ_Validate - Win32 Release"\r
+# Name "OPJ_Validate - Win32 Debug"\r
+# Begin Group "Source Files"\r
+\r
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"\r
+# Begin Source File\r
+\r
+SOURCE=.\md5.c\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\OPJ_Validate.c\r
+# End Source File\r
+# End Group\r
+# Begin Group "Header Files"\r
+\r
+# PROP Default_Filter "h;hpp;hxx;hm;inl"\r
+# Begin Source File\r
+\r
+SOURCE=.\md5.h\r
+# End Source File\r
+# End Group\r
+# Begin Group "Resource Files"\r
+\r
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+# End Group\r
+# End Target\r
+# End Project\r
diff --git a/testing/OPJ_Validate.dsw b/testing/OPJ_Validate.dsw
new file mode 100644 (file)
index 0000000..05a3403
--- /dev/null
@@ -0,0 +1,29 @@
+Microsoft Developer Studio Workspace File, Format Version 6.00\r
+# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!\r
+\r
+###############################################################################\r
+\r
+Project: "OPJ_Validate"=".\OPJ_Validate.dsp" - Package Owner=<4>\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<4>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
+Global:\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<3>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
diff --git a/testing/OPJ_Validate_Candidate_vs_Ref.bat b/testing/OPJ_Validate_Candidate_vs_Ref.bat
new file mode 100644 (file)
index 0000000..0fd61ad
--- /dev/null
@@ -0,0 +1,8 @@
+cd temp\r
+erase *.ppm\r
+erase *.j2k\r
+erase *.bmp\r
+erase *.tif\r
+erase *.jp2\r
+cd ..\r
+OPJ_Validate.exe OPJ_Param_File_v0_1.txt testv2\r
diff --git a/testing/OPJ_Validate_Candidate_vs_Ref.sh b/testing/OPJ_Validate_Candidate_vs_Ref.sh
new file mode 100644 (file)
index 0000000..edd3eaa
--- /dev/null
@@ -0,0 +1,16 @@
+#!/bin/bash
+cd temp
+erase *.ppm
+erase *.j2k
+erase *.bmp
+erase *.tif
+erase *.jp2
+cd ..
+
+echo
+echo "Type the name of the directory (inside OPJ_Binaries) "
+echo "containing your executables to compared with reference, followed by [ENTER] (example: rev101):"
+read compdir
+
+./OPJ_Validate linux_OPJ_Param_File_v0_1.txt $compdir
+echo
diff --git a/testing/OPJ_Validate_Create_Ref.bat b/testing/OPJ_Validate_Create_Ref.bat
new file mode 100644 (file)
index 0000000..83332fc
--- /dev/null
@@ -0,0 +1,4 @@
+cd temp\r
+erase *.md5\r
+cd ..\r
+OPJ_Validate.exe OPJ_Param_File_v0_1.txt rev490\r
diff --git a/testing/OPJ_Validate_Create_Ref.sh b/testing/OPJ_Validate_Create_Ref.sh
new file mode 100644 (file)
index 0000000..e44e053
--- /dev/null
@@ -0,0 +1,13 @@
+#!/bin/bash
+#Create Reference images and hash
+
+echo
+echo "Type the name of the directory (inside OPJ_Binaries) "
+echo "containing your reference executables, followed by [ENTER] (example: rev100):"
+read refdir
+cd temp
+rm *.md5
+cd ..
+./OPJ_Validate linux_OPJ_Param_File_v0_1.txt $refdir
+echo
+
diff --git a/testing/README.txt b/testing/README.txt
new file mode 100644 (file)
index 0000000..364ef8e
--- /dev/null
@@ -0,0 +1,46 @@
+Initialization\r
+--------------\r
+Download the source images into the /original directory from http://www.openjpeg.org/OPJ_Validate_OriginalImages.7z\r
+\r
+Usage\r
+-----\r
+Usage: OPJ_Validate batch_text_file bin_directory\r
+Example: OPJ_Validate OPJ_Param_File_v0_1.txt v1.1.a\r
+where OPJ_Param_File_v0_1.txt is a file containing a list of compression and decompression parameters\r
+and v1.1.a is a directory inside the directory OPJ_Binaries containing the openjpeg executables (j2k_to_image.exe and image_to_j2k.exe)\r
+\r
+Example with batch file: You consider revision 490 (/rev490) as stable, and would like to compare it a new version, revision 493 (rev493).\r
+\r
+Batch mode\r
+----------\r
+1) Calculate the reference by running the "OPJ_Validate_Create_Ref rev490" file (.sh or .bat depending on your os)\r
+2) Compare the candidate revision with ther reference by running the "OPJ_Validate_Candidate_vs_Ref rev493" file\r
+3) The results of the comparison are given at the end of the processing. They are also available in the bin directory OPJ_Binaries/rev493/report.txt\r
+\r
+Manual mode\r
+-----------\r
+1) Put the j2k_to_image.exe and image_to_j2k.exe binaries of both revisions in the OPJ_Binaries directory (OPJ_Binaries/rev490 and OPJ_Binaries/rev493)  \r
+2) Start by initializing the validation with revision 490. \r
+       a) Modify OPJ_Validate_init.bat and set the last line to "OPJ_Validate.exe OPJ_Param_File_v0_1.txt rev490"\r
+       b) Execute OPJ_Validate_init.bat\r
+3) Compare the reference files generated in the previous step with files generated with revision 493\r
+       a) Modify OPJ_Validate_run.bat and set the last line to "OPJ_Validate.exe OPJ_Param_File_v0_1.txt rev493"\r
+       b) Execute OPJ_Validate_run.bat\r
+4) Read the results in the binaries directory of revision 493 (OPJ_Binaries/rev493/report.txt)\r
+       Search for the word "ERROR:" in that file. \r
+       If this word is not present in the report, this means that both codecs of rev490 and rev493 gave the same results.\r
+       Otherwise, it means that for certain encoding/decoding parameters, the codecs behave differently.\r
+\r
+       Example of error\r
+               Task 17\r
+                  MD5 file: temp/A_4_2K_24_185_CBR_WB_000.tif.md5\r
+                  Command line: "OPJ_Binaries/rev473/j2k_to_image.exe -i original/A_4_2K_24_185_CBR_WB_000.j2k -o temp/A_4_2K_24_185_CBR_WB_000.tif "\r
+               ERROR: temp/tempmd5.txt and temp/A_4_2K_24_185_CBR_WB_000.tif.md5 are different.\r
+               The codec seems to behave differently.\r
+\r
+       This means that the rev490 and rev493 created two different versions of file A_4_2K_24_185_CBR_WB_000.tif with the command line given above.\r
+       An error might have been caused by switching to this new revision.\r
+\r
+       Warning: Do not take the last line of the report.txt file into account ( Cool. All files passed the tests !) as it is a bug. Search for the word "ERROR:" to detect potential errors.\r
+5) If no error is detected, you can commit the changes to the OpenJPEG repository\r
+\r
diff --git a/testing/linux_OPJ_Param_File_v0_1.txt b/testing/linux_OPJ_Param_File_v0_1.txt
new file mode 100644 (file)
index 0000000..0dafe2c
--- /dev/null
@@ -0,0 +1,89 @@
+#OPJ Parameter file\r
+#Version 0.1 - February 9th 2007\r
+#Usage: OPJ_Validate OpenJPEG_command_line\r
+#Example: OPJ_Validate image_to_j2k.exe -i original/Bretagne1.ppm -o original/Bretagne1.j2k -r 200, 50, 10\r
+#Attention: don't forget the *.exe extension for the executable file, and check the paths\r
+#\r
+image_to_j2k -i original/Bretagne1.ppm -o temp/Bretagne1_0.j2k -r 200,50,10\r
+j2k_to_image -i original/Bretagne1.j2k -o temp/Bretagne1.ppm\r
+image_to_j2k -i original/Bretagne2.ppm -o temp/Bretagne2_0.j2k -c [128,128],[128,128],[128,128] -r 100,20,2 -t 640,480 -b 32,32\r
+j2k_to_image -i original/Bretagne2.j2k -o temp/Bretagne2.ppm -r 2\r
+image_to_j2k -i original/Cevennes1.bmp -o temp/Cevennes1.j2k -r 10\r
+j2k_to_image -i original/Cevennes1.j2k -o temp/Cevennes1.bmp -l 2\r
+image_to_j2k -i original/Cevennes2.ppm -o temp/Cevennes2.jp2 -r 50\r
+j2k_to_image -i original/Cevennes2.jp2 -o temp/Cevennes2.ppm\r
+image_to_j2k -i original/Rome.bmp -o temp/Rome.jp2 -q 30,35,50 -p LRCP -n 3\r
+j2k_to_image -i original/Rome.jp2 -o temp/Rome.ppm\r
+image_to_j2k -i original/Bretagne1.ppm -o temp/Bretagne1_1.j2k -q 30,35,40 -n 2\r
+image_to_j2k -i original/Bretagne1.ppm -o temp/Bretagne1_2.j2k -q 30,35,40 -b 16,16 -c [101,101]\r
+image_to_j2k -i original/Bretagne2.ppm -o temp/Bretagne2_1.j2k -t 127,127 -p PCRL\r
+image_to_j2k -i original/X_4_2K_24_185_CBR_WB_000.tif -o temp/X_4_2K_24_185_CBR_WB_000.j2k -cinema2K 24\r
+image_to_j2k -i original/X_5_2K_24_235_CBR_STEM24_000.tif -o temp/X_5_2K_24_235_CBR_STEM24_000.j2k -cinema2K 48\r
+image_to_j2k -i original/X_6_2K_24_FULL_CBR_CIRCLE_000.tif -o temp/X_6_2K_24_FULL_CBR_CIRCLE_000.j2k -cinema2K 24\r
+#� remettre\r
+#image_to_j2k -i original/X_16_4K_24_185_CBR_WB_000.tif -o temp/X_16_4K_24_185_CBR_WB_000.j2k -cinema4K \r
+j2k_to_image -i original/A_4_2K_24_185_CBR_WB_000.j2k -o temp/A_4_2K_24_185_CBR_WB_000.tif\r
+j2k_to_image -i original/B_5_2K_24_235_CBR_STEM24_000.j2k -o temp/B_5_2K_24_235_CBR_STEM24_000.tif\r
+j2k_to_image -i original/C_6_2K_24_FULL_CBR_CIRCLE_000.j2k -o temp/C_6_2K_24_FULL_CBR_CIRCLE_000.tif\r
+#� remettre\r
+#j2k_to_image -i original/C_18_4K_24_FULL_CBR_CIRCLE_000.j2k -o temp/C_18_4K_24_FULL_CBR_CIRCLE_000.tif\r
+j2k_to_image -i original/p0_01.j2k -o temp/p0_01.tif\r
+j2k_to_image -i original/p0_02.j2k -o temp/p0_02.tif\r
+j2k_to_image -i original/p0_03.j2k -o temp/p0_03.tif\r
+j2k_to_image -i original/p0_04.j2k -o temp/p0_04.tif\r
+#a remettre\r
+#j2k_to_image -i original/p0_07.j2k -o temp/p0_07.tif\r
+j2k_to_image -i original/p0_08.j2k -o temp/p0_08.tif\r
+j2k_to_image -i original/p0_09.j2k -o temp/p0_09.tif\r
+j2k_to_image -i original/p0_10.j2k -o temp/p0_10.tif\r
+j2k_to_image -i original/p0_11.j2k -o temp/p0_11.tif\r
+j2k_to_image -i original/p0_12.j2k -o temp/p0_12.tif\r
+j2k_to_image -i original/p0_14.j2k -o temp/p0_14.tif\r
+j2k_to_image -i original/p0_15.j2k -o temp/p0_15.tif\r
+j2k_to_image -i original/p0_16.j2k -o temp/p0_16.tif\r
+j2k_to_image -i original/p1_01.j2k -o temp/p1_01.tif\r
+j2k_to_image -i original/p1_02.j2k -o temp/p1_02.tif\r
+j2k_to_image -i original/p1_04.j2k -o temp/p1_04.tif\r
+j2k_to_image -i original/p1_05.j2k -o temp/p1_05.tif\r
+j2k_to_image -i original/p1_06.j2k -o temp/p1_06.tif\r
+image_to_j2k -i original/c0p0_01.pgx -o temp/c0p0_01.j2k\r
+image_to_j2k -i original/c0p0_02.pgx -o temp/c0p0_02.j2k\r
+image_to_j2k -i original/c0p0_03r0.pgx -o temp/c0p0_03r0.j2k\r
+image_to_j2k -i original/c0p0_03r1.pgx -o temp/c0p0_03r1.j2k\r
+image_to_j2k -i original/c0p0_04.pgx -o temp/c00_p04.j2k\r
+image_to_j2k -i original/c0p0_05.pgx -o temp/c0p0_05.j2k\r
+image_to_j2k -i original/c0p0_06.pgx -o temp/c0p0_06.j2k\r
+image_to_j2k -i original/c0p0_07.pgx -o temp/c0p0_07.j2k\r
+image_to_j2k -i original/c0p0_08.pgx -o temp/c0p0_08.j2k\r
+image_to_j2k -i original/c0p0_09.pgx -o temp/c0p0_09.j2k\r
+image_to_j2k -i original/c0p0_10.pgx -o temp/c0p0_10.j2k\r
+image_to_j2k -i original/c0p0_11.pgx -o temp/c0p0_11.j2k\r
+image_to_j2k -i original/c0p0_12.pgx -o temp/c0p0_12.j2k\r
+image_to_j2k -i original/c0p0_13.pgx -o temp/c0p0_13.j2k\r
+image_to_j2k -i original/c0p0_14.pgx -o temp/c0p0_14.j2k\r
+image_to_j2k -i original/c0p0_15r0.pgx -o temp/c0p0_15r0.j2k\r
+image_to_j2k -i original/c0p0_15r1.pgx -o temp/c0p0_15r1.j2k\r
+image_to_j2k -i original/c0p0_16.pgx -o temp/c0p0_16.j2k\r
+image_to_j2k -i original/c0p1_04r0.pgx -o temp/c0p1_04r0.j2k\r
+image_to_j2k -i original/c0p1_05.pgx -o temp/c0p1_05.j2k\r
+image_to_j2k -i original/c1p0_01_0.pgx -o temp/c1p0_01_0.j2k\r
+image_to_j2k -i original/c1p0_02_0.pgx -o temp/c1p0_02_0.j2k\r
+image_to_j2k -i original/c1p0_03_0.pgx -o temp/c1p0_03_0.j2k\r
+image_to_j2k -i original/c1p0_04_0.pgx -o temp/c1p0_04_0.j2k\r
+image_to_j2k -i original/c1p0_05_0.pgx -o temp/c1p0_05_0.j2k\r
+image_to_j2k -i original/c1p0_06_0.pgx -o temp/c1p0_06_0.j2k\r
+image_to_j2k -i original/c1p0_07_0.pgx -o temp/c1p0_07_0.j2k\r
+image_to_j2k -i original/c1p0_08_0.pgx -o temp/c1p0_08_0.j2k\r
+image_to_j2k -i original/c1p0_09_0.pgx -o temp/c1p0_09_0.j2k\r
+image_to_j2k -i original/c1p0_10_0.pgx -o temp/c1p0_10_0.j2k\r
+image_to_j2k -i original/c1p0_11_0.pgx -o temp/c1p0_11_0.j2k\r
+image_to_j2k -i original/c1p0_12_0.pgx -o temp/c1p0_12_0.j2k\r
+image_to_j2k -i original/c1p0_13_0.pgx -o temp/c1p0_13_0.j2k\r
+image_to_j2k -i original/c1p0_14_0.pgx -o temp/c1p0_14_0.j2k\r
+image_to_j2k -i original/c1p0_15_0.pgx -o temp/c1p0_15_0.j2k\r
+image_to_j2k -i original/c1p0_16_0.pgx -o temp/c1p0_16_0.j2k\r
+image_to_j2k -i original/c1p1_02_0.pgx -o temp/c1p1_02_0.j2k\r
+image_to_j2k -i original/c1p1_05_0.pgx -o temp/c1p1_05_0.j2k\r
+image_to_j2k -i original/Bretagne2.ppm -o temp/Bretagne2_2.j2k -s 2,2 -SOP\r
+image_to_j2k -i original/Bretagne2.ppm -o temp/Bretagne2_3.j2k -EPH -M 38\r
+image_to_j2k -i original/Bretagne2.ppm -o temp/Bretagne2_4.j2k -d 150,300 -r 800\r
diff --git a/testing/md5.c b/testing/md5.c
new file mode 100644 (file)
index 0000000..735a27c
--- /dev/null
@@ -0,0 +1,276 @@
+/*\r
+ **********************************************************************\r
+ ** md5.c                                                            **\r
+ ** RSA Data Security, Inc. MD5 Message Digest Algorithm             **\r
+ ** Created: 2/17/90 RLR                                             **\r
+ ** Revised: 1/91 SRD,AJ,BSK,JT Reference C Version                  **\r
+ **********************************************************************\r
+ */\r
+\r
+/*\r
+ **********************************************************************\r
+ ** Copyright (C) 1990, RSA Data Security, Inc. All rights reserved. **\r
+ **                                                                  **\r
+ ** License to copy and use this software is granted provided that   **\r
+ ** it is identified as the "RSA Data Security, Inc. MD5 Message     **\r
+ ** Digest Algorithm" in all material mentioning or referencing this **\r
+ ** software or this function.                                       **\r
+ **                                                                  **\r
+ ** License is also granted to make and use derivative works         **\r
+ ** provided that such works are identified as "derived from the RSA **\r
+ ** Data Security, Inc. MD5 Message Digest Algorithm" in all         **\r
+ ** material mentioning or referencing the derived work.             **\r
+ **                                                                  **\r
+ ** RSA Data Security, Inc. makes no representations concerning      **\r
+ ** either the merchantability of this software or the suitability   **\r
+ ** of this software for any particular purpose.  It is provided "as **\r
+ ** is" without express or implied warranty of any kind.             **\r
+ **                                                                  **\r
+ ** These notices must be retained in any copies of any part of this **\r
+ ** documentation and/or software.                                   **\r
+ **********************************************************************\r
+ */\r
+\r
+/* -- include the following line if the md5.h header file is separate -- */\r
+#include "md5.h" \r
+\r
+/* forward declaration */\r
+static void Transform ();\r
+\r
+static unsigned char PADDING[64] = {\r
+  0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\r
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\r
+};\r
+\r
+/* F, G and H are basic MD5 functions: selection, majority, parity */\r
+#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))\r
+#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))\r
+#define H(x, y, z) ((x) ^ (y) ^ (z))\r
+#define I(x, y, z) ((y) ^ ((x) | (~z))) \r
+\r
+/* ROTATE_LEFT rotates x left n bits */\r
+#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))\r
+\r
+/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4 */\r
+/* Rotation is separate from addition to prevent recomputation */\r
+#define FF(a, b, c, d, x, s, ac) \\r
+  {(a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \\r
+   (a) = ROTATE_LEFT ((a), (s)); \\r
+   (a) += (b); \\r
+  }\r
+#define GG(a, b, c, d, x, s, ac) \\r
+  {(a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \\r
+   (a) = ROTATE_LEFT ((a), (s)); \\r
+   (a) += (b); \\r
+  }\r
+#define HH(a, b, c, d, x, s, ac) \\r
+  {(a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \\r
+   (a) = ROTATE_LEFT ((a), (s)); \\r
+   (a) += (b); \\r
+  }\r
+#define II(a, b, c, d, x, s, ac) \\r
+  {(a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \\r
+   (a) = ROTATE_LEFT ((a), (s)); \\r
+   (a) += (b); \\r
+  }\r
+\r
+void MD5Init (mdContext)\r
+MD5_CTX *mdContext;\r
+{\r
+  mdContext->i[0] = mdContext->i[1] = (UINT4)0;\r
+\r
+  /* Load magic initialization constants.\r
+   */\r
+  mdContext->buf[0] = (UINT4)0x67452301;\r
+  mdContext->buf[1] = (UINT4)0xefcdab89;\r
+  mdContext->buf[2] = (UINT4)0x98badcfe;\r
+  mdContext->buf[3] = (UINT4)0x10325476;\r
+}\r
+\r
+void MD5Update (mdContext, inBuf, inLen)\r
+MD5_CTX *mdContext;\r
+unsigned char *inBuf;\r
+unsigned int inLen;\r
+{\r
+  UINT4 in[16];\r
+  int mdi;\r
+  unsigned int i, ii;\r
+\r
+  /* compute number of bytes mod 64 */\r
+  mdi = (int)((mdContext->i[0] >> 3) & 0x3F);\r
+\r
+  /* update number of bits */\r
+  if ((mdContext->i[0] + ((UINT4)inLen << 3)) < mdContext->i[0])\r
+    mdContext->i[1]++;\r
+  mdContext->i[0] += ((UINT4)inLen << 3);\r
+  mdContext->i[1] += ((UINT4)inLen >> 29);\r
+\r
+  while (inLen--) {\r
+    /* add new character to buffer, increment mdi */\r
+    mdContext->in[mdi++] = *inBuf++;\r
+\r
+    /* transform if necessary */\r
+    if (mdi == 0x40) {\r
+      for (i = 0, ii = 0; i < 16; i++, ii += 4)\r
+        in[i] = (((UINT4)mdContext->in[ii+3]) << 24) |\r
+                (((UINT4)mdContext->in[ii+2]) << 16) |\r
+                (((UINT4)mdContext->in[ii+1]) << 8) |\r
+                ((UINT4)mdContext->in[ii]);\r
+      Transform (mdContext->buf, in);\r
+      mdi = 0;\r
+    }\r
+  }\r
+}\r
+\r
+void MD5Final (mdContext)\r
+MD5_CTX *mdContext;\r
+{\r
+  UINT4 in[16];\r
+  int mdi;\r
+  unsigned int i, ii;\r
+  unsigned int padLen;\r
+\r
+  /* save number of bits */\r
+  in[14] = mdContext->i[0];\r
+  in[15] = mdContext->i[1];\r
+\r
+  /* compute number of bytes mod 64 */\r
+  mdi = (int)((mdContext->i[0] >> 3) & 0x3F);\r
+\r
+  /* pad out to 56 mod 64 */\r
+  padLen = (mdi < 56) ? (56 - mdi) : (120 - mdi);\r
+  MD5Update (mdContext, PADDING, padLen);\r
+\r
+  /* append length in bits and transform */\r
+  for (i = 0, ii = 0; i < 14; i++, ii += 4)\r
+    in[i] = (((UINT4)mdContext->in[ii+3]) << 24) |\r
+            (((UINT4)mdContext->in[ii+2]) << 16) |\r
+            (((UINT4)mdContext->in[ii+1]) << 8) |\r
+            ((UINT4)mdContext->in[ii]);\r
+  Transform (mdContext->buf, in);\r
+\r
+  /* store buffer in digest */\r
+  for (i = 0, ii = 0; i < 4; i++, ii += 4) {\r
+    mdContext->digest[ii] = (unsigned char)(mdContext->buf[i] & 0xFF);\r
+    mdContext->digest[ii+1] =\r
+      (unsigned char)((mdContext->buf[i] >> 8) & 0xFF);\r
+    mdContext->digest[ii+2] =\r
+      (unsigned char)((mdContext->buf[i] >> 16) & 0xFF);\r
+    mdContext->digest[ii+3] =\r
+      (unsigned char)((mdContext->buf[i] >> 24) & 0xFF);\r
+  }\r
+}\r
+\r
+/* Basic MD5 step. Transform buf based on in.\r
+ */\r
+static void Transform (buf, in)\r
+UINT4 *buf;\r
+UINT4 *in;\r
+{\r
+  UINT4 a = buf[0], b = buf[1], c = buf[2], d = buf[3];\r
+\r
+  /* Round 1 */\r
+#define S11 7\r
+#define S12 12\r
+#define S13 17\r
+#define S14 22\r
+  FF ( a, b, c, d, in[ 0], S11, 3614090360); /* 1 */\r
+  FF ( d, a, b, c, in[ 1], S12, 3905402710); /* 2 */\r
+  FF ( c, d, a, b, in[ 2], S13,  606105819); /* 3 */\r
+  FF ( b, c, d, a, in[ 3], S14, 3250441966); /* 4 */\r
+  FF ( a, b, c, d, in[ 4], S11, 4118548399); /* 5 */\r
+  FF ( d, a, b, c, in[ 5], S12, 1200080426); /* 6 */\r
+  FF ( c, d, a, b, in[ 6], S13, 2821735955); /* 7 */\r
+  FF ( b, c, d, a, in[ 7], S14, 4249261313); /* 8 */\r
+  FF ( a, b, c, d, in[ 8], S11, 1770035416); /* 9 */\r
+  FF ( d, a, b, c, in[ 9], S12, 2336552879); /* 10 */\r
+  FF ( c, d, a, b, in[10], S13, 4294925233); /* 11 */\r
+  FF ( b, c, d, a, in[11], S14, 2304563134); /* 12 */\r
+  FF ( a, b, c, d, in[12], S11, 1804603682); /* 13 */\r
+  FF ( d, a, b, c, in[13], S12, 4254626195); /* 14 */\r
+  FF ( c, d, a, b, in[14], S13, 2792965006); /* 15 */\r
+  FF ( b, c, d, a, in[15], S14, 1236535329); /* 16 */\r
+\r
+  /* Round 2 */\r
+#define S21 5\r
+#define S22 9\r
+#define S23 14\r
+#define S24 20\r
+  GG ( a, b, c, d, in[ 1], S21, 4129170786); /* 17 */\r
+  GG ( d, a, b, c, in[ 6], S22, 3225465664); /* 18 */\r
+  GG ( c, d, a, b, in[11], S23,  643717713); /* 19 */\r
+  GG ( b, c, d, a, in[ 0], S24, 3921069994); /* 20 */\r
+  GG ( a, b, c, d, in[ 5], S21, 3593408605); /* 21 */\r
+  GG ( d, a, b, c, in[10], S22,   38016083); /* 22 */\r
+  GG ( c, d, a, b, in[15], S23, 3634488961); /* 23 */\r
+  GG ( b, c, d, a, in[ 4], S24, 3889429448); /* 24 */\r
+  GG ( a, b, c, d, in[ 9], S21,  568446438); /* 25 */\r
+  GG ( d, a, b, c, in[14], S22, 3275163606); /* 26 */\r
+  GG ( c, d, a, b, in[ 3], S23, 4107603335); /* 27 */\r
+  GG ( b, c, d, a, in[ 8], S24, 1163531501); /* 28 */\r
+  GG ( a, b, c, d, in[13], S21, 2850285829); /* 29 */\r
+  GG ( d, a, b, c, in[ 2], S22, 4243563512); /* 30 */\r
+  GG ( c, d, a, b, in[ 7], S23, 1735328473); /* 31 */\r
+  GG ( b, c, d, a, in[12], S24, 2368359562); /* 32 */\r
+\r
+  /* Round 3 */\r
+#define S31 4\r
+#define S32 11\r
+#define S33 16\r
+#define S34 23\r
+  HH ( a, b, c, d, in[ 5], S31, 4294588738); /* 33 */\r
+  HH ( d, a, b, c, in[ 8], S32, 2272392833); /* 34 */\r
+  HH ( c, d, a, b, in[11], S33, 1839030562); /* 35 */\r
+  HH ( b, c, d, a, in[14], S34, 4259657740); /* 36 */\r
+  HH ( a, b, c, d, in[ 1], S31, 2763975236); /* 37 */\r
+  HH ( d, a, b, c, in[ 4], S32, 1272893353); /* 38 */\r
+  HH ( c, d, a, b, in[ 7], S33, 4139469664); /* 39 */\r
+  HH ( b, c, d, a, in[10], S34, 3200236656); /* 40 */\r
+  HH ( a, b, c, d, in[13], S31,  681279174); /* 41 */\r
+  HH ( d, a, b, c, in[ 0], S32, 3936430074); /* 42 */\r
+  HH ( c, d, a, b, in[ 3], S33, 3572445317); /* 43 */\r
+  HH ( b, c, d, a, in[ 6], S34,   76029189); /* 44 */\r
+  HH ( a, b, c, d, in[ 9], S31, 3654602809); /* 45 */\r
+  HH ( d, a, b, c, in[12], S32, 3873151461); /* 46 */\r
+  HH ( c, d, a, b, in[15], S33,  530742520); /* 47 */\r
+  HH ( b, c, d, a, in[ 2], S34, 3299628645); /* 48 */\r
+\r
+  /* Round 4 */\r
+#define S41 6\r
+#define S42 10\r
+#define S43 15\r
+#define S44 21\r
+  II ( a, b, c, d, in[ 0], S41, 4096336452); /* 49 */\r
+  II ( d, a, b, c, in[ 7], S42, 1126891415); /* 50 */\r
+  II ( c, d, a, b, in[14], S43, 2878612391); /* 51 */\r
+  II ( b, c, d, a, in[ 5], S44, 4237533241); /* 52 */\r
+  II ( a, b, c, d, in[12], S41, 1700485571); /* 53 */\r
+  II ( d, a, b, c, in[ 3], S42, 2399980690); /* 54 */\r
+  II ( c, d, a, b, in[10], S43, 4293915773); /* 55 */\r
+  II ( b, c, d, a, in[ 1], S44, 2240044497); /* 56 */\r
+  II ( a, b, c, d, in[ 8], S41, 1873313359); /* 57 */\r
+  II ( d, a, b, c, in[15], S42, 4264355552); /* 58 */\r
+  II ( c, d, a, b, in[ 6], S43, 2734768916); /* 59 */\r
+  II ( b, c, d, a, in[13], S44, 1309151649); /* 60 */\r
+  II ( a, b, c, d, in[ 4], S41, 4149444226); /* 61 */\r
+  II ( d, a, b, c, in[11], S42, 3174756917); /* 62 */\r
+  II ( c, d, a, b, in[ 2], S43,  718787259); /* 63 */\r
+  II ( b, c, d, a, in[ 9], S44, 3951481745); /* 64 */\r
+\r
+  buf[0] += a;\r
+  buf[1] += b;\r
+  buf[2] += c;\r
+  buf[3] += d;\r
+}\r
+\r
+/*\r
+ **********************************************************************\r
+ ** End of md5.c                                                     **\r
+ ******************************* (cut) ********************************\r
+ */\r
diff --git a/testing/md5.h b/testing/md5.h
new file mode 100644 (file)
index 0000000..6fb35cf
--- /dev/null
@@ -0,0 +1,59 @@
+/*\r
+ **********************************************************************\r
+ ** md5.h -- Header file for implementation of MD5                   **\r
+ ** RSA Data Security, Inc. MD5 Message Digest Algorithm             **\r
+ ** Created: 2/17/90 RLR                                             **\r
+ ** Revised: 12/27/90 SRD,AJ,BSK,JT Reference C version              **\r
+ ** Revised (for MD5): RLR 4/27/91                                   **\r
+ **   -- G modified to have y&~z instead of y&z                      **\r
+ **   -- FF, GG, HH modified to add in last register done            **\r
+ **   -- Access pattern: round 2 works mod 5, round 3 works mod 3    **\r
+ **   -- distinct additive constant for each step                    **\r
+ **   -- round 4 added, working mod 7                                **\r
+ **********************************************************************\r
+ */\r
+\r
+/*\r
+ **********************************************************************\r
+ ** Copyright (C) 1990, RSA Data Security, Inc. All rights reserved. **\r
+ **                                                                  **\r
+ ** License to copy and use this software is granted provided that   **\r
+ ** it is identified as the "RSA Data Security, Inc. MD5 Message     **\r
+ ** Digest Algorithm" in all material mentioning or referencing this **\r
+ ** software or this function.                                       **\r
+ **                                                                  **\r
+ ** License is also granted to make and use derivative works         **\r
+ ** provided that such works are identified as "derived from the RSA **\r
+ ** Data Security, Inc. MD5 Message Digest Algorithm" in all         **\r
+ ** material mentioning or referencing the derived work.             **\r
+ **                                                                  **\r
+ ** RSA Data Security, Inc. makes no representations concerning      **\r
+ ** either the merchantability of this software or the suitability   **\r
+ ** of this software for any particular purpose.  It is provided "as **\r
+ ** is" without express or implied warranty of any kind.             **\r
+ **                                                                  **\r
+ ** These notices must be retained in any copies of any part of this **\r
+ ** documentation and/or software.                                   **\r
+ **********************************************************************\r
+ */\r
+\r
+/* typedef a 32 bit type */\r
+typedef unsigned long int UINT4;\r
+\r
+/* Data structure for MD5 (Message Digest) computation */\r
+typedef struct {\r
+  UINT4 i[2];                   /* number of _bits_ handled mod 2^64 */\r
+  UINT4 buf[4];                                    /* scratch buffer */\r
+  unsigned char in[64];                              /* input buffer */\r
+  unsigned char digest[16];     /* actual digest after MD5Final call */\r
+} MD5_CTX;\r
+\r
+void MD5Init ();\r
+void MD5Update ();\r
+void MD5Final ();\r
+\r
+/*\r
+ **********************************************************************\r
+ ** End of md5.h                                                     **\r
+ ******************************* (cut) ********************************\r
+ */\r
diff --git a/testing/original/README.txt b/testing/original/README.txt
new file mode 100644 (file)
index 0000000..d78d1bd
--- /dev/null
@@ -0,0 +1 @@
+Download the source images into this directory from http://www.openjpeg.org/OPJ_Validate_OriginalImages.7z